Here is a piece of C++ code that seems very peculiar. For some strange reason, sorting the data miraculously makes the code almost six times faster.Initially, I thought this might be just a language or compiler anomaly. So I tried it in Java.With a somewhat similar but less extreme result.My first thought was that sorting brings the data into the cache, but then I thought how silly that is because the array was just generated.Consider a railroad junction:\nNow for the sake of argument, suppose this is back in the 1800s - before long distance or radio communication.You are the operator of a junction and you hear a train coming. You have no idea which way it is supposed to go. You stop the train to ask the driver which direction they want. And then you set the switch appropriately.Is there a better way? You guess which direction the train will go!, the train will never have to stop.\n, the train will spend a lot of time stopping, backing up, and restarting. At the processor level, it is a branch instruction:You are a processor and you see a branch. You have no idea which way it will go. What do you do? You halt execution and wait until the previous instructions are complete. Then you continue down the correct path.Is there a better way? You guess which direction the branch will go!, the execution will never have to stop.\n, you spend a lot of time stalling, rolling back, and restarting.This is branch prediction. I admit it's not the best analogy since the train could just signal the direction with a flag. But in computers, the processor doesn't know which direction a branch will go until the last moment.So how would you strategically guess to minimize the number of times that the train must back up and go down the other path? You look at the past history! If the train goes left 99% of the time, then you guess left. If it alternates, then you alternate your guesses. If it goes one way every 3 times, you guess the same... This is more or less how branch predictors work.Most applications have well-behaved branches. So modern branch predictors will typically achieve >90% hit rates. But when faced with unpredictable branches with no recognizable patterns, branch predictors are virtually useless.Further reading: .Notice that the data is evenly distributed between 0 and 255. \nWhen the data is sorted, roughly the first half of the iterations will not enter the if-statement. After that, they will all enter the if-statement.This is very friendly to the branch predictor since the branch consecutively goes the same direction many times.\nEven a simple saturating counter will correctly predict the branch except for the few iterations after it switches direction.However, when the data is completely random, the branch predictor is rendered useless because it can't predict random data.\nThus there will probably be around 50% misprediction. (no better than random guessing)If the compiler isn't able to optimize the branch into a conditional move, you can try some hacks if you are willing to sacrifice readability for performance.Replace:with:This eliminates the branch and replaces it with some bitwise operations.C++ - Visual Studio 2010 - x64 ReleaseJava - Netbeans 7.1.1 JDK 7 - x64Observations:A general rule of thumb is to avoid data-dependent branching in critical loops. (such as in this example)This goes to show that even mature modern compilers can vary wildly in their ability to optimize code...With a sorted array, the condition  is first  for a streak of values, then becomes  for all later values. That's easy to predict. With an unsorted array, you pay for the branching cost.The reason why performance improves drastically when the data is sorted is that the branch prediction penalty is removed, as explained beautifully in 's answer.Now, if we look at the codewe can find that the meaning of this particular  branch is to add something when a condition is satisfied. This type of branch can be easily transformed into a  statement, which would be compiled into a conditional move instruction: , in an  system. The branch and thus the potential branch prediction penalty is removed.In , thus , the statement, which would compile directly (without any optimization) into the conditional move instruction in , is the ternary operator . So we rewrite the above statement into an equivalent one:While maintaining readability, we can check the speedup factor.On an Intel -2600K @ 3.4\u00a0GHz and Visual Studio 2010 Release Mode, the benchmark is (format copied from Mysticial):The result is robust in multiple tests. We get a great speedup when the branch result is unpredictable, but we suffer a little bit when it is predictable. In fact, when using a conditional move, the performance is the same regardless of the data pattern.Now let's look more closely by investigating the  assembly they generate. For simplicity, we use two functions  and . uses the conditional branch : uses the ternary operator :On a x86-64 machine,  generates the assembly below. uses much less code due to the usage of instruction . But the real gain is that  does not involve branch jumps, , which would have a significant performance penalty if the predicted result is not right.So why does a conditional move perform better?In a typical  processor, the execution of an instruction is divided into several stages. Roughly, we have different hardware to deal with different stages. So we do not have to wait for one instruction to finish to start a new one. This is called .In a branch case, the following instruction is determined by the preceding one, so we cannot do pipelining. We have to either wait or predict.In a conditional move case, the execution conditional move instruction is divided into several stages, but the earlier stages like  and  does not depend on the result of the previous instruction; only latter stages need the result. Thus, we wait a fraction of one instruction's execution time. This is why the conditional move version is slower than the branch when prediction is easy.The book  explains this in detail. You can check Section 3.6.6 for , entire Chapter 4 for , and Section 5.11.2 for a special treatment for .Sometimes, some modern compilers can optimize our code to assembly with better performance, sometimes some compilers can't (the code in question is using Visual Studio's native compiler). Knowing the performance difference between branch and conditional move when unpredictable can help us write code with better performance when the scenario gets so complex that the compiler can not optimize them automatically.If you are curious about even more optimizations that can be done to this code, consider this... Starting with the original loop:With loop interchange, we can safely change this loop to:Then, you can see that the \"if\" conditional is constant throughout the execution of the \"i\" loop, so you can hoist the \"if\" out:Then, you see that the inner loop can be collapsed into one single expression, assuming the floating point model allows it (/fp:fast is thrown, for example)That one is 100,000x faster than before (-8No doubt some of us would be interested in ways of identifying code that is problematic for the CPU's branch-predictor. The Valgrind tool  has a branch-predictor simulator, enabled by using the  flag. Running it over the examples in this question, with the number of outer loops reduced to 10000 and compiled with , gives these results:Drilling down into the line-by-line output produced by  we see for the loop in question:This lets you easily identify the problematic line - in the unsorted version the  line is causing 164,050,007 mispredicted conditional branches () under cachegrind's branch-predictor model, whereas it's only causing 10,006 in the sorted version.Alternatively, on Linux you can use the performance counters subsystem to accomplish the same task, but with native performance using CPU counters.It can also do source code annotation with dissassembly.See  for more details.Just read up on the thread and I feel an answer is missing. A common way to eliminate branch prediction that I've found to work particularly good in managed languages is a table lookup instead of using a branch. (although I haven't tested it in this case)This approach works in general if:Pfew, so what the hell is that supposed to mean?From a processor perspective, your memory is slow. To compensate for the difference in speed, they build in a couple of caches in your processor (L1/L2 cache) that compensate for that. So imagine that you're doing your nice calculations and figure out that you need a piece of memory. The processor will get his 'load' operation and loads the piece of memory into cache - and then uses the cache to do the rest of the calculations. Because memory is relatively slow, this 'load' will slow down your program. Like branch prediction, this was optimized in the Pentium processors: the processor predicts that it needs to load a piece of data and attempts to load that into the cache before the operation actually hits the cache. As we've already seen, branch prediction sometimes goes horribly wrong -- in the worst case scenario you need to go back and actually wait for a memory load, which will take forever ().Fortunately for us, if the memory access pattern is predictable, the processor will load it in its fast cache and all is well.First thing we need to know is what is ? While smaller is generally better, a rule of thumb is to stick to lookup tables that are <=4096 bytes in size. As an upper limit: if your lookup table is larger than 64K it's probably worth reconsidering.So we've figured out that we can create a small table. Next thing to do is get a lookup function in place. Lookup functions are usually small functions that use a couple of basic integer operations (and, or, xor, shift, add, remove and perhaps a multiply). What you want is to have your input translated by the lookup function to some kind of 'unique key' in your table, which then simply gives you the answer of all the work you wanted it to do.In this case: >=128 means we can keep the value, <128 means we get rid of it. The easiest way to do that is by using an 'AND': if we keep it, we AND it with 7FFFFFFF ; if we want to get rid of it, we AND it with 0. Notice also that 128 is a power of 2 -- so we can go ahead and make a table of 32768/128 integers and fill it with one zero and a lot of 7FFFFFFFF's.You might wonder why this works well in managed languages. After all, managed languages check the boundaries of the arrays with a branch to ensure you don't mess up...Well, not exactly... :-)There has been quite some work on eliminating this branch for managed languages. For example:in this case it's obvious to the compiler that the boundary condition will never hit. At least the Microsoft JIT compiler (but I expect Java does similar things) will notice this and remove the check all together. WOW - that means no branch. Similarly, it will deal with other obvious cases.If you run into trouble with lookups on managed languages - the key is to add a  to your lookup function to make the boundary check predictable - and watch it going faster.As data is distributed between 0 and 255 when array is sorted, around first half of the iterations will not enter the if-statement (if statement shared below).Question is what make the above statement not execute in certain case as in case of sorted data? Here comes the \"Branch predictor\" a branch predictor is a digital circuit that tries to guess which way a branch (e.g. an if-then-else structure) will go before this is known for sure. The purpose of the branch predictor is to improve the flow in the instruction pipeline. Branch predictors play a critical role in achieving high effective performance!The performance of an if-statement depends on whether its condition has a predictable pattern. If the condition is always true or always false, the branch prediction logic in the processor will pick up the pattern. On the other hand, if the pattern is unpredictable, the if-statement will be much more expensive.Let\u2019s measure the performance of this loop with different conditions:Here are the timings of the loop with different True-False patterns:A \u201c\u201d true-false pattern can make an if-statement up to six times slower than a \u201c\u201d pattern! Of course, which pattern is good and which is bad depends on the exact instructions generated by the compiler and on the specific processor.So there is no doubt about impact of branch prediction on performance!One way to avoid branch prediction errors is to build a lookup table, and index it using the data.  Stefan de Bruijn discussed that in his answer.But in this case, we know values are in the range [0, 255] and we only care about values >= 128.  That means we can easily extract a single bit that will tell us whether we want a value or not: by shifting the data to the right 7 bits, we are left with a 0 bit or a 1 bit, and we only want to add the value when we have a 1 bit.  Let's call this bit the \"decision bit\".By using the 0/1 value of the decision bit as an index into an array, we can make code that will be equally fast whether the data is sorted or not sorted.  Our code will always add a value, but when the decision bit is 0, we will add the value somewhere we don't care about.  Here's the code:This code wastes half of the adds, but never has a branch prediction failure.  It's tremendously faster on random data than the version with an actual if statement.But in my testing, an explicit lookup table was slightly faster than this, probably because indexing into a lookup table was slightly faster than bit shifting.  This shows how my code sets up and uses the lookup table (unimaginatively called  for \"LookUp Table\" in the code).  Here's the C++ code:In this case the lookup table was only 256 bytes, so it fit nicely in cache and all was fast.  This technique wouldn't work well if the data was 24-bit values and we only wanted half of them... the lookup table would be far too big to be practical.  On the other hand, we can combine the two techniques shown above: first shift the bits over, then index a lookup table.  For a 24-bit value that we only want the top half value, we could potentially shift the data right by 12 bits, and be left with a 12-bit value for a table index.  A 12-bit table index implies a table of 4096 values, which might be practical.EDIT: One thing I forgot to put in.The technique of indexing into an array, instead of using an  statement, can be used for deciding which pointer to use.  I saw a library that implemented binary trees, and instead of having two named pointers ( and  or whatever) had a length-2 array of pointers, and used the \"decision bit\" technique to decide which one to follow.  For example, instead of:this library would do something like:Here's a link to this code: , In the sorted case, you can do better than relying on successful branch prediction or any branchless comparison trick: completely remove the branch.Indeed, the array is partitioned in a contiguous zone with  and another with . So you should find the partition point with a dichotomic search (using  comparisons), then do a straight accumulation from that point.Something like (unchecked)or, slightly more obfuscatedA yet faster approach, that gives an  solution for both sorted or unsorted is:  (assuming a truly uniform distribution, 16384 samples with expected value 191.5) The above behavior is happening because of Branch prediction.To understand branch prediction one must first understand :Any instruction is broken into sequence of steps so that different steps can be executed concurrently in parallel. This technique is known as instruction pipeline and this is used to increase throughput in modern processors. To understand this better please see this .Generally modern processors have quite long pipelines, but for ease let's consider these 4 steps only.\nMoving back to the above question let's consider the following instructions:Without branch prediction the following would occur:To execute instruction B or instruction C the processor will have to wait till the instruction A doesn't reach till EX stage in the pipeline, as the decision to go to instruction B or instruction C depends on the result of instruction A. So the pipeline will look like this.\n\nAs a result of waiting for the result of instruction A, the total CPU cycles spent in the above case (without branch prediction; for both true and false) is 7.Branch predictor will tries to guess which way a branch (an if-then-else structure) will go before this is known for sure. It will not wait for the instruction A to reach the EX stage of the pipeline, but it will guess the decision and go onto that instruction (B or C in case of our example).\nIf it is later detected that the guess was wrong then the partially executed instructions are discarded and the pipeline starts over with the correct branch, incurring a delay. \nThe time that is wasted in case of a branch misprediction is equal to the number of stages in the pipeline from the fetch stage to the execute stage. Modern microprocessors tend to have quite long pipelines so that the misprediction delay is between 10 and 20 clock cycles. The longer the pipeline the greater the need for a good .In the OP's code, the first time when the conditional, the branch predictor does not have any information to base up prediction, so first time it will randomly choose the next instruction. Later in the for loop it can base the prediction on the history. \nFor an array sorted in ascending order, there are three possibilities:Let us assume that the predictor will always assume the true branch on the first run.So in the first case it will always take the true branch since historically all its predictions are correct.\nIn the 2nd case, initially it will predict wrong, but after a few iterations it will predict correctly.\nIn the 3rd case it will initially predict correctly till the elements are less than 128. After which it will fail for some time and the correct itself when it see branch prediction failure in history. In all these cases the failure will be too less in number and as a result only few times it will need to discard the partially executed instructions and start over with the correct branch, resulting in less CPU cycles. But in case of random unsorted array, the prediction will need to discard the partially executed instructions and start over with the correct branch most of the time and result in more CPU cycles compared to the sorted array.An official answer would be fromYou can also see from this lovely  why the branch predictor gets confused.Each element in the original code is a random valueso the predictor will change sides as the  blow.On the other hand, once it's sorted, the predictor will first move into a state of strongly not taken and when the values change to the high value the predictor will in three runs through change all the way from strongly not taken to strongly taken.In the same line (I think this was not highlighted by any answer) it's good to mention that sometimes (specially in software where the performance matters\u2014like in the Linux kernel) you can find some if statements like the following:or similarly:Both  and  are in fact macros that are defined by using something like the GCC's  to help the compiler insert prediction code to favour the condition taking into account the information provided by the user. GCC supports other builtins that could change the behavior of the running program or emit low level instructions like clearing the cache, etc. See  that goes through the available GCC's builtins.Normally this kind of optimizations are mainly found in hard-real time applications or embedded systems where execution time matters and it's critical. For example, if you are checking for some error condition that only happens 1/10000000 times, then why not inform the compiler about this? This way, by default, the branch prediction would assume that the condition is false.Frequently used Boolean operations in C++ produce many branches in compiled program. If these branches are inside loops and are hard to predict they can slow down execution significantly. Boolean variables are stored as 8-bit integers with the value  for  and  for .Boolean variables are overdetermined in the sense that all operators that have Boolean variables as input check if the inputs have any other value than  or , but operators that have Booleans as output can produce no other value than  or . This makes operations with Boolean variables as input less efficient than necessary.\nConsider example:This is typically implemented by the compiler in the following way:This code is far from optimal. The branches may take a long time in case of mispredictions. The Boolean operations can be made much more efficient if it is known with certainty that the operands have no other values than  and . The reason why the compiler does not make such an assumption is that the variables might have other values if they are uninitialized or come from unknown sources. The above code can be optimized if  and  have been initialized to valid values or if they come from operators that produce Boolean output. The optimized code looks like this: is used instead of  in order to make it possible to use the bitwise operators ( and ) instead of the Boolean operators ( and ). The bitwise operators are single instructions that take only one clock cycle. The OR operator () works even if  and  have other values than  or . The AND operator () and the EXCLUSIVE OR operator () may give inconsistent results if the operands have other values than  and . can not be used for NOT. Instead, you can make a Boolean NOT on a variable which is known to be  or  by XOR'ing it with :can be optimized to: cannot be replaced with  if  is an expression that should not be evaluated if  is  (  will not evaluate ,  will). Likewise,  can not be replaced with  if  is an expression that should not be evaluated if  is .Using bitwise operators is more advantageous if the operands are variables than if the operands are comparisons:is optimal in most cases (unless you expect the  expression to generate many branch mispredictions).This question has already been answered excellently many times over. Still I'd like to draw the group's attention to yet another interesting analysis.Recently this example (modified very slightly) was also used as a way to demonstrate how a piece of code can be profiled within the program itself on Windows. Along the way, the author also shows how to use the results to determine where the code is spending most of its time in both the sorted & unsorted case. Finally the piece also shows how to use a little known feature of the HAL (Hardware Abstraction Layer) to determine just how much branch misprediction is happening in the unsorted case.The link is here:\ntry n do it anything\nIf you are curious about even more optimisations that can be done to this code, consider this... Starting with the original loop:With loop interchange, we can safely change this loop to:Then, you can see that the \"if\" conditional is constant throughout the execution of the \"i\" loop, so you can hoist the \"if\" out:Then, you see that the inner loop can be collapsed into one single expression, assuming the floating point model allows it (/fp:fast is thrown, for example)That one is 100,000x faster than before 
Java

I'm trying to install the Android SDK on my Windows 7 x64 System.  is installed, but the Android SDK setup refuses to proceed, because it doesn't find the JDK installation.Is this a known issue? And is there a solution?Press  when you get the notification and then . This time it will find the JDK. Actual SETUP:Install the x64 JDK, and try the back-next option first, and then try setting  like the error message says, but if that doesn't work for you either, then try this:Do as it says, set  in your environment variables, but in the path use forward slashes instead of backslashes.Seriously.For me it failed when  was  but worked fine when it was  - drove me nuts!If this is not enough, also add to the beginning of the Environment Variable   Updated values in System Environment Variables:I found the solution and it's beautifully stupid. I found .Press the  button on the SDK error screen that tells you that the EXE couldn't detect the JDK. Then press .Who would have thought that would happen?It seems like it doesn't work without 32 bit JDK.\nJust install it and be happy...I downloaded the .zip archive instead and ran , and it worked like a charm. You had the same issue with the .exe otherwise.Warning: As a commenter mentioned, don't try this on a Windows\u00a07! I tested it with Windows\u00a0XP 64 bit.As the posted solution does NOT work for all (including me, myself, and I), I want to leave a note for those seeking for another way (without registry hacking, etc.) to solve this on a Windows 64 bit system. Just add PATH (capital letters!!) to your environment Variables and set the value to your JDK-Path.I added JDK to the existing \"Path\" which did not work, like it didn't with JAVA_HOME or the \"Back\"-Solution. Adding it to \"PATH\" finally did the trick.I hope this might be helpful for somebody.All you need are the following two registry entries. It appears as if whoever posted the other registry stuff basically just copied all the keys from  into ,\nwhich obviously isn't an ideal solution because most of the keys aren't needed.Non of these solutions worked for me. I fixed it by temporarily changing the filename of  to None of the solutions here worked for the 64-bit version.Putting the JDK path before the c:\\windows\\system32\\ path in your environment variables solves the problem. Otherwise the 32-bit java.exe is found before the 64-bit JDK version.After reading a couple of blog posts, it does seem to be even an easier fix by clicking  when the installer says couldn't find the JDK, and then simply click  again and magically it finds the JDK. No registry messing around or re-downloading etc..Adding JAVA_HOME environment variable (under ) did the trick for me. \nClicking \"Back\" and \"Next\" buttons didn't work.Windows 7 Professional x64, JDK 1.7.0_04 (64 bit, I don't have x86 version installed)I think that installer tries to find JDK in specific (1.6?) version and if it can't find it, checks JAVA_HOME which was not set in my case. I have another computer (the same system but with JDK 1.6 x64) and it worked without JAVA_HOME variable.I copied the Java.exe from to and it worked.I'm using 64 bit Windows 8.Setting the  environment variable to instead of fixed it for me.This registry fix worked  like a charm on my Windows 7 x64 setup:  Press  and .  will be enabled.The guy above who put this: \"I experienced this problem too, but none of the answers helped. What I did,  This was in fact the correct answer.For this SDK to install this is what I did. I am running the latest Microsoft OS Windows 8.This is what I did and it worked for me. =)Try downloading and installing the zipped version rather than the .exe installer.Also, ! Worked for me with backslash fix.I had the same problem and solved it by installing the x86 version of the JDK (on Windows\u00a0XP x64).I had the same problem, tried all the solutions but nothing worked. The problem is with Windows 7 installed is 64 bit and all the software that you are installing should be 32 bit. Android SDK itself is 32 bit and it identifies only 32 bit JDK. So install following software.I tried it and all works fine.I experienced this problem too, but none of the answers helped. What I did, I removed the last backslash from the JAVA_HOME variable and it started working. Also, remember not to include the bin folder in the path.Android SDK is 32 bit app, and it requires the 32 bit of JDK to work... the 64 bit JDK won't make any use for it...1-Simply done the \"JAVA_HOME\" environment variable thing.2-Right-Click on Android SDK and from compatibletiy Tab Select windows 7 and administrator.3-Run it again.Simply put your java bin path in front of your PATH environment.PATH beforePATH afterAnd now the Android SDK installer is working.BTW, I'm running Win7 x64.Yeah install the 32 bit version of the Java SE SDK (or any of the combinations). That should help solve your problem.For installer_r21.1-windows.exe on Windows 8 x 64 what worked for me was setting up my user environment variable JAVA_HOME to C:\\Program Files\\Java\\jdk1.7.0_10.\nHope this helps you all! :)You will have to download the 32-bit SDK version because Win7 64-bit is not supported only Windows Server 2003 has a supported 64-bit version.  During the download of Java SDK pick \"Windows\" as your platform and not \"Windowsx64\".\nOnce I did this android SDK installed like a charm.  Hope this helps.I'm running a 64-bit version of Windows 7 and I was getting this issue when attempting to install Android Studio 1.0 using the executable from:I tried all the listed solutions and several different versions of JDK 1.7 and 1.8 -- no dice. I went with installing the zipped version of the application and it worked like a charm:Still baffled by this problem; especially since beta versions of Android Studio worked just fine.The above methods did not work for me in Windows 8 Pro.Just set the path to Where C is your drive in which you have installed the JDK.Don't forget the backward slash at the end.I tried several posted solutions and then it took a system reboot before it started working, which may have been because I had just installed the JDK.  Here are all the things I had going on - not sure which ones were essential:
Java

I came across some Java code that had the following structure:I know that in C++ I can assign a parameter a default value.  For example:Does Java support this kind of syntax?  Are there any reasons why this two step syntax is preferable?No, the structure you found is how Java handles it (that is, with overloading instead of default parameters).For constructors,  Item 1 tip (Consider static factory methods instead of constructors) if the overloading is getting complicated. For other methods, renaming some cases or using a parameter object can help. This is when you have enough complexity that differentiating is difficult. A definite case is where you have to differentiate using the order of parameters, not just number and type.No, but you can use the , as described in .As described in the linked answer, the Builder Pattern lets you write code likein which some fields can have default values or otherwise be optional.There are several ways to simulate default parameters in Java:Please note that you can combine any of these approaches to achieve a desirable result.Sadly, no.Unfortunately, yes.could be written in Java 1.5 as:But whether or not you should depend on how you feel about the compiler generating afor each call.For multiple defaultable parameters:could be written in Java 1.5 as:This matches C++ syntax, which only allows defaulted parameters at the end of the parameter list.  Beyond syntax, there is a difference where this has run time type checking for passed defaultable parameters and C++ type checks them during compile.No, but you can very simply emulate them. What in C++ was:In Java, it will be an overloaded function:Earlier was mentioned, that default parameters caused ambiguous cases in function overloading. That is simply not true, we can see in the case of the C++: yes, maybe it can create ambiguous cases, but these problem can be easily handled. It simply wasn't developed in Java, probably because the creators wanted a much simpler language as C++ was - if they had right, is another question. But most of us don't think he uses Java because of its simplicity.You can do this is in Scala, which runs on the JVM and is compatible with Java programs.\ni.e.I might be stating the obvious here but why not simply implement the \"default\" parameter yourself?for the default you would ether usefunc(\"my string\");and if you wouldn't like to use the default, you would usefunc(\"my string\", false);No. In general Java doesn't have much (any) syntactic sugar, since they tried to make a simple language.It is not supported but there are several options like using parameter object pattern with some syntax sugar:In this sample we construct  with default values and override them in class instance initialization section No. You can achieve the same behavior by passing an Object which has smart defaults. But again it depends what your case is at hand.Try this solution:There are half a dozen or better issues such as this, eventually you arrive at the static factory pattern ... see the crypto api for that. Sort difficult to explain, but think of it this way: If you have a constructor, default or otherwise, the only way to propagate state beyond the curly braces is either to have a Boolean isValid; ( along with the null as default value v failed constructor ) or throw an exception which is never informative when getting it back from field users.Code Correct be damned, I write thousand line constructors and do what I need. I find using isValid at object construction - in other words, two line constructors - but for some reason I am migrating to the static factory pattern. I just seems you can do a lot if you in a method call, there are still sync() issues but defaults can be 'substituted' better ( safer )I think what we need to do here is address the issue of null as default value vis-a-vis something String one=new String(\"\"); as a member variable, then doing a check for null before assigning string passed to the constructor. Very remarkable the amount of raw, stratospheric computer science done in Java.C++ and so on has vendor libs, yes. Java can outrun them on large scale servers due to it's massive toolbox. Study static initializer blocks, stay with us.A similar approach to  that works in Java 8 is to use an interface with default getters. This will be more whitespace verbose, but is mockable, and it's great for when you have a bunch of instances where you actually want to draw attention to the parameters.This is how I did it ... it's not as convenient perhaps as having an 'optional argument' against your defined parameter, but it gets the job done:Notice I can invoke the same method name with either just a string or I can invoke it with a string and a boolean value. In this case, setting wipeClean to true will replace all of the text in my TextArea with the provided string. Setting wipeClean to false or leaving it out all together simply appends the provided text to the TextArea.Also notice I am not repeating code in the two methods, I am merely adding the functionality of being able to reset the TextArea by creating a new method with the same name only with the added boolean.I actually think this is a little cleaner than if Java provided an 'optional argument' for our parameters since we would need to then code for default values etc. In this example, I don't need to worry about any of that. Yes, I have added yet another method to my class, but it's easier to read in the long run in my humble opinion.You may use  to automatically generate the builder with default values.Just add @GenerateMethodInvocationBuilder to the class, or interface, and the @Default to parameters in methods where you want default values. A builder will be generated at compile time, using the default values that you specified with your annotations.And then you can invoke the methods.Or set any of the default values to something else.NO, But we have alternative in the form of function overloading.called when no parameter passedcalled when \"a\" parameter was passedcalled when parameter b passed
Java

I understood, I think, that a \"Bean\" is a Java class with properties and getters/setters. As much as I understand, it is the equivalent of a C struct. Is that true?Also, is there a real  difference between a bean and a regular class? Is there any special definition or an interface?Basically, why is there a term for this?: If you can be so kind and add information regarding the  interface, and what it means, to your answer, I'd be very grateful.A JavaBean is just a That's it. It's just a convention.  Lots of libraries depend on it though....With respect to , from the :In other words, serializable objects can be written to streams, and hence files, object databases, anything really.  Also, there is no syntactic difference between a JavaBean and another class -- a class defines a JavaBean if it follows the standards.There is a term for it because the standard allows libraries to programmatically do things with class instances you define in a predefined way. For example, if a library wants to stream any object you pass into it, it knows it can because your object is serializable (assuming the lib requires your objects be proper JavaBeans). There's a term for it to make it sound special.  The reality is nowhere near so mysterious.Basically, a \"Bean\":Update:As for :  That is nothing but a \"marker interface\" (an interface that doesn't declare any functions) that tells Java that the implementing class consents to (and implies that it is capable of) \"serialization\" -- a process that converts an instance into a stream of bytes.  Those bytes can be stored in files, sent over a network connection, etc, and have enough info to allow a JVM (at least, one that knows about the object's type) to reconstruct the object later -- possibly in a different instance of the application, or even on a whole other machine!Of course, in order to do that, the class has to abide by certain limitations.  Chief among them is that all instance fields must be either primitive types (int, bool, etc), instances of some class that is also serializable, or marked as  so that Java won't try to include them.  (This of course means that  fields will not survive the trip over a stream.  A class that has  fields should be prepared to reinitialize them if necessary.)A class that can not abide by those limitations should not implement  (and, IIRC, the Java compiler won't even  it do so.)JavaBeans are Java classes which adhere to an extremely simple coding convention.\nAll you have to do is to Properties of JavaBeansA JavaBean is a Java object that satisfies certain programming conventions: Example of JavaBeansJava Beans are using for less code and more work approach... \nJava Beans are used throughout Java EE as a universal contract for runtime discovery and access. For example, JavaServer Pages (JSP) uses Java Beans as data transfer objects between pages or between servlets and JSPs. Java EE's JavaBeans Activation Framework uses Java Beans for integrating support for MIME data types into Java EE. The Java EE Management API uses JavaBeans as the foundation for the instrumentation of resources to be managed in a Java EE environment. About Serialization:In object serialization an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.You will find Serialization useful when deploying your project across multiple servers since beans will be persisted and transferred across them.As per the Wikipedia:For more information follow this Explanation with an example.As for the Serialization, see the .Fields should be private for prevent outer classes to easily modify those fields.\nInstead of directly accesing to those fields, usuagly getter/setter methods are used.A public constructor without any argument.Getter and setter methods for accesing private fields.Regarding the second part of your question, Serialization is a persistence mechanism used to store objects as a sequence of signed bytes. Put less formally, it stores the state of an object so you can retrieve it later, by de-serialization.They are serializable, have a zero-argument constructor, and allow access to properties using getter and setter methods. The name \"Bean\" was given to encompass this standard, which aims to create reusable software components for Java. The objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. Otherwise, a bean is simply one of many objects in your application. \n .Java Beans is a standard, and its basic syntax requirements have been clearly explained by the other answers.However, IMO, it is more than a simple syntax standard. The real meaning or intended usage of Java Beans is, together with various tool supports around the standard,  to facilitate code reuse and component-based software engineering, i.e. enable developers to build applications by assembling existing components (classes) and without having to write any code (or only have to write a little glue code). Unfortunately this technology is way under-estimated and under-utilized by the industry, which can be told from the answers in this thread.If you read Oracle's , you can get a better understanding in that.To understand JavaBean you need to notice the followings:\nJavaBean is a conceptual stuff and can not represent a class of specific thingsJavaBean is a development tool can be visualized in the operation of reusable software componentsJavaBean is based on the Sun JavaBeans specification and can be  reusable components. Its biggest feature is the re-usability.A Java Bean is a java class [conceptual] that should follow following conventions:It is a reusable software component. It can encapsulate many object into one object so that same object can be accessed from multiples places and is a step towards easy maintenance of code. are just ordinary Java classes that follow certain conventions - you don't need special tools to create them.There are two primary conventions that must be followed in creating Java Bean classes:
Java

What's the advantage of using getters and setters - that only get and set - instead of simply using public fields for those variables?If getters and setters are ever doing more than just the simple get/set, I can figure this one out very quickly, but I'm not 100% clear on how:is any worse than:Whereas the former takes a lot less boilerplate code.\n rather than directly exposing fields of a class - beyond just the argument of encapsulation and making future changes easier. Because 2 weeks (months, years) from now when you realize that your setter needs to do  than just set the value, you'll also realize that the property has been used directly in 238 other classes :-)A public field is not worse than a getter/setter pair that does nothing except returning the field and assigning to it. First, it's clear that (in most languages) there is no functional difference. Any difference must be in other factors, like maintainability or readability.An oft-mentioned advantage of getter/setter pairs, isn't. There's this claim that you can change the implementation and your clients don't have to be recompiled. Supposedly, setters let you add functionality like validation later on and your clients don't even need to know about it. However, adding validation to a setter is a change to its preconditions, , which was, quite simply, \"you can put anything in here, and you can get that same thing later from the getter\".So, now that you broke the contract, changing every file in the codebase is something you should want to do, not avoid. If you avoid it you're making the assumption that all the code assumed the contract for those methods was different.If that should not have been the contract, then the interface was allowing clients to put the object in invalid states.  If that field could not really be set to anything from the start, why wasn't the validation there from the start?This same argument applies to other supposed advantages of these pass-through getter/setter pairs: if you later decide to change the value being set, you're breaking the contract. If you override the default functionality in a derived class, in a way beyond a few harmless modifications (like logging or other non-observable behaviour), you're breaking the contract of the base class. That is a violation of the Liskov Substitutability Principle, which is seen as one of the tenets of OO.If a class has these dumb getters and setters for every field, then it is a class that has no invariants whatsoever, . Is that really object-oriented design? If all the class has is those getters and setters, it's just a dumb data holder, and dumb data holders should look like dumb data holders:Adding pass-through getter/setter pairs to such a class adds no value. Other classes should provide meaningful operations, not just operations that fields already provide. That's how you can define and maintain useful invariants.There are reasons to use getters and setters, but if those reasons don't exist, making getter/setter pairs in the name of false encapsulation gods is not a good thing. Valid reasons to make getters or setters include the things often mentioned as the potential changes you can make later, like validation or different internal representations. Or maybe the value should be readable by clients but not writable (for example, reading the size of a dictionary), so a simple getter is a nice choice. But those reasons should be there when you make the choice, and not just as a potential thing you may want later. This is an instance of YAGNI ().Lots of people talk about the advantages of getters and setters but I want to play devil's advocate. Right now I'm debugging a very large program where the programmers decided to make everything getters and setters. That might seem nice, but its a reverse-engineering nightmare.Say you're looking through hundreds of lines of code and you come across this:It's a beautifully simply piece of code until you realize its a setter. Now, you follow that setter and find that it also sets person.firstName, person.lastName, person.isHuman, person.hasReallyCommonFirstName, and calls person.update(), which sends a query out to the database, etc. Oh, that's where your memory leak was occurring.Understanding a local piece of code at first glance is an important property of good readability that getters and setters tend to break. That is why I try to avoid them when I can, and minimize what they do when I use them.There are many reasons. My favorite one is when you need to change the behavior or regulate what you can set on a variable. For instance, lets say you had a setSpeed(int speed) method. But you want that you can only set a maximum speed of 100. You would do something like:Now what if EVERYWHERE in your code you were using the public field and then you realized you need the above requirement? Have fun hunting down every usage of the public field instead of just modifying your setter.My 2 cents :)One advantage of accessors and mutators is that you can perform validation.For example, if  was public, I could easily set it to  and then someone else could try to call a method on the object. But it's not there anymore! With a  method, I could ensure that  was never set to .Accessors and mutators also allow for encapsulation - if you aren't supposed to see the value once its set (perhaps it's set in the constructor and then used by methods, but never supposed to be changed), it will never been seen by anyone. But if you can allow other classes to see or change it, you can provide the proper accessor and/or mutator.In a pure object-oriented world getters and setters is a . Read this article: . In a nutshell, they encourage programmers to think about objects as of data structures, and this type of thinking is pure procedural (like in COBOL or C). In an object-oriented language there are no data structures, but only objects that expose behavior (not attributes/properties!)You may find more about them in Section 3.5 of  (my book about object-oriented programming).Depends on your language.  You've tagged this \"object-oriented\" rather than \"Java\", so I'd like to point out that ChssPly76's answer is language-dependent.  In Python, for instance, there is no reason to use getters and setters.  If you need to change the behavior, you can use a property, which wraps a getter and setter around basic attribute access.  Something like this:Well i just want to add that even if sometimes they are necessary for the encapsulation and security of your variables/objects, if we want to code a real Object Oriented Program, then we need to , cause sometimes we depend a lot on them when is not really necessary and that makes almost the same as if we put the variables public.Thanks, that really clarified my thinking. Now here is (almost) 10 (almost) good reasons NOT to use getters and setters:The last three I'm just leaving (N/A or D/C)...Getter and setter methods are public interfaces to access private class members.The encapsulation mantra is to make fields private and methods public.Even though the getter and setter methods do not add new functionality, we can change our mind come back later to make that methodAnywhere a value can be used, a method that returns that value can be added. Instead of:useSuppose we need to store the details of this . This  has the fields ,  and . Doing this involves creating methods for ,  and . Now if we need create another person, it becomes necessary to create the methods for , ,  all over again.Instead of doing this, we can create a bean  with getter and setter methods.  So tomorrow we can just create objects of this Bean  whenever we need to add a new person (see the figure). Thus we are reusing the fields and methods of bean class, which is much better.I know it's a bit late, but I think there are some people who are interested in performace :)I've done a little performance test. I wrote a class \"NumberHolder\" which, well, holds an Integer. You can either read that Integer by using the getter method\n or by directly accessing the number by using . My programm reads the number 1,000,000,000 times, via both ways. That process is repeated five times and the time is printed. I've got the following result:(Time 1 is the direct way, Time 2 is the getter)You see, the getter is (almost) always a bit faster. Then I tried with different numbers of cycles. Instead of 1 million, I used 10 million and 0.1 million.\nThe results:10 million cycles: With 10 million cycles, the times are almost the same.\nHere are 100 thousand (0.1 million) cycles:Also with different amounts of cycles, the getter is a little bit faster than the regular way. I hope this helped you! :)By the way, I am a german seventh grade, using my own knowledge and Google Translator. So don't be so strict with my english ;)It can be useful for lazy-loading.  Say the object in question is stored in a database, and you don't want to go get it unless you need it.  If the object is retrieved by a getter, then the internal object can be null until somebody asks for it, then you can go get it on the first call to the getter.I had a base page class in a project that was handed to me that was loading some data from a couple different web service calls, but the data in those web service calls wasn't always used in all child pages.  Web services, for all of the benefits, pioneer new definitions of \"slow\", so you don't want to make a web service call if you don't have to.I moved from public fields to getters, and now the getters check the cache, and if it's not there call the web service.  So with a little wrapping, a lot of web service calls were prevented.So the getter saves me from trying to figure out, on each child page, what I will need.  If I need it, I call the getter, and it goes to find it for me if I don't already have it.I spent quite a while thinking this over for the Java case, and I believe the real reasons are:In other words, the only way you can specify a field in an interface is by providing a method for writing a new value and a method for reading the current value.  Those methods are the infamous getter and setter....Don't use getters setters unless needed for your current delivery I.e. Don't think too much about what would happen in the future, if any thing to be changed its a change request in most of the production applications, systems.Think simple, easy, add complexity when needed.I would not take advantage of ignorance of business owners of deep technical know how just because I think it's correct or I like the approach.I have massive system written without getters setters only with access modifiers and some methods to validate n perform biz logic. If you absolutely needed the. Use anything.One aspect I missed in the answers so far, the access specification:One of the basic principals of OO design: It gives you many benefits, one of which being that you can change the implementation of the getter/setter behind the scenes but any consumer of that value will continue to work as long as the data type remains the same.EDIT: I answered this question because there are a bunch of people learning programming asking this, and most of the answers are very technically competent, but they're not as easy to understand if you're a newbie. We were all newbies, so I thought I'd try my hand at a more newbie friendly answer.The two main ones are polymorphism, and validation. Even if it's just a stupid data structure.Let's say we have this simple class:A very simple class that holds how much liquid is in it, and what its capacity is (in milliliters).What happens when I do:Well, you wouldn't expect that to work, right?\nYou want there to be some kind of sanity check. And worse, what if I never specified the maximum capacity? Oh dear, we have a problem.But there's another problem too. What if bottles were just one type of container? What if we had several containers, all with capacities and amounts of liquid filled? If we could just make an interface, we could let the rest of our program accept that interface, and bottles, jerrycans and all sorts of stuff would just work interchangably. Wouldn't that be better? Since interfaces demand methods, this is also a good thing.We'd end up with something like:Great! And now we just change Bottle to this:I'll leave the definition ofthe BottleOverflowException as an exercise to the reader.Now notice how much more robust this is. We can deal with any type of container in our code now by accepting LiquidContainer instead of Bottle. And how these bottles deal with this sort of stuff can all differ. You can have bottles that writer their state to disk when it changes, or bottles that save on SQL databases or GNU knows what else.And all these can have different ways to handle various whoopsies. The Bottle just checks and if it's overflowing it throws a RuntimeException. But that might be the wrong thing to do. \n(There is a useful discussion to be had about error handling, but I'm keeping it very simple here on purpose. People in comments will likely point out the flaws of this simplistic approach. ;) )And yes, it seems like we go from a very simple idea to getting much better answers quickly.There's also the third thing that not everyone has addressed: Getters and setters use method calls. That means that they look like normal methods everywhere else does. Instead of having weird specific syntax for DTOs and stuff, you have the same thing everywhere.In languages which don't support \"properties\" (C++, Java) or require recompilation of clients when changing fields to properties (C#), using get/set methods is easier to modify. For example, adding validation logic to a setFoo method will not require changing the public interface of a class.In languages which support \"real\" properties (Python, Ruby, maybe Smalltalk?) there is no point to get/set methods.From a object orientation design standpoint both alternatives can be damaging to the maintenance of the code by weakening the encapsulation of the classes. For a discussion you can look into this excellent article:  Getter and setter methods are accessor methods, meaning that they are generally a public interface to change private class members. You use getter and setter methods to define a property. You access getter and setter methods as properties outside the class, even though you define them within the class as methods. Those properties outside the class can have a different name from the property name in the class.There are some advantages to using getter and setter methods, such as the ability to let you create members with sophisticated functionality that you can access like properties. They also let you create read-only and write-only properties.Even though getter and setter methods are useful, you should be careful not to overuse them because, among other issues, they can make code maintenance more difficult in certain situations. Also, they provide access to your class implementation, like public members. OOP practice discourages direct access to properties within a class.When you write classes, you are always encouraged to make as many as possible of your instance variables private and add getter and setter methods accordingly. This is because there are several times when you may not want to let users change certain variables within your classes. For example, if you have a private static method that tracks the number of instances created for a specific class, you don't want a user to modify that counter using code. Only the constructor statement should increment that variable whenever it's called. In this situation, you might create a private instance variable and allow a getter method only for the counter variable, which means users are able to retrieve the current value only by using the getter method, and they won't be able to set new values using the setter method. Creating a getter without a setter is a simple way of making certain variables in your class read-only.Code .   is great for when .  Eventually all classes should be sort of \"miniprograms\" that have a well-defined interface .That said,  isn't about setting down that final version of the class as if you're pressing some cast iron statue on the first try.  While you're working with it, code is more like clay.   as you develop it and learn more about the problem domain you are solving.  During development classes may interact with each other than they should (dependency you plan to factor out), merge together, or split apart.  So I think the debate boils down to people not wanting to religiously writeSo you have:Instead ofNot only is  visually noisy, it gives this illusion that  is somehow a more complex process than it really is.  How you (as the class writer) regard the sanctity of  is particularly confusing to a user of your class if it has a passthru setter -- then it looks like you're putting up these gates to \"protect\" something you insist is valuable, (the sanctity of ) but yet even you concede 's protection isn't worth much by the ability for anyone to just come in and   to whatever value they want, without you even peeking at what they are doing.So I program as follows (assuming an \"agile\" type approach -- ie when I write code not knowing  what it will be doing/don't have time or experience to plan an elaborate waterfall style interface set):1) Start with all public members for basic objects with data and behavior.  This is why in all my C++ \"example\" code you'll notice me using  instead of  everywhere.2) When an object's internal behavior for a data member becomes complex enough, (for example, it likes to keep an internal  in some kind of order), accessor type functions are written.  Because I'm programming by myself, I don't always set the member  right away, but somewhere down the evolution of the class the member will be \"promoted\" to either  or .3) Classes that are fully fleshed out and have strict rules about their internals (ie  know exactly what they are doing, and you are not to \"fuck\" (technical term) with its internals) are given the  designation, default private members, and only a select few members are allowed to be .I find this approach allows me to avoid sitting there and religiously writing getter/setters when a lot of data members get migrated out, shifted around, etc. during the early stages of a class's evolution.There is a good reason to consider using accessors is there is no property inheritance. See next example:Output:You should use getters and setters when:So this is very rarely a general OO question; it's a language-specific question, with different answers for different languages (and different use cases).From an OO theory point of view, getters and setters are useless. The interface of your class is what it does, not what its state is. (If not, you've written the wrong class.) In very simple cases, where what a class does is just, e.g., represent a point in rectangular coordinates,* the attributes are part of the interface; getters and setters just cloud that. But in anything but very simple cases, neither the attributes nor getters and setters are part of the interface.Put another way: If you believe that consumers of your class shouldn't even know that you have a  attribute, much less be able to change it willy-nilly, then giving them a  method is the last thing you want to do.But nobody is ever doing general OO design. They're doing design, and implementation, in a specific language. And in some languages, getters and setters are far from useless.If your language doesn't have properties, then the only way to represent something that's conceptually an attribute, but is actually computed, or validated, etc., is through getters and setters.Even if your language does have properties, there may be cases where they're insufficient or inappropriate. For example, if you want to allow subclasses to control the semantics of an attribute, in languages without dynamic access, a subclass can't substitute a computed property for an attribute.As for the \"what if I want to change my implementation later?\" question (which is repeated multiple times in different wording in both the OP's question and the accepted answer): If it really is a pure implementation change, and you started with an attribute, you can change it to a property without affecting the interface. Unless, of course, your language doesn't support that. So this is really just the same case again.Also, it's important to follow the idioms of the language (or framework) you're using. If you write beautiful Ruby-style code in C#, any experienced C# developer other than you is going to have trouble reading it, and that's bad. Some languages have stronger cultures around their conventions than others.\u2014and it may not be a coincidence that Java and Python, which are on opposite ends of the spectrum for how idiomatic getters are, happen to have two of the strongest cultures.Beyond human readers, there will be libraries and tools that expect you to follow the conventions, and make your life harder if you don't. Hooking Interface Builder widgets to anything but ObjC properties, or using certain Java mocking libraries without getters, is just making your life more difficult. If the tools are important to you, don't fight them.One other use (in languages that support properties) is that setters and getters can imply that an operation is non-trivial.  Typically, you want to avoid doing anything that's computationally expensive in a property. and  are used to implement two of the fundamental aspects of Object Oriented Programming which are: Suppose we have an Employee class:Here the implementation details of Full Name is hidden from the user and is not accessible directly to the user, unlike a public attribute.   Additionally, this is to \"future-proof\" your class. In particular, changing from a field to a property is an ABI break, so if you do later decide that you need more logic than just \"set/get the field\", then you need to break ABI, which of course creates problems for anything else already compiled against your class.In an object oriented language the methods, and their access modifiers, declare the interface for that object. Between the constructor and the accessor and mutator methods it is possible for the developer to control access to the internal state of an object. If the variables are simply declared public then there is no way to regulate that access.I would just like to throw the idea of annotation : @getter and @setter. With @getter, you should be able to obj = class.field but not class.field = obj. With @setter, vice versa. With @getter and @setter you should be able to do both. This would preserve encapsulation and reduce the time by not calling trivial methods at runtime.I can think of one reason why you wouldn't just want everything public.For instance, variable you never intended to use outside of the class could be accessed, even irdirectly via chain variable access (i.e.  object.item.origin.x ).  By having mostly everything private, and only the stuff you want to extend and possibly refer to in subclasses as protected, and generally only having static final objects as public, then you can control what other programmers and programs can use in the API and what it can access and what it can't by using setters and getters to access the stuff you want the program, or indeed possibly other programmers who just happen to use your code, can modify in your program.  
Java

What is the main difference between  and ?\nIs there any performance issues when deciding on any one of these? is synchronized,  is not.  is faster than  because it's not .Here's a simple benchmark test:A  gives the numbers of  for  vs  for .Basically, StringBuffer methods are synchronized while StringBuilder are not.The operations are \"almost\" the same, but using synchronized methods in a single thread is overkill.That's pretty much about it.Quote from :So it was made to substitute it.The same happened with Vector and ArrayList. came first.  Sun was concerned with correctness under all conditions, so they made it synchronized to make it thread-safe just in case. came later.  Most of the uses of  were single-thread and unnecessarily paying the cost of the synchronization.Since  is a  for  without the synchronization, there would not be differences between any examples.If you  trying to share between threads, you can use , but consider whether higher-level synchronization is necessary, e.g. perhaps instead of using StringBuffer, should you synchronize the methods that use the StringBuilder.First lets see the :\nBoth StringBuilder and StringBuffer are mutable. That means you can change the content of them, with in the same location.:\nStringBuffer is mutable and synchronized as well. Where as StringBuilder is mutable but not synchronized by default.:\nWhen some thing is synchronized, then multiple threads can access, and modify it with out any problem or side effect.\nStringBuffer is synchronized, so you can use it with multiple threads with out any problem.\nStringBuilder : When you need a string, which can be modifiable, and only one thread is accessing and modifying it.\nStringBuffer : When you need a string, which can be modifiable, and multiple threads are accessing and modifying it. : Don't use StringBuffer unnecessarily, i.e., don't use it if only one thread is modifying and accessing it because it has lot of locking and unlocking code for synchronization which will unnecessarily take up CPU time. Don't use locks unless it is required. In single threads, , thanks to JVM optimisations. And in multithreading, you can't use safely a StringBuilder.Here is my test : Results :\nstrings: 319740\nBuffers : \nBuilder : 7 !So Builders are faster than Buffers, and WAY faster than strings concatenation.\nNow let's use an  for multiple threads :Now StringBuffers take  for 100000 appends. It's not the same test, but compared to the previous 37 ms, you can safely assume that . The reason is that the JIT/hotspot/compiler/something makes optimizations when it detects that there is  need for checking locks.But , because a concurrent thread tries to add something where it should not. Conclusion is that you don't have to chase StringBuffers. And where you have threads, think about what they are doing, before trying to gain a few nanoseconds.StringBuilder was introduced in Java 1.5 so it won't work with earlier JVMs.From the :StringBuilder class provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations. Here are the differences, i have noticed :StringBuffer :-StringBuilder:-Common thing :- and  are almost the same. The difference is that  is synchronized and  is not. Although,  is faster than , the difference in performance is very little.  is a SUN's replacement of . It just avoids synchronization from all the public methods. Rather than that, their functionality is the same.Example of good usage:If your text is going to change and is used by multiple threads, then it is better to use . If your text is going to change but is used by a single thread, then use .StringBuilder is not thread safe. String Buffer is. More info .EDIT: As for performance , after  kicks in , StringBuilder is the winner. However , for small iterations , the performance difference is negligible.StringBuffer\n - Synchronized hence threadsafe\n - thread safe hence slow\n - StringBuilder\n - Introduced in java 5.0\n - Asynchronous hence fast & efficient\n - User explicitly need to synchronized it, if he wants\n - You can replace it will StringBuilder without a any other change The  explains the difference:StringBuffer is mutable means one can change the value of the object . The object created through StringBuffer is stored in the heap .  StringBuffer  has the same methods as the StringBuilder , but each method in StringBuffer is synchronized that is StringBuffer is thread safe .because of this it does not allow  two threads to simultaneously access the same method . Each method can be accessed by one thread at a time .But being thread safe has disadvantages too as the performance of the StringBuffer hits due to thread safe property . Thus  StringBuilder is faster than the StringBuffer when calling the same methods of each class.StringBuffer value can be changed , it means it can be assigned to the new value . Nowadays its a most common interview question ,the differences between the above classes .\nString Buffer can be converted to the string by using\ntoString() method.StringBuilder  is same as the StringBuffer , that is it stores the object in heap and it can also be modified . The main difference between the StringBuffer and StringBuilder is that StringBuilder is also not thread safe. \nStringBuilder is fast as it is not thread safe .Resource:  (introduced in Java 5) is identical to , except its methods are not synchronized.  This means it has better performance than the latter, but the drawback is that it is not thread-safe.Read  for more details. is an immutable. is a mutable and synchronized.  is also mutable but its not synchronized.A simple program illustrating the difference between StringBuffer and StringBuilder:StringBuilder is  much faster than StringBuffer because It's non synchronized.Let take programmatically look how much StringBuilder faster than StringBuffer is synchronized, but  is not. As a result,  is faster than .\nis mutable. It can change in terms of length and content. StringBuffers are thread-safe, meaning that they have synchronized methods to control access so that only one thread can access a StringBuffer object's synchronized code at a time. Thus, StringBuffer objects are generally safe to use in a multi-threaded environment where multiple threads may be trying to access the same StringBuffer object at the same time.\nThe StringBuilder class is very similar to StringBuffer, except that its access is not synchronized so that it is not thread-safe. By not being synchronized, the performance of StringBuilder can be better than StringBuffer. Thus, if you are working in a single-threaded environment, using StringBuilder instead of StringBuffer may result in increased performance. This is also true of other situations such as a StringBuilder local variable (ie, a variable within a method) where only one thread will be accessing a StringBuilder object.StringBuffer is mutable means one can change the value of the object . The object created through StringBuffer is stored in the heap . StringBuffer  has the same methods as the StringBuilder , but each method in StringBuffer is synchronized that is StringBuffer is thread safe . StringBuilder  is same as the StringBuffer , that is it stores the object in heap and it can also be modified . The main difference between the StringBuffer and StringBuilder is that StringBuilder is not thread safe. \nStringBuilder is fast as it is not thread safe .  StringBuffer is used to store character strings that will be changed (String objects cannot be changed). It automatically expands as needed. Related classes: String, CharSequence.StringBuilder was added in Java 5. It is identical in all respects to StringBuffer except that it is not synchronized, which means that if multiple threads are accessing it at the same time, there could be trouble. For single-threaded programs, the most common case, avoiding the overhead of synchronization makes the StringBuilder very slightly faster.Better use StringBuilder since it is not synchronized and therefor better performance. StringBuilder is a drop-in replacement of the older StringBuffer.This link will make you understand the concepts of not only  and  but also their association and difference with  class. This will make you understand when to use which class.\nThere are no basic differences between StringBuilder and StringBuffer, only a few differences exist between them. In StringBuffer the methods are synchronized. This means that at a time only one thread can operate on them. If there are more than one thread then the second thread will have to wait for the first one to finish and the third one will have to wait for the first and second one to finish and so on. This makes the process very slow and hence the performance in case of StringBuffer is low.On the other hand StringBuilder is non synchronized. This means that at a time multiple threads can operate on the same StrinBuilder object at the same time. This makes the process very fast and hence performance of StringBuilder is high.Check the internals of synchronized append method of  and non-synchronized append method of .::Since append is ,  has performance overhead compared to  in multi-threading scenario. As long as you are not sharing buffer among multiple threads, use , which is fast due to absence of  in append methods.Since  is synchronized, it needs some extra effort, hence based on perforamance, its a bit slow than . :It is recommended to use StringBuilder whenever possible because it is faster than StringBuffer. However, if the thread safety is necessary, the best option is StringBuffer objects.String is an immutable object which means the value cannot be changed where as StringBuffer is mutable.The StringBuffer is Synchronized hence thread safe where as StringBuilder is not and suitable for only single threaded instances.Every method present in StringBuffer is Synchronized.\nhence at a time only one thread is allowed to operate StringBuffer object.\nIt Increases waiting time of a Thread and Creates Performance problems\nto overcome this problem SUN People intoduced StringBuilder in 1.5 version.
Java

Recently I ran into this error in my web application:It's a typical Hibernate/JPA + IceFaces/JSF application running on Tomcat 6 and JDK 1.6.\nApparently this can occur after redeploying an application a few times.What causes it and what can be done to avoid it?\nHow do I fix the problem?The solution was to add these flags to JVM command line when Tomcat is started:You can do that by shutting down the tomcat service, then going into the Tomcat/bin directory and running tomcat6w.exe. Under the \"Java\" tab, add the arguments to the \"Java Options\" box. Click \"OK\" and then restart the service.If you get an error  you should run:where  is the name of the server as viewed in services.mscSource: orx's comment on .You better try  rather than . I can not tell the precise use of this memory pool, but it have to do with the number of classes loaded into the JVM. (Thus enabling class unloading for tomcat can resolve the problem.) If your applications generates and compiles classes on the run it is more likely to need a memory pool bigger than the default. App server PermGen errors that happen after multiple deployments are most likely caused by references held by the container into your old apps' classloaders. For example, using a custom log level class will cause references to be held by the app server's classloader. You can detect these inter-classloader leaks by using modern (JDK6+) JVM analysis tools such as jmap and jhat to look at which classes continue to be held in your app, and redesigning or eliminating their use. Usual suspects are databases, loggers, and other base-framework-level libraries.See , and especially its .Common mistakes people make is thinking that heap space and permgen space are same, which is not at all true.  You could have lot of space remaining in the heap but still can run out of memory in permgen. Common causes of OutofMemory in PermGen is ClassLoader. Whenever a class is loaded into JVM, all its meta data, along with Classloader, is kept on PermGen area and they will be garbage collected when the Classloader which loaded them is ready for garbage collection. In Case Classloader has a memory leak than all classes loaded by it will remain in memory and cause permGen outofmemory once you repeat it a couple of times.  The classical example is . Now there are two ways to solve this:\n1. Find the cause of Memory Leak or if there is any memory leak.\n2. Increase size of PermGen Space by using JVM param  and .You can also check  in Java for more details.Use the command line parameter  for a Sun JVM (obviously substituting 128 for whatever size you need).Try  and if it persists, try I   (you can experiment which works best) to  as I'm using eclipse ide. In most of JVM,  is around  which runs out of memory if there are too many classes or huge number of Strings in the project.For eclipse, it is also described at . : Double Click on the tomcat server at  Tab :  and add  to the end of existing . I've been butting my head against this problem while deploying and undeploying a complex web application too, and thought I'd add an explanation and my solution.When I deploy an application on Apache Tomcat, a new ClassLoader is created for that app. The ClassLoader is then used to load all the application's classes, and on undeploy, everything's supposed to go away nicely. However, in reality it's not quite as simple.One or more of the classes created during the web application's life holds a static reference which, somewhere along the line, references the ClassLoader. As the reference is originally static, no amount of garbage collecting will clean this reference up - the ClassLoader, and all the classes it's loaded, are here to stay.And after a couple of redeploys, we encounter the OutOfMemoryError.Now this has become a fairly serious problem. I could make sure that Tomcat is restarted after each redeploy, but that takes down the entire server, rather than just the application being redeployed, which is often not feasible. So instead I've put together a solution in code, which works on Apache Tomcat 6.0. I've not tested on any other application servers, and must stress that .I'd also like to say that personally I hate this code, and that . The only time this should be used is if there's an external library your code is dependent on (In my case, it was a RADIUS client) that doesn't provide a means to clean up its own static references.Anyway, on with the code. This should be called at the point where the application is undeploying - such as a servlet's destroy method or (the better approach) a ServletContextListener's contextDestroyed method.Alternatively, you can switch to JRockit which handling permgen differently then sun's jvm.  It generally has better performance as well.I had the problem we are talking about here, my scenario is eclipse-helios + tomcat + jsf and what you were doing is making a deploy a simple application to tomcat. I was showing the same problem here, solved it as follows. In eclipse go to  tab double click on the registered server in my case tomcat 7.0, it opens my file server General registration information. On the section  click on the link  , this opens the execution of server options in the Arguments tab in VM arguments added in the end these two entriesand ready.The simplest answer these days is to use Java 8.  It no longer reserves memory exclusively for PermGen space, allowing the PermGen memory to co-mingle with the regular memory pool.Keep in mind that you will have to remove all non-standard  JVM startup parameters if you don't want Java 8 to complain that they don't do anything.The first thing one can do is to make the size of the permanent generation heap space bigger. This cannot be done with the usual \u2013Xms(set initial heap size) and \u2013Xmx(set maximum heap size) JVM arguments, since as mentioned, the permanent generation heap space is entirely separate from the regular Java Heap space, \nand these arguments set the space for this regular Java heap space. However, there are similar arguments which can be used(at least with the Sun/OpenJDK jvms) to make the size of the permanent generation heap bigger:Default is 64m.Another way to take care of that for good is to allow classes to be unloaded so your PermGen never runs out:Stuff like that worked magic for me in the past. One thing though, there\u2019s a significant performance trade off in using those, since permgen sweeps will  make like an extra 2 requests for every request you make or something along those lines. You\u2019ll need to balance your use with the tradeoffs.You can find the details of this error.Perm gen space error occurs due to use large space rather then jvm provided space to executed the code. The best solution for this problem in UNIX operating systems is to change some configuration on bash file. Following steps solve the problem.Run command  on terminal.Create  variable with following value:Save the bash file. Run command exec bash on terminal. Restart the server.I hope this approach will work on your problem. If you use a Java version lower than 8 this issue occurs sometimes. But if you use Java 8 the problem never occurs.The  space message indicates that the Permanent Generation\u2019s area in memory is exhausted. Any Java applications is allowed to use a limited amount of memory. The exact amount of memory your particular application can use is specified during application startup.The JDK 8 HotSpot JVM is now using native memory for the representation of class metadata and is called Metaspace; similar to the Oracle JRockit and IBM JVM's.The good news is that it means no more  space problems and no need for you to tune and monitor this memory space anymore using .Increasing Permanent Generation size or tweaking GC parameters will NOT help if you have a real memory leak. If your application or some 3rd party library it uses, leaks class loaders the only real and permanent solution is to find this leak and fix it. There are number of tools that can help you, one of the recent is , which has just released a new version with the required capabilities.Also if you are using log4j in your webapp, check this paragraph in log4j .It seems that if you are using , you cause memory leaks when you undeploy your webapp. I have a combination of Hibernate+Eclipse RCP, tried using  and  and it seems to be working for me.I tried several answers and the only thing what finally did the job was this configuration for the compiler plugin in the pom:hope this one helps. resolved this for me as well; however, I noticed that the servlet restart times were much worse, so while it was better in production, it was kind of a drag in development.The configuration of the memory depends on the nature of your app.What are you doing?What's the amount of transactions precessed?How much data are you loading?etc.etc.etcProbably you could profile your app and start cleaning up some modules from your app. Tomcat has hot deploy but it consumes memory. Try restarting your container once in a while.  Also you will need to know the amount of memory needed to run in production mode, this seems a good time for that research. They Say that the latest rev of Tomcat (6.0.28 or 6.0.29) handles the task of redeploying servlets  better.I run into exactly the same problem, but unfortunately none of the suggested solutions really worked for me. The problem did not happen during deployment, and I was neither doing any hot deployments.In my case the problem occurred every time at the same point during the execution of my web-application, while connecting (via hibernate) to the database. (also mentioned earlier) did provide enough insides to resolve the problem. Moving the jdbc-(mysql)-driver out of the WEB-INF and into the jre/lib/ext/ folder seems to have solved the problem. This is not the ideal solution, since upgrading to a newer JRE would require you to reinstall the driver.\nAnother candidate that could cause similar problems is log4j, so you might want to move that one as wellSet . Later on you may also try increasing . Hope it'll work. The same works for me. Setting only  didn't worked for me.\"They\" are wrong because I'm running 6.0.29 and have the same problem even after setting all of the options. As Tim Howland said above, these options only put off the inevitable. They allow me to redeploy 3 times before hitting the error instead of every time I redeploy.In case you are getting this in the eclipse IDE, even after setting the parameters \n, , etc, still if you are getting the same error, it most likely is that the eclipse is using a buggy version of JRE which would have been installed by some third party applications and set to default. These buggy versions do not pick up the PermSize parameters and so no matter whatever you set, you still keep getting these memory errors. So, in your eclipse.ini add the following parameters:  Also make sure you set the default JRE in the preferences in the eclipse to the correct version of java.The only way that worked for me was with the JRockit JVM. I have MyEclipse 8.6.The JVM's heap stores all the objects generated by a running Java program. Java uses the  operator to create objects, and memory for new objects is allocated on the heap at run time. Garbage collection is the mechanism of automatically freeing up the memory contained by the objects that are no longer referenced by the program.I was having similar issue.\nMine is JDK 7 + Maven 3.0.2 + Struts 2.0 + Google GUICE dependency injection based project.Whenever i tried running  command, it was showing following error and  occured I tried all the above useful tips and tricks but unfortunately none worked for me.\nWhat worked for me is described step by step below :=>Hope it helps, happy programming :)First step in such case is to check whether the GC is allowed to unload classes from PermGen. The standard JVM is rather conservative in this regard \u2013 classes are born to live forever. So once loaded, classes stay in memory even if no code is using them anymore. This can become a problem when the application creates lots of classes dynamically and the generated classes are not needed for longer periods. In such a case, allowing the JVM to unload class definitions can be helpful. This can be achieved by adding just one configuration parameter to your startup scripts:By default this is set to false and so to enable this you need to explicitly set the following option in Java options. If you enable CMSClassUnloadingEnabled, GC will sweep PermGen too and remove classes which are no longer used. Keep in mind that this option will work only when UseConcMarkSweepGC is also enabled using the below option. So when running ParallelGC or, God forbid, Serial GC, make sure you have set your GC to CMS by specifying:Assigning Tomcat more memory is NOT the proper solution.The correct solution is to do a cleanup after the context is destroyed and recreated (the hot deploy). The solution is to stop the memory leaks.If your Tomcat/Webapp Server is telling you that failed to unregister drivers (JDBC), then unregister them. This will stop the memory leaks. You can create a ServletContextListener and configure it in your web.xml. Here is a sample ServletContextListener:And here you configure it in your web.xml:
Java

I am relatively new to Java, and often find that I need to sort a  on the values. Since the values are not unique, I find myself converting the  into an , and sorting that array through  with a  that sorts on the value associated with the key. Is there an easier way?Here's a generic-friendly version you're free to use:And an associated JUnit4 test so you don't have to take my word for it:Java 7 VersionJava 8 Version. This will sort according to the value in ascending order; for descending order, it is just possible to uncomment the call to . If you intend to use the code provided, be sure to read the comments as well to be aware of the implications. For example, values can no longer be retrieved by their key. ( always returns .)It seems much easier than all of the foregoing. Use a TreeMap as follows:Output:I would use   to do this - if your values are  then you can useWhich will create a function (object) for the map [that takes any of the keys as input, returning the respective value], and then apply natural (comparable) ordering to them [the values].If they're not comparable, then you'll need to do something along the lines ofThese may be applied to a TreeMap (as  extends ), or a : If you are going to use a TreeMap, remember that if a comparison == 0, then the item is already in the list (which will happen if you have multiple values that compare the same).  To alleviate this, you could add your key to the comparator like so (presuming that your keys and values are ):= Note that this will still not work if your keys compare to 0, but this should be sufficient for most  items (as ,  and  are often in sync...)See  and .So now that we've got a comparator that does what we want, we need to get a result from it. Now this will most likely work work, but:Point 1 is a bit of a deal-breaker for me; google collections is incredibly lazy (which is good: you can do pretty much every operation in an instant; the real work is done when you start using the result), and this requires copying a  map!Don't worry though; if you were obsessed enough with having a \"live\" map sorted in this manner, you could solve not one but both(!) of the above issues with something crazy like the following:When we put, we ensure that the hash map has the value for the comparator, and then put to the TreeSet for sorting. But before that we check the hash map to see that the key is not actually a duplicate. Also, the comparator that we create will also include the key so that duplicate values don't delete the non-duplicate keys (due to == comparison).\nThese 2 items are  for ensuring the map contract is kept; if you think you don't want that, then you're almost at the point of reversing the map entirely (to ).The constructor would need to be called as From Java 8 offers a new answer: convert the entries into a stream, and use the comparator combinators from Map.Entry:This will let you consume the entries sorted in ascending order of value.  If you want descending value, simply reverse the comparator:If the values are not comparable, you can pass an explicit comparator:You can then proceed to use other stream operations to consume the data. For example, if you want the top 10 in a new map:Or print to :Sorting the keys requires the Comparator to look up each value for each comparison. A more scalable solution would use the entrySet directly, since then the value would be immediately available for each comparison (although I haven't backed this up by numbers).Here's a generic version of such a thing:There are ways to lessen memory rotation for the above solution. The first ArrayList created could for instance be re-used as a return value; this would require suppression of some generics warnings, but it might be worth it for re-usable library code. Also,  the Comparator does not have to be re-allocated at every invocation.Here's a more efficient albeit less appealing version:Finally, if you need to continously access the sorted information (rather than just sorting it once in a while), you can use an additional multi map. Let me know if you need more details...The commons-collections library contains a solution called . Or, you could have a look at the Google Collections API. It has  which you could use.And if you don't want to use these framework... they come with source code.I've looked at the given answers, but a lot of them are more complicated than needed or remove map elements when several keys have same value.Here is a solution that I think fits better:Note that the map is sorted from the highest value to the lowest.With Java 8, you can use the  to do it in a significantly less verbose way:To accomplish this with the new features in Java 8:The entries are ordered by their values using the given comparator. Alternatively, if your values are mutually comparable, no explicit comparator is needed:The returned list is a snapshot of the given map at the time this method is called, so neither will reflect subsequent changes to the other. For a live iterable view of the map:The returned iterable creates a fresh snapshot of the given map each time it's iterated, so barring concurrent modification, it will always reflect the current state of the map.While I agree that the constant need to sort a map is probably a smell, I think the following code is the easiest way to do it without using a different data structure.}And here is an embarrassingly incomplete unit test:}The result is a sorted list of Map.Entry objects, from which you can obtain the keys and values.Create customized comparator and use it while creating new TreeMap object.Use the below code in your main funcOutput:Use a generic comparator such as :The answer voted for the most does not work when you have 2 items that equals.\nthe TreeMap leaves equal values out.the exmaple:\nunsorted mapresultsSo leaves out E!!For me it worked fine to adjust the comparator, if it equals do not return 0 but -1.in the example:now it returns:unsorted map:results:as a response to Aliens (2011 nov. 22):\nI Am using this solution for a map of Integer Id's and names, but the idea is the same, so might be the code above is not correct (I will write it in a test and give you the correct code), this is the code for a Map sorting, based on the solution above:and this is the test class (I just tested it, and this works for the Integer, String Map:here is the code for the Comparator of a Map:and this is the testcase for this:of cource you can make this a lot more generic, but I just needed it for 1 case (the Map)Instead of using  as some do I'd suggest using . Actually what  does is something like this:It just calls  on the list and then uses . This way all the map entries will be copied three times: once from the map to the temporary list (be it a LinkedList or ArrayList), then to the temporary array and finally to the new map.My solution ommits this one step as it does not create unnecessary LinkedList. Here is the code, generic-friendly and performance-optimal:This is a variation of Anthony's answer, which doesn't work if there are duplicate values:Note that it's rather up in the air how to handle nulls. One important advantage of this approach is that it actually returns a Map, unlike some of the other solutions offered here.Major problem. If you use the first answer (Google takes you here), change the comparator to add an equal clause, otherwise you cannot get values from the sorted_map by keys:This is just too complicated. Maps were not supposed to do such job as sorting them by Value. The easiest way is to create your own Class so it fits your requirement.In example lower you are supposed to add TreeMap a comparator at place where * is. But by java API it gives comparator only keys, not values. All of examples stated here is based on 2 Maps. One Hash and one new Tree. Which is odd.The example:So change the map into a set this way:You will create class ,and the Comparator class:This way you can easily add more dependencies.And as the last point I'll add simple iterator:There are a lot of answers for this question already, but none provided me what I was looking for, a map implementation that returns keys and entries sorted by the associated value, and maintains this property as keys and values are modified in the map. Two   ask for this specifically. I cooked up a generic friendly example that solves this use case. This implementation does not honor all of the contracts of the Map interface, such as reflecting value changes and removals in the sets return from keySet() and entrySet() in the original object. I felt such a solution would be too large to include in a Stack Overflow answer. If I manage to create a more complete implementation, perhaps I will post it to Github and then to it link in an updated version of this answer.Based on @devinmoore code, a map sorting methods using generics and supporting both ascending and descending ordering.Here is an OO solution (i.e., doesn't use  methods):Hereby donated to the public domain.Afaik the most cleaner way is utilizing collections to sort map on value:Since  for values that can be equal, I used this:You might want to put  in a , but if you're only going to iterate over it right away, that's superfluous...Some simple changes in order to have a sorted map with pairs that have duplicate values. In the compare method (class ValueComparator) when values are equal do not return 0 but return the result of comparing the 2 keys. Keys are distinct in a map so you succeed to keep duplicate values (which are sorted by keys by the way). So the above example could be modified like this:I've merged the solutions of user157196 and Carter Page:If you have duplicate keys and only a small set of data (<1000) and your code is not performance critical you can just do the following: is the input to the code.The variable  will contain the data in decending order when iterated over. To change order just change > to a < in the if statement.Is not the fastest sort but does the job without any additional dependencies.For sure the solution of Stephen is really great, but for those who can't use Guava:Here's my solution for sorting by value a map.\nThis solution handle the case where there are twice the same value etc...The exec:\nThe output:Hope it will help some folksYou can try Guava's multimaps:As a result you get a map from original values to collections of keys that correspond to them. This approach can be used even if there are multiple keys for the same value.Depending on the context, using  which rememebers the order in which items are placed into the map.  Otherwise, if you need to sort values based on their natural ordering, I would recommend maintaining a separate List which can be sorted via .When I'm faced with this, I just create a list on the side. If you put them together in a custom Map implementation, it'll have a nice feel to it... You can use something like the following, performing the sort only when needed. (Note: I haven't really tested this, but it compiles... might be a silly little bug in there somewhere)(If you want it sorted by both keys and values, have the class extend TreeMap, don't define the accessor methods, and have the mutators call super.xxxxx instead of map_.xxxx)
Java

I know that Java enums are compiled to classes with private constructors and a bunch of public static members. When comparing two members of a given enum, I've always used , e.g.However, I just came across come code that uses the equals operator  instead:Which operator is the one I should be using?Both are technically correct. If you look at the source code for , it simply defers to .I use , however, as that will be null safe.Yes: enums have tight instance controls that allows you to use  to compare instances. Here's the guarantee provided by the language specification:This guarantee is strong enough that Josh Bloch recommends, that if you insist on using the singleton pattern, the best way to implement it is to use a single-element  (see: ; also )As a reminder, it needs to be said that generally,  is NOT a viable alternative to . When it is, however (such as with ), there are two important differences to consider:Bloch specifically mentions that immutable classes that have proper control over their instances can guarantee to their clients that  is usable.  is specifically mentioned to exemplify.To summarize, the arguments for using  on  are:Using  to compare two enum values works because there is only one object for each enum constant.On a side note, there is actually no need to use  to write null safe code if you write your  like this:This is a best practice known as  that you definitely should follow.As others have said, both  and  work in most cases. The compile time certainty that you're not comparing completely different types of Objects that others have pointed out is valid and beneficial, however the particular kind of bug of comparing objects of two different compile time types would also be found by FindBugs (and probably by Eclipse/IntelliJ compile time inspections), so the Java compiler finding it doesn't add that much extra safety.However:I actually think that the Java language should have defined == on Objects to call .equals() on the left hand value, and introduce a separate operator for object identity, but that's not how Java was defined.In summary, I still think the arguments are in favor of using  for  types. Here is a crude timing test to compare the two:Comment out the IFs one at a time. Here are the two compares from above in disassembled byte-code:The first (equals) performs a virtual call and tests the return boolean from the stack. The second (==) compares the object addresses directly from the stack. In the first case there is more activity.I ran this test several times with both IFs one at a time. The \"==\" is ever so slightly faster.In case of enum both are correct and right!!I prefer to use  instead of :Other reason, in addition to the others already discussed here, is you could introduce a bug without realizing it. Suppose you have this enums which is exactly the same but in separated pacakges (it's not common, but it could happen)::Then suppose you use the equals like next in  which is  but you import the second enum () instead the first without realizing it:So you will get allways  due is a different enum although you expect true because  is . And it could be be a bit difficult to see.So, if you instead use the operator  you will have a compilation error:Using anything other than  to compare enum constants is nonsense. It's like  \u2013 don't do it!However, there was a nasty bug (BugId ) in Sun JDK 6u10 and earlier that might be interesting for historical reasons. This bug prevented proper use of  on deserialized enums, although this is arguably somewhat of a corner case.Enums are classes that return one instance (like singletons) for each enumeration constant declared by  (immutable) so that  operator could be used to check their equality rather than using  methodI want to complement polygenelubricants answer:I personally prefer equals(). But it lake the type compatibility check. Which I think is an important limitation.To have type compatibility check at compilation time, declare and use a custom function in your enum.With this, you got all the advantage of both solution: NPE protection, easy to read code and type compatibility check at compilation time.I also recommend to add an UNDEFINED value for enum.In short, both have pros and cons.On one hand, it has advantages to use , as described in the other answers.On the other hand, if you for any reason replace the enums with a different approach (normal class instances), having used  bites you. (BTDT.)I would like to explicitly highlight this specific difference between the  operator and  method:The  method is meant to check whether  of the object(s) the reference variable(s) involved refer(s) to are the same.The  operator checks whether the reference variable(s) involved refer(s) .It's up to the implementing class to provide this differentiation as needed by the application. Otherwise the default behavior will be as provided by the  class (in Java) where as explained in :
Java

The following code produces the output \"Hello World!\" (no really, try it).The reason for this is that the Java compiler parses the Unicode character  as a new line and gets transformed into:Thus resulting into a comment being \"executed\".Since this can be used to \"hide\" malicious code or whatever an evil programmer can conceive, ?Why is this allowed by the Java specification?Unicode decoding takes place before any other lexical translation. The key benefit of this is that it makes it trivial to go back and forth between ASCII and any other encoding. You don't even need to figure out where comments begin and end!As stated in  this allows any ASCII based tool to process the source files:This gives a fundamental guarantee for platform independence (independence of supported character sets) which has always been a key goal for the Java platform. Being able to write any Unicode character anywhere in the file is a neat feature, and especially important in comments, when documenting code in non-latin languages. The fact that it can interfere with the semantics in such subtle ways is just an (unfortunate) side-effect.There are many gotchas on this theme and  by Joshua Bloch and Neal Gafter included the following variant:(This program turns out to be a plain \"Hello World\" program.)In the solution to the puzzler, they point out the following:Source: Since this hasn\u2019t addressed yet, here an explanation, why the translation of Unicode escapes happens before any other source code processing:The idea behind it was that it allows lossless translations of Java source code between different character encodings. Today, there is widespread Unicode support, and this doesn\u2019t look like a problem, but back then it wasn\u2019t easy for a developer from a western country to receive some source code from his Asian colleague containing Asian characters, make some changes (including compiling and testing it) and sending the result back, all without damaging something.So, Java source code can be written in any encoding and allows a wide range of characters within identifiers, character and  literals and comments. Then, in order to transfer it losslessly, all characters not supported by the target encoding are replaced by their Unicode escapes.This is a reversible process and the interesting point is that the translation can be done by a tool which doesn\u2019t need to know anything about the Java source code syntax as the translation rule is not dependent on it. This works as the translation to their actual Unicode characters inside the compiler happens independently to the Java source code syntax as well. It implies that you can perform an arbitrary number of translation steps in both directions without ever changing the meaning of the source code.This is the reason for another weird feature which hasn\u2019t even mentioned: the  syntax:When a translation tool is escaping characters and encounters a sequence that is already an escaped sequence, it should insert an additional  into the sequence, converting  to . The meaning doesn\u2019t change, but when converting into the other direction, the tool should just remove one  and replace only sequences containing a single  by their Unicode characters. That way, even Unicode escapes are retained in their original form when converting back and forth. I guess, no-one ever used that feature\u2026I'm going to completely ineffectually add the point, just because I can't help myself and I haven't seen it made yet, that the question is invalid since it contains a hidden premise which is wrong, namely that the code is in a comment!In Java source code \\u000d is equivalent in every way to an ASCII CR character. It is a line ending, plain and simple, wherever it occurs. The formatting in the question is misleading, what that sequence of characters actually syntactically corresponds to is:IMHO the most correct answer is therefore: the code executes because it isn't in a comment; it's on the next line. \"Executing code in comments\" is not allowed in Java, just like you would expect.Much of the confusion stems from the fact that syntax highlighters and IDEs aren't sophisticated enough to take this situation into account. They either don't process the unicode escapes at all, or they do it after parsing the code instead of before, like  does.The  escape terminates a comment because  escapes are uniformly converted to the corresponding Unicode characters  the program is tokenized.  You could equally use  instead of  to  a comment.This is a bug in your IDE, which should syntax-highlight the line to make it clear that the  ends the comment.This is also a design error in the language.  It can't be corrected now, because that would break programs that depend on it.   escapes should either be converted to the corresponding Unicode character by the compiler only in contexts where that \"makes sense\" (string literals and identifiers, and probably nowhere else) or they should have been forbidden to generate characters in the U+0000\u2013007F range, or both.  Either of those semantics would have prevented the comment from being terminated by the  escape, without interfering with the cases where  escapes are useful\u2014note that that  use of  escapes inside comments as a way to encode comments in a non-Latin script, because the text editor could take a broader view of where  escapes are significant than the compiler does.  (I am not aware of any editor or IDE that will display  escapes as the corresponding characters in  context, though.)There is a similar design error in the C family, where backslash-newline is processed before comment boundaries are determined, so e.g.I bring this up to illustrate that it happens to be easy to make this particular design error, and not realize that it's an error until it is too late to correct it, if you are used to thinking about tokenization and parsing the way compiler programmers think about tokenization and parsing.  Basically, if you have already defined your formal grammar and then someone comes up with a syntactic special case \u2014 trigraphs, backslash-newline, encoding arbitrary Unicode characters in source files limited to ASCII, whatever \u2014 that needs to be wedged in, it's easier to add a transformation pass  the tokenizer than it is to redefine the tokenizer to pay attention to where it makes sense to use that special case. For pedants: I am aware that this aspect of C was 100% intentional, with the rationale \u2014 I am not making this up \u2014 that it would allow you to mechanically force-fit code with arbitrarily long lines onto punched cards.  It was still an incorrect design decision.This was an intentional design choice that goes all the way back to the original design of Java.To those folks who ask \"who wants Unicode escapes in comments?\", I presume they are folks whose native language uses the Latin character set. In other words, it is inherent in the original design of Java that folks could use arbitrary Unicode characters wherever legal in a Java program, most typically in comments and strings.It is arguably a shortcoming in programs (like IDEs) used to view the source text that such programs cannot interpret the Unicode escapes and display the corresponding glyph.I agree with @zwol that this is a design mistake; but I'm even more critical of it. escape is useful in string and char literals; and that's the only place that it should exist. It should be handled the same way as other escapes like ; and   mean exactly .There is absolutely no point of having  in comments - nobody can read that.Similarly, there's no point of using  in other part of the program. The only exception is probably in public APIs that are coerced to contain some non-ascii chars - what's the last time we've seen that?The designers had their reasons in 1995, but 20 years later, this appears to be a wrong choice.The only people who can answer why Unicode escapes were implemented as they were are the people who wrote the specification.A plausible reason for this is that there was the desire to allow the entire BMP as possible characters of Java source code. This presents a problem though:This is incredibly difficult when Unicode escapes enter the fray: it creates a whole load of new lexer rules.The easy way out is to do lexing in two steps: first search and replace all Unicode escapes with the character it represents, and then parse the resulting document as if Unicode escapes don't exist.The upside to this is that it's easy to specify, so it makes the specification simpler, and it's easy to implement.The downside is, well, your example.
Java

In Java, arrays don't override , so if you try to print one directly, you get weird output including the memory location:But usually we'd actually want something more like . What's the simplest way of doing that? Here are some example inputs and outputs:Since Java 5 you can use  or  for arrays within arrays. Note that the  version calls  on each object in the array. The output is even decorated in the exact way you're asking.Examples:Output:Output:Output:Output:Always check the standard libraries first.  Try:or if your array contains other arrays as elements:This is nice to know, however, as for \"always check the standard libraries first\" I'd never have stumbled upon the trick of --since I was concentrating on the type of myarray to see how to do this. I didn't want to have to iterate through the thing: I wanted an easy call to make it come out similar to what I see in the Eclipse debugger and myarray.toString() just wasn't doing it.In JDK1.8 you can use aggregate operations and a lambda expression:If you're using Java 1.4, you can instead do:(This works in 1.5+ too, of course.)Starting with Java 8, one could also take advantage of the  method provided by the  to print out array elements, without the brackets, and separated by a delimiter of choice (which is the space character for the example shown below):The output will be \"Hey there amigo!\". only prints on one line. To actually get a table to print as a two dimensional table, I had to do this: It seems like the  method should take a separator string, but unfortunately it doesn't.Prior to Java 8 we could have used  to print one dimensional array and  for multi-dimensional arrays. We have got the option of  and  in Java 8 which can also be used for the printing the array.The output is:\nJust in case we want to print multi-dimensional array we can use  as:Now the point to observe is that the method , which in case of  returns us  and then method  maps each element of stream with the contents of a mapped stream produced by applying the provided mapping function to each element.The output is:As a direct answer, , using the  and  methods, is simply the best.Below I try to list some of the other methods suggested, attempting to improve a little, with the most notable addition being the use of the  operator, using a  , to mimic what the  is doing.Using regular  loop is the simplest way of printing array in my opinion.\nHere you have a sample code based on your intArrayIt gives output as yours\n    1, 2, 3, 4, 5Resource: There's one additional way if your array is of type char[]:prints A simplified shortcut I've tried is this:It will printNo loops required in this approach and it is best for small arrays onlyIt should always work whichever JDK version you use:It will work if the  contains Objects. If the  contains primitive types, you can use wrapper classes instead storing the primitive directly as..Example: Replace it with:Yes ! this is to be mention that converting an array to an object array OR to use the Object's array is costly and may slow the execution. it happens by the nature of java called autoboxing.   So only for printing purpose, It should not be used. we can make a function which takes an array as parameter and prints the desired format asI came across this post in  recently. It's not very convenient writing , then importing  all the time. Printing an array directly gives the internal representation and the hashCode. Now, all classes have  as the parent-type. So, why not hack the ? Without modification, the Object class looks like this:What if this is changed to:This modded class may simply be added to the class path by adding the following to the command line: .Now, with the availability of  since Java 5, the  can easily be changed to  to add support for arrays that contain other arrays.I found this to be a quite useful hack and it would be great if Java could simply add this. I understand potential issues with having very large arrays since the string representations could be problematic. Maybe pass something like a or a  for such eventualities. To add to all the answers, printing the object as a JSON string is also an option.Using Jackson:Using Gson:Using org.apache.commons.lang3.StringUtils.join(*) methods can be an option\nFor example:I used the following dependency You could loop through the array,  printing out each item, as you loop. For example:Output:In java 8 it is easy. there are two keywordsIf you want to print all elements in the array in the same line, then just use  instead of  i.e. Another way without method reference just use:for each loop can also be used to print elements of array:The simplest way to print an array is to use a for-loop:
Java

Is there anything like .NET's  in Java? has it. Or you could throw an .I think the  is what you are looking for.You could do it yourself (thats what I did) - in order to not be bothered with exception handling, you simply extend the RuntimeException, your class could look something like this:You could extend it to take a message - but if you use the method as I do (that is, as a reminder, that there is still something to be implemented), then usually there is no need for additional messages.I dare say, that I only use this method, while I am in the process of developing a system, makes it easier for me to not lose track of which methods are still not implemented properly :)No there isn't and it's probably not there, because there are very few valid uses for it. I would think twice before using it. Also, it is indeed easy to create yourself.Please refer to  about why it's even in .NET.I guess  comes close, although it doesn't say the operation is just not implemented, but unsupported even. That could imply no valid implementation is possible. Why would the operation be unsupported? Should it even be there? \nInterface segregation or Liskov substitution issues maybe?If it's work in progress I'd go for , but I've never caught myself defining a concrete method and then leave it for so long it makes it into production and there would be a need for such an exception.
Java

I have a string like this: I want to remove the whitespaces in the string. I tried  but this removes only whitespaces before and after the whole string. I also tried  but then the  also gets removed.How can I achieve a string with: removes all whitespaces and non-visible characters (e.g., tab, ). and  produce the same result.The second regex is 20% faster than the first one, but as the number consecutive spaces increases, the first one performs better than the second one.Assign the value to a variable, if not used directly: = Anything that is a word character = Anything that isn't a word character (including punctuation etc) = Anything that is a space character (including space, tab characters etc) = Anything that isn't a space character (including both letters and numbers, as well as punctuation etc)(Edit: As pointed out, you need to escape the backslash if you want  to reach the regex engine, resulting in .)The most correct answer to the question is:I just adapted this code from the other answers. I'm posting it because besides being exactly what the question requested, it also demonstrates that  as some of the answers sort of imply.(Experienced Java developers might say \"of course, you can't actually modify a String\", but the target audience for this question may well not know this.)How about . Refer .If you prefer utility classes to regexes, there is a method  in StringUtils in the Spring Framework.You've already got the correct answer from Gursel Koca but I believe that there's a good chance that this is not what you really want to do. How about parsing the key-values instead?One way to handle String manipulations is StringUtils from Apache commons.You can find it .\ncommons-lang includes lots more and is well supported.You should useinstead of:This way, it will work with more than one spaces between each string. \nThe + sign in the above regex means \"one or more \\s\"If you need to remove unbreakable spaces too, you can upgrade your code like this :You can do it so simply by//it work fine with any spaces \n*don't forget space in sting b means \"non word character\". The pattern for whitespace characters is . This is well documented in the .In java we can do following operation:for this you need to import following packages to your program:i hope it will help you.The easiest way to do this is by using the  class of  library such as \"\" for example.Use the static method \"\" on your input string & it will return you a string after removing all the white spaces from it. I tried your example string \"\" & it returned me exactly the string that you wanted - \"\". Hope this helps.there are many ways to solve this problem.\nyou can use split function or replace function of Strings.for more info refer smilliar problem Using Pattern And Matcher it is more Dynamic.First with space, second without space. Then it is done. This works for me and locates ll white spaces, not just spaces of a certain size.TRY THIS You can achieve this without using replaceAll() or any Predefined Method in Java.\nthis way is preferred:-public class RemoveSpacesFromString {}Use The code you want isThis will remove all the white spaces.
Java

How do I add local jar files (not yet part of the Maven repository) directly in my project's library sources?Install the JAR into your local Maven repository as follows:You can add local dependencies directly (as mentioned in ) like this:Firstly I would like to give credit for this answer to anonymous stackoverflow user - I am pretty sure I've seen similar answer here before - but now I cannot find it. The best option for having local jar files as a dependency is to create local maven repository. Such repo is nothing else than proper directory structure with pom files in it. On my example:\nI have master project on  location and subroject1 is on then I am creating mvn repository in:\nIn pom file in subproject1 located  repository needs to be specified which would take file path as an url parameter:Dependency can be specified as for any other repository. This makes your pom repository independent. For instance once desired jar is available in maven central you just need to delete it from your local repo and it will be pulled from default repo. The last but not least thing to do is to add jar file to local repository using -DlocalRepositoryPath switch like here:Onece jar file is installed such mvn repo can be committed to code repository and whole set up is system independent. ()I agree that having JARs committed to source code repo is not a good practice but in real life quick and dirty solution sometimes is better than full blown nexus repo to host one jar that you cannot publish. Create a new folder, let's say  at the root of your Maven project.Just add a local repo inside your  of your :Then for each external jar you want to install, go at the root of your project and execute:Yes , you can have but its not good idea.Instead install all these jars to maven reposI'd like such solution - use  in pom file:In this case you can perform  and jar will be installed in local maven repo. Now this jar is available during any maven step on this machine (do not forget to include this dependency as any other maven dependency in pom with  tag). It is also possible to bind jar install not to  step, but any other step you like.One way is to upload it to your own Maven repository manager (such as Nexus). It's good practice to have an own repository manager anyway.Another nice way I've recently seen is to include the Maven Install Plugin in your build lifecycle: You declare in the POM to install the files to the local repository. It's a little but small overhead and no manual step involved.Of course you can add jars to that folder. But maybe it does not what you want to achieve...If you need these jars for compilation, check this related question: Also, before anyone suggests it, do NOT use the system scope.The preferred way would be to create your own remote repository.See  for details on how to do it.\nHave a look at the '' section.Also take a look at....  This is the default but I've found in some cases explicitly setting that scope also Maven to find local libraries in the local repository.I want to share a code where you can upload a folder full of jars. It's useful when a provider doesn't have a public repository and you need to add lots of libraries  manually. I've decided to build a .bat instead of call directly to maven because It could be Out of Memory errors. It was prepared for a windows environment but is easy to adapt it to linux OS:After run this main from any IDE, run the update_repo_maven.bat.THIS ANSWER IS ONLY FOR ECLIPSE USERS:If you are using Eclipse, place the jar in lib/, right click on the jar name and click \"add to build path\". \nEclipse will create a \"referenced libraries\" and place the jar for youIt resolved the import of the jar right away in the program for me Note that it is NOT necessarily a good idea to use a local repo.\nIf this project is shared with others then everyone else will have problems and questions when it doesn't work, and the jar won't be available even in your source control system!Although the shared repo is the best answer, if you cannot do this for some reason then embedding the jar is better than a local repo. Local-only repo contents can cause lots of problems, especially over time.This is a short syntax for newer versions:It works when the JAR was built by Apache Maven - the most common case. Then it'll contain a pom.xml in a subfolder of the META-INF directory, which will be read by default.Source: On your local repository you can install your jar by issuing the commandsFollow this useful   to do the same from mkyoung's website. You can also check To install third party jar, Please call the command like below
Java

How might I convert an  object to a  array in Java?For example:The  method without passing any argument returns . So you have to pass an array as an argument, which will be filled with the data from the list, and returned. You can pass an empty array as well, but you can also pass an array with the desired size.: Originally the code above used . However,  reveals that due to JVM optimizations, using  is better now.An alternative in Java 8:Using copyOf, ArrayList to arrays might be done also.You can use the  method for :Or you can manually add the elements to an array:Hope this helps!In Java 8:in case some extra manipulation of the data is desired, for which the user wants a function, this approach is not perfect (as it requires passing the class of the element as second parameter), but works:import java.util.ArrayList;\nimport java.lang.reflect.Array; solution to covert any  to : You must  method.By using  method of ArrayList you can get .\nCast that  to \nHere the sample code:This is enough:
Java

I've always been told  to represent money with  or  types, and this time I pose the question to you: why? I'm sure there is a very good reason, I simply do not know what it is.Because floats and doubles cannot accurately represent the base 10 multiples we use for money. This issue isn't just for Java, it's for any programming language that uses native floating-point types, as it stems from how computers handle floating-point numbers by default.This is how an  floating-point number works: it dedicates a bit for the sign, a few bits to store an exponent for the base, and the rest for a multiple of that elevated base. This leads to numbers like 10.25 being represented in a form similar to 1025 * 10; except that instead of the base being 10, for s and s, it's two, so that would be 164 * 2. (That's still not exactly how they are represented in hardware, but this is simple enough and the math holds the same way.)Even in base 10, this notation cannot accurately represent most simple fractions. For instance, with most calculators, 1/3 results in a repeating 0.333333333333, with as many 3's as the digital display allows, because you just can't write 1/3 in decimal notation. However, for the purpose of money (at least for countries whose money value is within an order of magnitude of the US dollar), in most scenarios all you need is to be able to store multiples of 10, so we don't really care if 1/3 doesn't have an exact representation as an integer times a power of 10, and even the cheapest calculators handle cents just fine.The problem with floats and doubles is that the  of money-like numbers don't have an exact representation as a integer times a power of two. In fact, the only fractions of a hundred between 0/100 and 100/100 (which are significant when dealing with money because they're integer cents) that can be represented exactly as an IEEE-754 binary floating-point number are 0, 0.25, 0.5, 0.75 and 1. All the others are off by a small amount.Representing money as a  or  will probably look good at first as the software rounds off the tiny errors, but as you perform more additions, subtractions, multiplications and divisions on inexact numbers, you'll lose more and more precision as the errors add up. This makes floats and doubles inadequate for dealing with money, where perfect accuracy for multiples of base 10 powers is required.A solution that works in just about any language is to use integers instead, and count cents. For instance, 1025 would be $10.25. Several languages also have built-in types to deal with money. Among others, Java  has the  class, and C# has the  type.This is not a matter of accuracy, nor is it a matter of precision.  It is a matter of meeting the expectations of humans who use base 10 for calculations instead of base 2.  For example, using doubles for financial calculations does not produce answers that are \"wrong\" in a mathematical sense, but it can produce answers that are not what is expected in a financial sense.Even if you round off your results at the last minute before output, you can still occasionally get a result using doubles that does not match expectations.Using a calculator, or calculating results by hand, 1.40 * 165 = 231 exactly.  However, internally using doubles, on my compiler / operating system environment, it is stored as a binary number close to 230.99999... so if you truncate the number, you get 230 instead of 231.  You may reason that rounding instead of truncating would have given the desired result of 231.  That is true, but rounding always involves truncation.  Whatever rounding technique you use, there are still boundary conditions like this one that will round down when you expect it to round up.  They are rare enough that they often will not be found through casual testing or observation.  You may have to write some code to search for examples that illustrate outcomes that do not behave as expected.Assume you want to round something to the nearest penny.  So you take your final result, multiply by 100, add 0.5, truncate, then divide the result by 100 to get back to pennies.  If the internal number you stored was 3.46499999.... instead of 3.465, you are going to get 3.46 instead 3.47 when you round the number to the nearest penny.  But your base 10 calculations may have indicated that the answer should be 3.465 exactly, which clearly should round up to 3.47, not down to 3.46.  These kinds of things happen occasionally in real life when you use doubles for financial calculations.  It is rare, so it often goes unnoticed as an issue, but it happens.If you use base 10 for your internal calculations instead of doubles, the answers are always exactly what is expected by humans, assuming no other bugs in your code.Floats and doubles are approximate. If you create a BigDecimal and pass a float into the constructor you see what the float actually equals:this probably isn't how you want to represent $1.01.The problem is that the IEEE spec doesn't have a way to exactly represent all fractions, some of them end up as repeating fractions so you end up with approximation errors. Since accountants like things to come out exactly to the penny, and customers will be annoyed if they pay their bill and after the payment is processed they owe .01 and they get charged a fee or can't close their account, it's better to use exact types like decimal (in C#) or java.math.BigDecimal in Java.It's not that the error isn't controllable if you round: . It's just easier not to have to round in the first place. Most applications that handle money don't call for a lot of math, the operations consist of adding things or allocating amounts to different buckets. Introducing floating point and rounding just complicates things.I'm troubled by some of these responses.  I think doubles and floats have a place in financial calculations.  Certainly, when adding and subtracting non-fractional monetary amounts there will be no loss of precision when using integer classes or BigDecimal classes.  But when performing more complex operations, you often end up with results that go out several or many decimal places, no matter how you store the numbers.  The issue is how you present the result.If your result is on the borderline between being rounded up and rounded down, and that last penny really matters, you should be probably be telling the viewer that the answer is nearly in the middle - by displaying more decimal places.The problem with doubles, and more so with floats, is when they are used to combine large numbers and small numbers.  In java,results inThe result of floating point number is not exact, which makes them unsuitable for any financial calculation which requires exact result and not approximation. float and double are designed for engineering and scientific calculation and many times doesn\u2019t produce exact result also result of floating point calculation may vary from JVM to JVM. Look at below example of BigDecimal and double primitive which is used to represent money value, its quite clear that floating point calculation may not be exact and one should use BigDecimal for financial calculations.Output:While it's true that floating point type can represent only approximatively decimal data, it's also true that if one rounds numbers to the necessary precision before presenting them, one obtains the correct result. Usually.Usually because the double type has a precision less than 16 figures. If you require better precision it's not a suitable type. Also approximations can accumulate.It must be said that even if you use fixed point arithmetic you still have to round numbers, were it not for the fact that BigInteger and BigDecimal give errors if you obtain periodic decimal numbers. So there is an approximation also here.For example COBOL, historically used for financial calculations, has a maximum precision of 18 figures. So there is often an implicit rounding.Concluding, in my opinion the double is unsuitable mostly for its 16 digit precision, which can be insufficient, not because it is approximate.Consider the following output of the subsequent program. It shows that after rounding double give the same result as BigDecimal up to precision 16.As said earlier \"Representing money as a double or float will probably look good at first as the software rounds off the tiny errors, but as you perform more additions, subtractions, multiplications and divisions on inexact numbers, you\u2019ll lose more and more precision as the errors add up. This makes floats and doubles inadequate for dealing with money, where perfect accuracy for multiples of base 10 powers is required.\"JSR 354 provides an API for representing, transporting, and performing comprehensive calculations with Money and Currency. You can download it from this link: An example of creating a MonetaryAmount and printing it to the console looks like this::When using the reference implementation API, the necessary code is much simpler:The API also supports calculations with MonetaryAmounts:CurrencyUnit and MonetaryAmountMonetaryAmount has various methods that allow accessing the assigned currency, the numeric amount, its precision and more:MonetaryAmounts can be rounded using a rounding operator:When working with collections of MonetaryAmounts, some nice utility methods for filtering, sorting and grouping are available.Custom MonetaryAmount operationsResources: See Also: I'll risk being downvoted, but I think the unsuitability of floating point numbers for currency calculations is overrated. As long as you make sure you do the cent-rounding correctly and have enough significant digits to work with in order to counter the binary-decimal representation mismatch explained by zneak, there will be no problem.People calculating with currency in Excel have always used double precision floats (there is no currency type in Excel) and I have yet to see anyone complaining about rounding errors.Of course, you have to stay within reason; e.g. a simple webshop would probably never experience any problem with double precision floats, but if you do e.g. accounting or anything else that requires adding a large (unrestricted) amount of numbers, you wouldn't want to touch floating point numbers with a ten foot pole.If your computation involves various steps, arbitrary precision arithmetic won't cover you 100%.The only reliable way to use perfect representation of results(Use a custom Fraction data type that will batch division operations to the last step) and only convert to a decimal notation in last step.Arbitrary precision won't help because there always can be numbers that has so much decimal places, or some results such as 0.6666666... No arbitrary representation will cover the last example. So you will have small errors in each step.This errors will add-up, may eventually become not easy to ignore anymore. This is called .Some example... this works (actually don't work as expected), on almost any programming language... I've tried with Delphi, VBScript, Visual Basic, JavaScript and now with Java/Android:OUTPUT:I prefer using Integer or Long to represent currency.  BigDecimal junks up the source code too much.You just have to know that all your values are in cents.  Or the lowest value of whatever currency you're using.Many of the answers posted to this question discuss IEEE and the standards surrounding floating-point arithmetic.Coming from a non-computer science background (physics and engineering), I tend to look at problems from a different perspective. For me, the reason why I wouldn't use a double or float in a mathematical calculation is that I would lose too much information.What are the alternatives? There are many (and many more of which I am not aware!).BigDecimal in Java is native to the Java language.\nApfloat is another arbitrary-precision library for Java.The decimal data type in C# is Microsoft's .NET alternative for 28 significant figures.SciPy (Scientific Python) can probably also handle financial calculations (I haven't tried, but I suspect so).The GNU Multiple Precision Library (GMP) and the GNU MFPR Library are two free and open-source resources for C and C++.There are also numerical precision libraries for JavaScript(!) and I think PHP which can handle financial calculations.There are also proprietary (particularly, I think, for Fortran) and open-source solutions as well for many computer languages.I'm not a computer scientist by training. However, I tend to lean towards either BigDecimal in Java or decimal in C#. I haven't tried the other solutions I've listed, but they are probably very good as well.For me, I like BigDecimal because of the methods it supports. C#'s decimal is very nice, but I haven't had the chance to work with it as much as I'd like. I do scientific calculations of interest to me in my spare time, and BigDecimal seems to work very well because I can set the precision of my floating point numbers. The disadvantage to BigDecimal? It can be slow at times, especially if you're using the divide method.You might, for speed, look into the free and proprietary libraries in C, C++, and Fortran.I've reached to a pretty nice precision just dealing with cents.Here is the class:
Java

I have some questions regarding the usage and significance of the  keyword. The  keyword is all about different threads reading and writing to the same variables, objects and resources.  This is not a trivial topic in , but here is a quote from Sun: When you have two threads that are reading and writing to the same 'resource', say a variable named , you need to ensure that these threads access the variable in an atomic way.  Without the  keyword, your thread 1 may not see the change thread 2 made to , or worse, it may only be half changed.  This would not be what you logically expect.Again, this is a non-trivial topic in .  To learn more, explore topics here on SO and the Interwebs  about:Keep exploring these topics until the name  becomes permanently associated with the term  in your brain.  Well, I think we had enough of theoretical explanations, so consider this codeNote:  blocks the next thread's call to method test() as long as the previous thread's execution is not finished. Threads can access this method one at a time. Without  all threads can access this method simultaneously.When a thread calls the synchronized method 'test' of the object (here object is an instance of 'TheDemo' class) it acquires the lock of that object, any new thread cannot call ANY synchronized method of the same object as long as previous thread which had acquired the lock does not release the lock.Similar thing happens when any static synchronized method of the class is called. The thread acquires the lock associated with the class(in this case any non static synchronized method of an instance of that class can be called by any thread because that object level lock is still available). Any other thread will not be able to call any static synchronized method of the class as long as the class level lock is not released by the thread which currently holds the lock.The  keyword prevents concurrent access to a block of code or object by multiple Threads.  By default, a  is , so only one thread can access the table at a time.  On usage of  constructs like ,you must build thread safety features in your code to prevent memory consistency errors. means that in a multi threaded environment, an object having   method(s)/block(s) does not let two threads to access the  method(s)/block(s) of code at the same time. This means that one thread can't read while another thread updates it.The second thread will instead wait until the first thread completes its execution. The overhead is speed, but the advantage is guaranteed consistency of data.If your application is single threaded though,  blocks does not provide benefits.The  keyword causes a thread to obtain a lock when entering the method, so that only one thread can execute the method at the same time (for the given object instance, unless it is a static method).This is frequently called making the class thread-safe, but I would say this is a euphemism. While it is true that synchronization protects the internal state of the Vector from getting corrupted, this does not usually help the user of Vector much. Consider this:Even though the methods involved are synchronized, because they are being locked and unlocked individually, two unfortunately timed threads can create a vector with two elements.So in effect, you have to synchronize in your application code as well.Because method-level synchronization is a) expensive when you don't need it and b) insufficient when you need synchronization, there are now un-synchronized replacements (ArrayList in the case of Vector).More recently, the concurrency package has been released, with a number of clever utilities that take care of multi-threading issues.Synchronized keyword in Java has to do with thread-safety, that is, when multiple threads read or write the same variable.\nThe synchronized keyword is used to define a block of code where multiple threads can access the same variable in a safe way.Syntax-wise the  keyword takes an  as it's parameter (called ), which is then followed by a .Adding  keyword to a method definition is equal to the entire method body being wrapped in a synchronized code block with the  being   and  .\nWithout synchronization, it is not guaranteed in which order the reads and writes happen, possibly leaving the variable with garbage.\nIt is not enough to complete a write operation in a thread before (wall-clock time) another thread reads it, because hardware could have cached the value of the variable, and the reading thread would see the cached value instead of what was written to it.Thus in Java's case, you have to follow the Java Memory Model to ensure that threading errors do not happen.\nThink of it as a kind of turnstile like you might find at a football ground. There are parallel steams of people wanting to get in but at the turnstile they are 'synchronised'. Only one person at a time can get through. All those wanting to get through will do, but they may have to wait until they can go through.Threads communicate primarily by sharing access to fields and the objects reference fields refer to. This form of communication is extremely efficient, but makes two kinds of errors possible: . The tool needed to prevent these errors is synchronization. Synchronized blocks or methods prevents thread interference and make sure that data is consistent. At any point of time, only one thread can access a synchronized block or method () by acquiring a lock. Other thread(s) will wait for release of lock to access . Once the lock is released by current owner thread with  call, one of thread(s) will acquire the lock to access  guarded by  keyword.Methods are synchronized when you add  to method definition or declaration. You can also synchronize a particular block of code with-in a method. It means that only one thread can access  by acquiring a lock. Unless this thread calls , all other thread(s) will have to wait to acquire a lock. They don't have access to enter  with out acquiring lock.This can't be done with a magic. It's programmer  responsibility to identify  in application and guard it accordingly. Java provides a framework to guard your application, but where and what all sections to be guarded is the responsibility of programmer.More details from java documentation . By convention, a thread that needs exclusive and consistent access to an object's fields has to acquire the object's intrinsic lock before accessing them, and then release the intrinsic lock when it's done with them.A thread is said to own the intrinsic lock between the time it has acquired the lock and released the lock.  The other thread will block when it attempts to acquire the lock.Making methods synchronized has two :When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.This guarantees that changes to the state of the object are visible to all threads.Look for other alternatives to synchronization in :To my understanding synchronized basically means that the compiler write a monitor.enter and monitor.exit around your method. As such it may be thread safe depending on how it is used (what I mean is you can write an object with synchronized methods that isn't threadsafe depending on what your class does).I know that you have already gotten your answer . I write this, only to help the people who have the same question and are looking up this page for an answer . \nhere is an  explanation from  : \nConsider the following code : if  is an instance of    then making these methods synchronized has two effects:synchronized simple means no two threads can access the block/method simultaneously. When we say any block/method of a class is synchronized it means only one thread can access them at a time. Internally the thread which tries to access it first take a lock on that object and as long as this lock is not available no other thread can access any of the synchronized methods/blocks of that instance of the class.Note another thread can access a method of the same object which is not defined to be synchronized. A thread can release the lock by calling: ArrayList is non-synchronized which means multiple threads can work on ArrayList at the same time. For e.g. if one thread is performing an add operation on ArrayList, there can be an another thread performing remove operation on ArrayList at the same time in a multithreaded environmentwhile Vector is synchronized. This means if one thread is working on Vector, no other thread can get a hold of it. Unlike ArrayList, only one thread can perform an operation on vector at a timeSynchronized simply means that multiple threads if associated with single object can prevent dirty read and write if synchronized block is used on particular object. To give you more clarity , lets take an example :We've created two MyRunnable class objects , runnable1 being shared with thread 1 and thread 3 & runnable2 being shared with thread 2 only.\nNow when t1 and t3 starts without synchronized being used , PFB output which suggest that both threads 1 and 3 simultaneously affecting var value where for thread 2 , var has its own memory.Using Synchronzied, thread 3 waiting for thread 1 to complete in all scenarios. There are two locks acquired , one on runnable1 shared by thread 1 and thread 3 and another on runnable2 shared by thread 2 only.synchronized is a keyword in Java which is used to make happens before relationship in multithreading environment to avoid memory inconsistency and thread interference error.
Java

Maven2 is driving me crazy during the experimentation / quick and dirty mock-up phase of development.  I have a  file that defines the dependencies for the web-app framework I want to use, and I can quickly generate starter projects from that file. However, sometimes I want to link to a 3rd party library that doesn't already have a  file defined, so rather than create the  file for the 3rd party lib by hand and install it, and add the dependency to my , I would just like to tell Maven: \"In addition to my defined dependencies, include any jars that are in  too.\"  It seems like this ought to be simple, but if it is, I am missing something.Any pointers on how to do this are greatly appreciated. Short of that, if there is a simple way to point maven to a  directory and easily create a  with all the enclosed jars mapped to a single dependency which I could then name / install and link to in one fell swoop would also suffice.Most of the answers you'll find around the internet will suggest you to either install the dependency to your local repository or specify a \"system\" scope in the  and distribute the dependency with the source of your project. But both of these solutions are actually flawed.When you install a dependency to your local repository it remains there. Your distribution artifact will do fine as long as it has access to this repository. The problem is in most cases this repository will reside on your local machine, so there'll be no way to resolve this dependency on any other machine. Clearly making your artifact depend on a specific machine is not a way to handle things. Otherwise this dependency will have to be locally installed on every machine working with that project which is not any better.The jars you depend on with the \"System Scope\" approach neither get installed to any repository or attached to your target packages. That's why your distribution package won't have a way to resolve that dependency when used. That I believe was the reason why the use of system scope even got deprecated. Anyway you don't want to rely on a deprecated feature.After putting this in your :for each artifact with a group id of form  Maven will include the following location inside your project dir in its search for artifacts:To elaborate more on this you can read .Instead of creating this structure by hand I recommend to use a Maven plugin to install your jars as artifacts. So, to install an artifact to an in-project repository under  folder execute:If you'll choose this approach you'll be able to simplify the repository declaration in  to:Since executing installation command for each lib is kinda annoying and definitely error prone, I've created a  which automatically installs all the jars from a  folder to a project repository, while automatically resolving all metadata (groupId, artifactId and etc.) from names of files. The script also prints out the dependencies xml for you to copy-paste in your .When you'll have your in-project repository created you'll have solved a problem of distributing the dependencies of the project with its source, but since then your project's target artifact will depend on non-published jars, so when you'll install it to a repository it will have unresolvable dependencies. To beat this problem I suggest to include these dependencies in your target package. This you can do with either the  or better with the . The official documentaion on OneJar is easy to grasp.set scope == system and just make up a groupId, artifactId, and versionYou may create local repository on your projectFor example if you have  folder in project structureThat is all.For detailed information: Note: When using the System scope (), Maven needs absolute paths.If your jars are under your project's root, you'll want to prefix your systemPath values with ${basedir}.You really ought to get a framework in place via a repository and identifying your dependencies up front. Using the system scope is a common mistake people use, because they \"don't care about the dependency management.\" The trouble is that doing this you end up with a perverted maven build that will not show maven in a normal condition. You would be better off following an approach like .This is what I have done, it also works around the package issue and it works with checked out code.I created a new folder in the project in my case I used , but feel free to use In my POM I had a dependency that is not in any public maven repositoriesI then created the following directories  and copied the JAR file into that folder.I created the following POM file to represent the downloaded file (this step is optional, but it removes a WARNING) and helps the next guy figure out where I got the file to begin with.Two optional files I create are the SHA1 checksums for the POM and the JAR to remove the missing checksum warnings.Finally I add the following fragment to my pom.xml that allows me to refer to the local repository has command line usage to install a jar into the local repository, POM is optional but you will have to specify the GroupId, ArtifactId, Version and Packaging (all the POM stuff).This is how we add or install a local jari gave some default groupId and artifactId because they are mandatory :)Using  is a terrible idea for reasons explained by others, installing the file manually to your local repository makes the build unreproducible, and using  is not a good idea either because (1) that may not be a well-formed  URL (e.g. if the project is checked out in a directory with unusual characters), (2) the result is unusable if this project\u2019s POM is used as a dependency of someone else\u2019s project.Assuming you are unwilling to upload the artifact to a public repository, Simeon\u2019s suggestion of a helper module does the job. But there is an easier way now\u2026Use . Does exactly what you were asking for, with none of the drawbacks of the other approaches.I found another way to do this, see here from a To summarize (sorry about some copy & paste)After having really long discussion with CloudBees guys about properly maven packaging of such kind of JARs, they made an interesting good proposal for a solution:Creation of a fake Maven project which attaches a pre-existing JAR as a primary artifact, running into belonged POM install:install-file execution. Here is an example of such kinf of POM: But in order to implement it, existing project structure should be changed. First, you should have in mind that for each such kind of JAR there should be created different fake Maven project (module). And there should be created a parent Maven project including all sub-modules which are : all JAR wrappers and existing main project. The structure could be : When parent running via mvn:install or mvn:packaging is forced and sub-modules will be executed. That could be concerned as a minus here, since project structure should be changed, but offers a non static solution at the endWhat seems simplest to me is just configure your maven-compiler-plugin to include your custom jars. This example will load any jar files in a lib directory. The problem with  is that the dependencies' jars won't get distributed along your artifacts as transitive dependencies. Try what I've posted here: Then declare dependencies as usual.And please read the footer note.If you want a quick and dirty solution, you can do the following (though I do not recommend this for anything except test projects, maven will complain in length that this is not proper).Add a dependency entry for each jar file you need, preferably with a perl script or something similar and copy/paste that into your pom file.A strange solution I found: using Eclipse cheers,\nBalintEven though it does not exactly fit to your problem, I'll drop this here. My requirements were:Let's talk about (3) first: Just having the jars in a folder and somehow merging them into the final jar will not work for here, since the IDE will not understand this. This means all libraries have to be installed properly. However, I dont want to have everyone installing it using \"mvn install-file\".In my project I needed metawidget. Here we go:Every time you have a new library, just add a new execution and tell everyone to build the project again (you can improve this process with project hierachies).To install the 3rd party jar which is not in maven repository use maven-install-plugin.Below are steps:Below is the e.g one I used it for simonsite log4jBelow is the reference link:For those that didn't find a good answer here, this is what we are doing to get a jar with all the necessary dependencies in it. This answer () mentions to use the Maven Assembly plugin but doesn't actually give an example in the answer. And if you don't read all the way to the end of the answer (it's pretty lengthy), you may miss it. Adding the below to your pom.xml will generate This doesn't answer how to add them to your POM, and may be a no brainer, but would just adding the lib dir to your classpath work? I know that is what I do when I need an external jar that I don't want to add to my Maven repos. Hope this helps.What works in our project is what Archimedes Trajano wrote, but we had in our .m2/settings.xml something like this:and the * should be changed to central. So if his answer doesn't work for you, you should check your settings.xmlI alluded to some python code in a comment to the answer from @alex lehmann's , so am posting it here.A  batch solution (based on Alex's answer):Execute it like this: .\nThen open  and copy its content as dependencies.In my case, I only needed the libraries to compile my code, and this solution was the best for that purpose.I just wanted a quick and dirty workaround... I couldn't run the script from Nikita Volkov: syntax error + it requires a strict format for the jar names.I made this Perl script which works with whatever format for the jar file names, and it generates the dependencies in an xml so it can be copy pasted directly in a pom.If you want to use it, make sure you understand what the script is doing, you may need to change the  folder and the value for the  or ...
Java

What issues / pitfalls must be considered when overriding  and ? () must define an equivalence relation (it must be , , and ). In addition, it must be  (if the objects are not modified, then it must keep returning the same value). Furthermore,  must always return false. () must also be  (if the object is not modified in terms of , it must keep returning the same value).The  between the two methods is:If you override one, then you should override the other.Use the same set of fields that you use to compute  to compute .Use the excellent helper classes  and  from the  library. An example:When using a hash-based  or  such as , , , , or , make sure that the hashCode() of the key objects that you put into the collection never changes while the object is in the collection. The bulletproof way to ensure this is to make your keys immutable, .There are some issues worth noticing if you're dealing with classes that are persisted using an Object-Relationship Mapper (ORM) like Hibernate, if you didn't think this was unreasonably complicated already!If your objects are persisted using an ORM, in many cases you will be dealing with dynamic proxies to avoid loading object too early from the data store. These proxies are implemented as subclasses of your own class. This means that will return . For example:ORMs usually use the getters to force loading of lazy loaded objects. This means that  will be  if  is lazy loaded, even if  forces loading and returns \"John Doe\". In my experience, this crops up more often in  and .Persistent objects often use a  field to hold the key of the object. This field will be automatically updated when an object is first saved. Don't use an id field in . But you can use it in .A pattern I often use isBut: you cannot include  in . If you do, when an object is persisted, its  changes. If the object is in a , you'll \"never\" find it again.In my  example, I probably would use  for  and  plus  (just for paranoia) for . It's okay if there are some risk of \"collisions\" for , but never okay for .A clarification about the .This statement is the result of  being inheritance unfriendly. The JLS (Java language specification) specifies that if  then  must also return . If you omit that statement inheriting classes that override  (and change its behavior) will break this specification.Consider the following example of what happens when the statement is omitted:Doing  Also,  result give out true, as it should.This looks all very good, but look what happens if we try to use both classes:Obviously, this is wrong.If you want to ensure the symmetric condition. a=b if b=a and the Liskov substitution principle call  not only in the case of  instance, but check after for  instance:Which will output:Where, if  is not a reference of , then it might be a be a reference of class  (because you extend it), in this case you call  .For an inheritance-friendly implementation, check out Tal Cohen's solution, Summary:In his book  (Addison-Wesley, 2001), Joshua Bloch claims that \"There is simply no way to extend an instantiable class and add an aspect while preserving the equals contract.\"  Tal disagrees.His solution is to implement equals() by calling another nonsymmetric blindlyEquals() both ways.  blindlyEquals() is overridden by subclasses, equals() is inherited, and never overridden.Example:Note that equals() must work across inheritance hierarchies if the  is to be satisfied.Still amazed that none recommended the guava library for this. There are two methods in super class as java.lang.Object. We need to override them to custom object.Equal objects must produce the same hash code as long as they are equal, however unequal objects need not produce distinct hash codes.If you want get more, please check this link as This is another example,\nHave Fun! @.@There are a couple of ways to do your check for class equality before checking member equality, and I think both are useful in the right circumstances.I use #1 in a  equals implementation, or when implementing an interface that prescribes an algorithm for equals (like the  collection interfaces\u2014the right way to check with with  or whatever interface you're implementing). It's generally a bad choice when equals can be overridden because that breaks the symmetry property.Option #2 allows the class to be safely extended without overriding equals or breaking symmetry.If your class is also , the  and  methods should be consistent too. Here's a template for the equals method in a  class:For equals, look into  by . I love it very much. She's also a great FAQ about . View her other articles  (scroll down to \"Core Java\"), where she also goes on with Part-2 and \"mixed type comparison\". Have fun reading them!equals() method is used to determine the equality of two objects.as int value of 10 is always equal to 10. But this equals() method is about equality of two objects. When we say object, it will have properties. To decide about equality those properties are considered. It is not necessary that all properties must be taken into account to determine the equality and with respect to the class definition and context it can be decided. Then the equals() method can be overridden.we should always override hashCode() method whenever we override equals() method. If not, what will happen? If we use hashtables in our application, it will not behave as expected. As the hashCode is used in determining the equality of values stored, it will not return the right corresponding value for a key.Default implementation given is hashCode() method in Object class uses the internal address of the object and converts it into integer and returns it.Example Code Output:Logically we have: \u21d2 But  vice-versa!One gotcha I have found is where two objects contain references to each other (one example being a parent/child relationship with a convenience method on the parent to get all children).\nThese sorts of things are fairly common when doing Hibernate mappings for example.If you include both ends of the relationship in your hashCode or equals tests it's possible to get into a recursive loop which ends in a StackOverflowException.\nThe simplest solution is to not include the getChildren collection in the methods.
Java

What is an efficient way to implement a singleton pattern in Java?Use an enum:Joshua Bloch explained this approach in his  talk at Google I/O 2008: . Also see slides 30-32 of his presentation (): An  says: Depending on the usage, there are several \"correct\" answers.Since java5 the best way to do it is to use an enum:Pre java5, the most simple case is:Let's go over the code. First, you want the class to be final. In this case, I've used the  keyword to let the users know it is final. Then you need to make the constructor private to prevent users to create their own Foo. Throwing an exception from the constructor prevents users to use reflection to create a second Foo. Then you create a  field to hold the only instance, and a  method to return it. The Java specification makes sure that the constructor is only called when the class is first used.When you have a very large object or heavy construction code AND also have other accessible static methods or fields that might be used before an instance is needed, then and only then you need to use lazy initialization.You can use a  to load the instance. The code would then look like:Since the line  is only executed when the class FooLoader is actually used, this takes care of the lazy instantiation, and is it guaranteed to be thread safe.When you also want to be able to serialize your object you need to make sure that deserialization won't create a copy.The method  will make sure the only instance will be returned, even when the object was serialized in a previous run of your program.The solution posted by Stu Thompson is valid in Java5.0 and later. But I would prefer not to use it because I think it is error prone.It's easy to forget the volatile statement and difficult to understand why it is necessary. Without the volatile this code would not be thread safe anymore due to the double-checked locking antipattern. See more about this in paragraph 16.2.4 of . In short: This pattern (prior to Java5.0 or without the volatile statement) could return a reference to the Bar object that is (still) in an incorrect state.This pattern was invented for performance optimization. But this is really not a real concern anymore. The following lazy initialization code is fast and -more importantly- easier to read.Thread safe in Java 5+:: Pay attention to the  modifier here.  :)  It is important because without it, other threads are not guaranteed by the JMM (Java Memory Model) to see changes to its value.  The synchronization  take care of that--it only serializes access to that block of code.: \n@Bno 's answer details the approach recommended by Bill Pugh (FindBugs) and is arguable better.  Go read and vote up his answer too. I have just summarized all of the awesome answers and wrote it in my words.While implementing Singleton we have 2 options\n1. Lazy loading\n2. Early loadingLazy loading adds bit overhead(lots of to be honest) so use it only when you have a very large object or heavy construction code AND also have other accessible static methods or fields that might be used before an instance is needed, then and only then you need to use lazy initialization.Otherwise choosing early loading is a good choice.Most simple way of implementing Singleton is Everything is good except its early loaded singleton. Lets try lazy loaded singletonSo far so good but our hero will not survive while fighting alone with multiple evil threads who want many many instance of our hero.\nSo lets protect it from evil multi threadingbut it is not enough to protect out hero, Really!!! This is the best we can/should do to help our hero  This is called \"Double-Checked Locking idiom\". It's easy to forget the volatile statement and difficult to understand why it is necessary.\nFor details :  Now we are sure about evil thread but what about the cruel serialization? We have to make sure even while de-serialiaztion no new object is createdThe method  will make sure the only instance will be returned, even when the object was serialized in a previous run of our program.Finally we have added enough protection  against threads and serialization but our code is looking bulky and ugly. Lets give our hero a make overYes this is our very same hero :)\nSince the line  is only executed when the class  is actually used, this takes care of the lazy instantiation, and is it guaranteed to be thread safe.And we have came so far, here is the best way to achieve everything we did is best possible way Which internally will be treated like  That's it no more fear of serialization, threads and ugly code. Also . -Joshua Bloch in \"Effective Java\"      Now you might have realized why ENUMS are considered as best way to implement Singleton and thanks for your patience :)\nUpdated it on my . Forget , it's too problematic. This is the simplest solution:Make sure that you really need it. Do a google for \"singleton anti-pattern\" to see some arguments against it. There's nothing inherently wrong with it I suppose but it's just a mechanism for exposing some global resource/data so make sure that this is the best way. In particular I've found dependency injection more useful particularly if you are also using unit tests because DI allows you to use mocked resources for testing purposes.Don't forget the Singleton is only a Singleton for the Classloader that loaded it. If you are using multiple loaders (Containers) each COULD have its own version of the Singleton.I'm mystified by some of the answers that suggest DI as an alternative to using singletons; these are unrelated concepts. You can use DI to inject either singleton or non-singleton (e.g. per-thread) instances. At least this is true if you use Spring 2.x, I can't speak for other DI frameworks.So my answer to the OP would be (in all but the most trivial sample code) to:This approach gives you a nice decoupled (and therefore flexible and testable) architecture where whether to use a singleton is an easily reversible implementation detail (provided any singletons you use are threadsafe, of course).Really consider why you need a singleton before writing it. There is a quasi-religious debate about using them which you can quite easily stumble over if you google singletons in Java.Personally I try to avoid singletons as often as possible for many reasons, again most of which can be found by googling singletons. I feel that quite often singletons are abused because they're easy to understand by everybody, they're used as a mechanism for getting \"global\" data into an OO design and they are used because it is easy to circumvent object lifecycle management (or really thinking about how you can do A from inside B). Look at things like Inversion of Control (IoC) or Dependency Injection (DI) for a nice middleground.If you really need one then wikipedia has a good example of a proper implementation of a singleton.Following are 3 different approaches1) Enum2) Double checked Locking /Lazy loading3) Static factory methodI use the Spring Framework to manage my singletons.  It doesn't enforce the \"singleton-ness\" of the class (which you can't really do anyway if there are multiple class loaders involved) but provides a really easy way to build and configure different factories for creating different types of objects.Wikipedia has some  of singletons, also in Java. The Java 5 implementation looks pretty complete, and is thread-safe (double-checked locking applied).If you do not need lazy loading then simply tryIf you want lazy loading and you want your Singleton to be thread-safe, try the double-checking pattern As the double checking pattern is not guaranteed to work (due to some issue with compilers, I don't know anything more about that.), you could also try to synchronize the whole getInstance-method or create a registry for all your Singletons. Lazy loading, thread safe with blocking, low performance because of .Lazy loading, thread safe with non-blocking, high performance.I would say Enum singleton Singleton using enum in Java is generally way to declare enum singleton. Enum singleton may contain instance variable and instance method. For simplicity's sake, also note that if you are using any instance method than you need to ensure thread safety of that method if at all it affect the state of object.The use of an enum is very easy to implement and has no drawbacks regarding serializable objects, which have to be circumvented in the other ways.You can access it by , much easier than calling  method on Singleton.Another problem with conventional Singletons are that once you implement  interface, they no longer remain Singleton because  method always return a new instance  like constructor in Java. This can be avoided by using  and discarding newly created instance by replacing with singleton like below This can become even more complex if your Singleton Class maintain state, as you need to make them transient, but with in Enum Singleton, Serialization is guaranteed by JVM.You need  idiom if you need to load the instance variable of a class lazily. \nIf you need to load a static variable or a singleton lazily, you need  idiom. In addition, if the singleton needs to be seriliazble, all other fields needs to be transient and readResolve() method needs to be implemented in order to maintain the singleton object invariant. Otherwise, each time the object is deserialized, a new instance of the object will be created. What readResolve() does is replace the new object read by readObject(), which forced that new object to be garbage collected as there is no variable referring to it.For JSE 5.0 and above take the Enum approach, otherwise use static singleton holder approach ( (a lazy loading approach described by Bill Pugh). Latter solution is also thread-safe without requiring special language constructs (i.e. volatile or synchronized).Various ways to make singleton object:The simplest way to implement a Singleton that is thread-safe is using an EnumThis code works since the introduction of Enum in Java 1.5If you want to code a \u201cclassic\u201d singleton that works in a multithreaded environment (starting from Java 1.5) you should use this one.This is not thread-safe before 1.5 because the implementation of the volatile keyword was different.This implementation instantiates the singleton when the class is loaded and provides thread safety.This is how to implement a simple :This is how to properly lazy create your :Another argument often used against Singletons are their testability problems. Singletons are not easily mockable for testing purposes. If this turns out to be a problem, I like to make the following slight modification:The added  method allows setting a mockup implementation of the singleton class during testing:This also works with early initialization approaches:This has the drawback of exposing this functionality to the normal application too. Other developers working on that code could be tempted to use the \u00b4setInstance\u00b4 method to alter alter a specific function and thus changing the whole application behaviour, therefore this method should contain at least a good warning in it's javadoc.Still, for the possibility of mockup-testing (when needed), this code exposure may be an acceptable price to pay.simplest singleton classI still think after java 1.5, enum is the best available singleton implementation available as it also ensures that even in the multi threaded environments - only one instance is created.and you are done !!!Have a look at this post.From the best answer's \"Singleton\" section,You can also learn the example of Singleton from Java native classes themselves.To achieve this ( TRUE Singleton) ,Useful links: All answers in this post + : Initialization-on-demand holder idiom from wikipedia articleDemonstration of various methods of achieving Singletonoutput:Sometimes a simple \"\" is not enough. Just think of some basic data insertion you want to do.On the other hand you would have to synchronize any method that instantiates the singleton variable as such. Synchronisation is not bad as such, but it can lead to performance issues or locking (in very very rare situations using this example. The solution isNow what happens? The class is loaded via the class loader. Directly after the class was interpreted from a byte Array, the VM executes the  - block. that's the whole secret: The static-block is only called once, the time the given class (name) of the given package is loaded by this one class loader.As we have added the Synchronized keyword before getInstance, we have avoided the race condition in the case when two threads call the getInstance at the same time.
Java

I want to access my current working directory using OutPut:  My output is not correct because C drive is not my current directory.\nNeed help in this regard.This will print a See: Using  and , you can do the following to show what Java thinks is your current path. This for 7 and on, and uses NIO.This outputs  that in my case is where I ran the class from. Constructing paths in a relative way, by not using a leading separator to indicate you are constructing an absolute path, will use this relative path as the starting point.The following works on Java 7 and up (see  for documentation).What makes you think that  is not your current directory? The  property is explicitly to be \"User's current working directory\".To put it another way, unless you start Java from the command line,  probably is your CWD. That is, if you are double-clicking to start your program, the CWD is unlikely to be the directory that you are double clicking from.: It appears that this is only true for old windows and/or Java versions. This is the solution for megenerally, as a File object:you may want to have full qualified string like \"D:/a/b/c\" doing:Use . This works fine in JAR files as well. You can obtain  by  and the  in turn can be obtained by .I'm on Linux and get same result for both of these approaches:I hope you want to access the current directory including the package i.e. If your Java program is in  and you want to print until  then you can try the following code: This code is only tested in Windows with Oracle JRE.On  when you run a  file from , these both will return the same : , no matter, where youre jar file is. It depends just on what current directory are you using with your terminal, when you start the jar file.If your  with  would be called , then try:This will return a  with  of the  file.I had   files in the same directory . I wanted from the one  file to start the other  file which is in the same directory.The problem is that when you start it from the  the current directory is .\ud83c\udf42..\ud83c\udf42:None of the answers posted here worked for me.  Here is what did work:Edit:  The final version in my code:assume that you're trying to run your project inside eclipse, or netbean or stand alone from command line. I have write a method to fix itTo use, everywhere you want to get base path to read file, you can pass your anchor class to above method, result may be the thing you need :DBest,Using Windows user.dir returns the directory as expected, but NOT when you start your application with elevated rights (run as admin), in that case you get C:\\WINDOWS\\system32Current working directory is defined differently in different Java implementations. For certain version prior to Java 7 there was no consistent way to get the working directory. You could work around this by launching Java file with  and defining a variable to hold the infoSomething likeThat's not quite right, but you get the idea. Then ...Here's what I did to get the current working directory of my JavaFX app running on Windows 7 (Java 8).this is current directory name    this is current directory path
Java

I'm looking to make my code more readable as well as use tooling like IDE code inspection and/or static code analysis (FindBugs and Sonar) to avoid NullPointerExceptions.  Many of the tools seem incompatible with each others' // annotation and listing all of them in my code would be terrible to read.  Any suggestions of which one is the 'best'?  Here is the list of equivalent annotations I've found:I very much like the , which is an implementation of type annotations () which is used to implement defect checkers like a nullness checker.  I haven't really tried any others to offer any comparison, but I've been happy with this implementation.I'm not affiliated with the group that offers the software, but I am a fan.Four things I like about this system:I use the IntelliJ one, because I'm mostly concerned with IntelliJ flagging things that might produce a NPE. I agree that it's frustrating not having a standard annotation in the JDK. There's talk of adding it, it might make it into Java 7. In which case there will be one more to choose from!According to the  JSR-308 type annotations are deferred to Java 8.  JSR-305 annotations are not even mentioned.  There is a bit of info on the state of JSR-305 in an  of the latest JSR-308 draft.  This includes the observation that JSR-305 annotations seem to be abandoned.  The JSR-305 page also shows it as \"inactive\".In the mean time, the pragmatic answer is to use the annotation types that are supported by the most widely used tools ... and be prepared to change them if the situation changes.In fact, JSR-308 does not define any annotation types/classes, and it looks like they think it is out of scope.  (And they are right, given the existence of JSR-305).However, if JSR-308 really looks like making it into Java 8, it wouldn't surprise me if interest in JSR-305 revived.  AFAIK, the JSR-305 team hasn't formally abandoned their work.  They have just been quiet for 2+ years.It is interesting that Bill Pugh (the tech lead for JSR-305) is one of the guy behind FindBugs.For Android projects you should use  and . These and other helpful Android-specific annotations are available in the .From :JSR305 and FindBugs are authored by the same person. Both are poorly maintained but are as standard as it gets and are supported by all major IDEs. The good news is that they work well as-is.Here is how to apply @Nonnull to all classes, methods and fields by default.\nSee  and 2. Add the annotation to each package: : As of December 12th, 2012  is listed as \"Dormant\". According to the documentation:It looks like   making it into JDK 8 and although the JSR does not define @NotNull, the accompanying  does. At the time of this writing, the Maven plugin is unusable due to this bug: If anyone is just looking for the IntelliJ classes: you can get them from the maven repository withJust pointing out that the Java Validation API () doesn't come with a  annotation, which is very valuable in a static analysis context. It makes sense for runtime bean validation as this is the default for any non-primitive field in Java (i.e. nothing to validate/enforce). For the purposes stated that should weigh towards the alternatives.Eclipse has also its own annotations.See at  for details.Since Oracle decided not to standardize @NonNull (and @Nullable) for the moment, I'm afraid there is no good answer. All we can do is to find a pragmatic solution and mine is as follows:From a purely stylistic standpoint I would like to avoid any reference to IDE, framework or any toolkit except Java itself.This rules out:Which leaves us with either javax.validation.constraints or javax.annotation.\nThe former comes with JEE. If this is better than javax.annotation, which  might come eventually with JSE or never at all, is a matter of debate.\nI personally prefer javax.annotation because I wouldn't like the JEE dependency.This leaves us withwhich is also the shortest one.There is only one syntax which would even be better: java.annotation.Nullable. As other packages graduated\nfrom javax to java in the past, the javax.annotation would\nbe a step in the right direction.I was hoping that they all have basically the same trivial implementation,\nbut a detailed analysis showed that this is not true.First for the similarities:The @NonNull annotations all have the line except for The @Nullable annotations all have the lineexcept for (again) the org.jetbrains.annotations with their trivial implementation.For the differences:A striking one is thatall have runtime annotations  (@Retention(RUNTIME), whileare only compile time (@Retention(CLASS)).As described in  the impact of runtime annotations\nis smaller than one might think, but they have the benefit\nof enabling tools to do runtime checks in addition to the\ncompile time ones. Another important difference is  in the code the annotations can be used.\nThere are two different approaches. Some packages use JLS 9.6.4.1 style contexts. The following table gives an overview:org.eclipse.jdt.annotation, javax.annotation and org.checkerframework.checker.nullness.qual use the contexts defined in \nJLS 4.11, which is in my opinion the right way to do it.This leaves us with in this round.To help you to compare further details yourself I list the code of every annotation below.\nTo make comparison easier I removed comments, imports and the @Documented annotation.\n(they all had @Documented except for the classes from the Android package).\nI reordered the lines and @Target fields and normalized the qualifications.For completeness, here are the @Nullable implementations:The following two packages have no @Nullable, so I list them separately\nlombok has a pretty boring @NonNull.\nIn javax.validation.constraints the @NonNull is actually a @NotNull\nand it has a longish implementation.Form my experience javax.annotation is at least supported by Eclipse and the Checker Framework out of the box.My ideal annotation would be the java.annotation syntax with the Checker Framework implementation.If you don't intend to use the Checker Framework  the  (JSR-305) is still your best bet for the time being.If you are willing to buy into the Checker Framework just use\ntheir org.checkerframework.checker.nullness.qual.While waiting for this to be sorted out upstream (Java 8?), you could also just define your own project-local  and  annotations. This can be useful also in case you're working with Java SE, where   by default.This would admittedly largely be for decorative or future-proofing purposes, since the above obviously doesn't in and of itself add any support for the static analysis of these annotations.Unfortunately,  will not add more values than this project local Not Null suggestion here will not come with a single default annotation or its own  framework.\nSimilar to Find-bugs or , this JSR is poorly maintained by a small bunch of mostly academic teams. No commercial power behind it, thus  launches  (Early Draft Review at ) NOW, while  is supposed to ship in less than 6 months:-O\nSimilar to  btw. but unlike  has taken charge of that now away from its founders to minimize harm it'll do to the Java Platform.Every project, vendor and academic class like the ones behind the  and  will create its own proprietary checker annotation.Making source code incompatible for years to come, until a few popular compromises could be found and maybe added to  or , or via frameworks like  or ;-)If you're developing for android, you're  tied to Eclipse (edit: at time of writing, not anymore), which has its own annotations.  It's included in Eclipse 3.8+ (Juno), but disabled by default.You can enable it at Preferences > Java > Compiler > Errors/Warnings > Null analysis (collapsable section at the bottom).Check \"Enable annotation-based null analysis\" has recommendations on settings.  However, if you have external projects in your workspace (like the facebook SDK), they may not satisfy those recommendations, and you probably don't want to fix them with each SDK update ;-)I use:This answer is Android specific. Android has support package called . This provides  of  annotations and also provides  like ,  etc.To add  package, add the following dependency in your build.gradle:and then use:There is another way to do this in Java 8.\nI am doing 2 things to accomplish what I needed:Example:So my question is, do we even need to annotate when using java 8? Edit: I found out later that some consider a bad practice to use  in arguments, there is a good discussion with pros and cons here If you are working on a big project, you may be better of creating   and/or  annotations.For example:If you use the correct , then the annotations . From that point of view, it is just an  thing. Even though this is not a strict science, I think it makes most sense to use an  class for it.Doesn't sun have their own now? What's this:\nThis seems to be packaged with all the versions of Java I've used within the last few years. As mentioned in the comments below, you probably don't want to use these. In that case, my vote is for the IntelliJ jetbrains annotations!Another option is the annotations provided with ANTLR 4. Following , the artifact containing the  and  annotations includes an annotation processor that produces compile-time errors and/or warnings in the event one of these attributes is misused (for example, if both are applied to the same item, or if  is applied to item with a primitive type). The annotation processor provides additional assurance during the software development process that the information conveyed by the application of these annotations is accurate, including in cases of method inheritance.Distinguish between static analysis and runtime analysis. Use static analysis for internal stuff, and runtime analysis for the public boundaries of your code.For things that should not be null:For things that may be null (No runtime check required):This should give the best result: warnings in the IDE, errors by Findbugs and checkerframework, meaningful runtime exceptions.Some explanations:If you are building your application using Spring Framework I would suggest using  comming from  packaged in following dependency:The main advantage of this annotation is that Spring provides support for both method parameters and class fields annotated with . All you need to do to enable support is:Example:When you try calling method doSomething and pass null as the parameter value, spring (by means of HibernateValidator) will throw . No need for manuall work here.You can also validate return values.Another important benefit of  comming for Beans Validation Framework is that at the moment it is still developed and new features are planned for new version 2.0.What about ? There is nothing like that in Beans Validation 1.1. Well, I could arguee that if you decide to use  than everything which is NOT annotated with  is effectively \"nullable\", so the  annotation is useless.
Java

I have an  in Java for the cardinal & intermediate directions:How can I write a  loop that iterates through each of these  values?You can call the  method on your enum.This  method is . So it is not listed on  doc. Enum#values():You can do this as follows:Prior to Java 8 we need to print the values using for loop, like:But in Java 8 we can also make use of lambda and streams ():If you don't care about the order this should work:Java8 from Java5+ Try to use a for each
Java

Given the 2  implementations below, which one is preferred:or?More importantly, given we have only 3 properties it might not make a difference, but at what point would you switch from  concat to  ?Version 1 is preferable because it is shorter and  - no performance difference whatsoever.At the point where you're concatenating in a loop - that's usually when the compiler can't substitute  by itself.The key is whether you are writing a single concatenation all in one place or accumulating it over time.For the example you gave, there's no point in explicitly using StringBuilder. (Look at the compiled code for your first case.)But if you are building a string e.g. inside a loop, use StringBuilder.To clarify, assuming that hugeArray contains thousands of strings, code like this:is very time- and memory-wasteful compared with:I prefer:...because it's short and readable.I would  optimize this for speed unless you use it inside a loop with a very high repeat count  have measured the performance difference.I agree, that if you have to output a lot of parameters, this form can get confusing (like one of the comments say). In this case I'd switch to a more readable form (perhaps using  of apache-commons - taken from the answer of matt b) and ignore performance again.In most cases, you won't see an actual difference between the two approaches, but it's easy to construct a worst case scenario like this one:The output is:The problem is that to += append to a string reconstructs a new string, so it costs something linear to the length of your strings (sum of both).So - to your question:The second approach would be faster, but it's less readable and harder to maintain.\nAs I said, in your specific case you would probably not see the difference.I also had clash with my boss on the fact whether to use append or +.As they are using Append(I still cant figure out as they say every time a new object is created).\nSo I thought to do some R&D.Although I love Michael Borgwardt explaination but just wanted to show an explanation if somebody will really need to know in future.and disassembly of above class comes out asFrom the above two codes you can see Michael is right.In each case only one SB object is created.Since Java 1.5, simple one line concatenation with \"+\" and StringBuilder.append() generate exactly the same bytecode.So for the sake of code readability, use \"+\".2 exceptions : Using latest version of Java(1.8) the disassembly() shows the optimization introduced by compiler.  as well  will generate very similar code. However, it will be worthwhile inspecting the behaviour if we are using  in a for loop.Java: ByteCode:( loop excerpt)Java:ByteCdoe:( loop excerpt)There is a bit of  though. In first case, where  was used, new  is created for each for loop iteration and generated result is stored by doing a  call(29 through 41). So you are generating intermediate Strings that your really do not need while using  operator in  loop.Apache Commons-Lang has a  class which is super easy to use. It does a nice job of both handling the append-logic as well as formatting of how you want your toString to look.Will return output that looks like .Or in a more condensed form using chaining:Or if you want to use reflection to include every field of the class:You can also customize the style of the ToString if you want.For performance reasons, the use of  ( concatenation) is discouraged. The reason why is: Java  is an immutable, every time a new concatenation is done a new  is created (the new one has a different fingerprint from the older one already  ). Creating new strings puts pressure on the GC and slows down the program: object creation is expensive. Below code should make it more practical and clear at the same time. Results for a run are reported below. Not considering the results for 1 concatenation (JIT was not yet doing its job), even for 10 concatenations the performance penalty is relevant; for thousands of concatenations, the difference is huge. Lessons learned from this very quick experiment (easily reproducible with the above code): never use the  to concatenate strings together, even in very basic cases where a few concatenations are needed (as said, creating new strings is expensive anyway and puts pressure on the GC). In Java 9 the version 1 should be faster because it is converted to  call. More details can be found in :Make the toString method as readable as you possibly can!The sole exception for this in my book is if you can  to me that it consumes significant resources :)  (Yes, this means profiling)Also note that the Java 5 compiler generates faster code than the handwritten \"StringBuffer\" approach used in earlier versions of Java.  If you use \"+\" this and future enhancements comes for free.Can I point out that if you're going to iterate over a collection and use StringBuilder, you may want to check out  and  (in different flavours) ? Regardless of performance, it'll save you having to create StringBuilders and for loops for what seems like the  time.I compared four different approach to compare the performance. I exactly don't know what happens to gc, but the important thing for me is time. Compiler is important factor here.I used jdk1.8.0_45 under window8.1 platform.There seems to be some debate whether using StringBuilder is still needed with current compilers. So I thought I'll give my 2 cents of experience. I have a  result set of 10k records (yes, I need all of them in one batch.) Using the + operator takes about 5 minutes on my machine with . Using  takes less than a second for the same query. So the difference is huge. Inside a loop  is much faster. For simple strings like that I prefer to use In order, I would say the preferred method of constructing a string is using StringBuilder, String#concat(), then the overloaded + operator.  StringBuilder is a significant performance increase when working large strings just like using the + operator is a large decrease in performance (exponentially large decrease as the String size increases).  The one problem with using .concat() is that it can throw NullPointerExceptions.
Java

How are JSP and Servlet related to each other? Is JSP some kind of Servlet? How are JSP and JSF related to each other? Is JSF some kind of prebuild UI based JSP like ASP.NET-MVC?JSP is a  running on the server machine which allows you to write template text in client side languages (like HTML, CSS, JavaScript, ect.). JSP supports , which are backed by pieces of Java code that let you control the page flow or output dynamically. A well-known taglib is . JSP also supports , which can be used to access backend data (via attributes available in the page, request, session and application scopes), mostly in combination with taglibs.When a JSP is requested for the first time or when the web app starts up, the servlet container will compile it into a class extending  and use it during the web app's lifetime. You can find the generated source code in the server's work directory. In for example , it's the  directory. On a JSP request, the servlet container will execute the compiled JSP class and send the generated output (usually just HTML/CSS/JS) through the web server over a network to the client side, which in turn displays it in the web browser.Servlet is a  running on the server machine, which intercepts requests made by the client and generates/sends a response. A well-known example is the  which provides methods to hook on  requests using the popular  such as  and . You can configure s to listen to a certain HTTP URL pattern, which is configurable in , or more recently with , with  annotation.When a Servlet is first requested or during web app startup, the servlet container will create an instance of it and keep it in memory during the web app's lifetime. The same instance will be reused for every incoming request whose URL matches the servlet's URL pattern. You can access the request data by  and handle the response by . Both objects are available as method arguments inside any of the overridden methods of , such as  and .JSF is a  which is built on top of the Servlet API and provides  via taglibs which can be used in JSP or any other Java based view technology such as . Facelets is much more suited to JSF than JSP. It namely provides great  such as , while JSP basically only offers the  for templating, so that you're forced to create custom components with raw Java code (which is a bit opaque and a lot of tedious work in JSF) when you want to replace a repeated group of components with a single component. Since JSF 2.0, JSP has been deprecated as view technology in favor of Facelets.As being a MVC () framework, JSF provides the  as the sole request-response . It takes all the standard and tedious HTTP request/response work from your hands, such as gathering user input, validating/converting them, putting them in model objects, invoking actions and rendering the response. This way you end up with basically a JSP or Facelets (XHTML) page for  and a JavaBean class as . The JSF components are used to bind the view with the model (such as your ASP.NET web control does) and the  uses the  to do all the work.See See JSP is a specialized kind of servlet.JSF is a set of tags you can use with JSP.JSP and JSF both looks same, As Per Application Requirements goes, JSP is more suited for request - response based applications. JSF is targetted for richer event based Web applications. I see event as much more granular than request/response. JSP page is converted to servlet, and it has only minimal behaviour.JSF page is converted to components tree(by specialized FacesServlet) and it follows component lifecycle defined by spec. [  ]There are also situations where you can favor JSP over JSF. The application nature should be the deciding factor to choose the technology. If you have a rich GUI interaction and lot of Java scripting needed then favor JSF. Basically if your GUI app architecture is like Component oriented & even driven like Swing then JSF is the best.If the application is just a plain form submitting, not much of GUI interaction needed, then JSP could do well if learning a new tech is an overhead and also complex framework is unnecessary.Servlet - it's java server side layer.that is true that JSP is converted into servlet at the time of execution, and JSF is totally new thing in order to make the webpage more readable as JSF allows to write all the programming structures in the form of tag.The basic difference between Servlets and JSP is that in Servlets we write java code and in that we embed HTML code and there is just reverse case with JSP .\nIn JSP we write HTML code and in that we embed java code using tags provided by JSP. is java technology which enables Web developers and designers to rapidly develop and easily maintain, information-rich, dynamic Web pages that leverage existing business systems.  JSP technology separates the user interface from content generation, enabling designers to change the overall page layout without altering the underlying dynamic content. is the first non JSP page declaration language designed for  which provided a simpler and more powerful programming model to JSF developers as compare to JSP. It resolves different issues occurs in JSP for web applications development. Here is a table that compares the features of scriplets and facelets:\nJSF is an advanced framework wherein its very easy to implement Model-View-Controller (MVC) based architecture for projects. Main advantage of JSF over JSP is the easy dynamic rendering of the components on the browser based upon conditions and easy integration of ajax events.The front end of the JSF application i.e. xhtml files are the ones which are shown to the user via browser. These xhtml files internally invoke managed beans e.g. controllers wherein actual application logic is written.The controllers internally invoke various services which communicate with database (using Hibernate or JPA API). This is how the flow happens in short.JSF is also used in combination with RichFaces which is a framework for giving rich look and feel to your web application. JSF + RichFaces + Hibernate/JPA is a good technology to learn for sure !Jsp is also having in built servlet code which don't need any external compilation it can be run directly run. Changes will take effect in jsp directly in a browser.Servlet need to be compiled (i.e it will have specific class creation)Jsf is a view component of MVC FrameworkJSP stands for JAVA SERVER PAGE........ \njsp is not a servlet.\nJsp uses code and HTML tag both in itself you dont need to make a HTML and a servlet seprately.Jsp are playing magnificent role in web application.\nServlet is a java class plays an role to make your HTML page from static to dynamic .JSPs are the View component of MVC (Model View Controller).  The Controller takes the incoming request and passes it to the Model, which might be a bean that does some database access.  The JSP then formats the output using HTML, CSS and JavaScript, and the output then gets sent back to the requester.JSP have it's own life cycle\njsp_init()\njsp_service()\njsp_destroyAfter first request JSP convert to .java file. There is three type of tag we are using\n1.)ScriptlessHere developer can declare all those things which developer want to take the data  2.)Expression tagHere developer can use some print related data3.)DeclarationHere developer can declare some method related data.Servlet have it's own life cycle.After first request container will read the data from web.xml file\nthen after out welcome fill will be display.\nNow onward after performing action it will search the url and after this process it will search the particular servlet there it self. service operation will perform.JSF have it's own ui and it's life cycle can perform in six way,For ui here for table here we are using panel grid and there is different faces for this that is.
Java

What is the difference between ,  and  in Java? \nI don't see any difference in the output as all the three has  and . What are s?All three classes implement the  interface and offer mostly the same functionality. The most important difference is the order in which iteration through the entries will happen: is the generic name for hash-based maps. In the context of the Java API,\n is an obsolete class from the days of Java 1.1 before the collections framework existed. It should not be used anymore, because its API is cluttered with obsolete methods that duplicate functionality, and its methods are synchronized (which can decrease performance and is generally useless). Use  instead of Hashtable. I prefer visual presentation: All three represent mapping from unique keys to values, and therefore implement the  interface.Just some more input from my own experience with maps, on when I would use each one:See where each class is in the class hierarchy in the following diagram (). TreeMap implements  and  while  doesn't. is obsolete and the corresponding  class should be used.\nLook at how performance varying..\nTree map which is an implementation of Sorted map. The complexity of the put, get and containsKey operation is O(log n) due to the Natural ordering@Amit:  is an interface whereas  is a class which implements the  interface. That means if follows the protocol which  asks its implementers to do.\nA tree unless implemented as search tree, can't give you ordered data because tree can be any kind of tree. So to make TreeMap work like Sorted order, it implements SortedMap ( e.g, Binary Search Tree - BST, balanced BST like AVL and R-B Tree , even Ternary Search Tree - mostly used for iterative searches in ordered way ).In NUT-SHELL\n : gives data in O(1) , no ordering : gives data in O(log N), base 2. with ordered keys : is Hash table with linked list (think of indexed-SkipList) capability to store data in the way it gets inserted in the tree. Best suited to implement LRU ( least recently used ).Let me put it simple:These are different implementations of the same interface. Each implementation has some advantages and some disadvantages (fast insert, slow search) or vice versa.For details look at the javadoc of , , .All offer a key->value map and a way to iterate through the keys. The most important distinction between\nthese classes are the time guarantees and the ordering of the keys.Imagine you passed an empty TreeMap, HashMap, and LinkedHashMap into the following function:The output for each will look like the results below.For HashMap, the output was, in my own tests, { 0, 1, -1}, but it could be any ordering. There is no guarantee on the\nordering.\nTreemap,the output was,{ -1, 0, 1}\nLinkedList,the output was,{ 1, -1, 0}All three classes ,  and  implements  interface, and represents mapping from unique key to values. Ref: \ncan contain one null key.HashMap maintains no order. TreeMap can not contain any null key.TreeMap maintains ascending order.LinkedHashMap can be used to maintain insertion order, on which keys are inserted into Map or it can also be used to maintain an access order, on which keys are accessed.::1) HashMap map = new HashMap();2) TreeMap map = new TreeMap();3) LinkedHashMap map = new LinkedHashMap();
Java

As part of my requirement I need to convert the given decimal value which is measured in 10ms ticks into seconds. Example values are: 437540, 1207959583, 9468Need some help in how to convert this value into seconds using Java?There are 1000ms in a second.  is . Divide the number of  ticks by  and you'll have the number of seconds.
Java

Is there a function built into Java that capitalizes the first character of each word in a String, and does not affect the others?Examples:*( would be find too, but I don't expect it to be THAT smart.)A quick look at the  reveals only  and , which of course do not provide the desired behavior. Naturally, Google results are dominated by those two functions. It seems like a wheel that must have been invented already, so it couldn't hurt to ask so I can use it in the future.  (from )(Note: if you need  to become , then use  instead)If you're only worried about the first letter of the first word being capitalized:The following method converts all the letters into upper/lower case, depending on their position near a space or other special chars.Try this very simple wayexample givenString=\"ram is good boy\"Output will be: Ram Is Good BoyI've written a small Class to capitalize all the words in a String. Optional , each one with its behavior (capitalize before, after, or both, to handle cases like );Optional ; Don't breaks with .Output: Note: first letter will always be capitalized (edit the source if you don't want that).Please share your comments and help me to found bugs or to improve the code... Code:Using  make it very simple.Use the Split method to split your string into words, then use the built in string functions to capitalize each word, then append together. Pseudo-code (ish)In the end string looks something like\n\"The Sentence You Want To Apply Caps To\"This might be useful if you need to capitalize titles. It capitalizes each substring delimited by , except for specified strings such as  or . I haven't ran it yet because it's late, should be fine though. Uses Apache Commons  at one point. You can substitute it with a simple loop if you wish.im using this function i think is faster in performance.: HelloThere are many how to convert the first letter of the first word being capitalized. I have an idea. It's very simple:Here is a simple functionIf I'm not too late to the party here's my answer:This is just another way of doing it:Resuable Method for intiCap}I'm not sure how to use this SO answer box yet, but here is my solution.  I ran across this problem tonight and decided to search it. I found an answer by Neelam Singh that was almost there so I decided to fix the issue (broke on empty strings) and causes system crash.  The method you are looking for is named capString(String s) below. \nIt turns \"It's only 5am here\" into \"It's Only 5am Here\". The code is pretty well commented, so enjoy. Cheers!package com.lincolnwdaniel.interactivestory.model;public class StringS {}I made a solution in Java 8 that is imho more readable.The Gist for this solution can be found here. I decided to add one more solution for capitalizing words in a string:Function:Example call:Result:Did you mean ?For those of you using Velocity in your MVC, you can use the  method from .The Short and Precise way is as follows: without error if you try and change the name value to the three of values .Error freethis one work for Surname case..\nwith different type of separator, and keep the same sepator\njean-frederic  --> Jean-Frederic\njean frederic  --> Jean Fredericthe code work with GWT client side.If you prefer Guava...try this I had a requirement to make a generic toString(Object obj) helper class function, where I had to convert the fieldnames into methodnames - getXXX() of the passed Object. Here is the code And my toString() utility is like this
Java

I have a Spring  class () that has an  field (), but the field is  when I try to use it. The logs show that both the  bean and the  bean are being created, but I get a  whenever I try to call the  method on my service bean. Why isn't Spring autowiring the field?Controller class:Service class:Service bean that should be autowired in  but it isn't:When I try to , I get this exception:The field annotated  is  because Spring doesn't know about the copy of  that you created with  and didn't know to autowire it. has three main logical components: a registry (called the ) of components (beans) that are available to be used by the application, a configurer system that injects objects' dependencies into them by matching up the dependencies with beans in the context, and a dependency solver that can look at a configuration of many different beans and determine how to instantiate and configure them in the necessary order.The IoC container isn't magic, and it has no way of knowing about Java objects unless you somehow inform it of them. When you call , the JVM instantiates a copy of the new object and hands it straight to you--it never goes through the configuration process. There are three ways that you can get your beans configured.I have posted all of this code, using Spring Boot to launch, at ; you can look at a full running project for each approach to see everything you need to make it work. The most preferable option is to let Spring autowire all of your beans; this requires the least amount of code and is the most maintainable. To make the autowiring work like you wanted, also autowire the  like this:If you need to create a new instance of your service object for different requests, you can still use injection by using .If you really need objects created with  to be autowired, you can  to inject your objects. This approach inserts code into your object's constructor that alerts Spring that it's being created so that Spring can configure the new instance. This requires a bit of configuration in your build (such as compiling with ) and turning on Spring's runtime configuration handlers ( with the JavaConfig syntax). This approach is used by the Roo Active Record system to allow  instances of your entities to get the necessary persistence information injected.This approach is suitable only for interfacing with legacy code in special situations. It is nearly always preferable to create a singleton adapter class that Spring can autowire and the legacy code can call, but it is possible to directly ask the Spring application context for a bean.To do this, you need a class to which Spring can give a reference to the  object:Then your legacy code can call  and retrieve the beans it needs:If you are not coding a web application, make sure your class in which @Autowiring is done is a spring bean. Typically, spring container won't be aware of the class which we might think of as a spring bean. We have to tell the Spring container about our spring classes.This can be achieved by configuring in appln-contxt or  is to annotate class as  and please do not create the annotated class using new operator.\nMake sure you get it from Appln-context as below.I once encountered the same issue when I was not quite used to . The  field of one of my beans is null at runtime.The root cause is, instead of using the auto-created bean maintained by the Spring IoC container (whose  field is  properly injected), I am  my own instance of that bean type and using it. Of course this one's  field is null because Spring has no chance to inject it.Your problem is new (object creation in java style)With annotation , ,  beans are created in the\n    application context of Spring when server is started. But when we create objects \n    using new operator the object is not registered in  application context which  is already created. For Example Employee.java class i have used.Check this out:Actually you should use either JVM managed Objects or Spring managed Object to invoke methods.\nfrom your above code in your controller class you are creating new object to call your service class which have auto wired object.so it won't work that way. solution is make this MileageFeeCalculator as autowired object in Controller itself.Change your Controller class like below.I make Spring inject  in this bean:You can put this code also in the main application class if you want.Other classes can use it like this:In this way  (also intantiated with ) and .It seems to be rare case but here is what happened to me:We used  instead of  which is javaee standard supported by spring. Every places it worked fine and the beans injected correctly, instead of one place. The bean injection seems the sameAt last we found that the error was that we (actually, the eclipse ide out complete feature) imported  instead of  !So to summarize, make sure that your annotations (, ,  ,... ) have correct packages!Another solution would be putting call:\n\nTo MileageFeeCalculator constructor like this:You can also fix this issue using @Service annotation on service class and passing the required bean classA as a parameter to the other beans classB constructor and annotate the constructor of classB with @Autowired. Sample snippet here :I think you have missed to instruct spring to scan classes with annotation. You can use  on the configuration class of your spring application to instruct spring to scan. etc annotations add meta description.\n Spring only injects instances of those classes which are either created as bean or marked with annotation.Classes marked with annotation need to be identified by spring before injecting,  instruct spring look for the classes marked with annotation. When Spring finds  it searches for the related bean, and injects the required instance.Adding annotation only, does not fix or facilitate the dependency injection, Spring needs to know where to look for.
Java

I receive following error when I save the object using Hibernate You should include  (if using xml) or  (if using annotations) on your collection mapping.This happens because you have a collection in your entity, and that collection has one or more items which are not present in the database. By specifying the above options you tell hibernate to save them to the database when saving their parent.I believe this might be just repeat answer, but just to clarify, I got this on a  mapping as well as a .  In both cases, it was the fact that the  object I was adding to the  wasn't saved in the database yet.  So when I added the  to the , then saved the , Hibernate would toss the  message when saving the Parent.Adding in the  on the  reference to the  solved the problem in both cases.  This saved the  and the .Sorry for any repeat answers, just wanted to further clarify for folks.This happens when saving an object when Hibernate thinks it needs to save an object that is associated with the one you are saving. I had this problem and did not want to save changes to the referenced object so I wanted the cascade type to be NONE. The trick is to ensure that the ID and VERSION in the referenced object is set so that Hibernate does not think that the referenced object is a new object that needs saving. This worked for me.Look through all of the relationships in the class you are saving to work out the associated objects (and the associated objects of the associated objects) and ensure that the ID and VERSION is set in all objects of the object tree.Or, if you want to use minimal \"powers\" (e.g. if you don't want a cascade delete) to achieve what you want, use This isn't the only reason for the error. I encountered it just now for a typo error in my coding, which I believe, set a value of an entity which was already saved.I spotted the error by finding exactly which variable caused the error (in this case ). I used a  around the whole block of code that saved the entity and printed the traces.This occurred for me when persisting an entity in which the existing record in the database had a NULL value for the field annotated with @Version (for optimistic locking). Updating the NULL value to 0 in the database corrected this.If your collection is nullable just try: In my case it was caused by not having  on the  side of the bidirectional relationship. To be more precise, I had  on  side and did not have it on . Adding  to  resolved the issue.\n side: (caused the problem) (fixed by adding )To add my 2 cents, I got this same issue when I m accidentally sending  as the ID. Below code depicts my scenario .Here I m setting the existing department id to a new employee instance without actually getting the department entity first, as I don't want to another select query to fire.In some scenarios,  PKID is coming as  from calling method and I m getting the same error. i get this error when i use but it works with no problem when I use One other possible reason: in my case, I was attempting to save the child before saving the parent, on a brand new entity.The code was something like this in a User.java model:The setNewPassword() method creates a PasswordHistory record and adds it to the history collection in User. Since the create() statement hadn't been executed yet for the parent, it was trying to save to a collection of an entity that hadn't yet been created. All I had to do to fix it was to move the setNewPassword() call after the call to create().Simple way of solving this issue is save the both entity.\nfirst save the child entity and then save the parent  entity.\nBecause parent entity is depend on child entity for the foreign key value.Below simple exam of one to one relationshipbeside all other good answers, this could happen if you use  to persist an object and accidentally forget to use merged reference of the object in the parent class. consider the following exampleIn this case, you merge  but forget to use merged object of . to solve the problem you must rewrite the code like this.There is another possibility that can cause this error in hibernate. You may set an unsaved reference of your object  to an attached entity  and want to persist object . Even in this case, you will get the aforementioned error.Don't use  until you really have to.  and  have bidirectional  relation. Then the following code would work fine  while if the object is just a \"new\" one, then it would throw the same error.One possible cause of the error is the inexistence of the setting of the value of the parent entity ; for example for a department-employees relationship you have to write this in order to fix the error :
Java

Why doesn't Java include support for unsigned integers?  It seems to me to be an odd omission, given that they allow one to write code that is less likely to produce overflows on unexpectedly large input.  Furthermore, using unsigned integers can be a form of self-documentation, since they indicate that the value which the unsigned int was intended to hold is never supposed to be negative.  Lastly, in some cases, unsigned integers can be more efficient for certain operations, such as division.  What's the downside to including these?This is from an , about simplicity:Reading between the lines, I think the logic was something like this:Mostly, I'd say it was a reasonable decision. Possibly, I would have:Still, with a bit of kludging, operations on unsigned values up to 32 bits aren't tooo bad, and most people don't need unsigned 64-bit division or comparison.This is an older question and pat did briefly mention char, I just thought I should expand upon this for others who will look at this down the road. Let's take a closer look at the Java primitive types: - 8-bit signed integer - 16-bit signed integer - 32-bit signed integer - 64-bit signed integer - 16-bit character (unsigned integer)Although  does not support  arithmetic, it essentially can be treated as an  integer. You would have to explicitly cast arithmetic operations back into , but it does provide you with a way to specify  numbers.Yes, there isn't direct support for unsigned integers (obviously, I wouldn't have to cast most of my operations back into char if there was direct support). However, there certainly exists an unsigned primitive data type. I would liked to have seen an unsigned byte as well, but I guess doubling the memory cost and instead use char is a viable option.With JDK8 there are new APIs for  and  which provide helper methods when treating  and  values as unsigned values.Additionally,  provides a number of helper methods to do similar things for at the integer types which helps close the gap left by the lack of native support for  integers.As soon as signed and unsigned ints are mixed in an expression things start to get messy and you probably  lose information. Restricting Java to signed ints only really clears things up. I\u2019m glad I don\u2019t have to worry about the whole signed/unsigned business, though I sometimes do miss the 8th bit in a byte.This guy says because the C standard defines operations involving unsigned and signed ints to be treated as unsigned. This could cause negative signed integers to roll around into a large unsigned int, potentially causing bugs.Java does have unsigned types, or at least one:  char is an unsigned short.  So whatever excuse Gosling throws up it's really just his ignorance why there are no other unsigned types.Also Short types:  shorts are used all the time for multimedia.  The reason is you can fit 2 samples in a single 32-bit unsigned long and vectorize many operations.   Same thing with 8-bit data and unsigned byte.  You can fit 4 or 8 samples in a register for vectorizing.I think Java is fine as it is, adding unsigned would complicate it without much gain.\nEven with the simplified model most Java programmers don't know how the basic numeric types behave, just read the book \"Java Puzzlers\" and you will know what I mean.As for practical advice:If your values are somewhat arbitrary size and don't fit into int, use long.\nIf they don't fit into long use BigInteger.Use the smaller types only for arrays when you need to save space.If you need exactly 64/32/16/8 bits, use long/int/short/byte and stop worrying about the sign, except for division and comparison.See also  answer.With  it does have some support for them.We may yet see full support of unsigned types in Java despite Gosling's concerns.I know this post is too old; however for your interest, in Java 8 and later, you can use the int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 2-1. Use the Integer class to use int data type as an unsigned integer and Static methods like compareUnsigned, divideUnsigned etc have been added to the Integer class to support the arithmetic operations for unsigned integers.I've heard stories that they were to be included close to the orignal Java release. Oak was the precursor to Java, and in some spec documents there was mention of usigned values. Unfortunately these never made it into the Java language. As far as anyone has been able to figure out they just didn't get implemented, likely due to a time constraint.I once took a C++ course with someone on the C++ standards committee who implied that Java made the right decision to avoid having unsigned integers because (1) most programs that use unsigned integers can do just as well with signed integers and this is more natural in terms of how people think, and (2) using unsigned integers results in lots easy to create but difficult to debug issues such as integer arithmetic overflow and losing significant bits when converting between signed and unsigned types. If you mistakenly subtract 1 from 0 using signed integers it often more quickly causes your program to crash and makes it easier to find the bug than if it wraps around to 2^32 - 1, and compilers and static analysis tools and runtime checks have to assume you know what you're doing since you chose to use unsigned arithmetic. Also, negative numbers like -1 can often represent something useful, like a field being ignored/defaulted/unset while if you were using unsigned you'd have to reserve a special value like 2^32 - 1 or something similar.Long ago, when memory was limited and processors did not automatically operate on 64 bits at once, every bit counted a lot more, so having signed vs unsigned bytes or shorts actually mattered a lot more often and was obviously the right design decision. Today just using a signed int is more than sufficient in almost all regular programming cases, and if your program really needs to use values bigger than 2^31 - 1, you often just want a long anyway. Once you're into the territory of using longs, it's even harder to come up with a reason why you really can't get by with 2^63 - 1 positive integers. Whenever we go to 128 bit processors it'll be even less of an issue.Because  type is pure evil.The fact that in C  produces  is even more evil.Here is a snapshot of the problem that burned me more than once:Have you noticed the bug yet? I confess I only saw it after stepping in with the debugger. Because  is of unsigned type  the entire expression  evaluates as . That expression is intended to be a  position of the th ray from the middle one: the 1st ray from the middle one on the left side would have position -1, the 1st one on the right would have position +1, etc. After taking abs value and multiplying by the  angle I would get the angle between th ray and the middle one.Unfortunately for me the above expression contained the evil unsigned and instead of evaluating to, say, -1, it evaluated to 2^32-1. The subsequent conversion to  sealed the bug.After a bug or two caused by misuse of  arithmetic one has to start wondering whether the extra bit one gets is worth the extra trouble. I am trying, as much as feasible, to avoid any use of  types in arithmetic, although still use it for non-arithmetic operations such as binary masks.I can think of one unfortunate side-effect. In java embedded databases, the number of ids you can have with a 32bit id field is 2^31, not 2^32 (~2billion, not ~4billion).The reason IMHO is because they are/were too lazy to implement/correct that mistake. \nSuggesting that C/C++ programmers does not understand unsigned, structure, union, bit flag... Is just preposterous.Ether you were talking with a basic/bash/java programmer on the verge of beginning programming a la C, without any real knowledge this language or you are just talking out of your own mind. ;)when you deal every day on format either from file or hardware you begin to question, what in the hell they were thinking.A good example here would be trying to use an unsigned byte as a self rotating loop. \nFor those of you who do not understand the last sentence, how on earth you call yourself a programmer. DC
Java

I am trying to use a  method of a string. But if I place %1, %2, etc. in the string, java.util.UnknownFormatConversionException is thrown pointing to a confusing Java source code piece:From this I understand that  char is forbidden. If so, then what should I use for argument placeholders?I use  2.8.While all the previous responses are correct, they're all in Java. Here's a Scala example:I also have a blog post about  that might be useful.You don't need to use numbers to indicate positioning.  By default, the position of the argument is simply the order in which it appears in the string.Here's an example of the proper way to use this:You will always use a  followed by some other characters to let the method know how it should display the string.    is probably the most common, and it just means that the argument should be treated as a string.I won't list every option, but I'll give a few examples just to give you an idea: just uses a , so for a full description of the options you can see the .And, as BalusC mentions, you will see in the documentation that is possible to change the default argument ordering if you need to.   However, probably the only time you'd need / want to do this is if you are using the same argument more than once.Instead of looking at the source code, you should read the javadoc  and .You specify the format of the value after the %. For instance for decimal integer it is , and for String it is :Output: To do what you tried (use an argument index), you use: ,Output:You can use this;Output: Also note that Scala extends String with a number of methods (via implicit conversion to a WrappedString brought in by Predef) so you could also do the following:The official reference is the class .In Scala 2.10Here is a list of formatters used with String.format()This is a list of what  can do. The same goes for Although @Londo mentioned Scala's \"s\" string interpolator, I think Scala's  is more relevant to the original question. The example used a few time in other responses could also be written (since Scala 2.10) this way:The connection to the original question is to be aware that:The nice thing about string interpolation is that it lets you see which variable is being substituted directly into the string instead of having to match it with the arguments to the  method.In scala , for string Interpolation we have  that saves the day and make our life much easy: You want to define a function that takes input name and age and says Hello With the name and says its age.\nThat can be written like this:Hence , When you call this function: like this :Its output would be :You can write the code to change it in the same line, like if you want to add 10 years to the age ! then function could be :And now the output would be :
Java

What's the most idiomatic way in Java to verify that a cast from  to  does not lose any information?This is my current implementation:A new method has been added with  to do just that. Will throw an ArithmeticException in case of overflow. See:  Several other overflow safe methods have been added to Java 8. They end with . Examples: I think I'd do it as simply as:I think that expresses the intent more clearly than the repeated casting... but it's somewhat subjective.Note of potential interest - in C# it would just be:With Google Guava's  class, your method can be changed to:From the linked docs:Incidentally, you don't need the  wrapper, unless you want to leave it in place for changing out the functionality without extensive refactoring of course.With BigDecimal:here is a solution, in case you don't care about value in case it is bigger then needed ;)I claim that the obvious way to see whether casting a value changed the value would be to cast and check the result. I would, however, remove the unnecessary cast when comparing. I'm also not too keen on one letter variable names (exception  and , but not when they mean row and column (sometimes respectively)).However, really I would want to avoid this conversion if at all possible. Obviously sometimes it's not possible, but in those cases  is almost certainly the wrong exception to be throwing as far as client code is concerned.My first approach was:But that merely just casts the long to an int, potentially creating new  instances or retrieving them from the Long pool.The drawbacksSo this can be considered even worse than just casting the  to .Java integer types are represented as signed. With an input between 2 and 2 (or -2 and -2) the cast would succeed but your test would fail. What to check for is whether all of the high bits of the  are all the same:but Long can not exceed the maximum :)One other solution can be: I have tried this for cases where the client is doing a POST and the server DB understands only Integers while the client has a Long. 
Java

I was looking at the Proxy Pattern, and to me it seems an awful lot like the Decorator, Adapter, and Bridge patterns. Am I misunderstanding something? What's the difference? Why would I use the Proxy pattern versus the others? How have you used them in the past in real world projects?Proxy, Decorator, Adapter, and Bridge are all variations on \"wrapping\" a class.  But their uses are different..So are their structures.My take on the subject. All four patterns have a lot in common, all four are sometimes informally called wrappers, or wrapper patterns. All use composition, wrapping subject and delegating the execution to the subject at some point, do mapping one method call to another one. They spare client the necessity of having to construct a different object and copy over all relevant data. If used wisely, they save memory and processor.  By promoting loose coupling they make once stable code less exposed to inevitable changes and better readable for fellow developers.Adapter adapts subject (adaptee) to a different interface. This way we can add object be placed to a collection of nominally different types. Adapter expose only relevant methods to client, can restrict all others, revealing usage intents for particular contexts, like adapting external library, make it appear less general and more focused on our application needs. Adapters increase readability and self description of our code.Adapters shields one team from volatile code from other teams; a life savior tool when dealing with offshore teams ;-)Less mentioned purpose it to prevent the subject class from excess of annotations. With so many frameworks based on annotations this becomes more important usage then ever.Adapter helps to get around Java limitation of only single inheritance. It can combine several adaptees under one envelope giving impression of multiple inheritance.Code wise, Adapter is \u201cthin\u201d. It should not add much code to the adaptee class, besides simply calling the adaptee method and occasional data conversions necessary to make such calls.There are not many good adapter examples in JDK or basic libraries. Application developers create Adapters, to adapt libraries to application specific interfaces.Decorator not only delegate, not only maps one method to another, they do more, they modify behaviour of some subject methods, it can decide not call subject method at all, delegate to a different object, a helper object.Decorators typically add (transparently) functionality to wrapped object like logging, encryption, formatting, or compression to subject. This New functionality may bring a lot of new code. Hence, decorators are usually much \u201cfatter\u201d then Adapters. Decorator must be a sub-class of subject's interface. They can be used transparently instead of its subjects. See BufferedOutputStream, it is still OutputStream and can be used as such. That is a major technical difference from Adapters.Text book examples of whole decorators family is readily in JDK - the Java IO. All classes like ,  and  are decorators of . They can be onion layered, where one one decorator is decorated again, adding more functionality. Proxy is not a typical wrapper. The wrapped object, the proxy subject, may not yet exist at the time of proxy creation. Proxy often creates it internally. It may be a heavy object created on demand, or it is remote object in different JVM or different network node and even a non-Java object, a component in native code. It does not have to necessary wrap or delegate to another object at all.Most typical examples are remote proxies, heavy object initializers and access proxies.Facade is closely associated with design Principle of Least Knowledge (Law of Demeter).\nFacade is very similar to Adapter. They both wrap, they both map one object to another, but they differ in the intent. Facade flattens complex structure of a subject, complex object graph, simplifying access to a complex structure. Facade wraps a complex structure, providing a flat interface to it. This prevents client object from being exposed to inner relations in subject structure hence promoting loose coupling.More complex variant of Adapter pattern where not only implementation varies but also abstraction. It adds one more indirection to the delegation. The extra delegation is the bridge. It decouples Adapter even from adapting interface. It increases complexity more than any other of the other wrapping patterns, so apply with care.Pattern differences are also obvious when looking at their constructors.Real life example \u2013 . Purpose of this adapter is mapping of a simple flat class to more complex structure required externally and to prevent \"polluting\" subject class with excessive annotations.There's a great deal of overlap in many of the GoF patterns. They're all built on the power of polymorphism and sometimes only really differ in intent. (strategy vs. state)My understanding of patterns increased 100 fold after reading .I highly recommend it!They are quite similar, and the lines between them are quite gray. I suggest you read the  and  entries in the c2 wiki.The entries and discussions there are quite extensive, and they also link to other relevant articles. By the way, the c2 wiki is excellent when wondering about the nuances between different patterns.To sum the c2 entries up, I would say a decorator adds/changes behavior, but a proxy has more to do with access control (lazy instantiation, remote access, security etc). But like I said, the lines between them are gray, and I see references to proxies that could easily be viewed as decorators and vice versa.All good answers from experts have already explained what does each pattern stands for.I will  key points.e.g. (with chaining ) : e.g.:  package classes.e.g.  ( returns a )e.g. Collection classes in .  implemented by .Have a look at great SE questions/articles regarding examples of various design patterns All of the four patterns involve wrapping inner object/class with outer one, so they are very similar structurally. I would outline difference by the purpose:And by interface variation between inner and outer objects:I use it quite often when consuming web services.  The Proxy Pattern should probably be renamed to something more pragmatic, like 'Wrapper Pattern\".  I also have a library that is a Proxy to MS Excel.  It makes it very easy to automate Excel, without having to worry about background details such as what version is installed (if any). Speaking detail implementation, I find a difference between Proxy and Decorator, Adapter, Facade ... In common implementation of these patterns there's a target object wrapped by a enclosing object. Client uses enclosing object instead of target object. And the target object actually play an important part inside some of methods of enclosing object. However, in case of Proxy, enclosing object can play some methods by itself, it just initialize target object when client calls some methods that it needs target object take part in. This is lazy initialization. In case of other patterns, enclosing object is virtually based on target object. So target object is always initialized along with enclosing object in constructors/setters.Another thing, a proxy does exactly what a target does whereas other patterns add more functionality to target. This is quote from \nDefinitions belongs to book. Examples belongs to me. - Doesn\u2019t alter the interface, but adds responsibility. Assume you have a car interface,\nwhen you implement this for different model of the car (s, sv, sl) you may need to  for some models. Like has sunroof, airbag etc.. - Converts one interface to another. You have a car interface and you would like it to act like jeep. So you take the car, modify it and turn into a jeep.  - Makes an interface simpler.  Assume you have car, airplane, ship interfaces. Actually all you need is a class which sends people from one location to another. You want facade to decide what vehicle to use. Then you collect all those  under 1 umbrella and let it decide/delegate to keep it simple.Head First: \"A facade not only simplifies an interface, it decouples a client from a subsystem \nof components.\nFacades and adapters may wrap multiple classes, but a facade\u2019s intent is to simplify, while \nan adapter\u2019s is to convert the interface to something different.\"I would like to add examples to Bill Karwing answer (which is great btw.)\nI add also some key differences of implementation, that I feel are missingQuoted parts are from answer of [ (Bill Karwing)ProxyClass and ObjectClass that is proxied, should implement same interface, so they are interchangable DecoratorClass should(could) implement extended interface of ObjectClass. So the ObjectClass could be replaced by DecoratorClass, but not vice versa. Adapter provides a different interface to its subject. Proxy provides the same interface. Decorator provides an enhanced interface.Most of the information in this answer is from , which I recommend as an  for design patterns.I believe code will give a clear ideas (to complement others answers as well). Please see below, (Focus the types that a class implements and wraps)Design pattern is not mathematics, it is combination of art and software engineering. There is nothing like for this requirment you have to use proxy, bridge etc. Design patterns are created to solve the problems. If you anticipate a design problem, then use it. Based on experience, you will come to know for specific problem, which pattern to use. If you are good in solid design principles, you would have implemented design pattern without knowing it is pattern. Common example is statergy and factory patternsHence concentrate more on solid desighn principles, clean coding principles and ttd
Java

How can I achieve this?Everything I have tried so far always returns type  rather than the specific type used.As others mentioned, it's only possible via reflection in certain circumstances.If you really need the type, this is the usual (type-safe) workaround pattern:I have seen something like thisin the  ExampleGenerics are not  at run-time. This means the information is not present at run-time.Adding generics to Java while mantaining backward compatibility was a tour-de-force (you can see the seminal paper about it: ).There is a rich literature on the subject, and some people are  with the current state, some says that actually it's a  and there is no real need for it. You can read both links, I found them quite interesting.Sure, you can.Java does not  the information at run time, for backwards compatibility reasons.  But the information is  as metadata and can be accessed via reflection (but it is still not used for type-checking).From the official API:, for your scenario I would not use reflection.  I'm personally more inclined to use that for framework code.  In your case I would just add the type as a constructor param.Use Guava.A while back, I posted some full-fledge examples including abstract classes and subclasses .Note: this requires that you instantiate a  of  so it can bind the type parameter correctly. Otherwise it'll just return the type as .Java generics are mostly compile time, this means that the type information is lost at runtime.will be compiled to something likeTo get the type information at runtime you have to add it as an argument of the ctor.Example:Technique described in this  works for me.In short quick and dirty example:I dont think you can, Java uses type erasure when compiling so your code is compatible with applications and libraries that were created pre-generics.From the Oracle Docs:I used follow approach:This is my solution:Here is working solution!!!NOTES:\n\n 1. Has to be extended with typed class  ()\n\n 2. Has to be created as anonymous implementation ()   I think there is another elegant solution.What you want to do is (safely) \"pass\" the type of the generic type parameter up from the concerete class to the superclass.If you allow yourself to think of the class type as \"metadata\" on the class, that suggests the Java method for encoding metadata in at runtime:  annotations.First define a custom annotation along these lines:You can then have to add the annotation to your subclass.Then you can use this code to get the class type in  your base class:Some limitations of this approach are:You can't.  If you add a member variable of type T to the class (you don't even have to initialise it), you could use that to recover the type.Just in case you use store a variable using the generic type you can easily solve this problem adding a getClassType method as follows:I use the provided class object later to check if it is an instance of a given class, as follows:Here is my trick:To complete some of the answers here, I had to get the ParametrizedType of MyGenericClass, no matter how high is the hierarchy, with the help of recursion:Here's one way, which I've had to use once or twice:Along withI found this to be a simple understandable and easily explainable  solutionYou don't need a constructor.Here is my solutionNo matter how many level does your class hierarchy has,\nthis solution still works, for example:In this case, getMyType() = java.lang.String
Java

I have created the following function for checking the connection status:When I shut down the server for testing the execution waits a long time at lineDoes anyone know how to set the timeout in order to avoid waiting too long?Thanks!In my example two timeouts are set. The connection timeout throws \"java.net.SocketTimeoutException: Socket is not connected\" and the socket timeout \"java.net.SocketTimeoutException: The operation timed out\".If you want to set the Parameters of any existing HTTPClient (e.g. DefaultHttpClient or AndroidHttpClient) you can use the function .To set settings on the client:I've used this successfully on JellyBean, but should also work for older platforms ....HTHIf your are using Jakarta's  then you can do something like:If you're using the default http client, here's how to do it using the default http params:Original credit goes to For those saying that the answer of @kuester2000 does not work, please be aware that HTTP requests, first try to find the host IP with a DNS request and then makes the actual HTTP request to the server, so you may also need to set a timeout for the DNS request. If your code worked without the timeout for the DNS request it's because you are able to reach a DNS server or you are hitting the Android DNS cache. By the way you can clear this cache by restarting the device.This code extends the original answer to include a manual DNS lookup with a custom timeout:Used method:This class is from . Go and check the remarks if you will use it.If you are using the , call :you can creat HttpClient instance by the way with Httpclient-android-4.3.5,it can work well.An option is to use the  client, from Square.In the build.gradle, include this line: For example, if you want to set a timeout of 60 seconds, do this way:ps: If your minSdkVersion is greater than 8, you can use . So, you can simply use:For more details about the units, see .
Java

I have a poorly designed class in a 3rd-party  and I need to access one of its  fields. For example,\nwhy should I need to choose private field is it necessary?How can I use reflection to get the value of ?In order to access private fields, you need to get them from the class's  fields and then make them accessible:: as has been commented by , both accessing the field, setting it as accessible and retrieving the value will all throw s, although the only  exceptions you need to be mindful of are commented above.The  would be thrown if you asked for a field by a name which did not correspond to a declared field. The  would be thrown if the field was not accessible (for example, if it is private and has not been made accessible via missing out the  line.The s which may be thrown are either s (if the JVM's  will not allow you to change a field's accessibility), or s, if you try and access the field on an object not of the field's class's type:Try  from apache commons-lang3:Reflection isn't the only way. An alternative solution is to extract the class from the .jar, decompile it using (say)  or , change the field (or add an accessor), and recompile it against the original .jar. Then put the new .class ahead of the  in the classpath, or reinsert it in the . (the jar utility allows you to extract and reinsert to an existing .jar)This requires the  not to be signed, of course.One other option that hasn't been mentioned yet: use .  Groovy allows you to access private instance variables as a side effect of the design of the language.  Whether or not you have a getter for the field, you can just use As oxbow_lakes mentions, you can use reflection to get around the access restrictions (assuming your SecurityManager will let you).That said, if this class is so badly designed that it makes you resort to such hackery, maybe you should look for an alternative. Sure this little hack might be saving you a few hours now, but how much will it cost you down the road?Use the Soot Java Optimization framework to directly modify the bytecode.\nSoot is completely written in Java and works with new Java versions.Using the  you can access all the  fields and methods of one class to another .But as per the    in the section  they recommended that : here is following code snapts to demonstrate basic concepts of  Reflection1.javaReflection2.javaHope it will help.Just an additional note about reflection: I have observed in some special cases, when several classes with the same name exist in different packages, that reflection as used in the top answer may fail to pick the correct class from the object. So if you know what is the package.class of the object, then it's better to access its private field values as follows:(This is the example class that was not working for me)You need to do the following:
Java

Coming from C++ to Java, the obvious unanswered question is why didn't Java include operator overloading?Isn't  much simpler than ?Is there a known reason for this, valid arguments for  allowing operator overloading? Is the reason arbitrary, or lost to time?Assuming you wanted to overwrite the previous value of the object referred to by 'a', then a member function would have to be invoked.In C++, this expression tells the compiler to create 3 objects on the stack, perform addition, and  the resultant value from the temporary object into the existing object 'a'.However, in java, operator= doesn't perform value copy for reference types, and users can only create new reference types, not value types.  So for a user-defined type named 'Complex', assignment means to copy a reference to an existing value.consider instead:In C++, this copies the value, so the comparison will result not-equal.  In Java, operator= performs reference copy, so 'a' and 'b' are now referring to the same value.  As a result, the comparison will produce 'equal', since the object will compare equal to itself.The difference between copies and references only adds to the confusion of operator overloading.  As Sebastian mentioned, Java and C# both have to deal with value and reference equality separately -- operator+ would likely deal with values and objects, but operator= is already implemented to deal with references.In C++, you should only be dealing with one kind of comparison at a time, so it can be less confusing.  For example, on Complex, operator= and operator== are both working on values -- copying values and comparing values respectively.  There are a lot of posts complaining about operator overloading.I felt I had to clarify the \"operator overloading\" concepts, offering an alternative viewpoint on this concept.This argument is a fallacy.It is as easy to obfuscate code in C or Java through functions/methods than it is in C++ through operator overloads:For another example, let's see the  in Java:You are supposed to clone the object implementing this interface. But you could lie. And create a different object. In fact, this interface is so weak you could return another type of object altogether, just for the fun of it:As the  interface can be abused/obfuscated, should it be banned on the same grounds C++ operator overloading are supposed to be?We could overload the  method of a  class to have it return the stringified hour of the day. Should the  overloading be banned, too? We could sabotage  to have it return a random value, modify the operands... etc. etc. etc..Now that we know that code can be sabotaged even through the pristine Java methods, we can ask ourselves about the real use of operator overloading in C++?We'll compare below, for different cases, the \"same\" code in Java and C++, to have an idea of which kind of coding style is clearer.Please note that A and B could be of any type in C++, as long as the operator overloads are provided. In Java, when A and B are not primitives, the code can become very confusing, even for primitive-like objects (BigInteger, etc.)...In Java, we see that for each container to do the same thing (access its content through an index or identifier), we have a different way to do it, which is confusing.In C++, each container uses the same way to access its content, thanks to operator overload.The examples below use a  object, found using the first links found on Google for \"\" and \"\":And this is not limited to matrices. The  and  classes of Java suffer from the same confusing verbosity, whereas their equivalent in C++ are as clear as built-in types.Ok, in Java you can use  too... But, wait a second: This is operator overloading, isn't it? Isn't it cheating???:-DThe same generic code modifying operands should be usable both for built-ins/primitives (which have no interfaces in Java), standard objects (which could not have the right interface), and user-defined objects.For example, calculating the average value of two values of arbitrary types:Now that we have seen fair comparisons between C++ code using operator overloading, and the same code in Java, we can now discuss \"operator overloading\" as a concept.Indeed, the signification of , , , etc. changes depending on the types of the operands (numerics, vectors, quantum wave functions, matrices, etc.).Most of us, as part of our science courses, learned multiple significations for operators, depending on the types of the operands. Did we find them confusing, them?This is the most important part of operator overloading: Like in mathematics, or in physics, the operation depends on its operands' types.So, know the type of the operand, and you will know the effect of the operation.In C, the real behavior of an operator will change according to its operands. For example, adding two integers is different than adding two doubles, or even one integer and one double. There is even the whole pointer arithmetic domain (without casting, you can add to a pointer an integer, but you cannot add two pointers...).In Java, there is no pointer arithmetics, but someone still found string concatenation without the  operator would be ridiculous enough to justify an exception in the \"operator overloading is evil\" creed.It's just that you, as a C (for historical reasons) or Java (for , see below) coder, you can't provide your own.In C++, operator overloading for built-in types is not possible (and this is a good thing), but  types can have  operator overloads.As already said earlier, in C++, and to the contrary to Java, user-types are not considered second-class citizens of the language, when compared to built-in types. So, if built-in types have operators, user types should be able to have them, too.The truth is that, like the , ,  methods are for Java (), C++ operator overloading is so much part of C++ that it becomes as natural as the original C operators, or the before mentioned Java methods.Combined with template programming, operator overloading becomes a well known design pattern. In fact, you cannot go very far in STL without using overloaded operators, and overloading operators for your own class.Operator overloading should strive to respect the semantics of the operator. Do not subtract in a  operator (as in \"do not subtract in a  function\", or \"return crap in a  method\").Cast overloading can be very dangerous because they can lead to ambiguities. So they should really be reserved for well defined cases. As for  and , do not ever overload them unless you really know what you're doing, as you'll lose the the short circuit evaluation that the native operators  and  enjoy.Because James Gosling said so:Please compare Gosling's text above with Stroustrup's below:Some objects would greatly benefit from operator overloading (concrete or numerical types, like BigDecimal, complex numbers, matrices, containers, iterators, comparators, parsers etc.).In C++, you can profit from this benefit because of Stroustrup's humility. In Java, you're simply screwed because of Gosling's .The reasons for not adding operator overloading now in Java could be a mix of internal politics, allergy to the feature, distrust of developers (you know, the saboteur ones that seem to haunt Java teams...), compatibility with the previous JVMs, time to write a correct specification, etc..So don't hold your breath waiting for this feature...Yeah...While this is far from being the only difference between the two languages, this one never fails to amuse me.Apparently, the C# folks, with their , got it right at first try.Despite all the FUD against used defined operator overloading, the following languages support it: , , , , , , , , , , C++, , , , , , , , , , ...So many languages, with so many different (and sometimes opposing) philosophies, and yet they all agree on that point.Food for thoughts...James Gosling likened designing Java to the following:You can read the Basically operator overloading is great for a class that models some kind of point, currency or complex number. But after that you start running out of examples fast.Another factor was the abuse of the feature in C++ by developers overloading operators like '&&', '||', the cast operators and of course 'new'. The complexity resulting from combining this with pass by value and exceptions is well covered in the  book.Check out Boost.Units: It provides zero-overhead Dimensional analysis through operator overloading. How much clearer can this get?would actually output \"Energy = 4 J\" which is correct. has operator overloading, and runs in the JVM. If you don't mind the performance hit (which gets smaller everyday). It's automatic based on method names. e.g., '+' calls the 'plus(argument)' method.Well you can really shoot yourself in the foot with operator overloading. It's like with pointers people make stupid mistakes with them and so it was decided to take the scissors away.At least I think that's the reason.\nI'm on your side anyway. :)The Java designers decided that operator overloading was more trouble than it was worth. Simple as that.In a language where every object variable is actually a reference, operator overloading gets the additional hazard of being quite illogical - to a C++ programmer at least. Compare the situation with C#'s == operator overloading and Object.Equals and Object.ReferenceEquals (or whatever it's called).I think this may have been a conscious design choice to force developers to create functions whose names clearly communicate their intentions. In C++ developers would overload operators with functionality that would often have no relation to the commonly accepted nature of the given operator, making it nearly impossible to determine what a piece of code does without looking at the definition of the operator.Saying  that operator overloading leads to logical errors of type that operator does not match the operation logic, it's like saying nothing. The same type of error will occur if function name is inappropriate for operation logic - so what's the solution: drop the ability of function usage!? \n This is a comical answer - \"Inappropriate for operation logic\", every parameter name, every class, function or whatever can be logicly inappropriate.\nI think that this option should be available in respectable programing language, and those that think that it's unsafe - hey no bothy says you have to use it. \nLets take the C#. They drooped the pointers but hey - there is 'unsafe code' statement - program as you like on your own risk.Technically, there is operator overloading in every programming language that can deal with different types of numbers, e.g. integer and real numbers. Explanation: The term overloading means that there are simply several implementations for one function. In most programming languages different implementations are provided for the operator +, one for integers, one for reals, this is called operator overloading.Now, many people find it strange that Java has operator overloading for the operator + for adding strings together, and from a mathematical standpoint this would be strange indeed, but seen from a programming language's developer's standpoint, there is nothing wrong with adding builtin operator overloading for the operator + for other classes e.g. String. However, most people agree that once you add builtin overloading for + for String, then it is generally a good idea to provide this functionality for the developer as well.A completely disagree with the fallacy that operator overloading obfuscates code, as this is left for the developer to decide. This is na\u00efve to think, and to be quite honest, it is getting old.+1 for adding operator overloading in Java 8.Some people say that operator overloading in Java would lead to obsfuscation. Have those people ever stopped to look at some Java code doing some basic maths like increasing a financial value by a percentage using BigDecimal ? .... the verbosity of such an exercise becomes its own demonstration of obsfuscation. Ironically, adding operator overloading to Java would allow us to create our own Currency class which would make such mathematical code elegant and simple (less obsfuscated).Assuming Java as the implementation language then a, b, and c would all be references to type Complex with initial values of null. Also assuming that Complex is immutable as the mentioned  and similar immutable , I'd I think you mean the following, as you're assigning the reference to the Complex returned from adding b and c, and not comparing this reference to a.Sometimes it would be nice to have operator overloading, friend classes and multiple inheritance.However I still think it was a good decision. If Java would have had operator overloading then we could never be sure of operator meanings without looking through source code. At present that's not necessary. And I think your example of using methods instead of operator overloading is also quite readable. If you want to make things more clear you could always add a comment above hairy statements.
Java

I need to implement 256 bit AES encryption, but all the examples I have found online use a \"KeyGenerator\" to generate a 256 bit key, but I would like to use my own passkey. How can I create my own key? I have tried padding it out to 256 bits, but then I get an error saying that the key is too long. I do have the unlimited jurisdiction patch installed, so thats not the problem :)Ie. The KeyGenerator looks like this ...I was actually padding the password out to 256 bytes, not bits, which is too long. The following is some code I am using now that I have some more experience with this.The \"TODO\" bits you need to do yourself :-)Share the  (a ) and  (a \u20148 bytes selected by a  makes a good salt\u2014which doesn't need to be kept secret) with the recipient out-of-band. Then to derive a good key from this information:The magic numbers (which could be defined as constants somewhere) 65536 and 256 are the key derivation iteration count and the key size, respectively.The key derivation function is iterated to require significant computational effort, and that prevents attackers from quickly trying many different passwords. The iteration count can be changed depending on the computing resources available. The key size can be reduced to 128 bits, which is still considered \"strong\" encryption, but it doesn't give much of a safety margin if attacks are discovered that weaken AES.Used with a proper block-chaining mode, the same derived key can be used to encrypt many messages. In CBC, a random initialization vector (IV) is generated for each message, yielding different cipher text even if the plain text is identical. CBC may not be the most secure mode available to you (see AEAD below); there are many other modes with different security properties, but they all use a similar random input. In any case, the outputs of each encryption operation are the cipher text  the initialization vector:Store the  and the . On decryption, the  is regenerated in exactly the same way, using using the password with the same salt and iteration parameters. Initialize the cipher with this key  the initialization vector stored with the message:Java 7 included API support for AEAD cipher modes, and the \"SunJCE\" provider included with OpenJDK and Oracle distributions implements these beginning with Java 8. One of these modes is strongly recommended in place of CBC; it will protect the integrity of the data as well as their privacy.A  with the message \"Illegal key size or default parameters\" means that the cryptography strength  limited; the unlimited strength jurisdiction policy files are not in the correct location. In a JDK, they should be placed under  Based on the problem description, it sounds like the policy files are not correctly installed. Systems can easily have multiple Java runtimes; double-check to make sure that the correct location is being used.It's provides a simple abstraction for encryption and seems to match what's required here,A look at the  reveals a structure similar to . As noted in the question, this also requires the  (else you'll encounter ).  It's downloadable for ,  and . And sample output,After reading through erickson's suggestions, and gleaning what I could from a couple other postings and this example , I've attempted to update Doug's code with the recommended changes. Feel free to edit to make it better.Some notes: This uses a 128 bit encryption key - java apparently won't do 256 bit encryption out-of-the-box. Implementing 256 requires installing some extra files into the java install directory. Also, I'm not a crypto person. Take heed.I've implemented the erickson's answer in a really simple class:\n\nIf you get the  you have to install the Java Cryptography Extension (JCE) unlimited strength jurisdiction policy files:Just place the jars in your Generating your own key from a byte array is easy:But creating a 256-bit key isn't enough. If the key generator cannot generate 256-bit keys for you, then the  class probably doesn't support AES 256-bit either. You say you have the unlimited jurisdiction patch installed, so the AES-256 cipher should be supported (but then 256-bit keys should be too, so this might be a configuration problem).A workaround for lack of AES-256 support is to take some freely available implementation of AES-256, and use it as a custom provider. This involves creating your own  subclass and using it with . But this can be an involved process.What I've done in the past is hash the key via something like SHA256, then extract the bytes from the hash into the key byte[].After you have your byte[] you can simply do:Adding to @Wufoo's edits, the following version uses InputStreams rather than files to make working with a variety of files easier. It also stores the IV and Salt in the beginning of the file, making it so only the password needs to be tracked. Since the IV and Salt do not need to be secret, this makes life a little easier.Consider using First make sure you have  files installed before your proceed so that you can use 256-bit AES keys.Then do the following:You can now use the encryptor to encrypt your message. You can also perform streaming encryption if you'd like. It automatically generates and prepends a secure IV for your convenience.If it's a file that you wish to compress take a look at this answer\n for an even simpler approach.Use this class for encryption. It works.}And these are ivBytes and a random key;
Java

I want to know the difference between the specified error and the exception.What is the reason for getting each of them and any thought process on how to deal with such errors?While working on a project. If we are modifying the existing code to include the new jar file I get to face these exceptions.\nSometimes they will come in client side or server side for a java app distributed through webstart.Possible reasons I have come across:But as of now I am dealing with hit and trial method to get things working.Need more clarity and understanding regarding this.The difference from the Java API Specifications is as follows.For :For :So, it appears that the  occurs when the source was successfully compiled, but at runtime, the required  files were not found. This may be something that can happen in the distribution or production of JAR files, where not all the required  files were included.As for , it appears that it may stem from trying to make reflective calls to classes at runtime, but the classes the program is trying to call is does not exist.The difference between the two is that one is an  and the other is an . With  is an  and it arises from the Java Virtual Machine having problems finding a class it expected to find. A program that was expected to work at compile-time can't run because of  files not being found, or is not the same as was produced or encountered at compile-time. This is a pretty critical error, as the program cannot be initiated by the JVM.On the other hand, the  is an , so it is somewhat expected, and is something that is recoverable. Using reflection is can be error-prone (as there is some expectations that things may not go as expected. There is no compile-time check to see that all the required classes exist, so any problems with finding the desired classes will appear at runtime.A ClassNotFoundException is thrown when the reported class is not found by the ClassLoader. This typically means that the class is missing from the CLASSPATH. It could also mean that the class in question is trying to be loaded from another class which was loaded in a parent classloader and hence the class from the child classloader is not visible. This is sometimes the case when working in more complex environments like an App Server (WebSphere is infamous for such classloader issues).People often tend to confuse  with  however there's an important distinction. For example an exception (an error really since  is a subclass of java.lang.Error) likedoes not mean that the ActiveMQConnectionFactory class is not in the CLASSPATH. Infact its quite the opposite. It means that the class ActiveMQConnectionFactory was found by the ClassLoader however when trying to load the class, it ran into an error reading the class definition. This typically happens when the class in question has static blocks or members which use a Class that's not found by the ClassLoader. So to find the culprit, view the source of the class in question (ActiveMQConnectionFactory in this case) and look for code using static blocks or static members. If you don't have access the the source, then simply decompile it using JAD.On examining the code, say you find a line of code like below, make sure that the class SomeClass in in your CLASSPATH.Tip : To find out which jar a class belongs to, you can use the web site jarFinder . This allows you to specify a class name using wildcards and it searches for the class in its database of jars. jarhoo  allows you to do the same thing but its no longer free to use.If you would like to locate the which jar a class belongs to in a local path, you can use a utility like jarscan (  ). You just specify the class you'd like to locate and the root directory path where you'd like it to start searching for the class in jars and zip files.NoClassDefFoundError is a linkage error basically. It occurs when you try and instantiate an object (statically with \"new\") and it's not found when it was during compilation.ClassNotFoundException is more general and is a runtime exception when you try to use a class that doesn't exist. For example, you have a parameter in a function accepts an interface and someone passes in a class that implements that interface but you don't have access to the class. It also covers case of dynamic class loading, such as using loadClass() or Class.forName().A NoClassDefFoundError (NCDFE) happens when your code runs \"new Y()\" and it can't find the Y class.It may simply be that Y is missing from your class loader like the other comments suggest, but it could be that the Y class isn't signed or has an invalid signature, or that Y is loaded by a different classloader not visible to your code, or even that Y depends on Z which couldn't be loaded for any of the above reasons.If this happens, then the JVM will remember the result of loading X (NCDFE) and it will simply throw a new NCDFE every time you ask for Y without telling you why:The code simply tries to instantiate a new \"b\" class twice, other than that, it doesn't have any bugs, and it doesn't do anything.Compile the code with , Then run a by invoking  -- it should just print out two lines of text, and it should run fine without errors.Then delete the \"a$b.class\" file (or fill it with garbage, or copy a.class over it) to simulate the missing or corrupted class.  Here's what happens:The first invocation results in a ClassNotFoundException (thrown by the class loader when it can't find the class), which must be wrapped in an unchecked NoClassDefFoundError, since the code in question () should just work.The second attempt will of course fail too, but as you can see the wrapped exception is no more, because the ClassLoader seems to remember failed class loaders.  You see only the NCDFE with absolutely no clue as to what really happened.So if you ever see a NCDFE with no root cause, you need to see if you can track back to the very first time the class was loaded to find the cause of the error.From : : occurs when class loader could not find the required class in class path. So, basically you should check your class path and add the class in the classpath. : this is more difficult to debug and find the reason. This is thrown when at compile time the required classes are present, but at run time the classes are changed or removed or class's static initializes threw exceptions. It means the class which is getting loaded is present in classpath, but one of the classes which are required by this class are either removed or failed to load by compiler. So you should see the classes which are dependent on this class.:Now after compiling both the classes, if you delete Test1.class file and run Test class, it will throw: thrown when an application tries to load in a class through its name, but no definition for the class with the specified name could be found.: thrown if the Java Virtual Machine tries to load in the definition of a class and no definition of the class could be found.They're closely related. A  is thrown when Java went looking for a particular class by name and could not successfully load it. A  is thrown when Java went looking for a class that was linked into some existing code, but couldn't find it for one reason or another (e.g., wrong classpath, wrong version of Java, wrong version of a library) and is thoroughly fatal as it indicates that something has gone Badly Wrong.If you've got a C background, a CNFE is like a failure to / and an NCDFE is a problem with the linker; in the second case, the class files concerned should never have been actually compiled in the configuration you're trying to use them.Example #1:If  doesn't exist in any of the classpaths, then It throws .Example #2:If  existed while compiling B, but not found while execution, then It throws .Both are run time exceptions.Difference Between ClassNotFoundException Vs NoClassDefFoundError is thrown when there is attempt to load the class by referencing it via a String. For example the parameter to in Class.forName() is a String, and this raises the potential of invalid binary names being passed to the classloader.The ClassNotFoundException is thrown when a potentially invalid binary name is encountered; for instance, if the class name has the '/' character, you are bound to get a ClassNotFoundException. It is also thrown when the directly referenced class is not available on the classpath.On the other hand,  is thrown In short, a NoClassDefFoundError is usually thrown on new() statements or method invocations that load a previously absent class (as opposed to the string-based loading of classes for ClassNotFoundException), when the classloader is unable to find or load the class definition(s).Eventually, it is upto the ClassLoader implementation to throw an instance of ClassNotFoundException when it is unable to load a class. Most custom classloader implementations perform this since they extend the URLClassLoader. Usually classloaders do not explicitly throw a NoClassDefFoundError on any of the method implementations - this exception is usually thrown from the JVM in the HotSpot compiler, and not by the classloader itself.Given the Class loader sussystem actions:This is an article that helped me a lot to understand the difference: So a  is a root cause of .\nAnd a  is a special case of type loading error, that occurs at  step.Add one possible reason in practise:In practise,  may be thrown , e.g, you submit a timer task and in the timer task it throws , while in most cases, your program only catches . Then the  main loop is ended without any information. A similar Error to NoClassDefFoundError is , when your static initializer or the initializer for a static variable throws an exception. Exceptions occurs during the execution of program. A programmer can handle these exception by try catch block. We have two types of exceptions. Checked exception which throws at compile time. Runtime Exceptions which are thrown at run time, these exception usually happen because of bad programming.  These are not exceptions at all, it is beyond the scope of programmer. These errors are usually thrown by JVM.   I remind myself the following again and again when I need to refresh is a checked exception that occurs when we tell JVM to load a class by its string name using Class.forName() or ClassLoader.findSystemClass() or ClassLoader.loadClass() methods and mentioned class is not found in the classpath.Most of the time, this exception occurs when you try to run an application without updating the classpath with required JAR files. For Example, You may have seen this exception when doing the JDBC code to connect to your database i.e.MySQL but your classpath does not have JAR for it. error occurs when JVM tries to load a particular class that is the part of your code execution (as part of a normal method call or as part of creating an instance using the new keyword) and that class is not present in your classpath but was present at compile time because in order to execute your program you need to compile it and if you are trying use a class which is not present compiler will raise compilation error.Below is the brief descriptionYou can read  for more details.
Java

There is an online file (such as ) I need to grab and save to a directory. I know there are several methods for grabbing and reading online files (URLs) line-by-line, but is there a way to just download and save the file using Java?Give a try to :Using  is  much more efficient than a simple loop that reads from the source channel and writes to this channel. Many operating systems can transfer bytes directly from the source channel into the filesystem cache without actually copying them.Check more about it .: The third parameter in transferFrom is the maximum number of bytes to transfer.   will transfer at most 2^31 bytes,  will allow at most 2^63 bytes (larger than any file in existence). Use apache , just one line code:Simpler nio usage:You'll need to handle exceptions, probably external to this method.Downloading a file requires you to read it, either way you will have to go through the file in some way.  Instead of line by line, you can just read it by bytes from the stream:When using  use the following method to download a file from the Internet and save it to some directory:Documentation .This answer is almost exactly like selected answer but with two enhancements:  it's a method and it closes out the FileOutputStream object:Personally, I've found  to be more than capable of everything I've needed to do with regards to this.   is a great tutorial on using HttpClientThis is another java7 variant based on  with usage of try-with statement:There is an issue with simple usage of:if you need to download and save very large files, or in general if you need automatic retries in case connection is dropped.What I suggest in such cases is Apache HttpClient along with org.apache.commons.io.FileUtils. For example:It's possible to download the file with with Apache's  instead of . This code allows you to download a file in Java according to its URL and save it at the specific destination.In contrast to the single line of code:this code will give you more control over a process and let you specify not only time outs but  and  values, which are critical for many web-sites.There is method $.fetch() in  library.Code example:To summarize (and somehow polish and update) previous answers. The three following methods are practically equivalent. (I added explicit timeouts because I think they are a must, nobody wants a download to freeze forever when the connection is lost.)I don't find significant differences, all seem right to me. They are safe and efficient. (Differences in speed seem hardly relevant - I write 180Mb from local server to a SSD disk in times that fluctuate around 1.2 to 1.5 segs). They don't require external libraries. All work with arbitrary sizes and (to my experience) HTTP redirections.Additionally, all throw  if the resource is not found (error 404, typically), and  if the DNS resolution failed; other IOException correspond to errors during transmission.(Marked as community wiki, feel free to add info or corrections)There are many elegant and efficient answers here. But the conciseness can make us lose some useful information. In particular, one , and one might want to treat differently some kind of network-related errors - for example, to decide if we should retry the download.Here's a method that does not throw Exceptions for network errors (only for truly exceptional problems, as malformed url or problems writing to the file)Give it a try. It works for me perfectly.
Java

Which of the following is better practice in Java 8?Java 8:Java 7:I have lots of for loops that could be \"simplified\" with lambdas, but is there really any advantage of using them including performance and readability?I'll also extend this question to longer methods - I know that you cant return or break the parent function from a lambda and this should be mentioned to if they are compared, but is there anything else to be considered?The advantage comes into account when the operations can be executed in parallel. (See  - the section about internal and external iteration)\nfor my answer I assumed joins implementing the  interface. If joins implements only the  interface this is no longer true. The better practice is to use . Besides violating the  principle, the new-fangled  has at least the following deficiencies:As you can see, I'm not a big fan of the forEach() except in cases when it makes sense.Particularly offensive to me is the fact that  does not implement  (despite actually having method ) and cannot be used in a for-each, only with a forEach(). I recommend casting Streams into Iterables with . A better alternative is to use  which fixes a number of Stream API problems, including implementing .That said,  is useful for the following:Articles I used for reference: Looks like some of the original proposals for lambdas (such as ) solved some of the issues I mentioned (while adding their own complications, of course).When reading this question one can get the impression, that  in combination with lambda expressions is a shortcut/replacement for writing a traditional for-each loop. This is simply not true. This code from the OP:is  intended as a shortcut for writingand should certainly not be used in this way. Instead it is intended as a shortcut (although it is  exactly the same) for writingAnd it is as a replacement for the following Java 7 code:Replacing the body of a loop with a functional interface, as in the examples above, makes your code more explicit: You are saying that (1) the body of the loop does not affect the surrounding code and control flow, and (2) the body of the loop may be replaced with a different implementation of the function, without affecting the surrounding code. Not being able to access non final variables of the outer scope is not a deficit of functions/lambdas, it is a  that distinguishes the semantics of  from the semantics of a traditional for-each loop. Once one gets used to the syntax of , it makes the code more readable, because you immediately get this additional information about the code.Traditional for-each loops will certainly stay  (to avoid the overused term \"\") in Java. But this doesn't mean, that  should be considered bad practice or bad style. It is always good practice, to use the right tool for doing the job, and this includes mixing traditional for-each loops with , where it makes sense.Since the downsides of  have already been discussed in this thread, here are some reasons, why you might probably want to use : can be implemented to be faster than for-each loop, because the iterable knows the best way to iterate its elements, as opposed to the standard iterator way. So the difference is loop internally or loop externally. For example  may be simply implemented as as opposed to the for-each loop which requires a lot of scaffolding However, we also need to account for two overhead costs by using , one is making the lambda object, the other is invoking the lambda method. They are probably not significant.see also  for comparing internal/external iterations for different use cases.:  was the fastest.I felt I should add my results from benchmarking iteration.\nI took a very simple approach (no benchmarking frameworks) and benchmarked 5 different methods:The list in this class shall be iterated over and have some  applied to all it's members, each time via a different method.\nin the Main class I run the tested method three times to warm up the JVM. I then run the test method 1000 times summing the time it takes for each iteration method (using ). After that's done i divide that sum by 1000 and that's the result, average time.\nexample:I ran this on a i5 4 core CPU, with java version 1.8.0_05execution time: 4.21 msexecution time: 5.95 msexecution time: 3.11 msexecution time: 2.79 msexecution time: 3.6 msOne of most upleasing functional 's limitations is lack of checked exceptions support.One  is to replace terminal  with plain old foreach loop:Here is list of most popular questions with other workarounds on checked exception handling within lambdas and streams:I feel that I need to extend my comment a bit...That's probably the most notable aspect. FP became popular due to what you can get avoiding side-effects. I won't delve deep into what pros\\cons you can get from this, since this is not related to the question.However, I will say that the iteration using Iterable.forEach is inspired by FP and rather result of bringing more FP to Java (ironically, I'd say that there is no much use for forEach in pure FP, since it does nothing except introducing side-effects).In the end I would say that it is rather a matter of taste\\style\\paradigm you are currently writing in.From performance point of view there is no promised notable benefits from using Iterable.forEach over foreach(...).According to official  :... i.e. docs pretty much clear that there will be no implicit parallelism. Adding one would be LSP violation.Now, there are \"parallell collections\" that are promised in Java 8, but to work with those you need to me more explicit and put some extra care to use them (see mschenk74's answer for example).BTW: in this case  will be used, and it doesn't guarantee that actual work will be done in parallell (depends on underlying collection). might be not that obvious and a little stretched at a glance but there is another facet of style and readability perspective.First of all - plain old forloops are plain and old. Everybody already knows them.Second, and more important - you probably want to use Iterable.forEach only with one-liner lambdas. If \"body\" gets heavier - they tend to be not-that readable.\nYou have 2 options from here - use inner classes (yuck) or use plain old forloop.\nPeople often gets annoyed when they see the same things (iteratins over collections) being done various vays/styles in the same codebase, and this seems to be the case.Again, this might or might not be an issue. Depends on people working on code.
Java

How do I properly set the default character encoding used by the JVM (1.5.x) programmatically?I have read that  used to be the way to go for older JVMs... I don't have that luxury for reasons I wont get into.I have tried:And the property gets set, but it doesn't seem to cause the final getBytes call below to use UTF8:Unfortunately, the  property has to be specified as the JVM starts up; by the time your main method is entered, the character encoding used by  and the default constructors of  and  has been permanently cached.As  in a special case like this, the environment variable   be used to specify this property, but it's normally done like this: will reflect changes to the  property, but most of the code in the core Java libraries that need to determine the default character encoding do not use this mechanism.When you are encoding or decoding, you can query the  property or  to find the current default encoding, and use the appropriate method or constructor overload to specify it.From the  documentation\u2026By setting the (Windows) environment variable  to , the (Java)  property will be set automatically every time a JVM is started. You will know that the parameter has been picked up because the following message will be posted to :I have a hacky way that definitely works!!This way you are going to trick JVM which would think that charset is not set and make it to set it again to UTF-8, on runtime!I think a better approach than setting the platform's default character set, especially as you seem to have restrictions on affecting the application deployment, let alone the platform, is to call the much safer . That way your application is not dependent on things beyond its control.I personally feel that  should be deprecated, as it has caused serious problems in a number of cases I have seen, where the developer did not account for the default charset possibly changing.I can't answer your original question but I would like to offer you some advice -- don't depend on the JVM's default encoding.  It's always best to explicitly specify the desired encoding (i.e. \"UTF-8\") in your code.  That way, you know it will work even across different systems and JVM configurations.Try this : We were having the same issues.  We methodically tried several suggestions from this article (and others) to no avail.  We also tried adding the -Dfile.encoding=UTF8 and nothing seemed to be working.  For people that are having this issue, the following article finally helped us track down describes how the locale setting can break unicode/UTF-8 in Java/TomcatSetting the locale correctly in the ~/.bashrc file worked for us.Not clear on what you do and don't have control over at this point. If you can interpose a different OutputStream class on the destination file, you could use a subtype of OutputStream which converts Strings to bytes under a charset you define, say UTF-8 by default. If modified UTF-8 is suffcient for your needs, you can use :If this approach is not feasible, it may help if you clarify here exactly what you can and can't control in terms of data flow and execution environment (though I know that's sometimes easier said than determined). Good luck.I have tried a lot of things, but the sample code here works perfect.\nThe crux of the code is:We set there two system properties together and it makes the system take everything into utf8
Java

I'm trying to use a constant instead of a string literal in this piece of code: appears in the code rather often, and would be much better to refer to some  variable instead. Do you know where I can find such a variable in JDK?BTW, on a second thought, such constants are bad design: In Java 1.7+,  defines constants for  including . Now I use  constant from .The  library (which I'd highly recommend anyway, if you're doing work in Java) has a  class with static fields like , , etc.Since Java 7 you should just use  instead for comparable constants.Note that these constants aren't strings, they're actual  instances. All standard APIs that take a charset name also have an overload that take a  object which you should use instead.In case this page comes up in someones web search, as of Java 1.7 you can now use  to get access to constant definitions of standard charsets.There are none (at least in the standard Java library). Character sets vary from platform to platform so there isn't a standard list of them in Java.There are some 3rd party libraries which contain these constants though. One of these is Guava (Google core libraries): You can use  API or  property.But if you want your own constant, you'll need to define it yourself.This constant is available (among others as: , , etc.) in the class  as well.If you are using  for Java/Android you can use the following constant:
Java

I want to have a Class object, but I want to force whatever class it represents to extend class A and implement interface B.I can do:Or:but I can't do both.  Is there a way to do this?Actually, you  do what you want.  If you want to provide multiple interfaces or a class plus interfaces, you have to have your wildcard look something like this:See the  at sun.com, specifically the  section, at the bottom of the page.  You can actually list more than one interface if you wish, using  for each one that you need.This can get arbitrarily complicated.  To demonstrate, see the JavaDoc declaration of , which (wrapped onto two lines) is:why so complicated?  As said in the Java Generics FAQ: .It looks like this doesn't work for variable declaration, but it does work when putting a generic boundary on a class.  Thus, to do what you want, you may have to jump through a few hoops.  But you can do it.  You can do something like this, putting a generic boundary on your class and then:to get  that has the restriction that you want.  For more information and examples, check out page 3 of .  Note, in , the class name must come first, and interfaces follow.  And of course you can only list a single class.You can't do it with \"anonymous\" type parameters (ie, wildcards that use ), but you can do it with \"named\" type parameters. Simply declare the type parameter at method or class level.
Java

I am getting the following error when trying to get a JSON request and process it:Here is the JSON I am trying to send:In Controller, I have the following method signature:AllApplesDO is a wrapper of ApplesDO :ApplesDO:I think that Jackson is unable to convert JSON into Java objects for subclasses. Please help with the configuration parameters for Jackson to convert JSON into Java Objects. I am using Spring Framework.EDIT: Included the major bug that is causing this problem in the above sample class - Please look accepted answer for solution.So, finally I realized what the problem is. It is not a Jackson configuration issue as I doubted.Actually the problem was in  Class:There was a custom constructor defined for the class making it the default constructor. Introducing a dummy constructor has made the error to go away:This happens for these reasons:I would like to add another solution to this that does not require a dummy constructor. Since dummy constructors are a bit messy and subsequently confusing. We can provide a safe constructor and by annotating the constructor arguments we allow jackson to determine the mapping between constructor parameter and field.so the following will also work. Note the string inside the annotation must match the field name.When I ran into this problem, it was a result of trying to use an inner class to serve as the DO. Construction of the inner class (silently) required an instance of the enclosing class -- which wasn't available to Jackson.In this case, moving the inner class to its own .java file fixed the problem.Can you please test this structure. If I remember correct you can use it this way:Second, please add default constructor to each class it also might help.: Add a default constructor for each class you used as a mapping class. You missed this and issue arise!\nSimply add default constructor and it should work.If you start annotating constructor, you must annotate all fields.Notice, my Staff.name field is mapped to \"ANOTHER_NAME\" in JSON string.Failing custom jackson Serializers/Deserializers could also be the problem. Though it's not your case, it's worth mentioning.I faced the same exception and that was the case.You must realize what options Jackson has available for deserialization. In Java, method argument names are not present in compiled code. That's why Jackson can't generally use constructors to create a well defined object with everything already set.So, if there is an empty constructor and there are also setters, it uses the empty constructor and setters. If there are no setters, some dark magic (reflections) is used to do it.If you want to use constructor with Jackson, you must use the annotations as mentioned by @PiersyP in his answer. You can also use builder pattern. If you encounter some exceptions, good luck. Error handling in Jackson sucks big time, it's hard to understand that gibberish in error messages.You have to create dummy empty constructor in our model class.So while mapping json, it set by setter method.
Java

Just to be clear, I'm not looking for the MIME type.Let's say I have the following input: I'd like a way to break this input up, specifically into  for the extension.  Is there any built in way to do this in Java?  I would like to avoid writing my own parser.In this case, use  from Here is an example of how to use it (you may specify either full path or just file name):Do you really need a \"parser\" for this?Assuming that you're dealing with simple Windows-like file names, not something like .Btw, for the case that a directory may have a '.', but the filename itself doesn't (like ), you can doIf you use  library, you can resort to  utility class. It has a specific method, . For instance:In addition you may also obtain the filename with a similar function, :If on Android, you can use this:In order to take into account file names without characters  the dot, you have to use that slight variation of the accepted answer:My dirty and may tiniest using :Note that first  is greedy so it will grab most possible characters as far as it can and then just last dot and file extension will be left.If you plan to use Apache commons-io,and just want to check the file's extension and then do some operation,you can use ,here is a snippet:How about (using Java 1.5 RegEx):How about JFileChooser? It is not straightforward as you will need to parse its final output...which is a MIME type...OK...I forget that you don't want to know its MIME type.Interesting code in the following link:\nRelated question:\nHere's a method that handles  properly, even in a path with dots in directory names: is created to make finding  quicker since it won't have to search the whole string if there are some slashes in it.The  inside the original  is reused, adding no garbage there, and .Here I made a small method (however not that secure and doesnt check for many errors), but if it is only you that is programming a general java-program, this is more than enough to find the filetype. This is not working for complex filetypes, but those are normally not used as much. This is a tested methodAnd test case:extension should have \".txt\" in it when run.Getting File Extension from File NameHere's the version with Optional as a return value (cause you can't be sure the file has an extension)... also sanity checks... How about  version:or with null extension supported:result for *nix:\nfor windows, parsePath(\"c:\\windows\\readme.txt\"):\nJust a regular-expression based alternative. Not that fast, not that good. This particular question gives me a lot trouble then i found a very simple solution for this problem which i'm posting here.That's it.You can use the Java7 feature from java.io packageRefer the below code snippetJava has a built-in way of dealing with this, in the , that may work for your needs:Note that this static method uses the specifications  to retrieve \"content type,\" which can vary.let 'name' be the name of the file with extension file.
Java

I want to convert a  object to a  in Java.The format is  In Java, Convert a Date to a String using a format string:From Commons-lang  is full of goodies (if you have commons-lang in your classpath)The modern way is with the java.time classes that now supplant the troublesome old legacy date-time classes.First convert your  to an . The  class represents a moment on the timeline in  with a resolution of  (up to nine (9) digits of a decimal fraction).Conversions to/from java.time are performed by new methods added to the old classes.Both your  and  are in . If you want to see the date and time as UTC, so be it. Call  to generate a String in standard  format.For other formats, you need to transform your  into the more flexible .To get a String in your desired format, specify a . You could specify a custom format. But I would use one of the predefined formatters (), and replace the  in its output with a SPACE.By the way I do not recommend this kind of format where you purposely lose the  or time zone information. Creates ambiguity as to the meaning of that string\u2019s date-time value.Also beware of data loss, as any fractional second is being ignored (effectively truncated) in your String\u2019s representation of the date-time value.To see that same moment through the lens of some particular region\u2019s , apply a  to get a .To generate a formatted String, do the same as above but replace  with .If executing this code a very large number of times, you may want to be a bit more efficient and avoid the call to . Dropping that call also makes your code shorter. If so desired, specify your own formatting pattern in your own  object. Cache this instance as a constant or member for reuse.Apply that formatter by passing the instance.The  framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as , , & .The  project, now in , advises migration to java.time.To learn more, see the . And search Stack Overflow for many examples and explanations.Much of the java.time functionality is back-ported to Java 6 & 7 in  and further adapted to  in  (see ).The  project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time.Why don't you use Joda (org.joda.time.DateTime)?\nIt's basically a one-liner.Altenative one-liners in plain-old java:This uses  instead of  which is not thread-safe, btw.Slightly more repetitive but needs just one statement. \nThis may be handy in some cases.It looks like you are looking for .Format: yyyy-MM-dd kk:mm:ssThe easiest way to use it is as following:where \"yyyy-MM-dd'T'HH:mm:ss\" is the format of the reading dateoutput: Sun Apr 14 16:11:48 EEST 2013Notes: HH vs hh\n- HH refers to 24h time format\n- hh refers to 12h time formatIf you only need the time from the date, you can just use the feature of String.This will automatically cut the time part of the String and save it inside the .Here are examples of using new  to format  :It is nice about  that it can be efficiently cached as it is thread-safe (unlike )..Credits:Let's try thisOr a utility functionFrom 
Java

How do you kill a thread in Java?See this .  It goes into detail about why this was a bad method and what should be done to safely stop threads in general.  The way they recomend is to use a shared variable as a flag which asks the background thread to stop.  This variable can then be set by a different object requesting the thread terminate.  Generally you don't..You ask it to interrupt whatever it is doing using A good explanation of why is in the javadoc In Java threads are not killed, but the stopping of a thread is done in a . The thread is asked to terminate and the thread can then shutdown gracefully.Often a  field is used which the thread periodically checks and terminates when it is set to the corresponding value.I  use a  to check whether the thread should . If you use  as a field modifier, this will work reliable, but if your code becomes more complex, for instead uses other blocking methods inside the  loop, it might happen, that your code will  at all or at least  as you might want.Every thread has already a boolean flag  and you should make use of it. It can be implemented like this:Source code taken from . Since the  method is public you can let another thread invoke this method as you wanted.There is also a poorly named static method  which clears the interrupted status of the current thread.One way is by setting a class variable and using it as a sentinel.Set an external class variable, i.e. flag = true in the above example. Set it to false to 'kill' the thread.There is a way how you can do it. But if you had to use it, either you are a bad programmer or you are using a code written by bad programmers. So, you should think about stopping being a bad programmer or stopping using this bad code.\nThis solution is only for situations when THERE IS NO OTHER WAY.The question is rather vague. If you meant \u201chow do I write a program so that a thread stops running when I want it to\u201d, then various other responses should be helpful. But if you meant \u201cI have an emergency with a server I cannot restart right now and I just need a particular thread to die, come what may\u201d, then you need an intervention tool to match monitoring tools like .For this purpose I created . See its instructions for usage.I want to add several observations, based on the comments that have accumulated.There is of course the case where you are running some kind of not-completely-trusted code. (I personally have this by allowing uploaded scripts to execute in my Java environment. Yes, there are security alarm bell ringing everywhere, but it's part of the application.) In this unfortunate instance you first of all are merely being hopeful by asking script writers to respect some kind of boolean run/don't-run signal. Your only decent fail safe is to call the stop method on the thread if, say, it runs longer than some timeout.But, this is just \"decent\", and not absolute, because the code could catch the ThreadDeath error (or whatever exception you explicitly throw), and not rethrow it like a gentlemanly thread is supposed to do. So, the bottom line is AFAIA there is no absolute fail safe. I'd vote for .As for instance you have a long lasting operation (like a network request).\nSupposedly you are waiting for a response, but it can take time and the user navigated to other UI.\nThis waiting thread is now a) useless b) potential problem because when he will get result, it's completely useless and he will trigger callbacks that can lead to number of errors.All of that and he can do response processing that could be CPU intense. And you, as a developer, cannot even stop it, because you can't throw  lines in all code.So the inability to forcefully stop a thread it weird.There is no way to gracefully kill a thread.You can try to interrupt the thread, one commons strategy is to use a poison pill to message the thread to stop itself}Attempts of abrupt thread termination are well-known bad programming practice and evidence of poor application design. All threads in the multithreaded application explicitly and implicitly share the same process state and forced to cooperate with each other to keep it consistent, otherwise your application will be prone to the bugs which will be really hard to diagnose. So, it is a responsibility of developer to provide an assurance of such consistency via careful and clear application design.There are two main right solutions for the controlled threads terminations:Good and detailed explanation of the issues related to the abrupt threads termination as well as examples of wrong and right solutions for the controlled threads termination can be found here:Here are a couple of good reads on the subject:
Java

I've been programming in C# and Java recently and I am curious where the best place is to initialize my class fields.Should I do it at declaration?:or in a constructor?:I'm really curious what some of you veterans think is the best practice. I want to be consistent and stick to one approach.My rules:In C# it doesn't matter. The two code samples you give are utterly equivalent. In the first example the C# compiler (or is it the CLR?) will construct an empty constructor and initialise the variables as if they were in the constructor.\nIf there is already a constructor then any initialisation \"above\" will be moved into the top of it.In terms of best practice the former is less error prone than the latter as someone could easily add another constructor and forget to chain it.The semantics of C# differs slightly from Java here. In C# assignment in declaration is performed before calling the superclass constructor. In Java it is done immediately after which allows 'this' to be used (particularly useful for anonymous inner classes), and means that the semantics of the two forms really do match.If you can, make the fields final.I think there is one caveat. I once committed such an error: Inside of a derived class, I tried to \"initialize at declaration\" the fields inherited from an abstract base class. The result was that there existed two sets of fields, one is \"base\" and another is the newly declared ones, and it cost me quite some time to debug.The lesson: to initialize  fields, you'd do it inside of the constructor.Assuming the type in your example, definitely prefer to initialize fields in the constructor. The exceptional cases are:I always think of the field listing at the top of a class as the table of contents (what is contained herein, not how it is used), and the constructor as the introduction. Methods of course are chapters.What if I told you, it depends?I in general initialize everything and do it in a consistent way. Yes it's overly explicit but it's also a little easier to maintain. If we are worried about performance, well then I initialize only what has to be done and place it in the areas it gives the most bang for the buck.In a real time system, I question if I even need the variable or constant at all.And in C++ I often do next to no initialization in either place and move it into an Init() function. Why? Well, in C++ if you're initializing something that can throw an exception during object construction you open yourself to memory leaks.In Java, an initializer with the declaration means the field is always initialized the same way, regardless of which constructor is used (if you have more than one) or the parameters of your constructors (if they have arguments), although a constructor might subsequently change the value (if it is not final). So using an initializer with a declaration suggests to a reader that the initialized value is the value that the field has , regardless of which constructor is used and regardless of the parameters passed to any constructor. Therefore use an initializer with the declaration only if, and always if, the value for all constructed objects is the same.There are many and various situations.The situation is clear. I just need to prepare my list and prevent an exception from being thrown when someone adds an item to the list.I exactly know what values I want to have by default or I need to use some other logic.orSometimes I expect an empty list by default with a possibility of adding values through another constructor.There is a slight performance benefit to setting the value in the declaration.  If you set it in the constructor it is actually being set twice (first to the default value, then reset in the ctor).  I normally try the constructor to do nothing but getting the dependencies and initializing the related instance members with them. This will make you life easier if you want to unit test your classes.If the value you are going to assign to an instance variable does not get influenced by any of the parameters you are going to pass to you constructor then assign it at declaration time.The design of C# suggests that inline initialization is preferred, or it wouldn't be in the language. Any time you can avoid a cross-reference between different places in the code, you're generally better off.There is also the matter of consistency with static field initialization, which needs to be inline for best performance. The Framework Design Guidelines for  say this:\"Consider\" in this context means to do so unless there's a good reason not to. In the case of static initializer fields, a good reason would be if initialization is too complex to be coded inline.Being consistent is important, but this is the question to ask yourself:\n\"Do I have a constructor for anything else?\"Typically, I am creating models for data transfers that the class itself does nothing except work as housing for variables.In these scenarios, I usually don't have any methods or constructors. It would feel silly to me to create a constructor for the exclusive purpose of initializing my lists, especially since I can initialize them in-line with the declaration.So as many others have said, it depends on your usage. Keep it simple, and don't make anything extra that you don't have to.
Java

I need to figure out how to get or make a build number for my Android application. I need the build number to display in the UI. Do I have to do something with ?Use:And you can get the version code by using thisIf you're using the Gradle plugin/Android Studio, , version code and version name are available statically in . , and not another :No Context object needed!Also make sure to specify them in your  file instead of the .Slightly shorter version if you just want the version name. Yep, it's that easy now.I kept getting an empty string for  because I wasn't setting the  in my Grade build file (I migrated from ANT to Gradle). So, here are instructions for ensuring you're setting your  via Gradle.And since you've set the  and  in the  file now, you can also remove them from your  file, if they are there.There are two parts you need:\nandroid:versionCode \nandroid:versionNameversionCode is a number, and every version of the app you submit to the Market needs to have a higher number then the last.VersionName is a string, and can be anything you want it to be.  This is where you define your app as \"1.0\" or \"2.5\" or \"2 Alpha EXTREME!\" or whatever.Example:\nTo access it in code, do something like:Here is a , based on the solution of scottyab (edited by Xavi). It shows how to get the context first, if it's not provided by your method. Furthermore it uses multiple lines instead of calling multiple methods per line. This makes it easier when you have to debug your application.Now that you received the version name in the String , you can set it to a TextView or whatever you like.. If you're using PhoneGap, then create a custom PhoneGap plugin:Create a new class in your app's package:In the plugins.xml, add the following line:In your , add the following code:Then, you can get the versionName attribute by doing:Derived from  and .A very simple way is :Always do it with  block:I have SOLVE this by using Preference class. Here is the method for getting the version code:If you want to use it on xml then add below line on your gradle file:And then use it on your xml like this:For xamarin users, use this code to get version name and code1) VersionName2) VersionCodeSomeone who does\u2019t need  BuildConfig info for application's UI however wants to use these info for setting a CI job configuration or others, like me.There is a automatically generated file, BuildConfig.java, under your project directory as long as you build your project successfully.{WORKSPACE}/build/generated/source/buildConfig/{debug|release}/{PACKAGE}/BuildConfig.javaSplit information you need by python script or other tools. Here\u2019s an example:Please excuse my limited English ability, but hope this helps.First:and then use this:try this one: This code was mentioned above in pieces but here it is again all included. You need a try/catch block because it may throw a \"NameNotFoundException\".I hope this simplifies things for someone down the road. :)
Java

What is the best connection pooling library available for Java/JDBC?I'm considering the 2 main candidates (free / open-source): I've read a lot about them in blogs and other forums but could not reach a decision.Are there any relevant alternatives to these two?DBCP is out of date and not production grade. Some time back we conducted an in-house analysis of the two, creating a test fixture which generated load and concurrency against the two to assess their suitability under real life conditions. DBCP consistently generated exceptions into our test application and struggled to reach levels of performance which C3P0 was more than capable of handling without any exceptions. C3P0 also robustly handled DB disconnects and transparent reconnects on resume whereas DBCP never recovered connections if the link was taken out from beneath it. Worse still DBCP was returning Connection objects to the application for which the underlying transport had broken. Since then we have used C3P0 in 4 major heavy-load consumer web apps and have never looked back. It turns out that after many years of sitting on a shelf, the Apache Commons folk have taken  and it is now, once again, an actively developed project. Thus my original post may be out of date. That being said, I haven't yet experienced this new upgraded library's performance, nor heard of it being de-facto in any recent app framework, yet.I invite you to try out  -- it's free, open source, and faster than the available alternatives (see benchmark section).Disclaimer: I'm the author so you could say I'm biased :-)WallaceUPDATE: As of March 2010, still around 35% faster than the new rewritten Apache DBCP (\"tomcat jdbc\") pool. See dynamic benchmark link in benchmark section.Update #2: (Dec '13) After 4 years at the top, there's now a much faster competitor : Update #3: (Sep '14) Please consider BoneCP to be deprecated at this point, recommend switching to HikariCP.Update #4: (April '15) -- I no longer own the domain jolbox.com, but the new owner has kept the old content so beware.I was having trouble with DBCP when the connections times out so I trialled c3p0.  I was going to release this to production but then started performance testing.  I found that c3p0 performed terribly.  I couldn't configure it to perform well at all.  I found it twice as slow as DBCP.I then tried the .This was twice as fast as c3p0 and fixed other issues I was having with DBCP.  I spent a lot of time investigating and testing the 3 pools.  My advice if you are deploying to Tomcat is to use the new Tomcat JDBC pool.For the auto-reconnect issue with DBCP, has any tried using the following 2 configuration parameters?Have been using DBCP for a couple of years now in production. It is stable, survives DB server reboot. Just configure it properly. It only requires a handful of parameters to be specified so don't be lazy. Here is a snippet from our system production code which lists parameters that we explicitly set to make it work:Another alternative, Proxool, is mentioned in .You might be able to find out why Hibernate bundles c3p0 for its default connection pool implementation?Unfortunately they are all out of date. DBCP has been updated a bit recently, the other two are 2-3 years old, with many outstanding bugs.Here are some articles that show that DBCP has significantly higher performance than C3P0 or Proxool. Also in my own experience c3p0 does have some nice features, like prepared statement pooling and is more configurable than DBCP, but DBCP is plainly faster in any environment I have used it in.Difference between dbcp and c3p0? Absolutely nothing! (A Sakai developers blog)\nSee also the like to the JavaTech article \"Connection Pool Showdown\" in the comments on the blog post.Dbcp is production ready if configured properly.It is for example used on a commerce Website of 350000 visitors/ day and with pools of 200 connections.It handles very well timeouts provided you configure it correctly.Version 2 is on progress and it has a background which makes it reliable since Many\nProduction problems have been tackled.We use it for our batch server solution and it has been running hundreds of batches That work on millions of lines in database.Performance tests run by tomcat jdbc pool show it has better performance than cp30.Another alternative is .Here is the comparison Just got done wasting a day and a half with DBCP. Even though I'm using the latest DBCP release, I ran into exactly the same problems as  did. I would not recommend DBCP at all, especially it's knack of throwing connections out of the pool when the DB goes away, its inability to reconnect when the DB comes back and its inability to dynamically add connection objects back into the pool (it hangs forever on a post JDBCconnect I/O socket read)I'm switching over to C3P0 now. I've used that in previous projects and it worked and performed like a charm.c3p0 is good when we are using mutithreading projects. In our projects we used simultaneously multiple thread executions by using DBCP, then we got connection timeout if we used more thread executions. So we went with c3p0 configuration.A good alternative which is easy to use is . \"A Java-based database connection pooling utility, supporting time-based expiry, statement caching, connection validation, and easy configuration using a pool manager.\" 
Java

What is the difference between:and The annotation  indicates that this entity is the  of the relationship (that is: the corresponding table has a column with a foreign key to the referenced table), whereas the attribute  indicates that the entity in this side is the inverse of the relationship, and the owner resides in the \"other\" entity. This also means that you can access the other table from the class which you've annotated with \"mappedBy\" (fully bidirectional relationship).In particular, for the code in the question the correct annotations would look like this: The question was about using  on the  side (rare case). And the point here is in  (column name) along with .According to :Since  (almost) always the  of a bidirectional relationship in the JPA spec, the one to many association is annotated by @OneToMany(mappedBy=...)Troop has a bidirectional one to many relationship with Soldier through the troop property. You don't have to (must not) define any physical mapping in the mappedBy side.To map a bidirectional one to many, with the , you have to remove the mappedBy element and set the many to one @JoinColumn as insertable and updatable to false. This solution is not optimized and will produce some additional UPDATE statements.The annotation  ideally should always be used in the Parent side (Company class) of the bi directional relationship, in this case it should be in Company class pointing to the member variable 'company' of the Child class (Branch class) The annotation  is used to specify a mapped column for joining an entity association, this annotation can be used in any class (Parent or Child) but it should ideally be used only in one side (either in parent class or in Child class not in both) here in this case i used it in the Child side (Branch class) of the bi directional relationship indicating the foreign key in the Branch class.below is the working example :I'd just like to add that  does not always have to be related to the  as  answer suggests.  You can combine  with  even if the parent table has no table data pointing to the child table.It seems to only be available in  though.  It's useful for situations where you want the child class to just contain the ID of the parent, not a full on reference.
Java

I read  and thought that would easily be solved (not that it isn't solvable without) if one could write: I'm not sure if it is useful in many cases, but I wonder  it isn't and if something like this exists in other languages.What do you guys think?\nTo clarify: yes I know, that's impossible in Java and I don't really miss it. This is nothing I expected to work and was surprised getting a compiler error. I just had the idea and like to discuss it.It violates encapsulation. You shouldn't be able to bypass the parent class's behaviour. It makes sense to sometimes be able to bypass your  class's behaviour (particularly from within the same method) but not your parent's. For example, suppose we have a base \"collection of items\", a subclass representing \"a collection of red items\" and a subclass of that representing \"a collection of big red items\". It makes sense to have:That's fine - RedItems can always be confident that the items it contains are all red. Now suppose we  able to call super.super.add():Now we could add whatever we like, and the invariant in  is broken.Does that make sense?I think Jon Skeet has the correct answer. I'd just like to add that you  access shadowed variables from superclasses of superclasses by casting :which produces the output:(example from the )However, this  because method calls are determined based on the runtime type of the object.I think the following code allow to use super.super...super.method() in most case.\n(even if it's uggly to do that)Usage :I don't have enough reputation to comment so I will add this to the other answers.Jon Skeet answers excellently, with a beautiful example. Matt B has a point: not all superclasses have supers. Your code would break if you called a super of a super that had no super. Object oriented programming (which Java is) is all about objects, not functions. If you want task oriented programming, choose C++ or something else. If your object doesn't fit in it's super class, then you need to add it to the \"grandparent class\", create a new class, or find another super it does fit into. Personally, I have found this limitation to be one of Java's greatest strengths. Code is somewhat rigid compared to other languages I've used, but I always know what to expect. This helps with the \"simple and familiar\" goal of Java. In my mind, calling super.super is not simple or familiar. Perhaps the developers felt the same? In addition to the very good points that others have made, I think there's another reason: what if the superclass does not have a superclass?Since every class naturally extends (at least) ,  will always refer to a method in the superclass. But what if your class only extends  - what would  refer to then? How should that behavior be handled - a compiler error, a NullPointer, etc?I think the primary reason why this is not allowed is that it violates encapsulation, but this might be a small reason too.There's some good reasons to do this. You might have a subclass which has a method which is implemented incorrectly, but the parent method is implemented correctly. Because it belongs to a third party library, you might be unable/unwilling to change the source. In this case, you want to create a subclass but override one method to call the super.super method.As shown by some other posters, it is possible to do this through reflection, but it should be possible to do something like(SuperSuperClass this).theMethod();I'm dealing with this problem right now - the quick fix is to copy and paste the superclass method into the subsubclass method :)I think if you overwrite a method and want to all the super-class version of it (like, say for ), then you virtually always want to call the direct superclass version first, which one will call its superclass version in turn if it wants. I think it only makes rarely sense (if at all. i can't think of a case where it does) to call some arbitrary superclass' version of a method. I don't know if that is possible at all in Java. It can be done in C++:At a guess, because it's not used that often.  The only reason I could see using it is if your direct parent has overridden some functionality and you're trying to restore it back to the original.Which seems to me to be against OO principles, since the class's direct parent should be more closely related to your class than the grandparent is.I would put the super.super method body in another method, if possibleOr if you cannot change the super-super class, you can try this:In both cases, theresults to \"I am super super\"Here's a little something I'm using every time I need to call a method from a grandparent or grand.grandparent or grand.grand.grand....you get the idea.Say you have class A which instantiates class B which instantiates class C like so A->B->C1.create a private static A variable in A class;\n2.inside the constructor of A, set the instance variable to this;\n3. create a public static method in A class, which returns the instance of A class;\n4. use this method from any children necessary in order to access any public method from A;}After you can go to child class C or whatever and use it like so:It would seem to be possible to at least get the class of the superclass's superclass, though not necessarily the instance of it, using reflection; if this might be useful, please consider the Javadoc at run:\nA\nBUILD SUCCESSFUL (total time: 0 seconds)I have had situations like these when the architecture is to build common functionality in a common CustomBaseClass which implements on behalf of several derived classes.\nHowever, we need to circumvent common logic for specific method for a specific derived class. In such cases, we must use a super.super.methodX implementation.We achieve this by introducing a boolean member in the CustomBaseClass, which can be used to selectively defer custom implementation and yield to default framework implementation where desirable.However, with good architecture principles followed in framework as well as app, we could avoid such situations easily, by using hasA approach, instead of isA approach. But at all times it is not very practical to expect well designed architecture in place, and hence the need to get away from solid design principles and introduce hacks like this.\nJust my 2 cents...@Jon Skeet Nice explanation. \nIMO if some one wants to call super.super method then one must be want to ignore the behavior of immediate parent, but want to access the grand parent behavior.\nThis can be achieved through instance Of. As below codeHere is driver class,Output of this will be Class B printClass behavior will be ignored in this case.\nI am not sure about is this a ideal or good practice to achieve super.super, but still it is working.Output: Printed in the GrandDadIf you think you are going to be needing the superclass, you could reference it in a variable for that class. For example:Should print out:IMO, it's a clean way to achieve  behavior in Java.Output:\nCalling of super.super.method() make sense when you can't change code of base class. This often happens when you are extending an existing library.Ask yourself first, why are you extending that class? If answer is \"because I can't change it\" then you can create exact package and class in your application, and rewrite naughty method or create delegate:For instance, you can create  class in your application so this class should be loaded before the real one from jar. Then rewrite methods or constructors. This is absolute hack, and it is highly NOT recommended to use but it's WORKING! Using of this approach is dangerous because of possible issues with class loaders. Also this may cause issues each time you will update library that contains overwritten class.I think this is a problem that breaks the inheritance agreement. \nBy extending a class  you obey / agree  its behavior, features \nWhilst when calling , you want to break your own obedience  agreement.. However,  there  may happen situations when you feel the need to call  -  usually a bad design sign,  in your code or in the code you inherit ! \nIf the  and  classes cannot be refactored (some legacy code), then opt for composition over inheritance.\nEncapsulation breaking is when you  some methods by breaking the encapsulated code.\nThe methods  designed not to be overridden are marked\n .It is simply easy to do. For instance:C subclass of B and B subclass of A. Both of three have method methodName() for example.public abstract class A {}public class B extends A {}public class C extends B {}Run class C Output will be:\nClass A\nClass CInstead of output:\nClass A\nClass B\nClass C
Java

In C#, I can use the  statement to rethrow an exception while preserving the stack trace:Is there something like this in Java ()?will simply rethrow the exception you've caught (obviously the surrounding method has to permit this via its signature etc.). The exception will maintain the original stack trace.I would prefer:You can also wrap the exception in another one AND keep the original stack trace by passing in the Exception as a Throwable as the cause parameter:In Java is almost the same:In Java, you just throw the exception you caught, so  rather than just . Java maintains the stack trace.something like thisThis is a concrete example where the method throws an . The  means  can only hold an exception thrown from the try block. Additional reading material can be found  and .
Java

So I have tried to add my local .jar file dependency to my build.gradle file:And you can see that I added the .jar files into the referencedLibraries folder here: But the problem is that when I run the command: gradle build on the command line I get the following error:Here is my entire repo: If you really need to take that .jar from a local directory, Add next to your module gradle (Not the app gradle file):However, being a standard .jar in an actual maven repository, why don't you try this?According to , use a relative path for a local jar dependency as follows:You could also do this which would include all JARs in the local repository.  This way you wouldn't have to specify it every time.The accepted answer is good, however, I would have needed various library configurations within my multi-project Gradle build to use the same 3rd-party Java library. Adding '' to the '' path element within my '' closure meant each sub-project referenced the same '' directory, and  a version local to that sub-project:EDIT by Quizzie: changed \"${rootProject.projectDir}\" to \"$rootProject.projectDir\" (works in the newest Gradle version).A simple way to do this is it will compile all the .jar files in your libs directory in App.You can try reusing your local Maven repository for Gradle:I couldn't get the suggestion above at  to work.  This worked for me though.  For a file  that I stored in a  directory in the root of the project:The Question already has been answered in detail. I still want to add something that seems very surprising for me:The \"gradle dependencies\" task does not list any file dependencies. Even though you might think so, as they have been specified in the \"dependencies\" block after all..So don't rely on the output of this to check whether your referenced local lib files are working correctly.Goto File -> Project Structure -> Modules -> app -> Dependencies Tab -> Click on +(button) -> Select File Dependency - > Select jar file in the lib folderThis steps will automatically add your dependency to graldeVery Simple The best way to do it is to add this in your build.gradle file and hit the sync option The solution which worked for me is the usage of fileTree in build.gradle file.\nKeep the .jar which need to add as dependency in libs folder. The give the below code in dependenices block in build.gradle:An other way:Add library in the tree view. Right click on this one. Select menu \"Add As Library\".\nA dialog appear, let you select module. OK and it's done.
Java

HashSet is based on HashMap.If we look at  implementation, everything is been managed under . is used as a key of .And we know that  is not thread safe. That is why we have  in Java.Based on this, I am confused that Is there anything else that I am missing? I need to use  in a multi-threaded environment.Also, If I want to create my own  can I achieve it by just replacing the  to  and leaving the rest as is?There's no built in type for  because you can always  a set from a map. Since there are many types of maps, you use a method to produce a set from a given map (or map class).Prior to Java 8, you produce a concurrent hash set backed by a concurrent hash map, by using In Java 8 (pointed out by @Matt), you can get a concurrent hash set  via . This is a bit simpler than the old  which required you to pass in an empty map object. But it is specific to .Anyway, the Java designers could have created a new set interface every time a new map interface was created, but that pattern would be impossible to enforce when third parties create their own maps. It is better to have the static methods that derive new sets; that approach always works, even when you create your own map implementations.With  15 you can also simply use:It looks like Java provides a concurrent Set implementation with its .  A  is just a special kind of set implementation.  It still implements the Serializable, Cloneable, Iterable, Collection, NavigableSet, Set, SortedSet interfaces.  This might work for you if you only need the Set interface. You can use guava's  to get one. Java 6 also has that method in As pointed by  the best way to obtain a concurrency-able HashSet is by means of This worked for me and I haven't seen anybody really pointing to it. This is less efficient than the currently aproved solution, as Eugene points out, since it just wraps your set into a synchronized decorator, while a  actually implements low-level concurrency and it can back your Set just as fine. So thanks to Mr. Stepanenkov for making that clear.Like  mentioned it is as easy as:Why not use: CopyOnWriteArraySet from java.util.concurrent?
Java

I was reading Java's  source code and noticed some comparisons in if-statements.In Java 7, the method  usesIn Java 6,  didn't exist. The method  however usesWhat was the reason behind the change? Was it a performance issue or just a style? I could imagine that comparing against zero is faster, but performing a complete subtraction just to check whether it's negative seems a bit overkill to me. Also in terms of bytecode, this would involve two instructions ( and ) instead of one (). and  can mean two different things. Consider the following code:When run, this will only print . What happens is that  is clearly false, but  overflows and becomes , which is negative.Now, having said that, consider that the array has a length that is really close to . The code in  goes like this: is really close to  so  (which is ) might overflow and become  (i.e. negative). Then, subtracting   back into a positive number.This check ensures that the  is not executed. If the code were written as , it would be  in this case (since  is negative) so the  would be forced to  regardless of the .This overflow case is handled by the next if. When  has overflowed, this will be :  is defined as  and  is . The  is therefore rightly handled:  method returns  or .NB: this is what the  comment in this method is saying.I found :In Java 6, if you use the API as:And  overflows (this becomes negative),  will return false and you may mistakenly assume that the  was increased by .Looking at the code:If  is quite large, this will overflow, and  will be a negative number. A comparison like  will incorrectly evaluate  and the  will fail to grow.Instead, the code as written ( returns false) will allow the negative value of  to be further evaluated in the next line, resulting in recalculating  by invoking  () to allow for the  to grow up to .This is what the  comment is trying to communicate, though rather obliquely.So, bottom line, the new comparison protects against allocating an  larger than the predefined  while allowing it to grow right up to that limit if needed.The two forms behave exactly the same unless the expression  overflows, in which case they are opposite.  If  is a large negative, and  is a large positive, then  is clearly true, but  will overflow to become positive, so  is false.If you're familiar with x86 assembly code, consider that  is implemented by a , which branches around the body of the if statement when SF = OF.  On the other hand,  will act like a , which branches when SF = 0.  Hence, these behave differently precisely when OF = 1.
Java

My application  has the following flow screens :Now I have a common   button in each screens() I want that when user clicks on the log out button(from any screen), all the screens will be finished and a new screen  will open . I have tried nearly all  to achieve this.\nI also go through some answers in stackoverflow, but not being able to solve the problem.\nMy application is on Android 1.6 so not being able to use  Is there any way to solve the issue ?Use: This will clear all the activities on top of home. Assuming you are finishing the login screen when the user logs in and home is created and afterwards all the screens from 1 to 5 on top of that one. The code i posted will return you to home screen finishing all the other activites. You can add an extra in the intent and read that in the home screen activity and finish it also (maybe launch login screen again from there or something).I am not sure but you can also try going to login with this flag. I don't know how the activities will be ordered in that case. So don't know if it will clear the ones below the screen you are on including the one you are currently on but its definitely the way to go.Hope this helps. You may try . It will totally clears all previous activity(s) and start new activity. Before launching your new Activity, simply add the following code:Or if you want it to work in previous versions of Android:, they should press a button which loads the first Activity that runs when your application starts, clear all the other activities, then have the last remaining activity finish. Have the following code run when the user presses the exit button. In my case,  is the first activity in my program to run.The above code clears all the activities except for . Then put the following code inside the 's , to listen for when  is recreated and the 'EXIT' signal was passed:Android tries hard to discourage you from having an \"exit\" button in your application, because they want the user to never care about whether or not the programs they use are running in the background or not. The Android OS developers want your program to be able to survive an unexpected shutdown and power off of the phone, and when the user restarts the program, they pick up right where they left off. So the user can receive a phone call while they use your application, and open maps which requires your application to be freed for more resources. When the user resumes your application, they pick up right where they left off with no interruption. This exit button is usurping power from the activity manager, potentially causing problems with the automatically managed android program life cycle.This Will work for all Android versions. Where  the class added in Android Support library. Use the following for activityremove CLEAR_TASK flag for fragment use.I hope this may use for some people.From :Finish this activity as well as all activities immediately below it in the current task that have the same affinity. This is typically used when an application can be launched on to another task (such as from an ACTION_VIEW of a content type it understands) and the user has used the up navigation to switch out of the current task and in to its own task. In this case, if the user has navigated down into any other activities of the second application, all of those should be removed from the original task as part of the task switch.Note that this finish does not allow you to deliver results to the previous activity, and an exception will be thrown if you are trying to do so.A solution I implemented for this (I think I found it on Stack\u00a0Overflow somewhere, but I don't remember, so thanks to whoever did that in the first place):From any of your activities do this:Then in your LoginActivity, overwrite onKeyDown:For logout button on last screen of app, use this code on logout button listener to finish all open previous activities, and your problem is solved.    i have same problem\nyou can use  , like this :this code work for me .Android api If your application has minimum sdk version 16 then you can use Finish this activity as well as all activities immediately below it in the current task that have the same affinity.This is work for me In Top Payment screen remove all back-stack activits,Log in->Home->screen 1->screen 2->screen 3->screen 4->screen 5on screen 4 (or any other) -> If you are using  in your previous activities, just override  and call the  method inside it in all activities.. This will do the job...When user click on the logout button then write the following code:And also when after login if you call new activity do not use finish();for API >= 15 to API 23\nsimple solution.If you log in the user in  and from there you go to the other screens, use Simply, when you go from the login screen, not when finishing the login screen.And then in all forward activities, use this for logout:It works perfectly.I found this way, it'll clear all history and exitI found this solution to work on every device despite API level (even for < 11)On a side note, good to know\nThis answer works ()whereas this doesn't work  and doesn't append any new flags while  does.So this will also work
Java

I was using IntelliJ-IDEA IDE , I want to create a jar file from java compiled class files. but I not found command or file, How to create a jar file (like eclipse java archive export)\nthen you should press  or click the plus icon and create new artifact choose --> Next goto  --> choose your artifact.source:\nYou didn't specify your IDEA version. Before 9.0 use , in IDEA 9.0 use .In intellij8 I was using a specific plugin \"Jar Tool\" that is configurable and allows to pack a JAR archive.
Java

Since I use Maven I have been able to build and install in my local repository projects that have incomplete java doc tags (for example, a missing parameter). However, since I migrated to Java 8 (1.8.0-ea-b90) Maven is absolutely strict about missing documentation tags and show me lots of JavaDoc errors related to JavaDoc problems when I try to build or install a project where the JavaDoc is not \"perfect\". Some of the projects I am trying to compile and install in my local repository are third party projects from which I do not have control. So the workaround of just fixing all the javadocs in all these projects does not seem to be feasable in my scenario.This is a small part of the output I see when I execute  in my project:The JavaDoc plugin is configured like this in my POM:As I said before, everything is working fine if I go back to Java 7. \nMaybe is this a bug related to Maven running in Java 8 ?\nHow could I make it work (i.e., being able to build the Javadoc of the project and install its code in my local repository) with Java 8 ?\nI have tested with both Maven 3.0.3 and 3.0.5 in OSX.If I change my JavaDoc plugin configuration with  (thanks Martin):Then the project is installed in my local repository. However, the javadoc jar is still not generated:A fragment of the output I see in the console with this new configuration is:Any workaround about how to build the sources, install the project and generate the Java doc jar in one step as it was working with Java 7 ?The best solution would be to fix the javadoc errors. If for some reason that is not possible (ie: auto generated source code) then you can disable this check., which is summarized as:This is enabled by default, and will run a whole lot of checks before generating Javadocs. You need to turn this off for Java 8 as specified . You'll have to add this to your maven configuration:The easiest approach to get things working with both java 8 and java 7 is to use a profile in the build:Here is the most concise way I am aware of to ignore doclint warnings regardless of java version used. There is no need to duplicate plugin configuration in multiple profiles with slight modifications.Tested on oracle/open jdk 6, 7 and 8.Add into the global properties section in the pom file:The common solution provided here in the other answers (adding that property in the plugins section) did not work for some reason. Only by setting it globally I could build the javadoc jar successfully.Overriding  configuration only, does not fix the problem with  (used e.g during the release stage). Here's what I had to do:I don't think just turning off DocLint is a good solution, at least not long term. It is good that Javadoc has become a bit more strict so the right way to fix the build problem is to . Yes, you'll ultimately need to fix those source code files.Here are the things to look out for that you could previously get away with:You'll simply have to fix your source code files and keep building your Javadoc until it can build without a failure. Cumbersome yes, but personally I like when I have brought my projects up to DocLint level because it means I can be more confident that the Javadoc I produce is actually what I intend.There's of course the problem if you are generating Javadoc on some source code you've not produced yourself, for example because it comes from some code generator, e.g. . Strange that Oracle didn't prepare their own tools for JDK8 compliance before actually releasing JDK8. It seems . Only in this particular case I suggest to turn off DocLint as documented elsewhere on this page.Just add that to your POM and you're good to go.This is basically  plus .You could try setting the  property (see ) to :As you can see from the docs, the default value is .Since it depends on the version of your JRE which is used to run the maven command you propably dont want to disable  per default in your pom.xmlHence, from command line you can use the switch .Example: I'm not sure if this is going to help, but even i faced the exact same problem very recently with  version.  After reading through the above answers i have just added the maven option through command line and it worked for me.  So, just sharing here.I'm using java , haven't tried with java 1.7  bin/mkdistro.sh -DskipTests   
Java

I want to join a  with a glue string. Is there a function for this? has a  class which has a  function which will join arrays together to make a .For example:Generates the following :[EDIT: Update for Java8]Starting from Java8 it is possible to use  , too.Generates the same :If you were looking for what to use in android, it is:for example:You could easily write such a function in about ten lines of code:In Java 8 you can use 1) Stream API :2) new String.join method:  3) java.util.StringJoiner class: A little mod instead of using substring():Java 8 added a new static method to  which does exactly what you want:Using it:Results in:Google guava's library also has . You can see the String[] example also from the API.As already described in the api, beware of the immutability of the builder methods.It can accept an array of objects so it'll work in your case. In my previous experience, i tried joining a Stack which is an iterable and it works fine.Sample from me :prints out : Given:Then as an alternative to coobird's answer, where the glue is \", \":Or to concatenate with a different string, such as \" &amp; \".However... this one ONLY works if you know that the values in the array or list DO NOT contain the character string \", \".If you are using the  then you have the  class:Not in core, no. A search for \"java array join string glue\" will give you some code snippets on how to achieve this though.e.g.If you've landed here looking for a quick array-to-string conversion, try .Just for the  challenge, here are mines ;)Nothing built-in that I know of.Apache  has a class called  which contains many join functions.This is how I do it.A similar alternativeMy spin.Do you like my 3-lines way using only String class's methods?To get \"str1, str2\" from \"str1\", \"str2\", \"\" :Also you can add extra null-checkIn case you're using Functional Java library and for some reason can't use Streams from Java 8 (which might be the case when using Android + Retrolambda plugin), here is a functional solution for you:Note that it's not the most efficient approach, but it does work good for small lists.I do it this way using a StringBuilder:java.util.Arrays has an 'asList' method. Together with the java.util.List/ArrayList API this gives you all you need:;
Java

Edited:\nI need to change the values of several variables as they run several times thorugh a timer. I need to keep updating the values with every iteration through the timer. I cannot set the values to final as that will prevent me from updating the values however I am getting the error I describe in the initial question below:I had previously written what is below:Java doesn't support true , even though using an anonymous class like you are using here (new TimerTask() { ... }) looks like a kind of closure. - This is why it doesn't work:The variables lastPrice and price are local variables in the main() method. The object that you create with the anonymous class might last until after the main() method returns.When the main() method returns, local variables (such as lastPrice and price) will be cleaned up from the stack, so they won't exist anymore after main() returns.But the anonymous class object references these variables. Things would go horribly wrong if the anonymous class object tries to access the variables after they have been cleaned up.By making lastPrice and price , they are not really variables anymore, but constants. The compiler can then just replace the use of lastPrice and price in the anonymous class with the values of the constants (at compile time, ofcourse), and you won't have the problem with accessing non-existent variables anymore.Other programming languages that do support closures do it by treating those variables specially - by making sure they don't get destroyed when the method ends, so that the closure can still access the variables.@Ankur: You could do this:To avoid strange side-effects with closures in java variables referenced by an anonymous delegate must be marked as final, so to refer to lastPrice and price within the timer task they need to be marked as final.This obviously won't work for you because you wish to change them, in this case you should look at encapsulating them within a class.now just create a new Foo as final and call .tick from the timer.You can only access final variables from the containing class when using an anonymous class.  Therefore you need to declare the variables being used final (which is not an option for you since you are changing  and ), or don't use an anonymous class.So your options are to create an actual inner class, in which you can pass in the variables and use them in a normal fashionor:There is a quick (and in my opinion ugly) hack for your  and  variable which is to declare it like soand in your anonymous class you can set the value like thisGood explanations for why you can't do what you're trying to do already provided. As a solution, maybe consider:Seems like probably you could do a better design than that, but the idea is that you could group the updated variables inside a class reference that doesn't change.With anonymous classes, you are actually declaring a \"nameless\" nested class. For nested classes, the compiler generates a new standalone public class with a constructor that will take all the variables it uses as arguments (for \"named\" nested classes, this is always an instance of the original/enclosing class). This is done because the runtime environment has no notion of nested classes, so there needs to be a (automatic) conversion from a nested to a standalone class. Take this code for example:That won't work, because this is what the compiler does under the hood:The original anonymous class is replaced by some standalone class that the compiler generates (code is not exact, but should give you a good idea):As you can see, the standalone class holds a reference to the shared object, remember that everything in java is pass-by-value, so even if the reference variable 'shared' in EnclosingClass gets changed, the instance it points to is not modified, and all other reference variables pointing to it (like the one in the anonymous class: Enclosing$1), will not be aware of this. This is the main reason the compiler forces you to declare this 'shared' variables as final, so that this type of behavior won't make it into your already running code. Now, this is what happens when you use an instance variable inside an anonymous class (this is what you should do to solve your problem, move your logic to an \"instance\" method or a constructor of a class):This compiles fine, because the compiler will modify the code, so that the new generated class Enclosing$1 will hold a reference to the instance of EnclosingClass where it was instantiated (this is only a representation, but should get you going):Like this, when the reference variable 'shared' in EnclosingClass gets reassigned, and this happens before the call to Thread#run(), you'll see \"other hello\" printed twice, because now EnclosingClass$1#enclosing variable will keep a reference to the object of the class where it was declared, so changes to any attribute on that object will be visible to instances of EnclosingClass$1.For more information on the subject, you can see this excelent blog post (not written by me): When I stumble upon this issue, I just pass the objects to the inner class through the constructor. If I need to pass primitives or immutable objects (as in this case), a wrapper class is needed.Edit: Actually, I don't use an anonymous class at all, but a proper subclass:You cannot refer to non-final variables because Java Language Specification says so. From 8.1.3:\n\"Any local variable, formal method parameter or exception handler parameter used but not declared in an inner class must be declared final.\" \nI can see only part of your code - according to me scheduling modification of local variables is a strange idea. Local variables cease to exist when you leave the function. Maybe static fields of a class would be better?I just wrote something to  something along the . \nI found the best thing to do was to let  all the objects and then in your implemented method use that constructor objects. However, if you are writing a generic interface class, then you have to pass an Object, or better a list of Objects. This could be done by Object[] or even better,  because it is easier to call.See my example piece just below.Please see this post about Java closures that supports this out of the box:\nVersion 1 supports passing of non-final closures with autocasting:\nIf you want to change a value in a method call within an anonymous class, that \"value\" is actually a . So, if you use Guava, you can writeOne solution I have noticed isn't mentioned (unless I missed it, if I did please correct me), is the use of a class variable. Ran into this issue attempting to run a new thread within a method: . Calling  from the following will work. You do not necessarily have to declare it , just need to change the scope of the variable so it is not collected before the innerclass. This is unless of course your process is huge and changing the scope might create some sort of conflict. I didn't want to make my variable final as it was in no way a final/constant.If the variable required to be final, cannot be then you can assign the value of the variable to another variable and make THAT final so you can use it instead.use ClassName.this.variableName to reference the non-final variableCan you make , , and  fields of the anonymous inner class?The main concern is whether a variable inside the anonymous class instance can be resolved at run-time. It is not a must to make a variable final as long as it is guaranteed that the variable is inside the run-time scope. For example, please see the two variables _statusMessage and _statusTextView inside updateStatus() method.what worked for me is just define the variable outside this function of your.Just before main function declare i.e.Declare the variable as a static and reference it in the required method using className.variableyou can just declare the variable outside the outer class. After this, you will be able to edit the variable from within the inner class. I sometimes face similar problems while coding in android so I declare the variable as global and it works for me.Just an another explanation. Consider this example belowHere Output will bem1 Completes Thread t runningThread t runningThread t running................Now method m1() completes and we assign reference variable o to null , Now Outer Class Object is eligible for GC but Inner Class Object is still exist who has (Has-A) relationship with Thread object which is running. Without existing Outer class object there is no chance of existing m1() method and without existing m1() method there is no chance of existing its local variable but if Inner Class Object uses the local variable of m1() method then everything is self explanatory.To solve this we have to create a copy of local variable and then have to copy then into the heap with Inner class object, what java does for only final variable because they are not actually variable they are like constants(Everything happens at compile time only not at runtime).To solve the problem above, different languages make different decisions.for Java, the solution is as what we see in this article.for C#, the solution is allow side-effects and capture by reference is the only option.for C++11, the solution is to allow the programmer make the decision. They can choose to capture by value or by reference. If capturing by value, no side-effects would occur because the variable referenced is actually different. If capture by reference, side-effects may occur but the programmer should realize it.Because it's confusing if the variable isn't final, as the changes to it won't be picked up in the anonymous class.Just make the variables 'price' and 'lastPrice' final.-- EditOops, and you'll also need to not assign to them, obviously, in your function. You'll need new local variables. Anyway, I suspect someone has given you a better answer by now.
Java

I have a Spring MVC web app which uses Spring Security.  I want to know the username of the currently logged in user.  I'm using the code snippet given below .  Is this the accepted way?  I don't like having a call to a static method inside this controller - that defeats the whole purpose of Spring, IMHO.  Is there a way to configure the app to have the current SecurityContext, or current Authentication, injected instead?  If you are using , the easiest way is:A lot has changed in the Spring world since this question was answered. Spring has simplified getting the current user in a controller. For other beans, Spring has adopted the suggestions of the author and simplified the injection of 'SecurityContextHolder'. More details are in the comments.This is the solution I've ended up going with.  Instead of using  in my controller, I want to inject something which uses  under the hood but abstracts away that singleton-like class from my code.  I've found no way to do this other than rolling my own interface, like so:Now, my controller (or whatever POJO) would look like this:And, because of the interface being a point of decoupling, unit testing is straightforward. In this example I use Mockito:The default implementation of the interface looks like this:And, finally, the production Spring config looks like this:It seems more than a little silly that Spring, a dependency injection container of all things, has not supplied a way to inject something similar.  I understand  was inherited from acegi, but still.  The thing is, they're so close - if only  had a getter to get the underlying  instance (which is an interface), you could inject that.  In fact, I even  to that effect.One last thing - I've just substantially changed the answer I had here before.  Check the history if you're curious but, as a coworker pointed out to me, my previous answer would not work in a multi-threaded environment.  The underlying  used by  is, by default, an instance of , which stores s in a .  Therefore, it is not necessarily a good idea to inject the  directly into a bean at initialization time - it may need to be retrieved from the  each time, in a multi-threaded environment, so the correct one is retrieved.To make it just show up in your JSP pages, you can use the Spring Security Tag Lib:To use any of the tags, you must have the security taglib declared in your JSP:Then in a jsp page do something like this:NOTE: As mentioned in the comments by @SBerg413, you'll need to add to the \"http\" tag in the security.xml config for this to work.I agree that having to query the SecurityContext for the current user stinks, it seems a very un-Spring way to handle this problem.I wrote a static \"helper\" class to deal with this problem; it's dirty in that it's a global and static method, but I figured this way if we change anything related to Security, at least I only have to change the details in one place:I get authenticated user by\nHttpServletRequest.getUserPrincipal();Example:If you are using Spring Security ver >= 3.2, you can use the  annotation:Here,  is a custom object that implements  that is returned by a custom .More information can be found in the  chapter of the Spring Security reference docs.In Spring 3+ you have have following options.Option 1 : Option 2 : Option 3:Option 4 : Fancy one : Yes, statics are generally bad - generally, but in this case, the static is the most secure code you can write.  Since the security context associates a Principal with the currently running thread, the most secure code would access the static from the thread as directly as possible.  Hiding the access behind a wrapper class that is injected provides an attacker with more points to attack.  They wouldn't need access to the code (which they would have a hard time changing if the jar was signed), they just need a way to override the configuration, which can be done at runtime or slipping some XML onto the classpath.  Even using annotation injection in the signed code would be overridable with external XML.  Such XML could inject the running system with a rogue principal.  This is probably why Spring is doing something so un-Spring-like in this case.I would just do this:For the last Spring MVC app I wrote, I didn't inject the SecurityContext holder, but I did have a base controller that I had two utility methods related to this  ... isAuthenticated() & getUsername(). Internally they do the static method call you described.At least then it's only in once place if you need to later refactor.You could use Spring AOP aproach.\nFor example if you have some service, that needs to know current principal. You could introduce custom annotation i.e. @Principal , which indicate that this Service should be principal dependent.Then in your  advice, which I think needs to extend MethodBeforeAdvice, check that particular service has @Principal annotation and inject Principal name, or set it to 'ANONYMOUS' instead.The only problem is that even after authenticating with Spring Security, the user/principal bean doesn't exist in the container, so dependency-injecting it will be difficult.  Before we used Spring Security we would create a session-scoped bean that had the current Principal, inject that into an \"AuthService\" and then inject that Service into most of the other services in the Application.  So those Services would simply call authService.getCurrentUser() to get the object.  If you have a place in your code where you get a reference to the same Principal in the session, you can simply set it as a property on your session-scoped bean.The best solution if you are using Spring 3 and need the authenticated principal in your controller is to do something like this:Try thisI am using the  annotation in  classes as well as in  annotated ones. Ex.:Where  is the class i use for logged users services, and extends from . Something like:Really easy.Define  as a dependency in your controller method and spring will inject the current authenticated user in your method at invocation.this is old question but still we have different way to get user name during July-2016 using Spring 4, Boot, Security, OAuth2 and Angular2 \nPlease correct me if I'm wrong because I'm looking for simple solutionI like to share my way of supporting user details on freemarker page.\nEverything is very simple and working perfectly!You just have to place Authentication rerequest on  (page after form-login)\nThis is my Controler method for that page:And this is my ftl code:And that's it, username will appear on every page after authorisation.
Java

Which annotation,  () or  (Spring specific) should I be using when using DI?I have successfully used both in the past,  and My instinct is to stick with the  tag since it's been ratified by the jsr people.  Anyone have strong thoughts on this?In spring pre-3.0 it doesn't matter which one.In spring 3.0 there's support for the standard () annotation  - use it, with a combination of . Note that spring now also supports the  meta-annotation:So you can haveorAnd then:This makes less use of String-names, which can be misspelled and are harder to maintain.As for the original question: both, without specifying any attributes of the annotation, perform injection by type. The difference is:Both  (or ) and  work equally well. But there is a conceptual difference or a difference in the meaningSo, basically these are two quite distinct concepts. Unfortunately the Spring-Implementation of  has a built-in fallback, which kicks in when resolution by-name fails. In this case, it falls back to the -kind resolution by-type. While this fallback is convenient, IMHO it causes a lot of confusion, because people are unaware of the conceptual difference and tend to use  for type-based autowiring.The primary difference is,  is a spring annotation. Whereas  is specified by the JSR-250, as you pointed out yourself. So the latter is part of Java whereas the former is Spring specific.Hence, you are right in suggesting that, in a sense. I found folks use  with  because it is more powerful. Moving from some framework to some other is considered very unlikely, if not myth, especially in the case of Spring.I would like to emphasize one comment from  on  to this question. The comment brings a useful link: . I encourage you to read it entirely, however here is a quick summary of its usefulness: and Avoid  annotations unless you want to create a list of similar beans. For example you may want to mark a set of rules with a specific  annotation. This approach makes it simple to inject a group of rule classes into a list that can be used for processing data.Scan specific packages for components . While this will result in more  configurations it reduces the chance that you\u2019ll add unnecessary components to your Spring context. This is what I got from the  :-Both of them are equally good. The advantage of using Resource is in future if you want to another DI framework other than spring, your code changes will be much simpler. Using Autowired your code is tightly coupled with springs DI.@Autowired + @Qualifier will work only with spring DI, if you want to use some other DI in future @Resource is good option.other difference which I found very significant is @Qualifier does not support dynamic bean wiring, as @Qualifier does not support placeholder, while @Resource does it very well.For example:\nif you have an interface with multiple implementations like thiswith @Autowired & @Qualifier you need to set specific child implementation \nlike which does not provide placeholder while with @Resource you can put placeholder and use property file to inject specific child implementation likewhere service.name is set in property file as  Hope that helps someone :) is often used by high-level objects, defined via JNDI.  or  will be used by more common beans.As far as I know, it's not a specification, nor even a convention. It's more the logical way standard code will use these annotations.As a note here:\n and   work with   annotation. So, there are difference.
Java

I have an interface which returns .I would like to manipulate that result using the Java 8 Stream API.However Iterable can't \"Stream\". Any better idea how to use streams (without converting Iterable to List)?There's a much better answer than using  directly, which is both easier and gets a better result.   has a  method, so you should just use that to get your spliterator.  In the worst case, its the same code (the default implementation uses ), but in the more common case, where your  is already a collection, you'll get a better spliterator, and therefore better stream performance (maybe even good parallelism.)  Its also less code: As you can see, getting a stream from an Iterable (see ) is not very painful.  If you can use Guava library, since version 21, you can useYou can easily create a  out of an  or :I would like to suggest using  library, it hides spliterator magic behind the Seq.seq(iterable) call and also provides a whole bunch of additional useful functionality.I've created this class:I think it's perfectly readable because you don't have to think about spliterators and booleans (isParallel).A very simple work-around for this issue is to create a  extending  that holds a  method.Now any of your s can be trivially made streamable just by declaring them  instead of .
Java

I'm trying to understand how the concepts of ,  and  in the Java heap terminology, and more specifically the interactions between the three generations.My questions are:This seems like a common misunderstanding. In Oracle's JVM, the permanent generation is not part of the heap. It's a separate space for class definitions and related data. In Java 6 and earlier, interned strings were also stored in the permanent generation. In Java 7, interned strings are stored in the main object heap.Here is a .I like the descriptions given for each space in Oracle's :Java uses generational garbage collection. This means that if you have an object foo (which is an instance of some class), the more garbage collection events it survives (if there are still references to it), the further it gets promoted. It starts in the young generation (which itself is divided into multiple spaces - Eden and Survivor) and would eventually end up in the tenured generation if it survived long enough. : It is place where lived for short period and divided into two spaces: : This pool is basically contain tenured and virtual\n   (reserved) space and will be holding those objects which survived\n   after garbage collection from Young Generation. This memory pool as name also says contain permanent class metadata and descriptors information so PermGen space always reserved for classes and those that is tied to the classes for example static members. (Virtual or reserved) : If you are using HotSpot Java VM this includes code cache area that containing memory which will be used for compilation and storage of native code.The Java virtual machine is organized into three generations: a young generation, an old generation, and a permanent generation. Most objects are initially allocated in the young generation. The old generation contains objects that have survived some number of young generation collections, as well as some large objects that may be allocated directly in the old generation. The permanent generation holds objects that the JVM finds convenient to have the garbage collector manage, such as objects describing classes and methods, as well as the classes and methods themselves.The  is where all new objects are allocated and aged. When the young generation fills up, this causes a minor garbage collection. A young generation full of dead objects is collected very quickly. Some surviving objects are aged and eventually move to the old generation.The  is used to store long surviving objects. Typically, a threshold is set for young generation object and when that age is met, the object gets moved to the old generation. Eventually the old generation needs to be collected. This event is called a The  contains metadata required by the JVM to describe the classes and methods used in the application. The permanent generation is populated by the JVM at runtime based on classes in use by the application. parameters will be ignored nowImage source & oracle technetwork tutorial article: \"\" in above article explains the interactions between them with many diagrams. Have a look at summary diagram: is a very good survey on garbage collectors. It defines the basic concepts and terminology of garbage collection and includes many explanatory drawings. It is a \"must read\" for anybody who is interested in how automatic memory allocation works; reading it will make it much easier for you to read and understand the various documents that others have pointed at.(What that document lacks is any information about post-1993 research on garbage collectors, especially the whole business of multi-core systems. Still, you have to learn to walk before learning to run.)Assuming you're talking about the Sun JDK/OpenJDK, see the page on the OpenJDK website on .  There are a couple of links to even more information at the bottom.Although it is about tuning I can't resist recommend this  take a look at chapter 3 and go in depth if you like.Memory in SunHotSpot JVM is organized into three generations: young generation, old generation and permanent generation. FYI: The permanent gen is not considered a part of the Java heap.\n      Objects(except the large ones) are first allocated to the young generation. If an object remain alive after x no. of garbage collection cycles it gets promoted to the old/tenured gen. Hence we can say that the young gen contains the short lived objects while the old gen contains the objects having a long life. The permanent gen does not interact with the other two generations.
Java

How do I import a jar in Eclipse?You can add a jar in Eclipse by right-clicking on the Project \u2192 Build Path \u2192 Configure Build Path. Under Libraries tab, click Add Jars or Add External JARs and give the Jar. A quick demo .The above solution is obviously a \"Quick\" one. However, if you are working on a project where you need to commit files to the source control repository, I would recommend adding Jar files to a dedicated library folder within your source control repository and referencing few or all of them as mentioned above.Adding external Jar is not smart in case you want to change the project location in filesystem.The best way is to add the jar to build path so your project will compile if exported:Two choices:1/ From the project:2/ If you have already other jar imported, from the directory \"References Libraries\":Both will lead you to this screen where you can mange your libraries:Here are the steps:Just a comment on importing jars into Eclipse (plug-in development) projects:In case you are developing Eclipse plug-ins, it makes sense to use Eclipse's native bundling mechanism instead of just importing the jar into a plug-in project. Eclipse (or better its underlying OSGi runtime, Equinox) uses so-called bundles which contain some more information than plain jars (e.g., version infos, dependencies to other bundles, exported packages; see the MANIFEST.MF file). Because of this information, OSGi bundles can be dynamically loaded/unloaded and there is automatic dependency resolution available in an OSGi/Eclipse runtime. Hence, using OSGi bundles instead of plain jars (contained inside another OSGi bundle) has some advantages. (BTW: Eclipse plug-ins are the same thing as OSGi bundles.)There is a good chance that somebody already bundled a certain (3rd party) library as an OSGi bundle. You might want to take a look at the following bundle repositories:Eclipse -> Preferences -> Java -> Build Path -> User Libraries -> New(Name it) -> Add external Jars(I recommend dragging your new libraries into the eclipse  folder before any of these steps to keep everything together, that way if you reinstall Eclipse or your OS you won't have to rwlink anything except the JDK) Now select the jar files you want. Click OK. Right click on your project and choose Build Path -> Add LibraryFYI just code and then right click and Source->Organize Imports
Java

I hope this question is not considered too basic for this forum, but we'll see. I'm wondering how to refactor some code for better performance that is getting run a bunch of times.Say I'm creating a word frequency list, using a Map (probably a HashMap), where each key is a String with the word that's being counted and the value is an Integer that's incremented each time a token of the word is found.In Perl, incrementing such a value would be trivially easy:But in Java, it's much more complicated. Here the way I'm currently doing it:Which of course relies on the autoboxing feature in the newer Java versions. I wonder if you can suggest a more efficient way of incrementing such a value. Are there even good performance reasons for eschewing the Collections framework and using a something else instead?Update: I've done a test of several of the answers. See below.I've gotten a lot of good answers to this question--thanks folks--so I decided to run some tests and figure out which method is actually fastest. The five methods I tested are these:Here's what I did...I'll present the results first and the code below for those who are interested.The  method was, as expected, the slowest, so I'll give the speed of each method in comparison to the speed of that method.It would appear that only the MutableInt method and the Trove method are significantly faster, in that only they give a performance boost of more than 10%. However, if threading is an issue, AtomicLong might be more attractive than the others (I'm not really sure). I also ran TestForNull with  variables, but the difference was negligible.Note that I haven't profiled memory usage in the different scenarios. I'd be happy to hear from anybody who has good insights into how the MutableInt and Trove methods would be likely to affect memory usage.Personally, I find the MutableInt method the most attractive, since it doesn't require loading any third-party classes. So unless I discover problems with it, that's the way I'm most likely to go.Here is the crucial code from each method.A little research in 2016: , Best results per method (smaller is better):Time\\space results:\n@Hank GayAs a follow-up to my own (rather useless) comment: Trove looks like the way to go. If, for whatever reason, you wanted to stick with the standard JDK,  and  can make the code a  bit nicer, though YMMV.will leave  as the value in the map for . Realistically, increased friendliness to threading is all that this approach has to recommend it.It's always a good idea to look at the  for this kind of thing. In this case a  will do the trick:There are Map-like methods for iterating over keys/entries, etc. Internally the implementation currently uses a , so you will not incur boxing costs....at least in some cases. They have this nice . Especially nice because you are dealing with  as value in your map.E.g.Also possible to add more then 1 to the value:You should be aware of the fact that your original attempt contains two potentially expensive operations on a map, namely  and . The former performs an operation potentially pretty similar to the latter, so you're doing the same work !If you look at the API for Map,  operations usually return  when the map does not contain the requested element.Note that this will make a solution likedangerous, since it might yield s. You should check for a  first.\n\n, and this is very important, that s  contain  by definition. So not every returned  says \"there is no such element\". In this respect,  behaves  from  in actually telling you  there is such an element. Refer to the API for details.\n\nFor your case, however, you might not want to distinguish between a stored  and \"noSuchElement\". If you don't want to permit s you might prefer a . Using a wrapper library as was already proposed in other answers might be a better solution to manual treatment, depending on the complexity of your application.To complete the answer (and I forgot to put that in at first, thanks to the edit function!), the best way of doing it natively, is to  into a  variable, check for  and  it back in with a . The variable should be  because it's immutable anyway. The compiler might not need this hint, but its clearer that way.If you do not want to rely on autoboxing, you should say something like  instead.Another way would be creating a mutable integer:of course this implies creating an additional object but the overhead in comparison to creating an Integer (even with Integer.valueOf) should not be so much.And that's how you increment a value with simple code.Benefit:Another way is to use merge method, but this is too much for just incrementing a value.Suggestion: you should care about code readability more than little performance gain in most of the time.Memory rotation may be an issue here, since every boxing of an int larger than or equal to 128 causes an object allocation (see Integer.valueOf(int)). Although the garbage collector very efficiently deals with short-lived objects, performance will suffer to some degree.If you know that the number of increments made will largely outnumber the number of keys (=words in this case), consider using an int holder instead. Phax already presented code for this. Here it is again, with two changes (holder class made static and initial value set to 1):If you need extreme performance, look for a Map implementation which is directly tailored towards primitive value types. jrudolph mentioned .By the way, a good search term for this subject is \"histogram\".OK, may be an old question, but there is a shorter way with Java 8 :What it does : if  do not exists, put  as value, otherwise  to the value linked to .\nMore information Are you sure that this is a bottleneck? Have you done any performance analysis?Try using the NetBeans profiler (its free and built into NB 6.1) to look at hotspots.Finally, a JVM upgrade (say from 1.5->1.6) is often a cheap performance booster. Even an upgrade in build number can provide good performance boosts. If you are running on Windows and this is a server class application, use -server on the command line to use the Server Hotspot JVM. On Linux and Solaris machines this is autodetected.There are a couple of approaches:And use put(\"word\", new My(\"Word\") ); Then you can check if it exists and increment when adding.Avoid rolling your own solution using lists, because if you get innerloop searching and sorting, your performance will stink. The first HashMap solution is actually quite fast, but a proper like that found in Google Collections is probably better.Counting words using Google Collections, looks something like this:Using the HashMultiset is quite elegent, because a bag-algorithm is just what you need when counting words.I think your solution would be the standard way, but - as you noted yourself - it is probably not the fastest way possible.You may look at . That is a library which contains all sorts of fast primitive Collections. Your example would use a  which has a method adjustOrPutValue which does exactly what you want.A variation on the MutableInt approach that might be even faster, if a bit of a hack, is to use a single-element int array: It would be interesting if you could rerun your performance tests with this variation.  It might be the fastest.Edit: The above pattern worked fine for me, but eventually I changed to use Trove's collections to reduce memory size in some very large maps I was creating -- and as a bonus it was also faster.One really nice feature is that the  class has a single  call that, depending on whether there is already a value at that key, will either put an initial value or increment the existing value.  This is perfect for incrementing:Google Collections HashMultiset :\n - quite elegant to use\n - but consume CPU and memoryBest would be to have a method like :  \n(elegant, and low cost)Such a method will compute hash and index only once,\nand then we could do what we want with the entry\n(either replace or update the value).More elegant:\n - take a \n - extend it so that  put a new Entry if needed\n - Entry could be your own object.\n-->   Instead of calling containsKey() it is faster just to call map.get and check if the returned value is null or not.\"put\" need \"get\" (to ensure no duplicate key).\nSo directly do a \"put\",\nand if there was a previous value, then do an addition:If count starts at 0, then add 1: (or any others values...) This code is not thread safe. Use it to build then use the map, not to concurrently update it.  In a loop, keep old value to become the new value of next loop.The various primitive wrappers, e.g.,  are immutable so there's really not a more concise way to do what you're asking  you can do it with something like . I can give that a go in a minute and update. BTW,   a part of the .I'd use Apache Collections Lazy Map (to initialize values to 0) and use MutableIntegers from Apache Lang as values in that map. Biggest cost is having to serach the map twice in your method. In mine you have to do it just once. Just get the value (it will get initialized if absent) and increment it.The  library's  datastructure has an  method in the latest trunk head:Example usage:This program prints \"2\".@Vilmantas Baranauskas: Regarding this answer, I would comment if I had the rep points, but I don't.  I wanted to note that the Counter class defined there is NOT thread-safe as it is not sufficient to just synchronize inc() without synchronizing value().  Other threads calling value() are not guaranteed to see the the value unless a happens-before relationship has been established with the update.  You can make use of  method in  interface provided in Java 8. The method  checks if the specified key is already associated with a value or not? If no associated value then it attempts to compute its value using the given mapping function. In any case it returns the current (existing or computed) value associated with the specified key, or null if the computed value is null.On a side note if you have a situation where multiple threads update a common sum you can have a look at  class.Under high contention, expected throughput of this class is significantly higher than , at the expense of higher space consumption.If you're using , you can use a . It will be the most efficient approach in terms of memory usage and it will also perform well in terms of execution speed. is backed by a  which stores primitive ints instead of  objects. This reduces memory overhead and improves execution speed. provides the API you'd need since it's a  that also allows you to query for the number of occurrences of an item.Here's an example from the . I am a committer for Eclipse Collections.I don't know how efficient it is but the below code works as well.You need to define a  at the beginning. Plus, you can make more than just increment with this method.output is
Java

I need to create a list with all names of the files in a folder.For example, if I have:I want to store them in a  with  as values.What's the best way to do it in Java ?PS: I'm on Mac OS XYou could do it like that:Do you want to only get JPEG files or all files?Create a  object, passing the directory path to the constructor. Use the  to retrieve an array of  objects for each file in the directory, and then call the  method to get the filename.Here's how to look in the .First, you're dealing with IO, so look in the  . There are two classes that look interesting:  and . When I clicked on the first, it showed me that there was a a  method in the  class. And the documentation for that method says:Scrolling up in the  JavaDoc, I see the constructors. And that's really all I need to be able to create a  instance and call  on it. Scrolling still further, I can see some information about how files are named in different operating systems.
Java

What is the most accepted way to convert a  to an  in Java?^^PS : true = 1 and false = 0Using the ternary operator is the most simple, most efficient, and most readable way to do what you want. I encourage you to use this solution.However, I can't resist to propose an alternative, contrived, inefficient, unreadable solution.Hey, people like to vote for such cool answers !By the way, I often saw conversions from a boolean to an int for the sole purpose of doing a comparison of the two values (generally, in implementations of  method).  is the way to go in those specific cases.Java 7 introduced a new utility function that works with primitive types directly,  (Thanks )simpleThat depends on the situation. Often the most simple approach is the best because it is easy to understand:orBut sometimes it useful to use an Enum instead of a boolean flag. Let imagine there are synchronous and asynchronous processes:In Java, enum can have additional attributes and methods:If  and  mapping is what you want, you can do:If you want to obfuscate, use this:Lets play trick with . Default behavior of function: if both values are equal than it returns  otherwise .: As we know default return of Boolean.compare is -1 in case of mis-match so +1 make return value to  for  and  for If you use  (which I think a lot of projects use it), you can just use it like this:  method returns 1 if  is true, 0 otherwise
Java

OK, so the  annotation is good for marking that a test case shouldn't be run.However, sometimes I want to ignore a test based on runtime information.  An example might be if I have a concurrency test that needs to be run on a machine with a certain number of cores.  If this test were run on a uniprocessor machine, I don't think it would be correct to just pass the test (since it hasn't been run), and it certainly wouldn't be right to fail the test and break the build.So I want to be able to ignore tests at runtime, as this seems like the right outcome (since the test framework will allow the build to pass but record that the tests weren't run).  I'm fairly sure that the annotation won't give me this flexibility, and suspect that I'll need to manually create the test suite for the class in question.  However, the documentation doesn't mention anything about this and looking through the  it's also not clear how this would be done programmatically (i.e. how do I programatically create an instance of  or similar that is equivalent to that created by the  annotation?).If anyone has done something similar in the past, or has a bright idea of how else I could go about this, I'd be happy to hear about it.The JUnit way is to do this at run-time is .You can do it in a  method or in the test itself, but not in an  method. If you do it in the test itself, your  method will get run. To compare with the  annotation from , their sample code would look like this:Not to mention that it is much easier to capture and use the connection from the  method this way.You should checkout  project.  They have  annotation that performs conditional tests, like:[Code sample taken from their tutorial]In JUnit 4, another option for you may be to create an annotation to denote that the test needs to meet your custom criteria, then extend the default runner with your own and using reflection, base your decision on the custom criteria. It may look something like this:A quick note:  ignores rest of the steps but passes the test. \nTo fail the test, use  inside the conditional statement. Works same like  but fails the test.
Java

What is the best way to use the values stored in an Enum as String literals?\nFor example:Then later I could use  to return its string representation as . Without having to keep calling .You can't. I think you have three options here. All three offer a solution but with a slightly different approach...    Every enum has both a name() and a valueOf(String) method. The former returns the string name of the enum, and the latter gives the enum value whose name is the string. Is this like what you're looking for?There's also a static valueOf(Class, String) on Enum itself, so you could also useYou could override the  method for each enum value. or . It doesn't get better than that, I'm afraidAs Benny Neugebauer mentions, you could overwrite the toString(). However instead overwriting the toString for each enum field I like more something like this:You could also add a static method to retrieve all the fields, to print them all, etc.\nSimply call getValue to obtain the string associated to each Enum itemYou can use  however you often don't need to do this.As far as I know, the only way to get the name would beIf you really need it this way, however, you could do:you can call like below whereever you want to get value as string from enum.This will return \"Mode1\" as String.You can simply use:Enum is just a little bit special class. Enums can store additional fields, implement methods etc. For exampleNow you can say:and see output: \nmy solution for your problem!For my enums I don't really like to think of them being allocated with 1 String each.  This is how I implement a toString() method on enums.after many tries I have come with this solutionIt is an easy way without creating interface, class or getter settersSo just to build on some of the above answers.. A lot of times i'll use enumerators to represent \"types\" of things obviously, but then those types also have additional attributes, like an int ID and a string Description. The below solution works well for me to give an enumerator a bit more usefulness for me....and i'm new to Java btw.. so if there's issues with this i'd love to knowI'm supprised that non of those anwsers consider Enum with an Attribute. Enum will be easy to readable for a programmer, and Attribute can contain a full name, or \"pointer\" to translation. That way you can repeat names between enums, and you have no warries for uniquness of string in attribute since they can be very long.Usage:
Java

\nWe have a Spring MVC-based RESTful API which contains sensitive information. The API should be secured, however sending the user's credentials (user/pass combo) with each request is not desirable. Per REST guidelines (and internal business requirements), the server must remain stateless. The API will be consumed by another server in a mashup-style approach.We've been banging our heads against the wall trying to make this work, so hopefully someone out there has already solved this problem. Given the above scenario, how might you solve this particular need?We managed to get this working exactly as described in the OP, and hopefully someone else can make use of the solution. Here's what we did:Set up the security context like so:As you can see, we've created a custom , which basically just returns a  if the request wasn't authenticated in the filter chain by our .::Obviously,  contains some privy (and very case-specific) code and can't be readily shared. Here's its interface:That ought to get you off to a good start. Happy coding. :)You might consider .  Essentially the protocol is as follows:All of this communication is made through headers, which, as jmort253 points out, is generally more secure than communicating sensitive material in the url parameters.Digest Access Authentication is supported by .  Notice that, although the docs say that you must have access to your client's plain-text password, you can  for your client.Regarding tokens carrying information, JSON Web Tokens () is a brilliant technology. The main concept is to embed information elements (claims) into the token, and then signing the whole token so that the validating end can verify that the claims are indeed trustworthy.I use this Java implementation:  There is also a Spring module (spring-security-jwt), but I haven't looked into what it supports.
Java

The JUnit framework contains 2  classes (in different packages, obviously) and the methods on each appear to be very similar. Can anybody explain why this is?The classes I'm referring to are:  and .The old method (of Junit 3) was to mark the test-classes by extending junit.framework.TestCase. That inherited junit.framework.Assert itself and your test-class gained the ability to call the assert-methods this way.Since version 4 of junit, the framework uses Annotations for marking tests. So you no longer need to extend TestCase. But that means, the assert-methods aren't available. But you can make a static import of the new Assert-class. That's why all the assert-methods in the new class are static methods. So you can import it this way:After this static import, you can use this methods without prefix.At the redesign they also moved to the new package org.junit, that follows better the normal conventions for package-naming.JUnit 3.X: JUnit 4.X: Prefer the newest one, especially when running JDK5 and higher with annotation support.There is in fact a functional change:  will complain if you use the two-argument  with  or , while  will silently autobox it.I believe they are refactoring from  to  and  is maintained for backwards compatibility. I did a rough source code compare and there are no serious changes.Lot of comments were added in  and some refactorings are done.The only change is the comparison with Arrays. There are some code clean ups, but there's (imho) .
Java

When / what are the conditions when a  is created?Is it per a domain? For instance, if I have a Tomcat app server, and I deploy multiple web applications, will a different  be created per context (web application), or is it shared across web applications as long as they are the same domain?JSESSIONID cookie is created/sent when session is created. Session is created when your code calls  or  for the first time. If you just want to get the session, but not create it if it doesn't exist, use  -- this will return you a session or . In this case, new session is not created, and JSESSIONID cookie is not sent. (This also means that ... you and your code are in control  the session is created)Sessions are per-context:()Update: Every call to JSP page implicitly creates a new session if there is no session yet. This can be turned off with the  page directive, in which case session variable is not available on JSP page at all.Here is some information about one more source of the  cookie:I was just debugging some Java code that runs on a tomcat server. I was not calling  explicitly anywhere in my code but I noticed that a  cookie was still being set. I finally took a look at the generated Java code corresponding to a JSP in the work directory under Tomcat.It appears that, whether you like it or not, if you invoke a JSP from a servlet,  will get created!Added: I just found that by adding the following JSP directive:you can disable the setting of  by a JSP.CORRECTION: Please vote for Peter \u0160tibran\u00fd's answer - it is more correct and complete!A \"JSESSIONID\" is the unique id of the http session - . In the javadoc you will find the following sentence: \"Session information is scoped only to the current web application (ServletContext), so information stored in one context will not be directly visible in another.\"So when you first hit a site, a new session is created and bound to the SevletContext. If you deploy multiple applications, the session is not shared.You can also invalidate the current session and therefore create a new one. e.g. when switching from http to https (after login), it is a very good idea, to create a new session.Hope, this answers your question.Beware if your page is including other .jsp or .jspf (fragment)! If you don't set on them as well, the parent page will end up starting a new session and setting the JSESSIONID cookie.For .jspf pages in particular, this happens if you configured your web.xml with such a snippet:in order to enable scriptlets inside them.For links generated in a JSP with custom tags, I had to use in the JSP ANDin the Struts action
Java

I was thinking if exist a better/nicer way to negate a instanceof in Java.\nActually, I do something like:But, I think that should exist a \"beautiful\" syntax to do this.Someone know if it exists and how the syntax look like?\nBy beautiful, I might say something like this:No, there is no better way; yours is canonical.I don't know what you imagine when you say \"beautiful\", but what about this? I personally think it's worse than the classic form you posted, but somebody might like it...You could use the  method:... but it is still negated and pretty ugly.If you can use static imports, and your moral code allows themAnd then...This is just a fluent interface exercise, I'd never use that in real life code!\nGo for your classic way, it won't confuse anyone else reading your code!Usually you don't want just an  but an  clause as well.can be written asOr you can write the code so you don't need to know if its a String or not. e.g.can be written asok just my two cents, use a is string method:
Java

How can I transform a  value into an ? also does the trick:I also found the apache commons  class , so : Does it have to be specifically an InputStreamReader?  How about using ?Otherwise, you could use , but it's deprecated because of character conversion issues (which is why you should prefer StringReader).Same question as  - why not StringReader ?If it has to be InputStreamReader, then:Are you trying to get a)  functionality out of , or b)  functionality out of ?  You won't get b).   is not an .The purpose of  is to take an  - a source of bytes - and decode the bytes to chars in the form of a .  You already have your data as chars (your original String).  Encoding your String into bytes and decoding the bytes back to chars would be a redundant operation.If you are trying to get a  out of your source, use .If you are trying to get an  (which only gives you bytes), use apache commons  as suggested by other answers here.
Java

Is there a Java equivalent for  in C#/.NET? Or any code to accomplish this?This static method combines one or more strings into a path.Rather than keeping everything string-based, you should use a class which is designed to represent a file system path.If you're using Java 7 or Java 8, you should strongly consider using ;  can be used to combine one path with another, or with a string. The  helper class is useful too. For example:If you need to cater for pre-Java-7 environments, you can use , like this:If you want it back as a string later, you can call . Indeed, if you really wanted to mimic , you could just write something like:In Java 7, you should use :While the NIO2 Path class may seem a bit redundant to File with an unnecessarily different API, it is in fact subtly more elegant and robust.Note that  (as suggested by someone else) doesn't have an overload taking a , and doing  is NOT the same thing as .  is more intelligent. From the :The sister function to  is the excellent :The main answer is to use File objects. However  does have a class  that can do this kind of thing, such as the  method.To enhance JodaStephen's answer, Apache Commons IO has FilenameUtils which does this.  Example (on Linux):It's platform independent and will produce whatever separators your system needs.I know its a long time since Jon's original answer, but I had a similar requirement to the OP. By way of extending Jon's solution I came up with the following, which will take one or more path segments takes as many path segments that you can throw at it.Here's a solution which handles multiple path parts and edge conditions:If you do not need more than strings, you can use to get 
Java

I have a string that has two single quotes in it, the  character. In between the single quotes is the data I want.How can I write a regex to extract \"the data i want\" from the following text?Assuming you want the part between single quotes, use this regular expression with a :Example:Result:You don't need regex for this.Add apache commons lang to your project (), then use:Because you also ticked Scala, a solution without regex which easily deals with multiple quoted strings:as in javascript:the actual regexp is: if you use the non greedy modifier (as per another post) it's like this:it is cleaner.In Scala,There's a simple one-liner for this:By making the matching group optional, this also caters for quotes not being found by returning a blank in that case.See .
Java

What is the difference between , ,  & ?I was programming in Java and I encountered these phrases, what are the differences between them?The  (JVM) is the virtual machine that runs the Java bytecodes. The JVM doesn't understand Java source code, that's why you compile your  files to obtain  files that contain the bytecodes understood by the JVM. It's also the entity that allows Java to be a \"portable language\" (). Indeed, there are specific implementations of the JVM for different systems (Windows, Linux, MacOS, ), the aim is that with the same bytecodes they all give the same results.To explain the difference between JDK and JRE, the best is to read the  and consult the diagram:Note that Oracle is not the only one to provide JDKs.The  is the open-source implementation of the Java SE 7 JSR ().\nNow there is almost no difference between the Oracle JDK and the OpenJDK. Last year, Oracle took this decision :\n The differences are stated in this  :Depending on the used version, the VM can differ: OpenJDK is a specific JDK implementation.Java Developer Kit contains tools needed to develop the Java programs, and JRE to run the programs. The tools include compiler (javac.exe), Java application launcher (java.exe), Appletviewer, etc\u2026Compiler converts java code into byte code. Java application launcher opens a JRE, loads the class, and invokes its main method.You need JDK, if at all you want to write your own programs, and to compile them. For running java programs, JRE is sufficient.JRE is targeted for execution of Java files JRE = JVM + Java Packages Classes(like util, math, lang, awt,swing etc)+runtime libraries.JDK is mainly targeted for java development. I.e. You can create a Java file (with the help of Java packages), compile a Java file and run a java file.Java Runtime Environment contains JVM, class libraries, and other supporting files. It does not contain any development tools such as compiler, debugger, etc. Actually JVM runs the program, and it uses the class libraries, and other supporting files provided in JRE. If you want to run any java program, you need to have JRE installed in the systemThe Java Virtual Machine provides a platform-independent way of executing code;\nThat mean compile once in any machine and run it any where(any machine).As we all aware when we compile a Java file, output is not an \u2018exe\u2019 but it\u2019s a \u2018.class\u2019 file. \u2018.class\u2019 file consists of Java byte codes which are understandable by JVM. Java Virtual Machine interprets the byte code into the machine code depending upon the underlying operating system and hardware combination. It is responsible for all the things like garbage collection, array bounds checking, etc\u2026 JVM is platform dependent.The JVM is called \u201cvirtual\u201d because it provides a machine interface that does not depend on the underlying operating system and machine hardware architecture. This independence from hardware and operating system is a cornerstone of the write-once run-anywhere value of Java programs.There are different JVM implementations are there. These may differ in things like performance, reliability, speed, etc. These implementations will differ in those areas where Java specification doesn\u2019t mention how to implement the features, like how the garbage collection process works is JVM dependent, Java spec doesn\u2019t define any specific way to do this.A  is a virtual machine that can execute Java bytecode. It is the code execution component of the Java software platform.The  is an Oracle Corporation product aimed at Java developers. Since the introduction of Java, it has been by far the most widely used Java Software Development Kit (SDK)., is also referred to as the Java Runtime, Runtime Environment is a free and open source implementation of the Java programming language. It is the result of an effort Sun Microsystems began in 2006. The implementation is licensed under the GNU General Public License (GPL) with a linking exception.  (Java Development Kit) : (Java Runtime Environment)Java Runtime Environment contains JVM, class libraries, and other supporting files.\nJRE is targeted for execution of Java files. (Java Virtual Machine)The JVM  depending upon the underlying operating system and hardware combination. It is responsible for all the things like garbage collection, array bounds checking, etc\u2026 Java Virtual Machine provides a platform-independent way of executing code. is the virtual machine Java code executes on is the environment (standard libraries and JVM) required to run Java applications is the JRE with developer tools and documentation is an open-source version of the JDK, unlike the common JDK owned by OracleJava Virtual Machine (JVM)When you download JRE and install on your machine you got all the code required to create JVM. Java Virtual Machine is get created when you run a java program using java command e.g. java HelloWorld. JVM is responsible for converting byte code into machine specific code and that's why you have different JVM for Windows, Linux or Solaris but one JAR can run on all this operating system. Java Virtual machine is at heart of Java programming language and provide several feature to Java programmer including Memory Management and Garbage Collection, Security and other system level services. Java Virtual Machine can be customized e.g we can specify starting memory or maximum memory of heap size located inside JVM at the time of JVM creation. If we supplied invalid argument to java command it may refuse to create Java Virtual Machine by saying \"failed to create Java virtual machine: invalid argument\". In short Java Virtual Machine or JVM is the one who provides Platform independence to Java.Java Development Kit (JDK)JDK is also loosely referred as JRE but its lot more than JRE and it provides all the tools and executable require to compile debug and execute Java Program. Just like JRE, JDK is also platform specific and you need to use separate installer for installing JDK on Linux and Windows. Current Version of JDK is 1.7 which is also referred as Java7 and it contains javac (java compiler) based on programming rules of Java7 and Java which can execute java7 code with new features like String in Switch, fork-join framework or Automatic Resource Management. When you install JDK, installation folder is often referred as JAVA_HOME. All binaries are located inside JAVA_HOME/bin which includes javac, java and other binaries and they must be in your system PATH in order to compile and execute Java programs. For details on Path see how to set PATH for Java in Windows and UNIX.Java Runtime Environment (JRE)Java is every where in browser, in mobile, in TV or in set-top boxes and if you are into Java programming language than you know that Java code which is bundled in JAR (Java archive) file require Java virtual machine JVM to execute it. Now JVM is an executable or program like any other program and you can install that into your machine. You have seen browser often suggesting download JRE to run a Java Applet downloaded from Internet. Various version of JRE are available in java.oracle.com and most of the user who just want to execute Java program inside browser or standalone downloads JRE. All browsers including Internet Explorer, Firefox and Chrome can work with JRE.Another aspect worth mentioning: You will need it for development purposes like the name suggest.For example: a software company will have JDK install in their computer because they will need to develop new software which involves compiling and running their Java programs as well.So we can say that JDK = JRE + JVM.It's needed to run Java programs. You can't compile Java programs with it . For example: a regular computer user who wants to run some online games then will need JRE in his system to run Java programs. As you might know it run the bytecodes. It make Java platform independent because it executes the  file which you get after you compile the Java program regardless of whether you compile it on Windows, Mac or Linux.Well, like I said above. Now JDK is made by different company, one of them which happens to be an open source and free for public use is OpenJDK, while some others are Oracle Corporation's JRockit JDK or IBM JDK.However they all might appear the same to general user. If you are a Java programmer you will need JDK in your system and this package will include JRE and JVM as well but if you are normal user who like to play online games then you will only need JRE and this package will not have JDK in it.In other words JDK is grandfather JRE is father and JVM is their son.Java is the language and includes a strict and strongly typed syntax with which you should be very familiar by now.Java 2 Platform, Standard Edition, also known as J2SE, referred to the platform and included the classes in the java.lang and java.io packages, among others. It was the building block that Java applications were built upon.A Java Virtual Machine, or JVM, is a software virtual machine that runs compiled Java code. Because compiled Java code is merely bytecode, the JVM is responsible for compiling that bytecode to machine code before running it. (This is often called the Just In Time Compiler or JIT Compiler.) The JVM also takes care of memory management so that application code doesn\u2019t have to.The Java Development Kit, or JDK, was and remains the piece of software Java developers use to create Java applications. It contains a Java language compiler, a documentation generator, tools for working with native code, and (typically) the Java source code for the platform to enable debugging platform classes.The Java Runtime Environment, or JRE, was and remains the piece of software end users download to run compiled Java applications. It includes a JVM but does not contain any of the development tools bundled in the JDK. The JDK, however, does contain a JRE. - Compiles java to Byte Code. Consists of debuggers, Compilers etc - Executes the byte code. JVM is the one which makes java platform independent. But JVM varies for platforms   - JRE comprises of JVM along with java runtime libraries to execute java programs. : this actually means the byte code interpreter .It is platform dependent. For eg: in      Windows platform the '' or '' precess is the jvm process. : is a toolkit containing necessary libraries and utilities to develop and execute java program/application: is the execution environment for a java application.ie, it only support runtime dependencies including jvm for compiled program. If we want to compile a java program we need jdk. JVMJVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed.\nJVMs are available for many hardware and software platforms. JREJRE is an acronym for Java Runtime Environment.It is used to provide runtime environment.It is the implementation of JVM.It physically exists.It contains set of libraries + other files that JVM uses at runtime.JDKJDK is an acronym for Java Development Kit.It physically exists.It contains JRE + development tools.Link :- JVM : virtual machine of java. tells machine what to do with the Java Code. You cannot download JVM as is. It comes packaged in some other component.JRE: Some other component referred as above is the JRE. \nIt is JVM+ other jars to create runtime environmenyJDK: contains JRE(which in turn contains JVM). Once you get JDK you need not install JRE and JVM separately. It contains compiler which compiles your .java files to .class files Java Virtual Machine , actually executes the java bytecode.\nIt is the execution block on the JAVA platform. It converts the bytecode to the machine code. Java Runtime Environment , provides the minimum requirements for executing a Java application; it consists of the Java Virtual Machine (JVM), core classes, and supporting files. Java Development Kit, it has all the tools to develop your application software. It is as JRE+JVM  is a free and open source implementation of the Java Platform.In layman terms:- , where JDK is our complete package to work with Java, from creating compiling till running it.On the other hand JRE is just of running of code(Byte Code).Note:- Whether we are installing JDK or JRE, JVM would come bundled with both the packages and JVM is the part where JIT compiler converts the byte code into the machine specific code.Just read the article on In simple words :JVM : A specification which describes the the way/resources to run a java program. Actually executes the byte code and make java platform independent. In doing so, it is different for different platform. JVM for windows cannot work as JVM for UNIX.JRE : Implementation of JVM. (JVM + run time libraries)JDK : JRE + java compiler and other essential tools to build a java program from scratch: The complete package which you need to write and run java code: An independent implementation of JDK for making it much better: Converts Java code into bytecode and provides the specifications which tells how should a Java code be compiled, loaded, verified, checked for errors and executed.: Implementation of the JVM with which some Java libraries are used to Run the programJRE executes the application but JVM reads the instructions line by line so it's interpreter.JDK=JRE+Development ToolsJRE=JVM+Library Classes
Java

I'm trying to define my own exception class the easiest way, and this is what I'm getting:This is what Java compiler says:I had a feeling that this constructor has to be inherited from , isn't it?No, you don't \"inherit\" non-default constructors, you need to define the one taking a String in your class. Typically you use  in your constructor to invoke your parent constructor. For example, like this:A typical custom exception I'd define is something like this:I even create a template using Eclipse so I don't have to write all the stuff over and over again.If you use the new class dialog in Eclipse you can just set the Superclass field to  and check \"Constructors from superclass\" and it will generate the following:In response to the question below about not calling  in the defualt constructor, Oracle has :Reason for this is explained in the  article of the Java Platform which says: Exception class has two constructors If you inherit from Exception, you have to provide a constructor that takes a String as a parameter (it will contain the error message).
Java

Is there a way to iterate over Java SparseArray (for Android) ? I used  to easily get values by index. I could not find one.Seems I found the solution. I hadn't properly noticed the  function.So I'll go with something like this:If you don't care about the keys, then  can be used to while iterating through the sparse array to access the values directly.Ooor you just create your own ListIterator:For removing all the elements from  using the above looping leads to .To avoid this Follow the below code to remove all the elements from  using normal loopsSimple as Pie. Just make sure you fetch array size  actually perform the loop.Hope this helps.Here is simple  and  implementations for :If you want to iterate not only a value but also a key:It's useful to create utility methods that return  and :Now you can iterate :The answer is no because  doesn't provide it. As  put it, this thing doesn't provide any interfaces.You could loop from  and skip values that return , but that is about it.As I state in my comment, if you need to iterate use a  instead of a . For example, use a  which iterates in order by the key.The accepted answer has some holes in it. The beauty of the SparseArray is that it allows gaps in the indeces. So, we could have two maps like so, in a SparseArray...Notice the size here would be 2. If we iterate over size, we will only get values for the values mapped to index 0 and index 1. So the mapping with a key of 250 is not accessed. The best way to do this is to iterate over the size of your data set, then check those indeces with a get() on the array. Here is an example with an adapter where I am allowing batch delete of items.I think ideally the SparseArray family would have a getKeys() method, but alas it does not.
Java

I am successfully using this code to send   requests with some parameters via  methodNow I may need to send the parameters (i.e. param1, param2, param3) via  method because they are very long.\nI was thinking to add an extra parameter to that method (i.e. String httpMethod).How can I change the code above as little as possible to be able to send paramters either via  or ?I was hoping that changingtowould have done the trick, but the parameters are still sent via GET method.Has  got any method that would help?\nIs there any helpful Java construct?Any help would be very much appreciated.In a GET request, the parameters are sent as part of the URL.In a POST request, the parameters are sent as a body of the request, after the headers.To do a POST with HttpURLConnection, you need to write the parameters to the connection after you have opened the connection.This code should get you started:Here is a simple example that submits a form then dumps the result page to . Change the URL and the POST params as appropriate, of course:If you want the result as a  instead of directly printed out do:I couldn't get  to actually do the post, so I ended up with this:I find  really cumbersome to use. And you have to write a lot of boilerplate, error prone code. I needed a lightweight wrapper for my Android projects and came out with a library which you can use as well: .The above example could be written like this:You can find a list of alternative libraries on the link provided.I see some other answers have given the alternative, I personally think that intuitively you're doing the right thing ;).  Sorry, at devoxx where several speakers have been ranting about this sort of thing.That's why I personally use Apache's HTTPClient/ libraries to do this sort of work, I find their API to be easier to use than Java's native HTTP support.  YMMV of course! I had the same issue. I wanted to send data via POST.\nI used the following code:I used Jsoup for parse:Try this pattern:i have read above answers and have created a utility class to simplify HTTP request. i hope it will help you.here i sent jsonobject as parameter //jsonobject={\"name\":\"lucifer\",\"pass\":\"abc\"}//serverUrl = \"\" //host=192.168.100.12 Hello pls use this class to improve your post method I took Boann's answer and used it to create a more flexible query string builder that supports lists and arrays, just like php's http_build_query method:Appears that you also have to call \"at least once\" (as well as ) for it to treat it as a POST.So the minimum required code is:You can even use \"GET\" style parameters in the urlString, surprisingly.  Though that might confuse things.
Java

 has no method for hasNext. I want to check if the resultSet has any valueis this the correct way That's correct, initially the 's cursor is pointing to before the first row, if the first call to  returns  then there was no data in the .If you use this method, you may have to call  immediately after to reset it, since it has positioned itself past the first row now.It should be noted however, that  below is a more elegant solution to this question. Assuming you are working with a newly returned  whose cursor is pointing before the first row, an easier way to check this is to just call . This avoids having to back-track if the data is to be read.As explained in the documentation, this returns false if the cursor is not before the first record or if .\u00a0you could always do the next up front, and just do a post loop checkYou would usually do something like this:If you want to report an empty set, add a variable counting the items read. If you only need to read a single item, then your code is adequate.That would work if you want to see if there are any rows in the result set yes. Note that  always moves to the next row, so if you are planning on doing any reading from the result set you need to take that into account.Usual usage with ResultSet (when simply reading) is:Which obviously won't work correctly if you invoked  once already to check if the result set was empty, so watch out for that. Although there are methods for \"backing up\", they are not supported for all types of result sets.Best to use ResultSet.next() along with the do {...} while() syntax for this.The \"check for any results\" call ResultSet.next() moves the cursor to the first row, so use the do {...} while() syntax to process that row while continuing to process remaining rows returned by the loop.This way you get to check for any results, while at the same time also processing any results returned.According to the most viable answer the suggestion is to use \"isBeforeFirst()\". .There's a method called \"\". It's less overkill to get the exact same result. You check whether there is something in your \"resultset\" and don't advance your cursor. The documentation states: \"(...) false if there are \".However, there's a difference between \"isBeforeFirst()\" and \"first()\". First generates an exception if done on a resultset from type \"forward only\". Compare the two throw sections: \n\nOkay, basically this means that you should use \"isBeforeFirst\" as long as you have a \"forward only\" type. Otherwise it's less overkill to use \"first()\". To be totally sure of rather the resultset is empty or not regardless of cursor position, I would do something like this: This function will return true if ResultSet is empty, false if not or throw an SQLException if that ResultSet is closed/uninitialized. also returns false for empty result set but since cursor is before first row anyways, this method seems more clear.This is a practical and easy read piece I believe.Because if ResultSet has no raw then  returns false.The best thing for to do is to check the first row so that when you intend to get the data you can avoid the mistake of skipping a row. Something like:    if (!resultSet.first() ) { System.out.println(\"no data\"); }By using resultSet.next() you can easily get the result, whether resultSet containing any value or notIt is better to re execute query because when we call  first row of ResultSet will be executed and after it inside  we'll get result from next line. So I think re-execution of query inside  is the better option. you can do something like thisI've been attempting to set the current row to the first index (dealing with primary keys). I would suggestWhen the ResultSet is populated, it points to before the first row. When setting it to the first row (indicated by ) it will return true denoting it was successfully placed at row 1, or false if the row does not exist. We can extrapolate this towhich sets the current row to position i and will fail if the row doesn't exist. This is just an alternative method toI created the following method to check if a ResultSet is empty.It is very important to have the following considerations: object must be setted to let to ResultSet object go at the end and go back to top.: ResultSet object can shift at the end and go back to top. Further can catch last changes.: We can read the ResultSet object data, but can not updated.I think the easiest way for checking result set is via  under package This will check for null as well as empty result set condition. For more detail information you can refer to the following doc. \nInitially, the result set object (rs) points to the BFR (before first record). Once we use rs.next(), the cursor points to the first record and the rs holds \"true\". Using the while loop you can print all the records of the table. After all the records are retrieved, the cursor moves to ALR (After last record) and it will be set to null. Let us consider that there are 2 records in the table.In short hand, we can also write the condition as while (rs.next()).    
Java

I just created sample BB app, which can allow to choose the date.After choosing the date, I need to convert that long value to String, so that I can easily store the date value somewhere in database.\nI am new to Java and Blackberry development.How should I convert this long value to String? Also I want to convert back to long from String. I think for that I can use ?See the : If your Long might be null and you don't want to get a 4-letter  string, you might use , like: EDIT:You reverse it using  but in this direction you need to catch Simple and works fine :-)This works:very simple,\njust concatenate the long to a string.1.2.Can convert the long into string object, cool shortcut for converting into string...but use of  is advisableor
Java

I saw this keyword for the first time and I was wondering if someone could explain to me what it does.A  statement without a label will re-execute from the condition the innermost  or  loop, and from the update expression of the innermost  loop.   It is often used to early-terminate a loop's processing and thereby avoid deeply-nested  statements.  In the following example  will get the next line, without processing the following statement in the loop. With a label,  will re-execute from the loop with the corresponding label, rather than the innermost loop.  This can be used to escape deeply-nested loops, or simply for clarity.  Sometimes  is also used as a placeholder in order to make an empty loop body more clear.The same statement without a label also exists in C and C++.  The equivalent in Perl is .This type of control flow is not recommended, but if you so choose you can also use  to simulate a limited form of .  In the following example the  will re-execute the empty  loop. is kind of like . Are you familiar with ? It's easier to think about them in contrast:Let's see an exampleThis would get the sum of only odd numbers from 1 to 100If you think of the body of a loop as a subroutine,  is sort of like . The same keyword exists in C, and serves the same purpose. Here's a contrived example:This will print out only the odd numbers.Generally, I see  (and ) as a warning that the code  use some refactoring, especially if the  or  loop declaration isn't immediately in sight. The same is true for  in the middle of a method, but for a slightly different reason.As others have already said,  moves along to the next iteration of the loop, while  moves out of the enclosing loop.These can be maintenance timebombs because there is no immediate link between the / and the loop it is continuing/breaking other than context; add an inner loop or move the \"guts\" of the loop into a separate method and you have a hidden effect of the / failing.IMHO, it's best to use them as a measure of last resort, and then to make sure their use is grouped together tightly at the start or end of the loop so that the next developer can  see the \"bounds\" of the loop in one screen., , and  (other than the One True Return at the end of your method) all fall into the general category of \"hidden GOTOs\". They place loop and function control in unexpected places, which then eventually causes bugs.As already mentioned  will skip processing the code below it and until the end of the loop. Then, you are moved to the  and run the next iteration if this condition still holds (or if there is a flag, to the denoted loop's condition).It must be highlighted that in the case of  you are moved to the condition at the bottom after a , not at the beginning of the loop.This is why a lot of people fail to correctly answer what the following code will generate.*If your answer is that  will contain odd numbers only 100%... you are wrong!Consider an If Else condition. A continue statement executes what is there in a condition and gets out of the condition i.e. jumps to next iteration or condition. But a Break leaves the loop. \nConsider the following Program. '    It will print: aa cc Out of the loop. If you use break in place of continue(After if.), it will just . If the condition \"bb\" equals ss is satisfied: \nFor Continue: It goes to next iteration i.e. \"cc\".equals(ss).\nFor Break: It comes out of the loop and prints \"Out of the loop. \"
Java

For some reason, the OK button is not clickable when I try to create an AVD. Does anyone know what I'm doing wrong?Simply because  CPU/ABI says \"No system images installed for this target\". You need to install a system image.In the Android SDK Manager check that you have installed \"ARM EABI v7a System Image\" (for each Android version from 4.0 and on you have to install a system image to be able to run a virtual device)In your case only ARM system image exsits (Android 4.2). If you were running an older version, Intel has provided System Images (Intel x86 ATOM). You can check on the internet to see the comparison in performance between both.In my case (see image below) I haven't installed a System Image for Android 4.2, whereas I have installed ARM and Intel System Images for 4.1.2As long as I don't install the 4.2 System Image I would have the same problem as you. : This recent article  explains how to use/install correctly the intel system images to speed up the emulator.What I show in the picture is for Android 4.2, as it was the original question, but is true for every versions of Android.Of course (as @RedPlanet said), if you are developing for MIPS CPU devices you have to install the \"MIPS System Image\".Finally, as @SeanJA said,  to see the new installed images. But for me, I always restart a software which I updated to be sure it takes into account all the modifications, and I assume it is a good practice to do so.  Had to restart the Eclipse after completing the installation of ARM EABI v7a system image.This can happen when:For Ubuntu and running android-studio run to install the packages (these are not installed by default):I had the same problem while creating AVD with 4.2.2 images, I resolved it by doing the following :Hope this helps.  I had to move the folders inside a folder named \"default\" to the android-## folder so Eclipse could see the images.There is a new possible error for this one related to the latest Android Wear technology.  I was trying to get an emulator started for the wear SDK in preparation for next week.  The API level only supports it in the latest build of 4.4.2 KitKat.So if you are using something such as the wearable, it starts the default off still in Eclipse as 2.3.3 Gingerbread.  Be sure that your target matches the lowest possible supported target.  For the wearables its the latest 19 KitKat.I want to update this question with a screenshot of a recent Android Studio. It took a bit of poking around to find where to install new system images.You get to the SDK Manager through one of two paths.\nOption 1. Tools > Android > SDK Manager\nOption 2. Android Studio > Preferences > Appearance & Behavior > System Settings > Android SDK (This is for Mac; adapt for others.)In the pane \"SDK Platforms,\" check the \"Show Packages\" box to see the system images.Select the ones you want, click \"Apply\" and voil\u00e0! 
Java

Recently I read through this\n. The document is all about defining  and  effectively and correctly, but I am not able to figure out why we need to override these two methods. How can I take the decision to implement these method efficiently?Joshua Bloch says on Effective JavaLet's try to understand it with an example of what would happen if we override  without overriding  and attempt to use a .Say we have a class like this and that two objects of  are equal if their  is equal (with  and  generated by eclipse)If only  is overriden, then when you call  first will hash to some bucket and when you call  it will hash to some other bucket (as they have a different ). So, although they are equal, as they don't hash to the same bucket, the map can't realize it and both of them stay in the map.Although it is not necessary to override  if we override , let's see what would happen in this particular case where we know that two objects of  are equal if their  is equal but we do not override .Imagine you have thisIf you only override  then when you call  it takes first, calculates its  and stores it in a given bucket. Then when you call  it should replace first with second  as per the  because they are equal (according to the business requirement).But the problem is that equals was not redefined, so when the map hashes  and iterates through the bucket looking if there is an object  such that  is true it won't find any as  will be .Hope it was clearCollections such as HashMap and HashSet use the hashcode value of an object to determine how the object should be stored in the collection, and the hashcode is used again to help locate the object\nin the collection.Hashing retrieval is a two-step process.here is a small example why we should overrride equals() and hashcode().Consider an Employee class which has two fields age and name.Now create a class, insert Employee object to a HashSet and test whether that object is present or not.Now remove the commented line from hashcode() and execute the same you will find below resultNow can you see why if two objects are considered equal, their hashcodes must\nalso be equal? Otherwise, you'd never be able to find the object since the default\nhashcode method in class Object virtually always comes up with a unique number\nfor each object, even if the equals() method is overridden in such a way that two\nor more objects are considered equal. It doesn't matter how equal the objects are if\ntheir hashcodes don't reflect that. So one more time: If two objects are equal, their\nhashcodes must be equal as well.By defining  and  consistently, you can improve the usability of your classes as keys in hash-based collections. As the API doc for hashCode explains: \"This method is supported for the benefit of hashtables such as those provided by .\" The best answer to your question about how to implement these methods efficiently is suggesting you to read Chapter 3 of .Simply put, the equals-method in Object check for reference equality, where as two instances of your class could still be semantically equal when the properties are equal. This is for instance important when putting your objects into a container that utilizes equals and hashcode, like  and . Let's say we have a class like:We create two instances with the same :Without overriding equals we are getting:Correct? Well maybe, if this is what you want. But let's say we want objects with the same id to be the same object, regardless if it's two different instances. We override the equals (and hashcode):As for implementing equals and hashcode I can recommend using Ok, Let me explain the concept in very simple words.Firstly from a broader perspective we have collections,and hashmap is one of the datastructure in the collections.To understand why we have to override the both equals and hashcode method, if need to first understand what is hashmap and what is does.A hashmap is a datastructure which stores key value pairs of data in array fashion. Lets say a[], where each element in 'a' is a key value pair.Also each index in the above array can be linked list thereby having more than one values at one index.Now why is a hashmap used?\nIf we have to search among  a large array then searching through each if them will not be efficient, so what hash technique tells us that lets pre process the array with some logic and group the elements based on that logic i.e. Hashingeg: we have array 1,2,3,4,5,6,7,8,9,10,11 and we apply a hash function mod 10 so 1,11 will be grouped in together. So if we had to search for 11 in previous array then we would have to iterate the complete array but when we group it we limit our scope of iteration thereby improving speed. That datastructure used to store all the above information can be thought of as a 2d array for simplicityNow apart from the above hashmap also tells that it wont add any Duplicates in it. And this is the main reason why we have to override the equals and hashcodeSo when its said that explain the internal working of hashmap , we need to find what methods the hashmap has and how does it follow the above rules which i explained aboveso the hashmap has method called as put(K,V) , and according to hashmap it should follow the above rules of efficiently distributing the array and not adding any duplicatesso what put does is that it will first generate the hashcode for the given key to decide which index the value should go in.if nothing is present at that index then the new value will be added over there, if something is already present over there then the new value should be added after the end of the linked list at that index. but remember no duplicates should be added as per the desired behavior of the hashmap. so lets say you have two Integer objects aa=11,bb=11.\nas every object derived from the object class, the default implementation for comparing two objects is that it compares the reference and not values inside the object. So in the above case both though semantically equal will fail the equality test, and possibility that two objects which same hashcode and same values will exists thereby creating duplicates. If we override then we could avoid adding duplicates.\nYou could also refer to  :If you only override hash-code method nothing will happen. Because it always return new  for each object  as an Object class. :If you only override equal method,  is true it means the  of a and b must be same but not happen. Because you did not override  method.Note :   method of Object class always return new  for each object.So when you need to use your object in the hashing based collection, must override both  and .Because if you do not override them you will be use the default implentation in Object.Given that instance equality and hascode values generally require knowledge of what makes up an object they generally will need to be redefined in your class to have any tangible meaning.In order to use our own class objects as keys in collections like HashMap, Hashtable etc.. , we should override both methods ( hashCode() and equals() ) by having an awareness on internal working of collection. Otherwise, it leads to wrong results which we are not expected.They are methods of java.lang.Object class which is the super class of all the classes (custom classes as well and others defined in java API).This method simply checks if two object references x and y refer to the same object. i.e. It checks if x == y. for any reference value x, x.equals(x) should return true. for any reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true. for any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true. for any reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the object is modified.This method returns the hash code value for the object on which this method is invoked. This method returns the hash code value as an integer and is supported for the benefit of hashing based collection classes such as Hashtable, HashMap, HashSet etc. This method must be overridden in every class that overrides the equals method.Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.Resources: It is useful when using . The following is an excerpt from the :Joshua Bloch said it better than me in , so just Java puts a rule that So, if in our class we override equals we should override hashcode method also to fallow this rule.\nThese both methods  and  are used in  to store values as key-value pair.If we do override one and not the other , there is a possibility that the hashtable may not work as we want, if we use such object as key.Consider collection of balls in a bucket all in black color. Your Job is to color those balls as follows and use it for appropriate game,For Tennis - Yellow, Red.\nFor Cricket - WhiteNow bucket has balls in three colors Yellow, Red and White. And that now Coloring the balls - Hashing.\nChoosing the ball for game - Equals.If you did the coloring and some one chooses the ball for either cricket or tennis they wont mind the color!!!I was looking into the explanation \" If you only override hashCode then when you call  it takes first, calculates its hashCode and stores it in a given bucket. Then when you call  it should replace first with second as per the Map Documentation because they are equal (according to our definition).\" :I think 2nd time when we are adding in  then it should be the 'second' object like Assume you have class (A) that aggregates two other (B) (C), and you need to store instances of (A) inside hashtable. Default implementation only allows distinguishing of instances, but not by (B) and (C). So two instances of A could be equal, but default wouldn't allow you to compare them in correct way.  You can find a good tutorial here regarding significance of equals and hashcode methods.\n\nAdding to @Lombo 's answerThe default implementation of Object's equals() iswhich means two objects will be considered equal only if they have the same memory address which will be true only if you are\ncomparing an object with itself.But you might want to consider two objects the same if they have the same value for one\nor more of their properties (Refer the example given in @Lombo 's answer). So you will override  in these situations and you would give your own conditions for equality.Well.As long as you don't use  on your user-defined class,it is fine.\nBut some time in the future you might want to use  or  and if you don't  and , these Hash based collection won't work as intended.First of all,HashMap checks if the hashCode of  is the same as .\nOnly if the values are the same,it will proceed to check the equality in the same bucket.But here the hashCode is different for these 2 objects (because they have different memory address-from default implementation).\nHence it will not even care to check for equality.If you have a breakpoint inside your overridden equals() method,it wouldn't step in if they have different hashCodes.\n checks  and only if they are the same it would call your  method.Then you are missing the point of Hash based Collections.\nConsider the following :The following are the keys stored in the form of buckets.Say,you want to know if the map contains the key 10.\nWould you want to search all the buckets? or Would you want to search only one bucket?Based on the hashCode,you would identify that if 10 is present,it must be present in Bucket 1.\nSo only Bucket 1 will be searched !!In order to identity differences between two objects we need to override equals method.   hashCode produces integer in order to store object in data structures().Assume we have override equals method of Customer as above, \ncustomer1.equals(customer2);  // returns true by our own logicWhile working with data structure when we store object in buckets. If we use built-in hash technique, for above two customers it generates two different hashcode. So we are storing the same identical object in two different places. To avoid this kind of issues we should override the hashCode method also based on the following principles.  Both the methods are defined in Object class. And both are in its simplest implementation. So when you need you want add some more implementation to these methods then you have override in  your class. For Ex: eqauls() method in object only checks its equality on the reference. So if you need compare its state as well then you can override that as it is done in String class.The methods equals and hashcode are defined in the object class. By default if the equals method returns true, then the system will go further and check the value of the hash code. If the hash code of the 2 objects is also same only then the objects will be considered as same. So if you override only equals method, then even though the overridden equals method indicates 2 objects to be equal , the system defined hashcode may not indicate that the 2 objects are equal. So we need to override hash code as well.Please check the below link for proper and easy explanation:\nThe reason behind this:\nWhen your object fields can be null, implementing Object.equals can be a pain, because you have to check separately for null. Using Objects.equal lets you perform equals checks in a null-sensitive way, without risking a NullPointerException.\nif Both are overridden,Map<> if equals is not overriddenMap<> If hashCode is not overriddenMap<> HashCode Equal ContractIn the example below, if you comment out the override for equals or hashcode in the Person class, this code will fail to look up Tom's order. Using the default implementation of hashcode can cause failures in hashtable lookups.What I have below is a simplified code that pulls up people's order by Person. Person is being used as a key in the hashtable. method is used to get a unique integer for given object. This integer is used for determining the bucket location, when this object needs to be stored in some ,  like data structure. By default, Object\u2019s  method returns and integer representation of memory address where object is stored.The  method of objects is used when we insert them into a ,  or . More about  on Wikipedia.org for reference.To insert any entry in map data structure, we need both key and value. If both key and values are user define data types, the  of the key will be determine where to store the object internally. When require to lookup the object from the map also, the hash code of the key will be determine where to search for the object.The hash code only points to a certain \"area\" (or list, bucket etc) internally. Since different key objects could potentially have the same hash code, the hash code itself is no guarantee that the right key is found. The  then iterates this area (all keys with the same hash code) and uses the key's  method to find the right key. Once the right key is found, the object stored for that key is returned.So, as we can see, a combination of the  and  methods are used when storing and when looking up objects in a .NOTES: \nThere is no relationship between \"equals()\" and \"hashCode()\",\nbut the Java Doc says:You do this (override both equals() and hashCode() methods) for hash-code-based collections, like: HashMap, HashSet, etc.IMHO, it's as per the rule says - If two objects are equal then they should have same hash, i.e., equal objects should produce equal hash values.Given above, default equals() in Object is == which does comparison on the address, hashCode() returns the address in integer(hash on actual address) which is again distinct for distinct Object.If you need to use the custom Objects in the Hash based collections, you need to override both equals() and hashCode(), example If I want to maintain the HashSet of the Employee Objects, if I don't use stronger hashCode and equals I may endup overriding the two different Employee Objects, this happen when I use the age as the hashCode(), however I should be using the unique value which can be the Employee ID.[from Effective Java, by Joshua Bloch?]Isn't this the wrong way round?  Overriding hashCode likely implies you're writing a hash-key class, but overriding equals certainly does not. There are many classes that are not used as hash-keys, but do want a logical-equality-testing method for some other reason. If you choose \"equals\" for it, you may then be mandated to write a hashCode implementation by overzealous application of this rule. All that achieves is adding untested code in the codebase, an evil waiting to trip someone up in the future. Also writing code you don't need is anti-agile. It's just wrong (and an ide generated one will probably be incompatible with your hand-crafted equals). Surely they should have mandated an Interface on objects written to be used as keys? Regardless, Object should never have provided default hashCode() and equals() imho. It's probably encouraged many broken hash collections.But anyway, I think the \"rule\" is written back to front. In the meantime, I'll keep avoiding using \"equals\" for equality testing methods :-(
Java

I have a bunch of .keystore files and need to find one with specific CN and alias. Is there a way to do it with keytool, jarsigner or some other tool? I found a way to check if specific keystore was used to sign a specific apk, but I also need to get the alias and certificate name in each of the files.You can run the following command to list the content of your keystore file:If you are looking for a specific alias, you can also specify it in the command:If the alias is not found, it will display an exception:In order to get all the details I had to add the -v option to romaintaz answer:You can run from Java code.Certificate class holds all information about the keystore.@prateek Hope this is what you looking for!  open source visual tool to manage keystores.In a bash-like environment you can use:This command consist of 3 parts. As stated above, the  part will list all trusted certificates with all the details and that's why the  part comes to filter only the alias information among those details. And finally in the  part you can search for a specific alias (or part of it). The  turns the case insensitive mode on. Thus the given command will yield all aliases containing the pattern 'foo', f.e. foo, 123_FOO, fooBar, etc. For more information .This will list all certificates:
Java

Is there a way to declare an unsigned int in Java?Or the question may be framed as this as well:\nWhat is the Java equivalent of unsigned?Java has no .You can define a  instead of an  if you need to store large values but there's no way to exclude negative values.However, as of Java SE 8, there are a few new methods in the  class which allow you to use the  data type :Note that  variables are still signed when declared but unsigned arithmetic is now possible by using those methods in the  class.There is an Whether a value in an int is signed or unsigned depends on how the bits are interpreted - Java interprets bits as a signed value (it doesn't have unsigned primitives).If you have an int that you want to interpret as an unsigned value (e.g. you read an int from a DataInputStream that you know contains an unsigned value) then you can do the following trick.Note, that it is important that the hex literal is a long literal, not an int literal - hence the 'l' at the end.We needed unsigned numbers to model MySQL's unsigned , , ,  in , which is why we have created , a minimalistic library offering wrapper types for unsigned integer numbers in Java. Example:All of these types extend  and can be converted into higher-order primitive types and . Hope this helps.(Disclaimer: I work for the company behind these libraries)For unsigned numbers you can use these classes from :They support various operations:The thing that seems missing at the moment are byte shift operators. If you need those you can use BigInteger from Java.Perhaps this is what you meant?Use  for 16 bit unsigned integers.You can use the Math.abs(number) function. It returns a positive number.
Java

What is ? Is  an instance of anything? What set does  belong to?How is it represented in the memory?No, there is no type which  is an .This means that for any type  and , for any , where ,  is always .As the JLS quote above says, in practice you can simply pretend that it's \"merely a special literal that can be of any reference type\".In Java,  (this isn't always the case in other languages). Note also that by contract, it also has this special property (from ):It is also the  (for variables that have them) for all reference types:How this is used varies. You can use it to enable what is called  of fields, where a field would have its initial value of  until it's actually used, where it's replaced by the \"real\" value (which may be expensive to compute).There are also other uses. Let's take a real example from :This is a very common use pattern:  is used to denote non-existence of an object.Here's another usage example, this time from :So here,  would return  for each line, until it finally returns a  to signify the end. This allows you to process each line as follows:One can design the API so that the termination condition doesn't depend on  returning , but one can see that this design has the benefit of making things concise. Note that there is no problem with empty lines, because an empty line .Let's take another example, this time from :Here we start to see how using  can complicate things. The first statement says that if the key isn't mapped,  is returned. The second statement says that even if the key is mapped,  can  be returned.In contrast,  keeps things simpler by not permitting  keys and values; its , if returns , unambiguously means that the key isn't mapped.You can read through the rest of the APIs and find where and how  is used. Do keep in mind that they aren't always the  examples.Generally speaking,  are used as a special value to signify:In Java? None of your concern. And it's best kept that way.This is now borderline subjective. Some people say that  causes many programmer errors that could've been avoided. Some say that in a language that catches  like Java, it's good to use it because you will fail-fast on programmer errors. Some people avoid  by using , etc.This is a huge topic on its own, so it's best discussed as answer to another question.I will end this with a quote from the inventor of  himself,  (of quicksort fame):The  goes deeper; it's a recommended watch.No.  That is why  will return  for all classes .  (Don't be fooled by the fact that you can assign  to a variable whose type is an object type.  Strictly speaking, the assignment involves an implicit type conversion; see below.)It is the one and only member of the null type, where the null type is defined as follows:  See above.  In some contexts,  is used to denote \"no object\" or \"unknown\" or \"unavailable\", but these meanings are application specific.That is implementation specific, and you won't be able to see the representation of  in a pure Java program.  (But  is represented as a zero machine address / pointer in most if not all Java implementations.)It is nothing.No as it is nothing It can't be instance of any thing.No any setIf some reference points to it like:In heap memory some space assigned to new created object. And o will point to that assigned space in memory.Now This means now o will not point to that memory space of object.No it's not the instance of anything, instanceof will always be false.The null keyword is a literal that represents a null reference, . null is the default value of reference-type variables.Also maybe have a look at Null in Java(tm)In C and C++, \"NULL\" is a constant defined in a header file, with a value like:or:or:depending on the compiler and memory model options. NULL is not, strictly speaking, part of C/C++ itself.In Java(tm), \"null\" is not a keyword, but a special literal of the null type. It can be cast to any reference type, but not to any primitive type such as int or boolean. The null literal doesn't necessarily have value zero. And it is impossible to cast to the null type or declare a variable of this type.Null is not an instance of any class.However, you can assign null to variables of any (object or array) type: is a special value that is not an instance of any class. This is illustrated by the following program: is special value, it is not instance of anything. For obviously reason it cannot be  anything. has direct JVM support: three instructions are used to implement it: then mentions the effects of  on other instructions: it throws a  for many of them. also mentions  in generic terms:There are two major categories of types in Java:  and . Variables declared of a primitive type store values; variables declared of a reference type store references. In this case, the initialization statement declares a variables \u201cx\u201d. \u201cx\u201d stores String reference. It is  here. First of all, null is not a valid object instance, so there is no memory allocated for it. It is simply a value that indicates that the object reference is not currently referring to an object.An interesting way to see null in java in my opinion is to see it as something that DOES NOT denote an absence of information but simply as a literal value that can be assigned to a reference of any type. If you think about it if it denoted absence of information then for a1==a2 to be true doesn't make sense (in case they were both assigned a value of null) as they could really could be pointing to ANY object (we simply don't know what objects they should be pointing to)... By the way null == null returns true in java. If java e.g. would be like SQL:1999 then null==null would return unknown (a boolean value in SQL:1999 can take three values : true,false and unknown but in practise unknown is implemented as null in real systems)... 
Java

I have;Is there a (easy) way to retrieve the generic type of the list?If those are actually fields of a certain class, then you can get them with a little help of reflection:You can also do that for parameter types and return type of methods.But if they're inside the same scope of the class/method where you need to know about them, then there's no point of knowing them, because you already have declared them yourself.Short answer: no.This is probably a duplicate, can't find an appropriate one right now.Java uses something called type erasure, which means at runtime both objects are equivalent. The compiler knows the lists contain integers or strings, and as such can maintain a type safe environment. This information is lost (on an object instance basis) at runtime, and the list only contain 'Objects'.You CAN find out a little about the class, what types it might be parametrized by, but normally this is just anything that extends \"Object\", i.e. anything. If you define a type asAClass.class will only contain the fact that the parameter A is bounded by MyClass, but more than that, there's no way to tell.You can do the same for method parameters as well:If you need to get the generic type of a returned type, I used this approach when I needed to find methods in a class which returned a  and then access their generic types:This outputs:Expanding on Steve K's answer:At runtime, no, you can't.However via reflection the type parameters  accessible. TryThe method  returns a Type object. In this case, it will be an instance of , which in turn has methods  (which will contain , in this case) and , which will return an array (in this case, of length one, containing either  or ).The generic type of a collection should only matter if it actually has objects in it, right? So isn't it easier to just do:There's no such thing as a generic type in runtime, but the objects inside at runtime are guaranteed to be the same type as the declared generic, so it's easy enough just to test the item's class before we process it.For finding generic type of one field:As others have said, the only correct answer is no, the type has been erased.If the list has a non-zero number of elements, you could investigate the type of the first element ( using it's getClass method, for instance ). That won't tell you the generic type of the list, but it would be reasonable to assume that the generic type was some superclass of the types in the list.I wouldn't advocate the approach, but in a bind it might be useful.Generally impossible, because  and  share the same runtime class.You might be able to reflect on the declared type of the field holding the list, though (if the declared type does not itself refer to a type parameter whose value you don't know).The type is erased so you will not be able to. See  and 
Java

What is the best way of searching the whole classpath for an annotated class?I'm doing a library and I want to allow the users to annotate their classes, so when the Web application starts I need to scan the whole classpath for certain annotation.Do you know a library or a Java facility to do this?Edit: I'm thinking about something like the new functionality for Java EE 5 Web Services or EJB's. You annotate your class with  or  and the system finds these classes while loading so they are accessible remotely.Use  APIAnd another solution is .Quick review: I just released an uber-fast and lightweight classpath scanner  that does not call the classloader to load classes on the classpath in order to determine subclasses, superclasses, annotations etc., but rather reads the classfile binary headers directly (inspired by, but simpler than, rmueller's classpath scanner, linked in another comment).My classpath scanner can find classes on the classpath that extend a given superclass, that implement a given interface, or that have a given class annotation, and can find files within the classpath of any type whose path matches a given regular expression.Here is an example of usage:The scanner also records the latest last-modified timestamp of any file or directory encountered, and you can see if that latest last-modified timestamp has increased (indicating that something on the classpath has been updated) by calling:This can be used to enable dynamic class-reloading if something on the classpath is updated, for example to support hot-replace of route handler classes in a webserver. The above call is several times faster than the original call to scan(), since only modification timestamps need to be checked.If you want a really  (no dependencies, simple API, 15 kb jar file) and  solution, take a look at  found at  Disclaimer: I am the author.You can use Java Pluggable Annotation Processing API to write annotation processor which will be executed during the compilation process and will collect all annotated classes and build the index file for runtime use.This is the fastest way possible to do annotated class discovery because you don't need to scan your classpath at runtime, which is usually very slow operation. Also this approach works with any classloader and not only with URLClassLoaders usually supported by runtime scanners.The above mechanism is already implemented in  library.To use it annotate your custom annotation with  meta-annotation. This will create at compile time an index file: META-INF/annotations/com/test/YourCustomAnnotation listing all annotated classes. You can acccess the index at runtime by executing:Use the , or  if you are not in Java 6.Perhaps an annotation processor could produce the necessary files under META-INF/services at compile-time.Try .It can be used to search the classpath or your web application lib directory for specific annotations.You might want to use  Slightly offtopic, but Spring also does something similar, using , which you could perhaps study the source code of?I'm not sure if it will help you or not, but you could look into the apache commons-discovery project.With Spring you can also just write the following using AnnotationUtils class. i.e.:For more details and all different methods check official docs: \nJava does not have \"Discovery\".  The only way I know of is to scan the directory that the .class files should be in, parse the names and use that.  Horribly ugly, maybe there is a better package these days--I haven't looked in a few years.Usually this problem used to be addressed by including a properties file or a .xml file with the classnames in it.I'd be interested in hearing a better answer as well.Google  seems to be much faster than Spring. Found this feature request that adresses this difference: This is a reason to use Reflections as startup time of my application is really important during development. Reflections seems also to be very easy to use for my use case (find all implementers of an interface).The Classloader API doesn't have an \"enumerate\" method, because class loading is an \"on-demand\" activity -- you usually have thousands of classes in your classpath, only a fraction of which will ever be needed (the rt.jar alone is 48MB nowadays!).So, even if you  enumerate all classes, this would be very time- and memory-consuming. The simple approach is to list the concerned classes in a setup file (xml or whatever suits your fancy); if you want to do this automatically, restrict yourself to one JAR or one class directory. If you want a Scala library, use Sclasner:\n
Java

Date.getTime() returns milliseconds since Jan 1, 1970. Unixtime is seconds since Jan 1, 1970. I don't usually code in java, but I'm working on some bug fixes. I have:Is there a better way to get unixtime in java?Based on John M's suggestion, I ended up with:Avoid the Date object creation w/ .  A divide by 1000 gets you to Unix epoch.As mentioned in a comment, you typically want a primitive long (lower-case-l long) not a boxed object long (capital-L Long) for the unixTime variable's type.Java 8 added a new API for working with dates and times. \nWith Java 8 you can use returns an  that represents the current system time. With  you get the epoch seconds (unix time) from the .
Java

How do I convert  into  in Java?Of course, I'm interested in any other answer than doing it in a loop, item by item. But if there's no other answer, I'll pick that one as the best to show the fact that this functionality is not part of Java.There is no shortcut for converting from  to  as  does not deal with boxing and will just create a  which is not what you want. You have to make a utility method.Also from ... com.google.common.primitives.Ints:in Java 8 you can do thisI'll add another answer with a different method; no loop but an anonymous class that will utilize the autoboxing features:Arrays.asList will not work as some of the other answers expect.This code will  create a list of 10 integers. It will print , not :This will create a list of integers:If you already have the array of ints, there is not quick way to convert, you're better off with the loop.On the other hand, if your array has Objects, not primitives in it, Arrays.asList will work:The smallest piece of code would be:where ArrayUtils comes from commons-lang :)In Java 8 with stream:or with CollectorsIt's also worth checking out , which was closed with reason \"Not a defect\" and the following text:\"Autoboxing of entire arrays is not specified behavior, for good reason.\nIt can be prohibitively expensive for large arrays.\"give a try to this class:testcase:The best shot:Examples:Here is a generic way to convert array to ArrayListUsageIf you're open to using a third party library, this will work in :Note: I am a committer for .
Java

I need to determine the current year in Java as an integer. I would like to be able to use this value as a counter that I can, for example, use to run from now until a specified year in the past (i.e. my value starts at 2008, and I have a \"firstYearOfData\" value that is set to 1994. I can now run my process from 2008 back to 1994). I could just use java.util.Date(), but it is deprecated.Not sure if this meets with the criteria of not setting up a new Calendar?  (Why the opposition to doing so?)Using Java 8's time API (assuming you are happy to get the year in your system's default time zone), you could use :This simplest (using Calendar, sorry) is:There is also the new , as well as The easiest way is to get the year from Calendar.If you want the year of any date object, I used the following method:If your application is making heavy use of Date and Calendar objects, you really should use Joda Time, because  is mutable.  has performance problems when its fields get updated, and is clunky for datetime arithmetic. As some people answered above:If you want to use the variable later, better use:If you need the year for just a condition you better use:For example using it in a do while that checks introduced year is not less than the current year-200 or more than the current year (Could be birth year): by  wisely shows how to use the new  in Java 8. But that answer fails to address the critical issue of time zone in determining a date.That code depends on the JVM's current default time zone. The default zone is used in determining what today\u2019s date is. Remember, for example, that in the moment after midnight in Paris the date in Montr\u00e9al is still 'yesterday'. So your results may vary by what machine it runs on, a user/admin changing the host OS time zone, or any Java code  changing the JVM's current default. Better to specify the time zone.By the way, always use . Never use the 3-4 letter codes that are neither standardized nor unique.Example in java.time of Java 8.Some idea as above, but using the  2.7 library.If your goal is to jump a year at a time, no need to extract the year number. Both Joda-Time and java.time have methods for adding/subtracting a year at a time. And those methods are smart, handling Daylight Saving Time and other anomalies.Example in Joda-Time 2.7.You can also use Java 8's :That's how I used, simple and easiest wayYou can also use 2 methods from java.time.YearMonth( Since Java 8 ):I use special functions in my library to work with days/month/year ints -You can do the whole thing using Integer math without needing to instantiate a calendar:May be off for an hour or two at new year but I don't get the impression that is an issue?
Java

I'm working on my usual projects on Eclipse, it's a J2EE application, made with Spring, Hibernate and so on. I'm using Tomcat 7 for this (no particular reason, I don't exploit any new feature, I just wanted to try that). Every time I debug my application, it happens that Eclipse debugger pops out like it has reached a breakpoint, but it is not the case, in fact it stops on a Java source file that is . There is no stack trace on the console, it just stops. Then if I click on resume it goes on and the app works perfectly. This is what shows in the debugger window:I really can't explain this, because I'm not using  at all. Must be something from Tomcat, Hibernate or Spring. It's very annoying because I always have to resume during debugging.Any clues?The posted stack trace indicates that a RuntimeException was encountered in a Daemon thread. This is typically uncaught at runtime, unless the original developer caught and handled the exception.Typically, the debugger in Eclipse is configured to suspend execution at the location where the exception was thrown, on all uncaught exceptions. Note that the exception might be handled later, lower down in the stack frame and might not lead to the thread being terminated. This would be cause of the behavior observed. is straightforward:\nGo to  >  >  >  and uncheck .There's a more specific solution, which prevents Eclipse breaking on s thrown only from a given class.This behavior is triggered by tomcat when a webapp is reloaded. It's part of tomcat  that (among other things) forces the renewal of its threads.This is now fixed from versions 7.0.54 and 8.0.6 of tomcat :\nI have noticed that this often occurs after modifying server files (jsp or java) and STS has trouble reloading the application.This usually leads to restarting the server in order to get it to get the changes synchronized. After introducing JRebel - it appears to have gone away. So, I would like to think it is a reproducible issue in STS when hotswapping code in debug mode. By removing the native hotswapping, it eliminates the issue with it breaking inside the ThreadPoolExecutor class. 
Java

I need to get a  out of a , but I don't know how to do it. The following fails:How can I fix it so that it works?Use the  method taking a typed array argument of the same size.A different size can also, but that would force the  method to create a new array to return instead of reusing the provided argument, which may end up to be less efficient. See also .Use   method:In Java 8 we can use streams API:We can also make use of the overloaded version of  which takes  as:The purpose of the generator function here is to take an integer (size of desired array) and produce an array of desired size. I personally prefer the former approach using method reference than the later one using lambda expression.Guava style:more info: 
Java

How do I get my project's runtime dependencies copied into the  folder?  As it is right now, after  the  folder contains only my project's jar, but none of the runtime dependencies.This works for me:The best approach depends on what you want to do:Works for me with dependencies directory created in target folder. Like it!Take a look at the , specifically, the .  Take a look at  under the heading .  Set the  configuration property to ${basedir}/target/lib (I believe, you'll have to test).Hope this helps.A simple and elegant solution for the case where one needs to copy the dependencies to a target directory without using any other phases of maven (I found this very useful when working with Vaadin).Complete pom example:Then run The jar file dependencies can be found in Try something like this:If you want to do this on an occasional basis (and thus don't want to change your POM), try this command-line:If you omit the , the dependences are placed in .If you want to deliver a bundle of your application jar, together with all it's dependencies and some scripts to invoke the MainClass, look at the .The following configuration will generate scripts for Window and Linux to launch the application (with a generated path referencing all the dependency jars, download all dependencies (into a lib folder below target/appassembler). The  can then be used to package the whole appassembler directory to a zip which is installed/deployed along with the jar to the repository.The assembly descriptor (in src/main/assembly) to package the direcotry as a zip would be:If you make your project a war or ear type maven will copy the dependencies.You can use the the  to create an uber jar in which you can bundle all your 3rd party dependencies.supposinghere ist what worked for me:Just to spell out what has already been said in brief. I wanted to create an executable JAR file that included my dependencies along with my code. This worked for me:(1) In the pom, under <build><plugins>, I included:(2) Running mvn compile assembly:assembly produced the desired my-project-0.1-SNAPSHOT-jar-with-dependencies.jar in the project's target directory.(3) I ran the JAR with java -jar my-project-0.1-SNAPSHOT-jar-with-dependencies.jarIt's a heavy solution for embedding heavy dependencies, but Maven's  does the trick for me.  @ should work, although for simpler cases you should only need this excerpt from the : If you're having problems related to dependencies not appearing in the WEB-INF/lib file when running on a Tomcat server in Eclipse, take a look at this:You simply had to add the Maven Dependencies in Project Properties > Deployment Assembly.
Java

I upgraded from Java 1.6 to Java 1.7 today.\nSince then an error occur when I try to establish a connection to my webserver over SSL:Here is the code:Its only a test project thats why I allow and use untrusted certificates with the code:I sucessfully tried to connect to .\nwhere is my fault?Thanks.Java 7 introduced SNI support which is enabled by default. I have found out that certain misconfigured servers send an \"Unrecognized Name\" warning in the SSL handshake which is ignored by most clients... except for Java. As  mentioned, the Oracle engineers refuse to \"fix\" this bug/feature.As workaround, they suggest to set the  property. To allow your programs to work without re-compiling, run your app as:The property can also be set in the Java code, but it must be set . Once the SSL library has loaded, you can change the property, but it . To disable SNI on runtime (with the aforementioned limitations), use:The disadvantage of setting this flag is that SNI is disabled everywhere in the application. In order to make use of SNI and still support misconfigured servers:For the Webscarab SSL proxy,  implements the fall-back setup.I had what I believe the same issue is.\nI found that I needed to adjust the Apache configuration to include a ServerName or ServerAlias for the host.This code failed:And this code worked:Wireshark revealed that during the TSL/SSL Hello the warning\nAlert (Level: Warning, Description: Unrecognized Name), Server Hello\nWas being sent from the server to the client.\nIt was only a warning, however, Java 7.1 then responded immediately back with a \"Fatal, Description: Unexpected Message\", which I assume means the Java SSL libraries don't like to see the warning of unrecognized name.From the Wiki on Transport Layer Security (TLS):112 Unrecognized name   warning TLS only; client's Server Name Indicator specified a hostname not supported by the serverThis led me to look at my Apache config files and I found that if I added a ServerName or ServerAlias for the name sent from the client/java side, it worked correctly without any errors.You can disable sending SNI records with the System property jsse.enableSNIExtension=false. If you can change the code it helps to use  (with no host parameter or with a connected socket). In this case it will not send a server_name indication.Instead of relying on the default virtual host mechanism in apache, you can define one last catchall virtualhost that uses an arbitrary ServerName and a wildcard ServerAlias, e.g.In that way you can use SNI and apache will not send back the SSL warning. Of course, this only works if you can describe all of your domains easily using a wildcard syntax.We also ran into this error on a new Apache server build.The fix in our case was to define a  in the  that corresponded to the host name that Java was trying to connect to.  Our  was set to the internal host name. Our SSL cert was using the external host name, but that was not sufficient to avoid the warning.To help debug, you can use this ssl command:If there is a problem with that hostname, then it will print this message near the top of the output:I should also note that we did not get that error when using that command to connect to the internal host name, even though it did not match the SSL cert. Use:It should be useful. To retry on a SNI error in Apache HttpClient 4.4 - the easiest way we came up with (see ):andandYou cannot supply system properties to the jarsigner.exe tool, unfortunately.I have submitted defect , referencing @eckes' defect  and explaining why it was closed in error.My defect is specifically about the impact on the jarsigner tool, but perhaps it will lead them to reopening the other defect and addressing the issue properly. Actually, it turns out that you CAN supply system properties to the Jarsigner tool, it's just not in the help message. Use Ran into this issue with  and jvm 1.7 and 1.8. On AWS, we did not have the option to change the ServerName and ServerAlias to match (they are different) so we did the following:In  we added the following:That allowed us to bypass the issue with the \"Unrecognized Name\".I hit the same problem and it turned out that reverse dns was not setup correct, it pointed to wrong hostname for the IP. After I correct reverse dns and restart httpd, the warning is gone.\n(if I don't correct reverse dns, adding ServerName did the trick for me as well)I have also come across this issue whilst upgrading from Java 1.6_29 to 1.7.Alarmingly, my customer has discovered a setting in the Java control panel which resolves this.In the Advanced Tab you can check 'Use SSL 2.0 compatible ClientHello format'.This seems to resolve the issue.We are using Java applets in an Internet Explorer browser.Hope this helps.I had the same problem with an Ubuntu Linux server running subversion when accessed via Eclipse.It has shown that the problem had to do with a warning when Apache (re)started:This has been due to a new entry in , where another  directive was entered alongside the directive in .After removing the directive in , the problem had vanished (after restarting Apache, naturally)Just to add a solution here. This might help for LAMP usersThe above mentioned line in the virtual host configuration was the culprit.Virtual Host Configuration when errorWorking ConfigurationMy 's  was commented out by default. It worked after uncommenting.There is an  where you can just use your own HostnameVerifier to implicitly trust certain connections. The issue comes with Java 1.7 where SNI extensions have been added and your error is due to a server misconfiguration.You can either use \"-Djsse.enableSNIExtension=false\" to disable SNI across the whole JVM or read my blog where I explain how to implement a custom verifier on top of a URL connection.
Java

? Convert the  to a  and iterate over that? Something else?I use a for loop to iterate the string and use  to get each character to examine it.  Since the String is implemented with an array, the  method is a constant time operation.That's what I would do.  It seems the easiest to me.As far as correctness goes, I don't believe that exists here.  It is all based on your personal style.Two optionsorThe first is probably faster, then 2nd is probably more readable. Note most of the other techniques described here break down if you're dealing with characters outside of the BMP (Unicode ), i.e.  that are outside of the u0000-uFFFF range. This will only happen rarely, since the code points outside this are mostly assigned to dead languages. But there are some useful characters outside this, for example some code points used for mathematical notation, and some used to encode proper names in Chinese.In that case your code will be:The  method requires Java 5+.Source: I agree that StringTokenizer is overkill here. Actually I tried out the suggestions above and took the time. My test was fairly simple: create a StringBuilder with about a million characters, convert it to a String, and traverse each of them with charAt() / after converting to a char array / with a CharacterIterator a thousand times (of course making sure to do something on the string so the compiler can't optimize away the whole loop :-) ).The result on my 2.6 GHz Powerbook (that's a mac :-) ) and JDK 1.5:As the results are significantly different, the most straightforward way also seems to be the fastest one. Interestingly, charAt() of a StringBuilder seems to be slightly slower than the one of String.BTW I suggest not to use CharacterIterator as I consider its abuse of the '\\uFFFF' character as \"end of iteration\" a really awful hack. In big projects there's always two guys that use the same kind of hack for two different purposes and the code crashes really mysteriously. Here's one of the tests:There are some dedicated classes for this:If you have  on your classpath, the following is a pretty readable alternative. Guava even has a fairly sensible custom List implementation for this case, so this shouldn't be inefficient.UPDATE: As @Alex noted, with Java 8 there's also  to use. Even the type is IntStream, so it can be mapped to chars like:If you need to iterate through the code points of a  (see this ) a shorter / more readable way is to use the  method added in Java 8:or using the stream directly instead of a for loop:There is also  if you want a stream of the characters (although it is an , since there is no ).I wouldn't use  as it is one of classes in the JDK that's legacy.The javadoc says:See .Put the length into  and use  loop.StringTokenizer is totally unsuited to the task of breaking a string into its individual characters.  With  you can do that easily by using a regex that matches nothing, e.g.:But StringTokenizer doesn't use regexes, and there's no delimiter string you can specify that will match the nothing between characters.  There  one cute little hack you can use to accomplish the same thing: use the string itself as the delimiter string (making every character in it a delimiter) and have it return the delimiters:However, I only mention these options for the purpose of dismissing them.  Both techniques break the original string into one-character strings instead of char primitives, and both involve a great deal of overhead in the form of object creation and string manipulation.  Compare that to calling charAt() in a for loop, which incurs virtually no overhead. Elaborating on  and .Above answers point out the problem of many of the solutions here which don't iterate by code point value -- they would have trouble with any . The java docs also outline the issue  (see \"Unicode Character Representations\").  Anyhow, here's some code that uses some actual surrogate chars from the supplementary Unicode set, and converts them  to a String.  Note that .toChars() returns an array of chars:  if you're dealing with surrogates, you'll necessarily have two chars.  This code should work for  Unicode character.This Example Code will Help you out!
Java

How to convert a  value into an  value in Java?or if you don't need to worry about null:And in both situations, you might run into overflows (because a Long can store a wider range than an Integer).Here are three ways to do it:All three versions generate almost identical byte code:If you care to check for overflows and have  handy, there is : is dead simple, and throws  on overflow:You'll need to type cast it.Bear in mind that a long has a bigger range than an int so you might lose data.If you are talking about the boxed types, then read the .The best simple way of doing so is:Assuming not null  longValIt works for example y you get an Object that can be an Integer or a Long. I know that is ugly, but it happens...If you are using Java 8 Do it as belowIn java ,there is a rigorous way to convert a long to intnot only lnog can convert into int,any type of class extends Number can convert to other Number type in general,here I will show you how to convert a long to int,other type vice versa.
Java

Unlike C#'s , where an execution pipeline can be executed as many times as we want, in Java a stream can be 'iterated' only once. Any call to a terminal operation closes the stream, rendering it unusable.\nThis 'feature' takes away a lot of power. I imagine the reason for this is  technical. What were the design considerations behind this strange restriction?Edit: in order to demonstrate what I am talking about, consider the following implementation of Quick-Sort in C#:Now to be sure, I am not advocating that this is a good implementation of quick sort! It is however great example of the expressive power of lambda expression combined with stream operation. And it can't be done in Java!\nI can't even ask a stream whether it is empty without rendering it unusable. I have some recollections from the early design of the Streams API that might shed some light on the design rationale.Back in 2012, we were adding lambdas to the language, and we wanted a collections-oriented or \"bulk data\" set of operations, programmed using lambdas, that would facilitate parallelism. The idea of lazily chaining operations together was well established by this point. We also didn't want the intermediate operations to store results.The main issues we needed to decide were what the objects in the chain looked like in the API and how they hooked up to data sources. The sources were often collections, but we also wanted to support data coming from a file or the network, or data generated on-the-fly, e.g., from a random number generator.There were many influences of existing work on the design. Among the more influential were Google's  library and the Scala collections library. (If anybody is surprised about the influence from Guava, note that , Guava lead developer, was on the  expert group.) On Scala collections, we found this talk by Martin Odersky to be of particular interest: . (Stanford EE380, 2011 June 1.)Our prototype design at the time was based around . The familiar operations , , and so forth were extension (default) methods on . Calling one added an operation to the chain and returned another . A terminal operation like  would call  up the chain to the source, and the operations were implemented within each stage's Iterator.Since these are Iterables, you can call the  method more than once. What should happen then?If the source is a collection, this mostly works fine. Collections are Iterable, and each call to  produces a distinct Iterator instance that is independent of any other active instances, and each traverses the collection independently. Great.Now what if the source is one-shot, like reading lines from a file? Maybe the first Iterator should get all the values but the second and subsequent ones should be empty. Maybe the values should be interleaved among the Iterators. Or maybe each Iterator should get all the same values. Then, what if you have two iterators and one gets farther ahead of the other? Somebody will have to buffer up the values in the second Iterator until they're read. Worse, what if you get one Iterator and read all the values, and only  get a second Iterator. Where do the values come from now? Is there a requirement for them all to be buffered up  somebody wants a second Iterator?Clearly, allowing multiple Iterators over a one-shot source raises a lot of questions. We didn't have good answers for them. We wanted consistent, predictable behavior for what happens if you call  twice. This pushed us toward disallowing multiple traversals, making the pipelines one-shot.We also observed others bumping into these issues. In the JDK, most Iterables are collections or collection-like objects, which allow multiple traversal. It isn't specified anywhere, but there seemed to be an unwritten expectation that Iterables allow multiple traversal. A notable exception is the NIO  interface. Its specification includes this interesting warning:[bold in original]This seemed unusual and unpleasant enough that we didn't want to create a whole bunch of new Iterables that might be once-only. This pushed us away from using Iterable.About this time, an  appeared that described a spot of trouble he'd had with Scala. He'd written this code:It's pretty straightforward. It parses lines of text into  objects and prints them out twice. Except that it actually only prints them out once. It turns out that he thought that  was a collection, when in fact it's an iterator. The second call to  encounters an empty iterator, from which all values have been exhausted, so it prints nothing.This kind of experience convinced us that it was very important to have clearly predictable results if multiple traversal is attempted. It also highlighted the importance of distinguishing between lazy pipeline-like structures from actual collections that store data. This in turn drove the separation of the lazy pipeline operations into the new Stream interface and keeping only eager, mutative operations directly on Collections.  the rationale for that.What about allowing multiple traversal for collection-based pipelines but disallowing it for non-collection-based pipelines? It's inconsistent, but it's sensible. If you're reading values from the network,  you can't traverse them again. If you want to traverse them multiple times, you have to pull them into a collection explicitly.But let's explore allowing multiple traversal from collections-based pipelines. Let's say you did this:(The  operation is now spelled .)If source is a collection, then the first  call will create a chain of Iterators back to the source, execute the pipeline operations, and send the results into the destination. The second call to  will create another chain of Iterators, and execute the pipeline operations . This isn't obviously wrong but it does have the effect of performing all the filter and map operations a second time for each element. I think many programmers would have been surprised by this behavior.As I mentioned above, we had been talking to the Guava developers. One of the cool things they have is an  where they describe features that they decided  to implement along with the reasons. The idea of lazy collections sounds pretty cool, but here's what they have to say about it. Consider a  operation that returns a :To take a specific example, what's the cost of  or  on a List? For commonly used classes like , they're O(1). But if you call one of these on a lazily-filtered list, it has to run the filter over the backing list, and all of a sudden these operations are O(n). Worse, it has to traverse the backing list on  operation.This seemed to us to be  laziness. It's one thing to set up some operations and defer actual execution until you so \"Go\". It's another to set things up in such a way that hides a potentially large amount of recomputation.In proposing to disallow non-linear or \"no-reuse\" streams,  described the  of allowing them as giving rise to \"unexpected or confusing results.\" He also mentioned that parallel execution would make things even trickier. Finally, I'd add that a pipeline operation with side effects would lead to difficult and obscure bugs if the operation were unexpectedly executed multiple times, or at least a different number of times than the programmer expected. (But Java programmers don't write lambda expressions with side effects, do they? DO THEY??)So that's the basic rationale for the Java 8 Streams API design that allows one-shot traversal and that requires a strictly linear (no branching) pipeline. It provides consistent behavior across multiple different stream sources, it clearly separates lazy from eager operations, and it provides a straightforward execution model.With regard to , I am far from an expert on C# and .NET, so I would appreciate being corrected (gently) if I draw any incorrect conclusions. It does appear, however, that  permits multiple traversal to behave differently with different sources; and it permits a branching structure of nested  operations, which may result in some significant recomputation. While I appreciate that different systems make different tradeoffs, these are two characteristics that we sought to avoid in the design of the Java 8 Streams API.The quicksort example given by the OP is interesting, puzzling, and I'm sorry to say, somewhat horrifying. Calling  takes an  and returns an , so no sorting is actually done until the final  is traversed. What the call seems to do, though, is build up a tree structure of  that reflects the partitioning that quicksort would do, without actually doing it. (This is lazy computation, after all.) If the source has N elements, the tree will be N elements wide at its widest, and it will be lg(N) levels deep.It seems to me -- and once again, I'm not a C# or .NET expert -- that this will cause certain innocuous-looking calls, such as pivot selection via , to be more expensive than they look. At the first level, of course, it's O(1). But consider a partition deep in the tree, at the right-hand edge. To compute the first element of this partition, the entire source has to be traversed, an O(N) operation. But since the partitions above are lazy, they must be recomputed, requiring O(lg N) comparisons. So selecting the pivot would be an O(N lg N) operation, which is as expensive as an entire sort.But we don't actually sort until we traverse the returned . In the standard quicksort algorithm, each level of partitioning doubles the number of partitions. Each partition is only half the size, so each level remains at O(N) complexity. The tree of partitions is O(lg N) high, so the total work is O(N lg N).With the tree of lazy IEnumerables, at the bottom of the tree there are N partitions. Computing each partition requires a traversal of N elements, each of which requires lg(N) comparisons up the tree. To compute all the partitions at the bottom of the tree, then, requires O(N^2 lg N) comparisons.(Is this right? I can hardly believe this. Somebody please check this for me.)In any case, it is indeed cool that  can be used this way to build up complicated structures of computation. But if it does increase the computational complexity as much as I think it does, it would seem that programming this way is something that should be avoided unless one is extremely careful.While the question appears simple, the actual answer requires some background to make sense. If you want to skip to the conclusion, scroll down...Using basic concepts, C#'s  concept is more closely related to , which is able to create as many  as you want.  create . Java's  create The history of each concept is similar, in that both  and  have a basic motivation to allow 'for-each' style looping over the members of data collections. That's an oversimplification as they both allow more than just that, and they also arrived at that stage via different progressions, but it is a significant common feature regardless.Let's compare that feature: in both languages, if a class implements the /, then that class must implement at least a single method (for C#, it's  and for Java it's ). In each case, the instance returned from that (/) allows you to access the current and subsequent members of the data. This feature is used in the for-each language syntax. in C# has been extended to allow a number of other language features (). Features added include selections, projections, aggregations, etc. These extensions have a strong motivation from use in set-theory, similar to SQL and Relational Database concepts.Java 8 has also had functionality added to enable a degree of functional programming using Streams and Lambdas. Note that Java 8 streams are not primarily motivated by set theory, but by functional programming. Regardless, there are a lot of parallels.So, this is the second point. The enhancements made to C# were implemented as an enhancement to the  concept. In Java, though, the enhancements made were implemented by creating new base concepts of Lambdas and Streams, and then also creating a relatively trivial way to convert from  and  to Streams, and visa-versa.So, comparing IEnumerable to Java's Stream concept is incomplete. You need to compare it to the combined Streams and Collections API's in Java.Streams are not designed to solve problems the same way that iterators are:With an , you get a data value, process it, and then get another data value.With Streams, you chain a sequence of functions together, then you feed an input value to the stream, and get the output value from the combined sequence. Note, in Java terms, each function is encapsulated in a single  instance. The Streams API allows you to link a sequence of  instances in a way that chains a sequence of transformation expressions.In order to complete the  concept, you need a source of data to feed the stream, and a terminal function that consumes the stream.The way you feed values in to the stream may in fact be from an , but the  sequence itself is not an , it is a compound function.A  is also intended to be lazy, in the sense that it only does work when you request a value from it.Note these significant assumptions and features of Streams:When you consider that a Java Stream is just a part of a supply, stream, and collect system, and that Streams and Iterators are often used together with Collections, then it is no wonder that it is hard to relate to the same concepts which are almost all embedded in to a single  concept in C#.Parts of IEnumerable (and close related concepts) are apparent in all of the Java Iterator, Iterable, Lambda, and Stream concepts.There are small things that the Java concepts can do that are harder in IEnumerable, and visa-versa.Adding Streams gives you more choices when solving problems, which is fair to classify as 'enhancing power', not 'reducing', 'taking away', or 'restricting' it.This question is misguided, because streams are function sequences, not data. Depending on the data source that feeds the stream, you can reset the data source, and feed the same, or different stream.Comparing an  to a  is misguided. The context you are using to say  can be executed as many times as you want, is best compared to Java , which can be iterated as many times as you want. A Java  represents a subset of the  concept, and not the subset that supplies data, and thus cannot be 'rerun'.The first statement is true, in a sense. The 'takes away power' statement is not. You are still comparing Streams it IEnumerables. The terminal operation in the stream is like a 'break' clause in a for loop. You are always free to have another stream, if you want, and if you can re-supply the data you need. Again, if you consider the  to be more like an , for this statement, Java does it just fine.The reason is technical, and for the simple reason that a Stream a subset of what think it is. The stream subset does not control the data supply, so you should reset the supply, not the stream. In that context, it is not so strange.Your quicksort example has the signature:You are treating the input  as a data source:Additionally, return value is  too, which is a supply of data, and since this is a Sort operation, the order of that supply is significant. If you consider the Java  class to be the appropriate match for this, specifically the  specialization of , since List is a supply of data which has a guaranteed order or iteration, then the equivalent Java code to your code would be:Note there is a bug (which I have reproduced), in that the sort does not handle duplicate values gracefully, it is a 'unique value' sort.Also note how the Java code uses data source (), and stream concepts at different point, and that in C# those two 'personalities' can be expressed in just . Also, although I have use  as the base type, I could have used the more general , and with a small iterator-to-Stream conversion, I could have used the even more general s are built around s which are stateful, mutable objects. They don\u2019t have a \u201creset\u201d action and in fact, requiring to support such rewind action would \u201ctake away much power\u201d. How would  be supposed to handle such a request?On the other hand, for s which have a retraceable origin, it is easy to construct an equivalent  to be used again. Just put the steps made to construct the  into a reusable method. Keep in mind that repeating these steps is not an expensive operation as all these steps are lazy operations; the actual work starts with the terminal operation and depending on the actual terminal operation entirely different code might get executed.It would be up to you, the writer of such a method, to specify what calling the method twice implies: does it reproduce exactly the same sequence, as streams created for an unmodified array or collection do, or does it produce a stream with a similar semantics but different elements like a stream of random ints or a stream of console input lines, etc.By the way, to avoid confusion, a terminal operation  the  which is distinct from  the  as calling  on the stream does (which is required for streams having associated resources like, e.g. produced by ).It seems that a lot of confusion stems from misguiding comparison of  with . An  represents the ability to provide an actual , so its like an  in Java. In contrast, a  is a kind of iterator and comparable to an  so it\u2019s wrong to claim that this kind of data type can be used multiple times in .NET, the support for  is optional. The examples discussed here rather use the fact that an  can be used to fetch  s and that works with Java\u2019s s  as well; you can get a new . If the Java developers decided to add the  operations to  directly, with intermediate operations returning another , it was really comparable and it could work the same way.However, the developers decided against it and the decision is discussed in . The biggest point is the confusion about eager Collection operations and lazy Stream operations. By looking at the .NET API, I (yes, personally) find it justified. While it looks reasonable looking at  alone, a particular Collection will have lots of methods manipulating the Collection directly and lots of methods returning a lazy , while the particular nature of a method isn\u2019t always intuitively recognizable. The worst example I found (within the few minutes I looked at it) is  whose name matches  the name of the inherited (is this the right terminus for extension methods?)  while having an entirely contradicting behavior.Of course, these are two distinct decisions. The first one to make  a type distinct from / and the second to make  a kind of one time iterator rather than another kind of iterable. But these decision were made together and it might be the case that separating these two decision never was considered. It wasn\u2019t created with being comparable to .NET\u2019s in mind.The actual API design decision was to add an improved type of iterator, the . s can be provided by the old s (which is the way how these were retrofitted) or entirely new implementations. Then,  was added as a high-level front-end to the rather low level s. That\u2019s it. You may discuss about whether a different design would be better, but that\u2019s not productive, it won\u2019t change, given the way they are designed now.There is another implementation aspect you have to consider. s are  immutable data structures. Each intermediate operation may return a new  instance encapsulating the old one but it may also manipulate its own instance instead and return itself (that doesn\u2019t preclude doing even both for the same operation). Commonly known examples are operations like  or  which do not add another step but manipulate the entire pipeline). Having such a mutable data structure and attempts to reuse (or even worse, using it multiple times at the same time) doesn\u2019t play well\u2026For completeness, here is your quicksort example translated to the Java  API. It shows that it does not really \u201ctake away much power\u201d.It can be used likeYou can write it even more compact asI think there are very few differences between the two when you look closely enough.At it's face, an  does appear to be a reusable construct:However, the compiler is actually doing a little bit of work to help us out; it generates the following code:Each time you would actually iterate over the enumerable, the compiler creates an enumerator.  The enumerator is not reusable; further calls to  will just return false, and there is no way to reset it to the beginning.  If you want to iterate over the numbers again, you will need to create another enumerator instance.To better illustrate that the IEnumerable has (can have) the same 'feature' as a Java Stream, consider a enumerable whose source of the numbers is not a static collection.  For example, we can create an enumerable object which generates a sequence of 5 random numbers:Now we have very similar code to the previous array-based enumerable, but with a second iteration over :The second time we iterate over  we will get a different sequence of numbers, which isn't reusable in the same sense.  Or, we could have written the  to thrown an exception if you try to iterate over it multiple times, making the enumerable actually unusable (like a Java Stream).Also, what does your enumerable-based quick sort mean when applied to a ?So, the biggest difference is that .NET allows you to reuse an  by implicitly creating a new  in the background whenever it would need to access elements in the sequence.This implicit behavior is often useful (and 'powerful' as you state), because we can repeatedly iterate over a collection.But sometimes, this implicit behavior can actually cause problems.  If your data source is not static, or is costly to access (like a database or web site), then a lot of assumptions about  have to be discarded; reuse is not that straight-forwardIt is possible to bypass some of the \"run once\" protections in the Stream API; for example we can avoid  exceptions (with message \"stream has already been operated upon or closed\") by referencing and reusing the  (rather than the  directly).For example, this code will run without throwing an exception:However the output will be limited torather than repeating the output twice. This is because the  used as the  source is stateful and stores its current position. When we replay this  we start again at the end.We have a number of options to solve this challenge:This will print as expected.
Java

I have a update view, where I need to preselect the value stored in database for a Spinner.I was having in mind something like this, but the  has no  method, so I am stuck.Suppose your  is named , and it contains as one of its choices: \"some value\".To find and compare the position of \"some value\" in the Spinner use this:A simple way to set spinner based on value isWay to complex code are already there, this is just much plainer. I keep a separate ArrayList of all the items in my Spinners.  This way I can do indexOf on the ArrayList and then use that value to set the selection in the Spinner.Based on , I came up with this single line solution... it's not very pretty, but you can blame whoever maintains the code for  for neglecting to include a function that does this for that.You'll get a warning about how the cast to a  is unchecked... really, you could just use an  as Merrill did, but that just exchanges one warning for another.Based on Merrill's answer\nhere is how to do with a CursorAdapterIf you need to have an indexOf method on any old Adapter (and you don't know the underlying implementation) then you can use this:if you are using string array this is the best way:    You can use this also,Here is how to do it if you are using a  (where  is the name of the db column that you used to populate your ):(Maybe you will also need to close the cursor, depending on whether you are using a loader.)Also (a refinement of ) this is the corresponding way to do it if you are filling your Spinner from an array:There is actually a way to get this using an index search on the AdapterArray and all this can be done with reflection.  I even went one step further as I had 10 Spinners and wanted to set them dynamically from my database and the database holds the value only not the text as the Spinner actually changes week to week so the value is my id number from the database.Here is the indexed search you can use on almost any list as long as the fields are on top level of object.Cast method which can be create for all primitives  here is one for string and int.here is my solutionand getItemIndexById belowHope this help!I am using a custom adapter, for that this code is enough:So, your code snippet will be like this:This is my simple method to get the index by string.Use following line to select using value:To make the application remember the last selected spinner values, you can use below code:I had the same issue when trying to select the correct item in a spinner populated using a cursorLoader. I retrieved the id of the item I wanted to select first from table 1 and then used a CursorLoader to populate the spinner. In the onLoadFinished I cycled through the cursor populating the spinner's adapter until I found the item that matched the id I already had. Then assigned the row number of the cursor to the spinner's selected position. It would be nice to have a similar function to pass in the id of the value you wish to select in the spinner when populating details on a form containing saved spinner results. As some of the previous answers are very right, I just want to make sure from none of you fall in such this problem.If you set the values to the  using , you MUST get the position of the value using the same string structure .You must get the position of needed value like this:Otherwise, you'll get the , item not found!I used  because of .I hope that will be helpful for you.Here is my hopefully complete solution. I have following enum:used in following classCode to set the spinner by HTTPMethod enum-member:Where  is defined in a layout-file, and  is delivered by android-studio.you have to pass your custom adapter with position like REPEAT[position]. and it works properly.
Java

I want to get a list of files in a directory, but I want to sort it such that the oldest files are first.  My solution was to call File.listFiles and just resort the list based on File.lastModified, but I was wondering if there was a better way.Edit: My current solution, as suggested, is to use an anonymous Comparator:I think your solution is the only sensible way.  The only way to get the list of files is to use  and the documentation states that this makes no guarantees about the order of the files returned.  Therefore you need to write a  that uses  and pass this, along with the array of files, to .This might be faster if you have many files. This uses the decorate-sort-undecorate pattern so that the last-modified date of each file is fetched only  rather than every time the sort algorithm compares two files. This potentially reduces the number of I/O calls from O(n log n) to O(n).It's more code, though, so this should only be used if you're mainly concerned with speed and it is measurably faster in practice (which I haven't checked).You might also look at , it has a built in  and many other nice utilities for working with files.What's about similar approach, but without boxing to the Long objects:In Java 8:Imports :Code :If the files that you are sorting are being modified / updated while the sort is being performed you will be violating the transitivity requirement of the comparator's general contract. To avoid this potential bug, you'll want to build up a static lookup table of last modified values to use in the comparator for each file, something like the following:You can try guava :You can use Apache   libraryI came to this post when i was searching for the same issue but in .\nI don't say this is the best way to get sorted files by last modified date, but its the easiest way I found yet.Below code may be helpful to someone-Thanks
Java

I don't understand why there is no inheritance in Java annotations, just as Java classes. I think it would be very useful.For example: I want to know if a given annotation is a validator. With inheritance, I could reflexively navigate through superclasses to know if this annotation extends a ValidatorAnnotation. Otherwise, how can I achieve this?So, can anyone give me a reason why this design decision?About the reason why it wasn't designed that way you can find the answer in the  Design FAQ, where it says: So, yes I guess, the reason is it just KISS. Anyway, it seems this issue (along with many others) are being looked into as part of , and you can even find an alternative compiler with this functionality already developed by .Extensible annotations would effectively add the burden of specifying and maintaing another type system.  And this would be a fairly unique type system, so you could not simply apply an OO type paradigm.  Think through all the issues when you introduce polymorphism and inheritance to an annotation (e.g. what happens when sub-annotation changes meta-annotation specs such as retention?)And all this added complexity for what use-case?  You want to know if a given annotation belongs to a category?Try this:As you can see, you can easily group and categorize annotations without undue pain using the provided facilities.  So,  is the reason for not introducing a meta-type type system to the Java language.[p.s. edit]I used the String simply for demonstration and in view of an open ended meta annotation.  For your own given project, you obviously can use an enum of category types and specify multiple categories (\"multiple inheritance\") to a given annotation.  Do note that the values are entirely bogus and for demonstration purposes only:In a sense you already have it with Annotations - meta Annotations. If you annotate an annotation with meta information, that is in many ways equivalent to extending an additional interface. Annotations are interfaces, so polymorphism doesn't really come into play, and since they are static in nature, there can be no runtime dynamic dispatching.In your validator example, you could just on the annotation get the annotated type and see if it has a validator meta-annotation.The only use case I could see that inheritance would help is if you wanted to be able to get the annotation by super type, but that would add a whole bunch of complexity, because a given method or type may have two such annotations on it, meaning that an array would have to be returned instead of just a single object.So I think the ultimate answer is that the use cases are esoteric and complicate more standard use cases making it not worth it.Never thought about that but... seems that you're right, there is no problem with annotations inheritance facility (at least I don't see the problem with it).About your example with  annotation - you can exploit  approach then. I.e. you apply particular meta-annotation to the whole annotation interface.The designers of Java annotation support made a number of \"simplifications\" to the detriment of the Java community. The second one is being remedied in Java 8, but its too late. Many frameworks have been written based on what was possible in Java 5 and now these API warts are here to stay for a good long time.the same problem I have. No, you can't. I did 'disciplined' myself to write properties in annotations to respect some standards, so outside when you get annotation you can 'sniff' what kind od annotation it is by properties it has. One thing I could think of is the possibility to have multiple annotations. So you could add validator and a more specific annotation at the same place. But I could be mistaken :)I might be three years late in responding to this question, but I found it interesting because I found myself in the same spot. Here's my take on it. You can view annotations as Enums. They provide a one-way kind of information - use it or lose it. I had a situation where I wanted to simulate GET, POST, PUT and DELETE in a web-app. I so badly wanted to have a \"super\" annotation that was called \"HTTP_METHOD\". It later on dawned on me that it didn't matter. Well, I had to settle with using a hidden field in the HTML form to identify DELETE and PUT (because POST and GET were available anyway).On the server-side, I looked out for a hidden request parameter with the name, \"_method\". If the value was PUT or DELETE, then it overrode the associated HTTP request method. Having said that, it didn't matter whether or not I needed to extend an annotation to get the work done. All the annotations looked the same, but they were treated differently on the server side.So in your case, drop the itch to extend annotations. Treat them as 'markers'. They \"represent\" some information, and not necessarily \"manipulate\" some information.
Java

How to convert a String to CharSequence in Java?Since   , you can pass a  wherever you need a , or assign a  to a :If you want to convert a  to a , just use the  method that must be implemented by every concrete implementation of .Hope it helps.Straight answer: is an interface, and the  class implements .CharSequence is an interface and String is its one of the implementations other than StringBuilder, StringBuffer and many other.So, just as you use , you can use  or simply You can use 
Java

Just wondering if anyone has tried using new Java 7 language features with Android?\nI know that Android reads the bytecode that Java spits out and turns it to dex. So I guess my question is can it understand the bytecode of Java 7?If you are using , the Java 7  should be enabled automatically without any patches. Try-with-resource requires API Level 19+, and NIO 2.0 stuff are missing. If you can't use Java 7 features, see 's answer on how to edit your .The following is for historical interest only.A small part of Java 7 can certainly be used with Android (note: I have only tested on 4.1). First of all, you could not use Eclipse's ADT because  that only Java compiler 1.5 and 1.6 are compliant. You could recompile ADT but I find there is no simple way to do that aside from recompiling the whole Android together. But you don't need to use Eclipse. For instance, ,  and other javac-based IDEs supports compiling to Android  you could set the compliance even up to Java 8 with:This only allows Java 7 , and you can hardly benefit from anything since a half of improvement also comes from the library. Features you could use are those which do not depend on the library:And these features cannot be used :... \"yet\" :) It turns out that, although Android's library is targeting for 1.6, the Android source does contain interfaces like  and traditional interfaces like  does inherit from AutoCloseable (SafeVarargs is really missing, though). We could confirm its existence via reflection. They are hidden simply because the Javadoc has the  tag, which caused the \"android.jar\" not to include them.There is already as existing questionon how to get those methods back. You just need to  the existing \"android.jar\" reference of the current Platform with our customized one, then many of the Java 7 APIs will become available (the procedure is similar to that in Eclipse. Check Project Structure \u2192 SDKs.)In additional to AutoCloseable, (only) the following Java 7  are also revealed:That's basically all. In particular, NIO 2.0 does not exist, and Arrays.asList is still not @SafeVarargs.Yes, I have tried. But this is not a great test as the compatibility was limited to level 6 with no way (no simple way at least) to really use java 7:So I had  working, and also other apps, more complicated and using , ,  and , but this only proves that the compatibility handling of Java 7 seems to be well done and working with Android.Anyway, the SDK is designed to be used with Java 5 or 6, as explained .We may have something working with Java 7, but it would be working \"by accident\". The building of the DEX may work properly or not, and once the DEX built, it may work or not. This because using a non-qualified JDK gives unpredictable results by definition.Even if someone has succesfully built an Android app under plain Java 7, this does not qualify the JDK. The same process applied to another application may fail, or the resulting application may have bugs tied to the use of that JDK. Not recommended.For those who are involved on webapps development, this exactly the same as deploying a web application built under Java 5 or 6 under an application server qualified for Java 4 only (let's say Weblogic 8 for example). This may work, but this is not something that can be recommended for other purposes than trying.Quote from dalvikvm.com:That means, the .java source file does not matter, it's only the .class bytecode.As far as I know, only  was added to the JVM bytecode in Java 7, the rest is compatible to Java 6. The Java language itself does not use . Other new features, like the  statement using s or the multi- are just syntatic sugar and did not require byte code changes. For example, the multi- just copies the -block for each possible exception.The only problem should be that the new classes introduced in Java 7 are missing in Android, like , so I'm not sure if you can use the -with-resources feature (somebody tried it?).Any comments on that? Am I missing something?As of the Android SDK v15, along with Eclipse 3.7.1, Java 7 is  supported for Android development. Setting the source compatibility to 1.7 mandates setting the generated .class file compatibility to 1.7, which leads to the following error by the Android compiler:To expand on the above answer by @KennyTM, if you are targeting 4.0.3 and above (), you can use the hidden APIs by adding a few classes to your target's SDK android.jar.Once you do this, you can use try-with-resources on any Closeable, as well as implement AutoCloseable in your own classes.I've made a zip containing sources and binaries of all the classes that needed to be modified in android.jar to make these APIs available. You just need to unpack it and add the binaries to your android-sdk/platforms/android-NN/android.jarAlso of note is that, in the past couple of months, Elliott Hughes has made a few commits to the Android tree: , , ,  and . So, there is finally some progress going on.With the release of SDK 19 it is no longer necessary to patch android.jar with the additional APIs.The best method to use try-with-resources in Android Studio for an app that targets 4.0.3 and above () is add the following  to your :Android Studio will complain that try-with-resources can't be used with this API level, but my experience is that it can. The project will build and run without issue on devices with 4.0.3 and above. I've experienced no issues with this, with an app that has been installed into 500k+ devices.To ignore this warning, add the following to your :It seems that getting this to work with pure ant is a bit of a kludge.But it worked for me: In order to use Java 7 features in code build by Android's ant based build system, simply put the following in your  in your projects root directory:Some people might be interested in this git project I've found, that seems to allow to run Java 7 on android. \nHowever too much of a risk if I add this in the current project I work on. So I'll wait until Google to officially support Java 7.
Java

What's the reason Java doesn't allow us to doI could understand .NET didn't allow us to do that, as in .NET you have value types that at run-time can have different sizes, but in Java all kinds of T will be object references, thus having the same size (correct me if I'm wrong).What is the reason?It's because Java's arrays (unlike generics) contain, at runtime, information about its component type. So you must know the component type when you create the array. Since you don't know what  is at runtime, you can't create the array.Quote:(I believe it is , but am not sure)See it in context here: By failing to provide a decent solution, you just end up with something worse IMHO.The common work around is as follows.is replaced with (assuming T extends Object and not another class)I prefer the first example, however more acedemic types seem to prefer the second, or just prefer not to thing about it.  Most of the examples of why you can't just use an Object[] equally apply to List or Collection (which are supported), so I see them as very poor arguments.Note: this is one of the reasons the Collections library itself doesn't compile without  warnings.  If you this usecase cannot be supported without warnings, something is fundermentally broken with the generics model IMHO.The reason this is impossible is that Java implements its Generics purely on the compiler level, and there is only one class file generated for each class.\nThis is called .At runtime, the compiled class needs to handle all of its uses with the same bytecode. So,  would have absolutely no idea what type needs to be instantiated.The answer was already given but if you already have an Instance of T then you can do this:Hope, I could Help,\nFerdi265This last line would compile just fine, but if we run this code, we would get an ArrayStoreException because we\u2019re trying to put a double into an integer array. The fact that we are accessing the array through a Number reference is irrelevant here, what matters is that the array is an array of integers.This means that we can fool the compiler, but we cannot fool the run-time type system. And this is so because arrays are what we call a reifiable type. This means that at run-time Java knows that this array was actually instantiated as an array of integers which simply happens to be accessed through a reference of type Number[].So, as we can see, one thing is the actual type of the object, an another thing is the type of the reference that we use to access it, right?Now, the problem with generic types in Java is that the type information for type parameters is discarded by the compiler after the compilation of code is done; therefore this type information is not available at run time. This process is called type erasure. There are good reasons for implementing generics like this in Java, but that\u2019s a long story, and it has to do with binary compatibility with pre-existing code.Let\u2019s consider now the following unsafe code:If the Java compiler does not stop us from doing this, the run-time type system cannot stop us either, because there is no way, at run time, to determine that this list was supposed to be a list of integers only. The Java run-time would let us put whatever we want into this list, when it should only contain integers, because when it was created, it was declared as a list of integers. That\u2019s why the compiler rejects line number 4 because it is unsafe and if allowed could break the assumptions of the type system.As such, the designers of Java made sure that we cannot fool the compiler. If we cannot fool the compiler (as we can do with arrays) then we cannot fool the run-time type system either.As such, we say that generic types are non-reifiable, since at run time we cannot determine the true nature of the generic type.I skipped some parts of this answers you can read full article here:\n I like the answer indirectly given\nby .  However, I propose it is wrong.  I changed Gafter's code a little.  It compiles and it runs for a while then it bombs where Gafter predicted it wouldThe output isSo it appears to me you can create generic array types in java.  Did I misunderstand the question?The main reason is due to the fact that arrays in Java are covariant.There's a good overview .I know I'm a little late to the party here, but I figured I might be able to help any future googlers since none of these answers fixed my issue.  Ferdi265's answer helped immensely though.I'm trying to create my own Linked list, so the following code is what worked for me:In the toArray() method lies the way to create an array of a generic type for me:In my case, I simply wanted an array of stacks, something like this:Since this was not possible, I used the following as a workaround:Ugly, but Java is happy.Note: as mentioned by BrainSlugs83 in the comment to the question, it is totally possible to have arrays of generics in .NETThere surely must be a good way around it (maybe using reflection), because it seems to me that that's exactly what  does. I quote:So one way around it would be to use this function i.e. create an  of the objects you want in the array, then use  to create the actual array. It wouldn't be speedy, but you didn't mention your requirements.So does anyone know how  is implemented?It is because generics were added on to java after they made it, so its kinda clunky because the original makers of java thought that when making an array the type would be specified in the making of it. So that does not work with generics so you have to do \nE[] array=(E[]) new Object[15];\nThis compiles but it gives a warning. If we cannot instantiate generic arrays, why does the language have generic array types? What's the point of having a type without objects?The only reason I can think of, is varargs - . Otherwise they could have completely scrubbed generic array types. (Well, they didn't really have to use array for varargs, since varargs didn't exist before . That's probably another mistake.)So it is a lie, you  instantiate generic arrays, through varargs!Of course, the problems with generic arrays are still real, e.g.We can use this example to actually demonstrate the danger of  array.On the other hand, we've been using generic varargs for a decade, and the sky is not falling yet. So we can argue that the problems are being exaggerated; it is not a big deal. If explicit generic array creation is allowed, we'll have bugs here and there; but we've been used to the problems of erasure, and we can live with it.And we can point to  to refute the claim that the spec keeps us from the problems that they claim to keep us from. If Sun had more time and resources for , I believe they could have reached a more satisfying resolution.From :To me, it sounds very weak. I think that anybody with a sufficient understanding of generics, would be perfectly fine, and even expect, that the ArrayStoredException is not thrown in such case.
Java

All I am trying to do is to get the current class name, and java appends a useless non-sense  to the end of my class name. How can I get rid of it and only return the actual class name?The \"$1\" is not \"useless non-sense\". If your class is anonymous, a number is appended.If you don't want the class itself, but its declaring class, then you can use . For example:You can move that in some static utility method.But note that this is not the current class name. The anonymous class is different class than its enclosing class. The case is similar for inner classes.Try,This will work as long as you don't use it in a static method.Try using\n or .  If it's an anonymous class, use You can use , like so:this answer is late, but i think there is another way to do this in the context of anonymous handler class.let's say:it will achieve the same result. additionally, it's actually quite convenience since every class is defined at compile time, so no dynamicity is damaged.above that, if the class is really nested, i.e.  actually is enclosed by , the class of B can be easily known as:In your example,  probably refers to an anonymous class instance. Java gives a name to those classes by appending a  to the name of the enclosing class.I'm assuming this is happening for an anonymous class. When you create an anonymous class you actually create a class that extends the class whose name you got.The \"cleaner\" way to get the name you want is:If your class is an anonymous inner class,  should give you the class that it was created from. If you created it from an interface than you're sort of SOL because the best you can do is  which might give you more than one interface.The \"hacky\" way is to just get the name with  and use a regex to drop the .The combination of both answers. Also prints a method name:I've found this to work for my code,, however my code is getting the class out of an array within a for loop.
Java

In Java I'm trying to test for a null value, from a ResultSet, where the column is being cast to a primitive  type. From the code fragment above, is there a better way to do this, and I assume that the second  test is redundant?Educate us, and Thanks The default for  when the field value is  is to return , which is also the default value for your  declaration. In which case your test is completely redundant.If you actually want to do something different if the field value is NULL, I suggest:(Edited as @martin comments below; the OP code as written would not compile because  is not initialised)Another solution:I think, it is redundant.  should return an  object or , if the column value actually was . So it should even be possible to do something like:Just check if the field is  or not using . Substitute  with whatever null-case value you want.Or, if you can guarantee that you use the right DB column type so that  really returns an  (and thus not ,  or ), then you can also just typecast it to an .AFAIK you can simply useeven if it is NULL.With java 8 you can do this:In that case you ensure that the nVal will be null (and not zero) if the SQL value is NULLFor convenience, you can create a wrapper class around ResultSet that returns null values when  ordinarily would not.Another nice way of checking, if you have control the SQL, is to add a default value in the query itself for your int column. Then just check for that value.e.g for an Oracle database, use NVLthen checkOf course this also is under the assumption that there is a value that wouldn't normally be found in the column.
Java

I'm migrating a piece of code to make use of generics. One argument for doing so is that the for loop is much cleaner than keeping track of indexes, or using an explicit iterator.In about half the cases, the list (an ArrayList) is being iterated in reverse order by using an index today.Can someone suggest a cleaner way of doing this (since I dislike the  when working with collections), though it does work? I can't add any new dependencies outside the JDK.Try this: offers  and . As in most cases for Guava, the former delegates to the latter if the argument is an , so you can use the former in all cases.  These do not create new copies of the list but just \"reversed views\" of it.ExampleI don't think it's possible using the for loop syntax.  The only thing I can suggest is to do something like:... but I wouldn't say this is \"cleaner\" given that it's going to be less efficient.Option 1: Have you thought about reversing the List with  and then using foreach?Of course, you may also want to refactor your code such that the list is ordered correctly so you don't have to reverse it, which uses extra space/time.EDIT:Option 2: Alternatively, could you use a  instead of an ArrayList?  It will allow you to iterate forwards and backwardsEDIT:Option 3: As others have suggested, you could write an Iterator that will go through the list in reverse, here is an example:Create a custom reverseIterable You could use the concrete class  instead of the general interface . Then you have a  for iterating with the reverse direction.Don't know why there is no  with ...Here is an (untested) implementation of a .  When  is called it creates and returns a private  implementation, which simply maps calls to  to  and calls to  are mapped to .  It means you could iterate over an  in reverse as follows:Very simple Example:This is an old question, but it's lacking a java8-friendly answer. Here are some ways of reverse-iterating the list, with the help of the Streaming API:If the lists are fairly small so that performance is not a real issue, one can use the -metod of the -class in . Yields pretty -code, and the original list stays the same. Also, the reversed list is backed by the original list, so any change to the original list will be reflected in the reversed one.Yields the following result:Which means that reverse iteration of myList can be written as:Also found google collections  method.To have code which looks like this:Put this code into a file called \"In.java\":You could use  from Apache Commons-Collections:As has been suggested at least twice, you can use  with a , in particular with a . If you want to use the for-each loop (i.e., have an ), you can construct and use a wraper like this:Reason : \"Don't know why there is no descendingIterator with ArrayList...\"Since array list doesnot keep the list in the same order as data has been added to list. So, never use Arraylist .Linked list will keep the data in same order of ADD to list.So , above in my example, i used ArrayList() in order to make user to twist their mind and make them to workout something from their side.Instead of thisUSE:
Java

How can I detect I am in Release mode or Debug mode in android? The simplest, and best long-term solution, is to use . This is a  value that will be  for a debug build,  otherwise:There have been reports that this value is not 100% reliable from Eclipse-based builds, though I personally have not encountered a problem, so I cannot say how much of an issue it really is.If you are using Android Studio, or if you are using Gradle from the command line, you can add your own stuff to  or otherwise tweak the  and  build types to help distinguish these situations at runtime.The solution from Illegal Argument is based on the value of the  flag in the manifest. If that is how you wish to distinguish a \"debug\" build from a \"release\" build, then by definition, that's the best solution. However, bear in mind that going forward, the  flag is really an independent concept from what Gradle/Android Studio consider a \"debug\" build to be. Any build type can elect to set the  flag to whatever value that makes sense for that developer and for that build type.Try the following:It is taken from bundells post from Yes, you will have no problems using:Unless you are importing the wrong BuildConfig class. Make sure you are referencing your project's BuildConfig class, not from any of your dependency libraries.Due to the mixed comments about , I used the following to disable crashlytics (and analytics) in debug mode :then, in your code you detect the  flag as follows:use the same concept in your app and rename  to anything you want. I like this approach because I can see the flag in the configuration and I can control the flag.Alternatively, you could differentiate using If you're running debug build\n returns true. And for release build  returns true.
Java

What function does the  (caret) operator serve in Java?When I try this:...it gives me:...so I guess it doesn't perform exponentiation. But what is it then? in Java is the exclusive-or (\"xor\") operator.Let's take  as example:This the truth table for bitwise () and logical () xor:More simply, you can also think of xor as \"this  that, but !\".As for integer exponentiation, unfortunately Java does not have such an operator. You can use  (casting the result to  if necessary).You can also use the traditional bit-shifting trick to compute some powers of two. That is,  is two to the -th power for .Addressing your  need, you actually don't need to compute various powers of 10. You can use what is called the , which is not only simple but also efficient.Since you're doing this as a personal exercise, I won't give the Java code, but here's the main idea:It may look complicated at first, but it really isn't. You basically read the digits left to right, and you multiply your result so far by 10 before adding the next digit.In table form:As many people have already pointed out, it's the  operator. Many people have also already pointed out that if you want exponentiation then you need to use .But I think it's also useful to note that  is just one of a family of operators that are collectively known as bitwise operators:From .These operators can come in handy when you need to read and write to integers where the individual bits should be interpreted as flags, or when a specific range of bits in an integer have a special meaning and you want to extract only those. You can do a lot of every day programming without ever needing to use these operators, but if you ever have to work with data at the bit level, a good knowledge of these operators is invaluable.It's bitwise XOR, Java does not have an exponentiation operator, you would have to use  instead.It is the  bitwise operator.As others have said, it's bitwise XOR. If you want to raise a number to a given power, use , where  is a number and  is the power.Lot many people have already explained about what it is and how it can be used but apart from the obvious you can use this operator to do a lot of programming tricks likeLot many such tricks can be done using bit wise operators, interesting topic to explore.use Math.pow instead:That is because you are using the xor operator.In java, or just about any other language, ^ is bitwise xor,\nso of course,10 ^ 1 = 11.\nIt's interesting how Java and C# don't have a power operator.As already stated by the other answer(s), it's the . For more information on bit-operators in Java, see: AraK's link points to the definition of exclusive-or, which explains how this function works for two boolean values.The missing piece of information is how this applies to two integers (or integer-type values). Bitwise exclusive-or is applied to pairs of corresponding binary digits in two numbers, and the results are re-assembled into an integer result.To use your example:A simple way to define bitwise XOR is to say the result has a 1 in every place where the two input numbers differ.With 4 and 5, the only difference is in the last place; so0101 ^ 0100 = 0001 (5 ^ 4 = 1) .It is the Bitwise xor operator in java which results 1 for different value of bit (ie 1 ^ 0 = 1) and 0 for same value of bit (ie 0 ^ 0 = 0) when a number is written in binary form.ex :- To use your example:The binary representation of 5 is 0101.\nThe binary representation of 4 is 0100.A simple way to define Bitwise XOR is to say the result has a 1 in every place where the two input numbers differ.0101 ^ 0100 = 0001 (5 ^ 4 = 1) .It is the bitwise xor operator in java which results 1 for different value (ie 1 ^ 0 = 1) and 0 for same value (ie 0 ^ 0 = 0).^ is binary (as in base-2) xor, not exponentiation (which is not available as a Java operator). For exponentiation, see java.lang.Math.pow().In other languages like Python you can do 10**2=100, try it.Meanwhile, in Groovy:Running the above using for example gives:
Java

I'm trying to remove some elements from  while iterating it like this:Of course, I get  when trying to remove item from the list at the same time when iterating . Is there some simple solution to do that right?Use an  and call :As an alternative to everyone else's answers I've always done something like this:This will avoid you having to deal with the iterator directly, but requires another list.  I've always preferred this route for whatever reason.Java 8 user can do that: It will remove elements in the list, for which someCondition is satisfiedYou have to use the iterator's remove() method, which means no enhanced for loop:No, no, NO!In single threated tasks you don't need to use Iterator, moreover, CopyOnWriteArrayList (due to performance hit).Solution is much simpler: .According to Java copyright owners (some years ago Sun, now Oracle) , it uses iterator to walk through collection and just hides it to make code looks better. But, unfortunately as we can see, it produced more problems than profits, otherwise this topic would not arise.For example, this code will lead to java.util.ConcurrentModificationException when entering next iteration on modified ArrayList:But following code works just fine:So, try to use indexing approach for iterating over collections and avoid for-each loop, as they are not equivalent!\nFor-each loop uses some internal iterators, which check collection modification and throw ConcurrentModificationException exception. To confirm this, take a closer look at the printed stack trace when using first example that I've posted:For multithreading use corresponding multitask approaches (like synchronized keyword).While other suggested solutions work, If you really want the solution to be made thread safe you should replace ArrayList with If you want to modify your List during traversal, then you need to use the . And then you can use  to remove the elements during traversal.One alternative method is convert your  to , iterate them and remove them directly from the  based on your logic.You can use the iterator remove() function to remove the object from underlying collection object. But in this case you can remove the same object and not any other object from the list.from  Though one answer is accepted and this is an old one, I thought posting this answer as it does not use 
Java

In Java, you can define multiple top level classes in a single file, providing that at most one of these is public (see ).  See below for example.e.g., PublicClass.java:My suggested name for this technique (including multiple top-level classes in a single source file) would be \"mess\". Seriously, I don't think it's a good idea - I'd use a nested type in this situation instead. Then it's still easy to predict which source file it's in. I don't believe there's an official term for this approach though.As for whether this actually changes between implementations - I highly doubt it, but if you avoid doing it in the first place, you'll never need to care :)javac doesn't actively prohibit this, but it does have a limitation that pretty much means that you'd never want to refer to a top-level class from another file unless it has the same name as the file it's in.Suppose you have two files, Foo.java and Bar.java.Foo.java contains:Bar.java contains:Let's also say that all of the classes are in the same package (and the files are in the same directory).What happens if Foo.java refers to Baz but not Bar and we try to compile Foo.java? The compilation fails with an error like this:This makes sense if you think about it. If Foo.java refers to Baz, but there is no Baz.java (or Baz.class), how can javac know what source file to look in?If you instead tell javac to compile Foo.java and Bar.java at the same time, or even if you had previously compiled Bar.java (leaving the Baz.class where javac can find it) then this error goes away. This makes your build process feel very unreliable and flaky, however.Because the actual limitation, which is more like \"don't refer to a top-level class from another file unless it has the same name as the file it's in or you're also referring to a class that's in that same file that's named the same thing as the file\" is kind of hard to follow, people usually go with the much more straightforward (though stricter) convention of just putting one top-level class in each file. This is also better if you ever change your mind about whether a class should be public or not.Sometimes there really is a good reason why everybody does something in a particular way.I believe you simply call  what it is: a . You can also declare  as well.e.g., elsewhere on SO: As for changes in behavior between versions, there was this discussion about something that \"worked perfectly\" in 1.2.2. but stopped working in 1.4 in sun's forum: .Multi-class single-file demo.I'm not aware of any which don't have that restriction - all the file based compilers won't allow you to refer to source code classes in files which are not named the same as the class name. ( if you compile a multi-class file, and put the classes on the class path, then any compiler will find them )You can have as many classes as you wish like thisAccording to Effective Java 2nd edition (Item 13):The nested class may be static or non-static based on whether the member class needs access to the enclosing instance (Item 22).
Java

I'm putting together a Swing application where I often want to replace the contents of a JPanel. To do this, I'm calling , then adding my new content, then calling .However I'm finding that the old content is still actually visible (though obscured by the the new content). If I add a call to  in addition to , it works as expected.I'm sure on other occasions I've experienced that just calling  is enough.So basically my question is - should I need to call both functions and if not, when should I call each of them?You need to call  and . The former tells Swing that an area of the window is dirty (which is necessary to erase the image of the old children removed by ); the latter tells the layout manager to recalculate the layout (which is necessary when adding components). This should cause  of the panel to repaint, but may not cause the panel itself to do so (see  for the list of repaint triggers).On a more general note: rather than reusing the original panel, I'd recommend building a new panel and swapping them at the parent.Any time you do a remove() or a removeAll(), you should callafter you have completed add()'ing the new components.Calling validate() or revalidate() is mandatory when you do a remove() - see the relevant javadocs.My own testing indicates that repaint() is also necessary. I'm not sure exactly why. is called on a container once new components are added or old ones removed.  this call is an instruction to tell the layout manager to reset based on the new component list.   will trigger a call to repaint what the component thinks are 'dirty regions.'  Obviously not all of the regions on your  are considered dirty by the . is used to tell a component to repaint itself.  It is often the case that you need to call this in order to cleanup conditions such as yours.yes you need to call \n    repaint();\n    revalidate();\nwhen you call removeAll() then you have to call repaint() and revalidate()
Java

I want to know what actually happens when you annotate a method with @Transactional?\nOf course, I know that Spring will wrap that method in a Transaction.But, I have the following doubts:Source: [Yes, I am a newbie and I don't mind accepting the fact that I don't know this]Cheers !!This is a big topic. The Spring reference doc devotes multiple chapters to it. I recommend reading the ones on  and , as Spring's declarative transaction support uses AOP at its foundation.But at a very high level, Spring creates proxies for classes that declare  on the class itself or on members. The proxy is mostly invisible at runtime. It provides a way for Spring to inject behaviors before, after, or around method calls into the object being proxied. Transaction management is just one example of the behaviors that can be hooked in. Security checks are another. And you can provide your own, too, for things like logging. So when you annotate a method with , Spring dynamically creates a proxy that implements the same interface(s) as the class you're annotating. And when clients make calls into your object, the calls are intercepted and the behaviors injected via the proxy mechanism. Transactions in EJB work similarly, by the way.As you observed, through, the proxy mechanism only works when calls come in from some external object. When you make an internal call within the object, you're really making a call through the \"\" reference, which bypasses the proxy. There are ways of working around that problem, however. I explain one approach in  in which I use a  to inject an instance of the proxy into \"self-referencing\" classes at runtime. I save this reference to a member variable called \"\". Then if I need to make internal calls that require a change in the transaction status of the thread, I direct the call through the proxy (e.g. \"\".) The forum post explains in more detail. Note that the  code would be a little different now, as it was written back in the Spring 1.x timeframe. But hopefully it gives you an idea. I have an updated version that I could probably make available.When Spring loads your bean definitions, and has been configured to look for @Transactional annotations, it will create these proxy objects around your actual bean. These proxy objects are instances of classes that are auto-generated at runtime. The default behaviour of these proxy objects when a method is invoked is just to invoke the same method on the \"target\" bean (i.e. your bean). However, the proxies can also be supplied with interceptors, and when present these interceptors will be invoked by the proxy before it invokes your target bean's method. For target beans annotated with @Transactional, Spring will create a TransactionInterceptor, and pass it to the generated proxy object. So when you call the method from client code, you're calling the method on the proxy object, which first invokes the TransactionInterceptor (which begins a transaction), which in turn invokes the method on your target bean. When the invocation finishes, the TransactionInterceptor commits/rolls back the transaction. It's transparent to the client code.As for the \"external method\" thing, if your bean invokes one of its own methods, then it will not be doing so via the proxy. Remember, Spring wraps your bean in the proxy, your bean has no knowledge of it. Only calls from \"outside\" your bean go through the proxy.Does that help?As a visual person, I like to weigh in with a sequence diagram of the proxy pattern. If you don't know how to read the arrows, I read the first one like this:  executes .\n(I was allowed to post the photo on condition that I mentioned its origins. Author: Noel Vaes, website: www.noelvaes.eu)
Java

I\u2019m currently monitoring a Java application with jconsole. The memory tab lets you choose between:What is the difference between them ? The heap memory is the runtime data area from which the Java VM allocates memory for all class instances and arrays. The heap may be of a fixed or variable size. The garbage collector is an automatic memory management system that reclaims heap memory for objects.Non-heap memory includes a method area shared among all threads and memory required for the internal processing or optimization for the Java VM. It stores per-class structures such as a runtime constant pool, field and method data, and the code for methods and constructors. The method area is logically part of the heap but, depending on the implementation, a Java VM may not garbage collect or compact it. Like the heap memory, the method area may be of a fixed or variable size. The memory for the method area does not need to be contiguous..With Java8, non heap region no more contains PermGen but Metaspace, which is a major change in Java8, supposed to get rid of out of memory errors with java as metaspace size can be increased depending on the space required by jvm for class data.The new keyword allocates memory on the Java heap. The heap is the main pool of memory,accessible to the whole of the application. If there is not enough memory available to allocate for that object, the JVM attempts to reclaim some memory from the heap with a garbage collection. If it still cannot obtain enough memory, an OutOfMemoryError is thrown, and the JVM exits.The heap is split into several different sections, called generations. As objects survive more garbage collections, they are promoted into different generations. The older generations are not garbage collected as often. Because these objects have already proven to be longer lived, they are less likely to be garbage collected.When objects are first constructed, they are allocated in the Eden Space. If they survive a garbage collection, they are promoted to Survivor Space, and should they live long enough there, they are allocated to the Tenured Generation. This generation is garbage collected much less frequently.There is also a fourth generation, called the Permanent Generation, or PermGen. The objects that reside here are not eligible to be garbage collected, and usually contain an immutable state necessary for the JVM to run, such as class definitions and the String constant pool. Note that the PermGen space is planned to be removed from Java 8, and will be replaced with a new space called Metaspace, which will be held in native memory.\nreference\uff1a\n is part of memory allocated to JVM by Operating System.Objects reside in an area called the heap. The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected.You can find more details about  in below SE question:PermGen has been replaced with Metaspace since Java 8 release.Regarding your queries: The Java Virtual Machine (JVM) generates native code and stores it in a memory area called the codecache. The JVM generates native code for a variety of reasons, including for the dynamically generated interpreter loop, Java Native Interface (JNI) stubs, and for Java methods that are compiled into native code by the just-in-time (JIT) compiler. The JIT is by far the biggest user of the codecache.
Java

I'm familiar with ORM as a concept, and I've even used nHibernate several years ago for a .NET project; however, I haven't kept up with the topic of ORM in Java and haven't had a chance to use any of these tools.But, now I may have the chance to begin to use some ORM tools for one of our applications, in an attempt to move away from a series of legacy web services.I'm having a hard time telling the difference betweeen the JPA spec, what you get with the Hibernate library itself, and what JDO has to offer.So, I understand that this question is a bit open-ended, but I was hoping to get some opinions on:Some notes:IMO, I would recommend Hibernate.There have been some comments / questions about what you should do if you  to use Hibernate-specific features.  There are many ways to look at this, but my advice would be:In reality, you will probably need to trade-off  you are worried by vendor tie-in versus  you need those vendor specific extensions.And there are other factors too, like how well you / your staff know the respective technologies, how much the products will cost in licensing, and whose story you believe about what is going to happen in the future for JDO and JPA.Make sure you evaluate the DataNucleus implementation of JDO. We started out with Hibernate because it appeared to be so popular but pretty soon realized that it's not a 100% transparent persistence solution. There are too many caveats and the documentation is full of 'if you have this situation then you must write your code like this' that took away the fun of freely modeling and coding however we want. JDO has  caused me to adjust my code or my model to get it to 'work properly'. I can just design and code simple POJOs as if I was going to use them 'in memory' only, yet I can persist them transparently.The other advantage of JDO/DataNucleus over hibernate is that it doesn't have all the run time reflection overhead and is more memory efficient because it uses build time byte code enhancement (maybe add 1 sec to your build time for a large project) rather than hibernate's run time reflection powered proxy pattern.Another thing you might find annoying with Hibernate is that a reference you have to what you think is the object... it's often a 'proxy' for the object. Without the benefit of byte code enhancement the proxy pattern is required to allow on demand loading (i.e. avoid pulling in your entire object graph when you pull in a top level object). Be prepared to override equals and hashcode because the object you think you're referencing is often just a proxy for that object. Here's an example of frustrations you'll get with Hibernate that you won't get with JDO:\nIf you like coding to 'workarounds' then, sure, Hibernate is for you. If you appreciate clean, pure, object oriented, model driven development where you spend all your time on modeling, design and coding and none of it on ugly workarounds then spend a few hours evaluating . The hours invested will be repaid a thousand fold.For quite some time now DataNucleus' implements the JPA persistence standard in addition to the JDO persistence standard so porting existing JPA projects from Hibernate to DataNucleus should be very straight forward and you can get all of the above mentioned benefits of DataNucleus with very little code change, if any.\nSo in terms of the question, the choice of a particular standard, JPA (RDBMS only) vs JDO (RDBMS + No SQL + ODBMSes + others), DataNucleus supports both, Hibernate is restricted to JPA only.Another issue to consider when choosing an ORM is the efficiency of its dirty checking mechanism - that becomes very important when it needs to construct the SQL to update the objects that have changed in the current transaction - especially when there are a lot of objects.\nThere is a detailed technical description of Hibernate's dirty checking mechanism in this SO answer: \nI have recently evaluated and picked a persistence framework for a java project and my findings are as follows:What I am seeing is that the support in favour of  is primarily:and the support in favour of  is primarily:I am seeing a lot of pro-JPA posts from JPA developers who have clearly not used JDO/Datanucleus offering weak arguments for not using JDO.I am also seeing a lot of posts from JDO users who have migrated to JDO and are much happier as a result.In respect of JPA being more popular, it seems that this is due in part due to RDBMS vendor support rather than it being technically superior. (Sounds like VHS/Betamax to me).JDO and it's reference implementation Datanucleus is clearly not dead, as shown by Google's adoption of it for GAE and active development on the source-code (http://sourceforge.net/projects/datanucleus/).I have seen a number of complaints about JDO due to bytecode enhancement, but no explanation yet for why it is bad. In fact, in a world that is becoming more and more obsessed by NoSQL solutions, JDO (and the datanucleus implementation) seems a much safer bet.I have just started using JDO/Datanucleus and have it set up so that I can switch easily between using db4o and mysql. It's helpful for rapid development to use db4o and not have to worry too much about the DB schema and then, once the schema is stabilised to deploy to a database. I also feel confident that later on, I could deploy all/part of my application to GAE or take advantage of distributed storage/map-reduce a la hbase /hadoop / cassandra without too much refactoring.I found the initial hurdle of getting started with Datanucleus a little tricky - The documentation on the datanucleus website is a little hard to get into - the tutorials are not as easily to follow as I would have liked. Having said that, the more detailed documentation on the API and mapping is very good once you get past the initial learning curve.The answer is, it depends what you want. I would rather have cleaner code, no-vendor-lock-in, more pojo-orientated, nosql options verses more-popular. If you want the warm fussy feeling that you are doing the same as the majority of other developers/sheep, choose JPA/hibernate. If you want to lead in your field, test drive  JDO/Datanucleus and make your own mind up.I would suggest neither! Use Spring DAO's  together with ,  and  instead.My own personal experience with Hibernate is that the time saved up-front is more than offset by the endless days you will spend down the line trying to understand and debug issues like unexpected cascading update behaviour.If you are using a relational DB then the closer your code is to it, the more control you have. Spring's DAO layer allows fine control of the mapping layer, whilst removing the need for boilerplate code. Also, it integrates into Spring's transaction layer which means you can very easily add (via AOP) complicated transactional behaviour without this intruding into your code (of course, you get this with Hibernate too).JDO is not dead actually so please check your facts.\nJDO 2.2 was released in Oct 2008\nJDO 2.3 is under development.This is developed openly, under Apache. More releases than JPA has had, and its ORM specification is still in advance of even the JPA2 proposed featuresJDO is having advanced features than JPA see I am using JPA (OpenJPA implementation from Apache which is based on the KODO JDO codebase which is 5+ years old and extremely fast/reliable). IMHO anyone who tells you to bypass the specs is giving you bad advice. I put the time in and was definitely rewarded. With either JDO or JPA you can change vendors with minimal changes (JPA has orm mapping so we are talking less than a day to possibly change vendors). If you have 100+ tables like I do this is huge. Plus you get built0in caching with cluster-wise cache evictions and its all good. SQL/Jdbc is fine for high performance queries but transparent persistence is far superior for writing your algorithms and data input routines. I only have about 16 SQL queries in my whole system (50k+ lines of code).Anyone who says that JDO is dead is an astroturfing FUD monger and they know it.JDO is alive and well. The specification is still more powerful, mature and advanced than the much younger and constrained JPA.If you want to limit yourself to only what's available in the JPA standard you can write to JPA and use DataNucleus as a high performance, more transparent persistence implementation than the other implementations of JPA. Of course DataNucleus also implements the JDO standard if you want the flexibility and efficiency of modeling that JDO brings.I've been looking into this myself and can't find a strong difference between the two. I think the big choice is in which implementation you use. For myself I've been considering the  platform as it is a data-store agnostic implementation of both.I've used Hibernate (JPA implementation) and JPOX (JDO implementation) in the same project.  JPOX worked ok, but ran into bugs fairly quickly, there where some Java 5 language features it did not support at the time.  It had problems playing nice with XA transactions.  I was generating the database schema from the JDO objects.  It wanted to connect to a database every time which is annoying if your Oracle connection happens not be working.We then switched to Hibernate.  We toyed around with just using pure JPA for awhile, but we needed to use some of the Hibernate specific features to do the mapping.  Running the same code on multiple databases is very easy.  Hibernate seems to cache objects aggressively or just have strange caching behavior at times. There are a few DDL constructs Hibernate can not handle and so they are defined in an additional file that is run to initialize the database.  When I've run into a Hibernate problem there are often many people that have run into the same problem which makes googling for solutions easier.  Finally, Hibernate seems to be well designed and reliable.Some other responders have suggested just using SQL.  The real killer use case for object relational mapping is testing and development.  The databases that are built to handle large volumes of data are typically expensive and or they are difficult to install.  They are difficult to test with.  There are plenty of in-memory Java databases that can be used to test with, but are typically useless for production.  Being able to use a real, but limited database, will increase development productivity and code reliability.I made a sample WebApp in May 2012 that uses JDO 3.0 & DataNucleus 3.0 - take a look how clean it is:\nOkay maybe it's a little bit too clean, because I use the POJOs both for the database and the JSON client, but it's fun :)PS: Contains a few SuppressWarnings annotations (developed in IntelliJ 11)
Java

If something is not working properly or some plugins are loaded properly in my Eclipse. I often get suggestion to open Eclipse in clean mode. So, how to run in clean mode? and what happens if I do so?What it does:How to use it:(From: )Other eclipse command line options: For clean mode: start the platform likeThat's all. The platform will clear some cached OSGi bundle information, it helps or is recommended if you install new plugins manually or remove unused plugins.It will not affect any workspace related data.You can start Eclipse in clean mode from the command line:Using the  option is the way to go, as mentioned by the other answers.Make sure that you remove it from your  or shortcut after you've fixed the problem.  It causes Eclipse to reevaluate all of the plugins everytime it starts and can dramatically increase startup time, depending on how many Eclipse plugins you have installed.it will take much time then normal start and it will fresh up all resources.For cleaning up in a launch configuration, see this tip:For Windows users:\nYou can do as RTA said or through command line do this:\nNavigate to the locaiton of the eclipse executable then run:First check the name of your executable using the command 'dir' on its pathEasier option is to\nuse For Mac OS X Yosemite I was able to use the open command.This worked for me:
Java

What does AtomicBoolean do that a volatile boolean cannot achieve?They are just totally different. Consider this example of a  integer:If two threads call the function concurrently,  might be 5 afterwards, since the compiled code will be somewhat similar to this (except you cannot synchronize on ):If a variable is volatile, every atomic access to it is synchronized, but it is not always obvious what actually qualifies as an atomic access. With an  object, it is guaranteed that every method is \"atomic\". Thus, if you use an  and , you can be sure that the result will be . In the same way, if two threads both negate a  variable concurrently, with an  you can be sure it has the original value afterwards, with a , you can't. So whenever you have  modifying a field, you need to make it atomic or use explicit synchronization.The purpose of  is a different one. Consider this exampleIf you have a thread running  and another thread calling , you might run into an infinite loop if you omit , since the first thread might cache the value of stop. Here, the  serves as a hint to the compiler to be a bit more careful with optimizations.I use volatile fields when said field is ONLY UPDATED by its owner thread and the value is only read by other threads, you can think of it as a publish/subscribe scenario where there are many observers but only one publisher. However if those observers must perform some logic based on the value of the field and then push back a new value then I go with Atomic* vars or locks or synchronized blocks, whatever suits me best. In many concurrent scenarios it boils down to get the value, compare it with another one and update if necessary, hence the compareAndSet and getAndSet methods present in the Atomic* classes. Check the JavaDocs of the  package for a list of Atomic classes and an excellent explanation of how they work (just learned that they are lock-free, so they have an advantage over locks or synchronized blocks)You can't do ,  as atomic operation with volatile boolean (unless of course you synchronize it). has methods that perform their compound operations atomically and without having to use a  block. On the other hand,  can only perform compound operations if done so within a  block.The memory effects of reading/writing to  are identical to the  and  methods of  respectively.For example the  method will atomically perform the following (without a  block):Hence, the  method will let you write code that is guaranteed to execute only once, even when called from multiple threads. For example:Is guaranteed to only notify the listener once (assuming no other thread sets the  back to  again after it being set to ). keyword guarantees happens-before relationship among threads sharing that variable. It doesn't guarantee you that 2 or more threads won't interrupt each other while accessing that boolean variable.If there are multiple threads accessing class level variable then\neach thread can keep copy of that variable in its threadlocal cache.Making the variable volatile will prevent threads from keeping the copy of variable in threadlocal cache.Atomic variables are different and they allow atomic modification of their values.Boolean primitive type is atomic for write and read operations, volatile guarantees the happens-before principle. So if you need a simple get() and set() then you don't need the AtomicBoolean.On the other hand if you need to implement some check before setting the value of a variable, e.g. \"if true then set to false\", then you need to do this operation atomically as well, in this case use compareAndSet and other methods provided by AtomicBoolean, since if you try to implement this logic with volatile boolean you'll need some synchronization to be sure that the value has not changed between get and set.Remember the IDIOM -READ - MODIFY- WRITE this you can't achieve with volatile (usually you do this to define a  variable checked in the thread's main loop).However, if you have multiple threads modifying the boolean, you should use an . Else, the following code is not safe:This operation is done in two steps:If an other thread modify the value between  and , you might got a wrong result.  methods avoid this problem by doing steps  and  atomically.The Atomic* classes wrap a volatile primitive of the same type. From the source:So if all you are doing is getting and setting a Atomic* then you might as well just have a volatile field instead.What the Atomic* classes give you however, are methods that provide more advanced functionality such as , , and others that implement multiple operations (get/increment/set, test/set) without locking. That's why the Atomic* classes are so powerful.For example, the following code will work in a multi-threaded environment safely:However, if multiple threads are using the following, there will be race conditions because  is actually: get, increment, and set.It's also important to note that wrapping your volatile field using Atomic* class is a good way to encapsulate the critical shared resource from an object standpoint. This means that developers can't just deal with the field assuming it is not shared possibly injecting problems with a field++; or other code that introducing race conditions.
Java

lets assume this URL...(Here id needs to be sent in a POST request)I want to send the  to the server's , which accepts it in a POST method.How can i do this from within Java?I tried this :But I still can't figure out how to send it via POSTSince some of the classes, in the original answer, are deprecated in the newer version of Apache HTTP Components, I'm posting this update.By the way, you can access the full documentation for more examples .I recommend to use Apache HttpClient. its faster and easier to implement.for more information check this url: Sending a POST request is easy in vanilla Java. Starting with a , we need t convert it to a  using . After that, we need to cast it to a , so we can access its  method to set our method. We finally say that we are going to send data over the connection.We then need to state what we are going to send:A normal POST coming from a http form has a  format. We need to convert our input to this format:We can then attach our form contents to the http request with proper headers and send it.We can also send json using java, this is also easy:Remember that different servers accept different content-types for json, see  question.Sending files can be considered more challenging to handle as the format is more complex. We are also going to add support for sending the files as a string, since we don't want to buffer the file fully into the memory.For this, we define some helper methods:We can then use these methods to create a multipart post request as follows:The first answer was great, but I had to add try/catch to avoid Java compiler errors.\nAlso, I had troubles to figure how to read the  with Java libraries.  Here is the more complete code :A simple way using Apache HTTP Components isTake a look at the Posting code that can send form data in post requests and works even on Java 7simplest way to send parameters with the post request:You have done. now you can use .\nGet response content as string:Call  and  Actually only the latter is needed as POST then becomes the default method.
Java

In Java, static final variables are constants and the convention is that they should be in upper-case. However, I have seen that most people declare loggers in lower-case which comes up as a violation in . e.g:Just search or  for \"static final logger\" and you will see this for yourself.Should we be using LOGGER instead? The logger reference is not a constant, but a final reference, and should NOT be in uppercase. A constant VALUE should be in uppercase.To add more value to crunchdog's answer, The  states this in paragraph 3.3 Field NamingFollowing this convention,  is a  object reference as stated in point 2, but because it  followed by \"\" everytime you use it, it can not be considered as a constant and thus should be lower case.From effective java, 2nd ed.,In summary, constant == static final, plus if it's a reference (vs. a simple type), immutability.Looking at the slf4j logger,\nIt is immutable. On the other hand, the JUL logger is mutable. The log4j logger is also mutable. So to be correct, if you are using log4j or JUL, it should be \"logger\", and if you are using slf4j, it should be LOGGER.Note that the slf4j javadocs page linked above has an example where they user \"logger\", not \"LOGGER\".These are of course only conventions and not rules. If you happen to be using slf4j and you want to use \"logger\" because you are used to that from other frameworks, or if it is easier to type, or for readability, go ahead.I like Google's take on it ()Examples:If you are using an automated tool to check your coding standards and it violates said standards then it or the standards should be fixed. If you're using an external standard, fix the code.The convention in Sun Java is uppercase for public static constants. Obviously a logger is not constant, but represents a mutable thing ( otherwise there would be no point calling methods on it in the hope that something will happen ); there's no specific standard for non-constant final fields.If you google this, you might find that in some cases, the loggers are not defined as static final. Add some quick copy-n-paste to this, and this might explain it. in all our code, and this corresponds to our naming convention (and our CheckStyle is happy with it).We even go further, taking advantage of the strict naming convention in Eclipse.\nWe create a new class with a code template of :The logger is commented out, as initially we don't need it. But should we need it later, we just uncomment it.Then in the code, we use code templates that expect this logger to be present.\nExample with the try-catch template:We have a few more templates that use it. The .I personally think it looks really big in upper-case. Moreover, since it's a class that it's not directly related to the class behaviour, I don't see a major problem in using  instead of . But if you are going to be strictly pedantic, then use .Don't forget that PMD will respect a comment with in it. This will cause PMD to skip the line from its checks, this will allow you to choose whichever style you want. Usually constants are in uppercase.Loggers, however, should not be static but looked up for every \"new\" of the containing class if using the slf4j facade.  This avoids some nasty classloader issues in notably web containers, plus it allows the logger framework to do special stuff depending on the invocation context.Not necessarily. Read this - If your coding standards - if you have any - say that it should be uppercase then yes.I don't see any stringent reason for one way or the other. I think it totally depends on your personal likes resp. your company coding standards.BTW: I prefer \"LOGGER\" ;-)
Java

With Java:I have a  that represents a file.How do I write this to a file (ie. )I know it's done with InputStream, but I can't seem to work it out.Use Or, if you insist on making work for yourself...Without any libraries:With :With :All of these strategies require that you catch an IOException at some point too. Another solution using :From  onward you can use the  statement to avoid leaking resources and make your code easier to read. More on that .To write your  to a file you would do:Also since Java 7, one line with java.nio.file.Files:Where data is your byte[] and filePath is a String.  You can also add multiple file open options with the StandardOpenOptions class.  Add throws or surround with try/catch.Try an  or more specifically Actually, you'd be  to a ...Basic example:This is a program where we are reading and printing array of bytes offset and length using String Builder and Writing the array of bytes offset length to the new file.`O/P in console : fghij                  O/P in new file :cdefg//////////////////////////  1] File to Byte [] //////////////////////////////////////////   2] Byte [] to File ///////////////////////////
Java

I am new to Maven. I am trying to package my project. But, it automatically runs the tests. The tests insert some content in the database. This is not what I want, I need to avoid running tests while package the application. Anybody knows how run the package with out test?Run maven with Just provide the command mentioned below which will ignore executing the test cases,you can add this plugin configuration to your pom if you do not want to set command line arg:Note that -Dmaven.test.skip prevents Maven building the test-jar artifact. If you'd like to skip tests but create artifacts as per a normal build use:You can pass the  flag as a JVM argument, to skip running tests when the package phase (and the previous ones in the default lifecycle) is run:You can also pass the  flag alone to the mvn executable. If you want to include this information in your POM, you can create a new profile where you can configure the  to .If you are trying this in Windows Powershell, you will get this error:The reason for this is, in Powershell the \"\" has special meaning and it is causing problem with maven.The solution is to prepend it with a backtick (`), like so..Reference: You only have to provide No longer need the '=true' there.is also a way to add in pom fileTests should always[1] run before package. If you need to turn off the tests, you're doing something wrong. In other words, you're trying to solve the wrong problem. Figure out what your problem really is, and ask that question. It sounds like it's database-related.[1] You might skip tests when you need to quickly generate an artifact for local, development use, but in general, creating an artifact should always follow a successful test run.Answering an old and accepted question here. You can add this in your pom.xml if you want to avoid passing command line argument all the time:You are, obviously, doing it the wrong way. Testing is an important part of pre-packaging. You shouldn't ignore or skip it, but rather do it the right way. Try changing the database to which it inserts the data(like test_db). It may take a while to set it up. And to make sure this database can be used forever, you should delete all the data by the end of tests. JUnit4 has annotations which make it easy for you. Use @Before, @After @Test annotations for the right methods. You need to spend sometime on it, but it will be worth it! worked for me since the  did not work anymore.
Java

In  I used to do to initialize all my array elements to 0.Is there a similar shortcut in Java?\nI want to avoid using the loop, is it possible?A default value of 0 for arrays of integral types is guaranteed by the :If you want to initialize an array to a different value, you can use  (which will of course use a loop internally).While the other answers are correct (int array values are by default initialized to 0), if you wanted to explicitly do so (say for example if you wanted an array filled with the value 42), you can use the fill() method of the  class:Or if you're a fan of 1-liners, you can use the  routine:Would give arr the value:(though it's , and not , if you need the primitive type you could defer to the  routine:In java all elements are initialised to 0 by default. You can save the loop.How it Reduces the Performance of your application....? Read Following.In Java Language Specification the  for any Object can be given as Follows.For type , the  is , that is, the value of (byte) is .For type , the  is , that is, the value of (short) is .For type , the  is , that is, .For type , the  is , that is, .For type , the  is , that is, .For type , the  is , that is, .For type , the  is the  character, that is, ''.For type , the  is .For , the  is .By Considering all this you don't need to initialize with zero values for the array elements because by default all array elements are 0 for int array.Because An  is a container object that holds a fixed number of values of a single type. \nNow the Type of array for you is  so consider the default value for all array elements will be  Because it is .Now  the  for  so that all array elements has  is .you can assign null value by using loop as you suggest in your Question.The more use of machine cycle  More time to Process the data . so that your application data processing can be considered as a low level(Slow up-to some Level).You can save the loop, initialization is already made to 0. Even for a local variable.But please correct the place where you place the brackets, for readability (recognized best-practice):If you are using Float or Integer then you can assign default value like this ...Yes, int values in an array are initialized to zero. But you are not guaranteed this. Oracle documentation states that this is a bad coding practice.You can create a new empty array with your existing array size, and you can assign back them to your array. This may faster than other.\nSnipet: Result :declare the array as instance variable in the class i.e. out of every method and JVM will give it 0 as default value. You need not to worry anymore  result \n    0123456\n    -1012345\n    -2-101234\n    -3-2-10123\n    -4-3-2-1012\n    -5-4-3-2-101\n    -6-5-4-3-2-10
Java

What is the easy way to concatenate two byte arrays?Say,How do I concatenate two byte arrays and store it in another byte array?Most straightforward:The most elegant way to do this is with a ByteArrayOutputStream.Here's a nice solution using 's :The great thing about this method is that its signature is -which means that you can concatenate an arbitrary number of arrays in a single method call.Another possibility is using .Something likeNote that the array must be appropriately sized to start with, so the allocation line is required (as  simply returns the backing array, without taking the offset, position or limit into account).Another way is to use a utility function (you could make this a static method of a generic utility class if you like):Invoke like so:It will also work for concatenating 3, 4, 5 arrays, etc.Doing it this way gives you the advantage of fast arraycopy code which is also very easy to read and maintain.If you prefer  like @kalefranz, there is always the posibility to concatenate two  (or even more) in one line, like this:You can use third party libraries for Clean Code like Apache Commons Lang and use it like:Two  calls are lean and mean, but not easy on the eyes (harder to understand as a code reviewer, that is).A more readable approach using :For two or multiple arrays, this simple and clean utility method can be used:If you are merging two byte arrays which contain PDF, this logic will not work. We need to use a third-party tool like PDFbox from Apache:This is my way to do it!
Java

Imagine that I have this class:Now, I have another class that uses the above class:So this is the problem: I have accessed a private field of a class from outside!\nHow can I prevent this? I mean how can I make this array immutable? Does this mean that with every getter method you can work your way up to access the private field? (I don't want any libraries such as Guava. I just need to know the right way to do this).You must return a  of your array.If you can use a List instead of an array, :Modifier  protects only field itself from being accessed from other classes, but not the object references by this field.  If you need to protect referenced object, just do not give it out.  Changeto:or toThe  has already been mentioned - the  strangely not! My solution would also be to use the list from the outside and wrap the array as follows:The problem with copying the array is: if you're doing it every time you access the code and the array is big, you'll create a lot of work for the garbage collector for sure. So the copy is a simple but really bad approach - I'd say \"cheap\", but memory-expensive! Especially when you're having more than just 2 elements.If you look at the source code of  and  there is actually not much created. The first just wraps the array without copying it, the second just wraps the list, making changes to it unavailable.You can also use  which should be better than the standard . The class is part of  libraries that was create by Google.Here is the description:Here is a simple example of how to use it:at this point of view you should use system array copy:You could return a copy of the data. The caller who chooses to change the data will only be changing the copyThe nub of the problem is that you are returning a pointer to a mutable object. Oops.  Either you render the object immutable (the unmodifiable list solution) or you return a copy of the object.  As a general matter, finality of objects does not protect objects from being changed if they are mutable.  These two problems are \"kissing cousins.\"Returning an unmodifiable list is a good idea. But a list that is made unmodifiable during the call to the getter method can still be changed by the class, or classes that are derived from the class.Instead you should make it clear to anybody that extends the class that the list should not be modified.So in your example it could lead to the following code:In the above example I've made the  field public, in principle you could do away with the method call, as the values are already known.You could also assign the strings to a  field made unmodifiable during construction of the class instance. Using a constant or instantiation arguments (of the constructor) depends on the design of the class.Yes, you should return a a copy of the array:
Java

What's a \"static factory\" method?We avoid providing direct access to database connections because they're resource intensive. So we use a static factory method  that creates a connection if we're below the limit.  Otherwise, it tries to provide a \"spare\" connection, failing with an exception if there are none.The  is a way to encapsulate object creation.  Without a factory method, you would simply call the class's  directly: .  With this pattern, you would instead call the factory method:  .  The constructors are marked private, so they cannot be called except from inside the class, and the factory method is marked as  so that it can be called without first having an object.There are a few advantages to this pattern.  One is that the factory can choose from many subclasses (or implementers of an interface) and return that.  This way the caller can specify the behavior desired via parameters, without having to know or understand a potentially complex class hierarchy.Another advantage is, as Matthew and James have pointed out, controlling access to a limited resource such as connections.  This a way to implement  - instead of building, using, and tearing down an object, if the construction and destruction are expensive processes it might make more sense to build them once and recycle them.  The factory method can return an existing, unused instantiated object if it has one, or construct one if the object count is below some lower threshold, or throw an exception or return  if it's above the upper threshold.As per the article on Wikipedia, multiple factory methods also allow different interpretations of similar argument types.  Normally the constructor has the same name as the class, which means that you can only have one constructor with a given .  Factories are not so constrained, which means you can have two different methods that accept the same argument types: and This can also be used to improve readability, as Rasmus notes.NOTE! \"The  is  the same as the  pattern\" (c) Effective Java, Joshua Bloch.Factory Method: \"Define an interface for creating an object, but let the classes which implement the interface decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses\" (c) GoF.\"Static factory method is simply a static method that returns an instance of a class.\" (c) Effective Java, Joshua Bloch. Usually this method is inside a particular class.The defference:The key idea of static factory method is to gain control over object creation and delegate it from constructor to static method. The decision of object to be created is like in Abstract Factory made ouside the method (in common case, but not allways). While the key (!) idea of Factory Method is to delegate decision of what instance of class to create inside Factory Method. E.g. classic Singleton implementation is a special case of static factory method.  Example of commonly used static factory methods:Readability can be improved by static factory methods:ComparetofromIt all boils down to maintainability.  The best way to put this is whenever you use the  keyword to create an object, you're coupling the code that you're writing to an implementation.The factory pattern lets you separate how you create an object from what you do with the object.  When you create all of your objects using constructors, you are essentially hard-wiring the code that uses the object to that implementation.  The code that uses your object is \"dependent on\" that object.  This may not seem like a big deal on the surface, but when the object changes (think of changing the signature of the constructor, or subclassing the object) you have to go back and rewire things everywhere.Today factories have largely been brushed aside in favor of using Dependency Injection because they require a lot of boiler-plate code that turns out to be a little hard to maintain itself.  Dependency Injection is basically equivalent to factories but allows you to specify how your objects get wired together declaratively (through configuration or annotations).If the constructor of a class is private then you cannot create an object for class from outside of it. We cannot create an object for above class from outside of it. So you cannot access x, y from outside of the class. Then what is the use of this class? \nHere is solution :  method.\nInclude the below method in the above class  So now you can create an object for this class from outside of it. Like the way...A static method which returns the object of the class by executing its private constructor  is called  method.I thought i will add some light to this post on what i know. We used this technique extensively in our . Instead of  you can also use  to instantiate a class. Code listing:: Each time you invoke a constructor an object will get created but you might not want that. suppose you want to check some condition only then you want to create a new object.You would not be creating a new instance of Vinoth each time, unless your condition is satisfied. Another example taken from .This method translates a boolean primitive value into a Boolean object reference. The  method illustrates us, it never creates an object. The ability of  to return the same object from repeated  allows classes to maintain strict control over what instances exist at any time. is that, unlike , they can return an  of any  of their return type. One application of this flexibility is that an API can return objects without making their classes public. Hiding implementation classes in this fashion leads to a very compact API.Calendar.getInstance() is a great example for the above, It creates depending on the locale a ,  or by default one .Another example which i could think is , where you make your constructors private create an own  method where you make sure, that there is always just one instance available. A factory method a method that abstracts away the instantiation of an object.  Generally factories are useful when you know that you need a new instance of a class that implements some interface but you don't know the implementing class.This is useful when working with hierarchies of related classes, a good example of this would be a GUI toolkit.  You could simply hard-code calls to the constructors for concrete implementations of each widget but if you ever wanted to swap one toolkit for another you'd have a lot of places to change.  By using a factory you reduce the amount of code you would need to change.One of the advantages that stems from Static factory is that that API can return objects without making their classes public. This lead to very compact API. In java this is achieved by Collections class which hides around 32 classes which makes it collection API very compact.A static factory method is good when you want to ensure that only one single instance is going to return the concrete class to be used.For example, in a database connection class, you may want to have only one class create the database connection, so that if you decide to switch from Mysql to Oracle you can just change the logic in one class, and the rest of the application will use the new connection.If you want to implement database pooling, then that would also be done without affecting the rest of the application.It protects the rest of the application from changes that you may make to the factory, which is the purpose.The reason for it to be static is if you want to keep track of some limited resource (number of socket connections or file handles) then this class can keep track of how many have been passed out and returned, so you don't exhaust the limited resource.A member declared with the keyword 'static'.Methods that create and return new objects.The programming language is relevant to the meaning of 'static' but not to the definition of 'factory'.Java implementation contains utilities classes  and  both of them contains , examples of it and how to use :Also  class have such :
Java

There is an issue with the Android appcompat v7 library on Samsung devices running Android 4.2. I keep getting crashes with the following stack trace in my Developer Console:This is line 215 of CustomActivity.java:The crashes come from an array of devices, but always Samsung, and always Android 4.2.A quick web search leads me to believe that many people have the same issue, some of the steps I have tried to solve the issue are:Despite these steps, and despite it working on all other devices and Android versions the crash reports still come through.EDIT:The solution that worked for me was (Using Proguard) to replace this:with this:Credit goes to the .Old answer (Temporary Workaround):\nIt happens in a project where I use an  ActionBar. My solution was to check for those conditions and change the app flow:Then in the activity's onCreate method:As pointed out this is not a definitive solution, it is just a way to allow users to have access to limited functionality while a more permanent solution is found. As  saidThe better solution is add the following lines instead:On which device you are facing this problem ? (Samsung/HTC etc.)If it is Samsung,Various Samsung phones are included older versions of the android support library in the framework or classpath. If you use the new material support library, you'll see this crash on those Samsung devices:To fix this, you must rename that class. Easiest way to do that is by running proguard. If you don't want to obfuscate, here's a 1 liner to rename just the offending classes:There's an issue tracking this problem, but since it's really a Samsung bug, it's never going to get fixed on their end. Only way to fix it on the Google/AOSP side is to rename these internal classes.This issue returned in  where the  package was removed from the library jar. As suggested in the comments above (credits to the people who suggested it there), now also the proguard configuration has to change.To get the answer suggested above working again, try adding these lines to your proguard files:In stead of the old fix:According to the last posts of the bug-report, this should be fixed on the new version of the support library (24.0.0) :\nSomeone  it fixed it.This version is available , so you should update to it.Yes. Samsung already knows about  problem.\nI can suggest you try to using same implementation of Popup from . It is not best way, but will be works.I was having the same problem of this MenuBuilder class not found in USB debugging mode. I solved this problem by simply setting the  to  in both release and debug  block of  . like this:I set the  to true in  type to prevent app from crashing via USB debugging to a live handset.I enabled proguard with the default proguard properties provided with an eclipse project and the problem was fixed for me. Based on some comments here  , some people might have to repackage using:\n-repackageclasses \"android.support.v7\"I got the same error when trying to run a 'Hello World' app on my Samsung Galaxy Tab 3 tablet via Android Studio. The app would appear to launch and then it would crash instantly and that error would show in the console in Android Studio. I did a system update on the tablet and now I am able to run the 'Hello World' app and I'm not getting the error anymore. I hope this helps someone to resolve their issue. Note: The system update I performed on the tablet did not update the Android OS version, because it still says that the version is 4.2.2.Change the Compile Sdk Version of your project to  The default is set to STEPS
Java

Seeing various locking related question and (almost) always finding the 'loop because of spurious wakeups' terms I wonder, has anyone experienced such kind of a wakeup (assuming a decent hardware/software environment for example)?I know the term 'spurious' means no apparent reason but what can be the reasons for such kind of an event?( Note: I'm not questioning the looping practice.) A helper question (for those who like code samples):If I have the following program, and I run it:What can I do to wake this  up spuriously without waiting forever for a random event?The Wikipedia  has this tidbit:: If a Linux process is signaled its waiting threads will each enjoy a nice, hot .I buy it. That's an easier pill to swallow than the typically vague \"it's for performance\" reason often given.I have a production system that exhibits this behaviour.\nA thread waits on a signal that there is a message in the queue.\nIn busy periods, up to 20% of the wakeups are spurious (ie when it wakes there is nothing in the queue).\nThis thread is the only consumer of the messages.\nIt runs on a Linux SLES-10 8-processor box and is built with GCC 4.1.2.\nThe messages come from an external source and are processed asynchronously because there are problems if my system does not read them fast enough. wrote a  a while back about being hit by the spurious wakeup problem. So yes, it happensI'm guessing it's in the spec (as a possibility) because of limitations of some of the platforms which Java gets deployed on? although I may be wrong!To answer the question in the titile -  it does happen.Though the  mentions a good deal about spurious wakeups a nice explanation for the same that I came across is as follows - I was reading this answer from  and found it reasonable enough. Also read. Just to add this. Yes it happens and I spent three days searching for the cause of a multi-threading problem on a 24 core machine (JDK 6). 4 of 10 executions experienced that without any pattern. This never happened on 2 core or 8 cores.Studied some online material and this is not a Java problem but a general rare but expected behavior.
Java

Consider these two methods:Both report an \"unchecked cast\" warning - I get why. The thing that baffles me is why can I calland it compiles? The compiler should know that  does not implement . The call togives an error (as expected)Can someone explain why would this behaviour be considered valid? How would it be useful?The client does not know that this call is unsafe - the client's code compiles without warning. Why wouldn't the compile warn about that / issue an error?Also, how is it different from this example:Trying to pass  gives an error, as expected:If that is reported as an error, why  isn't? is an . Therefore even if  does not implement  it would be perfectly possible to create a classTherefore you can writebecause the inferred type  is the intersection type .This is a bit odd in the case of  because  is final, but  doesn't play any role in these rules. For example you can writeOn the other hand,  is not an , so it would be impossible to extend  to get a subtype of , because java does not support multiple-inheritance for classes.With the  example, you need to remember that generics are neither covariant nor contravariant. This means that if  is a subtype of ,  is neither a subtype nor a supertype of . Since  does not implement , you cannot use  in your  method.You can, however get this to compileIf you have a method that  a  like this:you can doAgain, this is because the inferred type is  and this is a subtype of .Intersection types occur implicitly when you specify multiple bounds (e.g. ).For further information,  is the part of the JLS where it explains how type bounds work. You can include multiple interfaces, e.g.but only the first bound may be a non-interface.The type that is inferred by your compiler prior to the assignment for  is . This type  weird, because  is final, but it's a perfectly valid type in Java. It is then cast to , which is perfectly OK.There is exactly one possible value for the  type: . With the following implementation:The following assignment will work:Because of this possible value, there's no reason why the assignment should be wrong, even if it is obviously useless. A warning would be useful.In fact, I've recently blogged about this . You should (almost) never design a generic method to return arbitrary types because you can (almost) never guarantee that the inferred type will be delivered. An exception are methods like , in case of which the emptiness of the list (and generic type erasure) is the reason why any inference for  will work:
Java

As per my understanding I think:Am I correct?Now if am correct, I have the following question:\nThe  internally uses the hashcode of the object. So if two objects can have the same hashcode, then how can the  track which key it uses?Can someone explain how the  internally uses the hashcode of the object?A hashmap works like this (this is a little bit simplified, but it illustrates the basic mechanism):It has a number of \"buckets\" which it uses to store key-value pairs in. Each bucket has a unique number - that's what identifies the bucket. When you put a key-value pair into the map, the hashmap will look at the hash code of the key, and store the pair in the bucket of which the identifier is the hash code of the key. For example: The hash code of the key is 235 -> the pair is stored in bucket number 235. (Note that one bucket can store more then one key-value pair).When you lookup a value in the hashmap, by giving it a key, it will first look at the hash code of the key that you gave. The hashmap will then look into the corresponding bucket, and then it will compare the key that you gave with the keys of all pairs in the bucket, by comparing them with .Now you can see how this is very efficient for looking up key-value pairs in a map: by the hash code of the key the hashmap immediately knows in which bucket to look, so that it only has to test against what's in that bucket.Looking at the above mechanism, you can also see what requirements are necessary on the  and  methods of keys:Your third assertion is incorrect.It's perfectly legal for two unequal objects to have the same hash code. It's used by  as a \"first pass filter\" so that the map can quickly find  entries with the specified key. The keys with the same hash code are then tested for equality with the specified key.You wouldn't want a requirement that two unequal objects couldn't have the same hash code, as otherwise that would limit you to 2 possible objects. (It would also mean that different types couldn't even use an object's fields to generate hash codes, as other classes could generate the same hash.) is an array of  objects.Consider  as just an array of objects.Have a look at what this  is:Each  object represents a key-value pair. The field  refers to another  object if a bucket has more than one .Sometimes it might happen that hash codes for 2 different objects are the same. In this case, two objects will be saved in one bucket and will be presented as a linked list. \nThe entry point is the more recently added object. This object refers to another object with the  field and so on. The last entry refers to .When you create a  with the default constructorThe array is created with size 16 and default 0.75 load balance.If the bucket already has at least one element, a new one gets added and placed in the first position of the bucket. Its  field refers to the old element.You can find excellent information at To Summarize:  HashMap stores both key and value object as Map.Entry. Hashmap applies hashcode(key) to get the bucket. if there is collision ,HashMap uses LinkedList to store object.  HashMap uses Key Object's hashcode to find out bucket location and then call keys.equals() method to identify correct node in LinkedList and return associated value object for that key in Java HashMap.Here is a rough description of  mechanism, for  version, .capacity, means hashtable's bucket count, it could be get from , also could be calculated via  and , thus no need to be defined as a class field.: Get effective capacity.The hashcode determines which bucket for the hashmap to check.  If there is more than one object in the bucket then a linear search is done to find which item in the bucket equals the desired item (using the ) method.In other words, if you have a perfect hashcode then hashmap access is constant, you will never have to iterate through a bucket (technically you would also have to have MAX_INT buckets, the Java implementation may share a few hash codes in the same bucket to cut down on space requirements).  If you have the worst hashcode (always returns the same number) then your hashmap access becomes linear since you have to search through every item in the map (they're all in the same bucket) to get what you want.Most of the time a well written hashcode isn't perfect but is unique enough to give you more or less constant access.You're mistaken on point three.  Two entries can have the same hash code but not be equal.  Take a look at the implementation of .  You can see that it checks that the hashes are equal and the keys are equal.  Were point three true, then it would be unnecessary to check that the keys are equal.  The hash code is compared before the key because the former is a more efficient comparison.  If you're interested in learning a little more about this, take a look at the Wikipedia article on , which I believe is the mechanism that the OpenJdk implementation uses.  That mechanism is subtly different than the \"bucket\" approach one of the other answers mentions.  This is a Most Confusing Question for many of us in Interviews.But its not that complex.We knowTHIS IMAGE WILL HELP YOU UNDERSTAND: So here we see that if both the objects S1 and S2 have different content, then we are pretty sure that our overridden Hashcode method will generate different Hashcode(116232,11601) for both objects. NOW since there are different hash codes, so it won't even bother to call EQUALS method. Because a different Hashcode GUARANTEES DIFFERENT content in an object.Hash map works on the principle of hashing HashMap get(Key k) method calls hashCode method on the key object and applies returned hashValue to its own static hash function to find a bucket location(backing array) where keys and values are stored in form of a nested class called Entry (Map.Entry) . So you have concluded that from the previous line that Both key and value is stored in the bucket as a form of  Entry object . So thinking that Only value is stored  in the bucket is not correct and will not give a good impression on the interviewer .If key is null , then Null keys always map to hash 0, thus index 0.If key is not null then , it will call hashfunction on the key object , see line 4 in above method i.e. key.hashCode()  ,so after key.hashCode() returns hashValue , line 4 looks likeand now ,it applies returned hashValue into its own hashing function .We might wonder why we are calculating the hashvalue again using hash(hashValue). Answer is It defends against poor quality hash functions.Now final  hashvalue is used to find the bucket location at which the Entry object is stored . Entry object stores in the bucket like this (hash,key,value,bucketindex) I will not get into the details of how HashMap works, but will give an example so we can remember how HashMap works by relating it to reality.We have Key, Value ,HashCode and bucket.For sometime, we will relate each of them with the following:Using Map.get(key) :Stevie wants to get to his friend's(Josse) house who lives in a villa in a VIP society, let it be JavaLovers Society. \nJosse's address is his SSN(which is different for everyone).\nThere's an index maintained in which we find out the Society's name based on SSN.\nThis index can be considered to be an algorithm to find out the HashCode.Using Map.put(key,Value)This finds a suitable society for this Value by finding the HashCode and then the value is stored.I hope this helps and this is open for modifications.HashMap works on the principle of hashing, we have put() and get() method for storing and retrieving object from HashMap. When we pass both key and value to put() method to store on HashMap, it uses key object hashcode() method to calculate hashcode and they by applying hashing on that hashcode, it identifies bucket location for storing value object. While retrieving, it uses key object equals method to find out correct key value pair and return value object associated with that key. HashMap  uses linked list in case of collision and object will be stored in next node of linked list.\nAlso HashMap stores both key+value tuple in every node of linked list.As it is said, a picture is worth 1000 words. I say: some code is better than 1000 words. Here's the source code of HashMap. Get method:So it becomes clear that hash is used to find the \"bucket\" and the first element is always checked in that bucket. If not, then  of the key is used to find the actual element in the linked list.Let's see the  method:It's slightly more complicated, but it becomes clear that the new element is put in the tab at the position calculated based on hash: here  is the index where the new element will be put (or it is the \"bucket\").  is the size of the  array (array of \"buckets\").First, it is tried to be put as the first element of in that \"bucket\". If there is already an element, then append a new node to the list.It gonna be a long answer , grab a drink and read on \u2026Hashing is all about storing a key-value pair in memory that can be read and written faster. Lets Say I want to store 4 key value pairs -So to store the keys we need an array of 4 element . Now how do I map one of these 4 keys to 4 array indexes (0,1,2,3)? So java finds the hashCode of individual keys and map them to a particular array index . \nHashcode Formulae is - Hash and girl !! I know what you are thinking. Your fascination about that wild duet might made you miss an important thing .  answer is ,   . So  is mapped to  in our case . which is second element of the array . and the value \u201cahhan\u201d  is stored in a LinkedList associated with array index 1 . -  If you try to find  of the keys  and   using the formulae described above you\u2019ll see both giving us same . Whooaa !! lesson learnt -Now the hash map looks like \u2013Now if some body tries to find the value for the key  , java quickly will find the hashCode of it , module it and start searching for it\u2019s value in the LinkedList corresponding  . So this way we need not search all the 4 array indexes thus making data access faster.But , wait , one sec .   there are 3 values in that linkedList corresponding Array index 1, how it finds out which one was was the value for key \u201chorsemints\u201d ? It stores both key value pair as map entry. So actually Map looks like this . Now you can see While traversing through the linkedList corresponding to ArrayIndex1 it actually compares key of each entry to of that LinkedList to \u201chorsemints\u201d and when it finds one it just returns the value of it .Hope you had fun while reading it :)
Java

May I know what is the difference between:-Are these technologies/framework complementary to each other? Or they are alternatives to each other (after I use one of them, then I don't need to use the other)?Thanks.So, to summarize:I don't want to make things more confusing but note that Java EE 6 provides modern, standardized and very nice equivalent of the above frameworks: JSF 2.0 and Facelets for the presentation, JPA 2.0 for the persistence, Dependency Injection, etc. For a new development, this is IMO a  option, Java EE 6 is a  stack.Generally...Hibernate is used for handling database operation. There are rich set of database utility functionality, which reduce your number of lines of code. Especially you have to read @Annotation of hibernate. It is ORM framework, persistance layer.Spring provides rich set of Injectioin based working mechanism. Currently Spring become so much famous. You have to also read about Spring AOP. There is bridge between Struts and Hibernate. Mainly Spring provides this kind of utility.Struts2 provides action based programming. There are rich set of Struts tags. You can use it. Struts proves action based programming so you have to maintain all the relavant control of your view.In Addition Tapestry is different framework of JAva. In which you have to handle only .tml (template file). YOu have to create main 2 files for any class. One is JAVA class and another one is its template. Both name's are same. Tapestry automatically called related classes.You can see the overview and ranking for yourself . Hibernate is an ORM, so you can use either struts+Hiberante or spring+hibernate to build a web app. Different web frameworks and many are alternatives to each other.Spring is an application framework which deals with IOC(Inversion of Container).Struts 2 is a web application MVC framework which deals with actions.Hibernate is an ORM(Object Relation Mapping) that deals with persistent data. In hibernate you need not bother about how to create table in SQL and you need not to remember connection ,prepared statement like that data is persisted in a database. So, basically it makes a developer's life easy.  pages and components are simple  consisting of getters and setters for easy access to Java language features.
Java

Hibernate has a handful of methods that, one way or another, takes your object and puts it into the database. What are the differences between them, when to use which, and why isn't there just one intelligent method that knows when to use what?The methods that I have identified thus far are:Here's my understanding of the methods.  Mainly these are based on the  though as I don't use all of these in practice.\nCalls either save or update depending on some checks.  E.g. if no identifier exists, save is called.  Otherwise update is called.\nPersists an entity.  Will assign an identifier if one doesn't exist.  If one does, it's essentially doing an update.  Returns the generated ID of the entity.\nAttempts to persist the entity using an existing identifier.  If no identifier exists, I believe an exception is thrown.\nThis is deprecated and should no longer be used.  Instead there is...\nNow this is where my knowledge starts to falter.  The important thing here is the difference between transient, detached and persistent entities.  For more info on the object states, .  With save & update, you are dealing with persistent objects.  They are linked to a Session so Hibernate knows what has changed.  But when you have a transient object, there is no session involved.  In these cases you need to use merge for updates and persist for saving.\nAs mentioned above, this is used on transient objects.  It does not return the generated ID.This link explains in good manner :We all have those problems that we encounter just infrequently enough that when we see them again, we know we\u2019ve solved this, but can\u2019t remember how.The NonUniqueObjectException thrown when using Session.saveOrUpdate() in Hibernate is one of mine. I\u2019ll be adding new functionality to a complex application. All my unit tests work fine. Then in testing the UI, trying to save an object, I start getting an exception with the message \u201ca different object with the same identifier value was already associated with the session.\u201d Here\u2019s some example code from Java Persistence with Hibernate.To understand the cause of this exception, it\u2019s important to understand detached objects and what happens when you call saveOrUpdate() (or just update()) on a detached object.When we close an individual Hibernate Session, the persistent objects we are working with are detached. This means the data is still in the application\u2019s memory, but Hibernate is no longer responsible for tracking changes to the objects.If we then modify our detached object and want to update it, we have to reattach the object. During that reattachment process, Hibernate will check to see if there are any other copies of the same object. If it finds any, it has to tell us it doesn\u2019t know what the \u201creal\u201d copy is any more. Perhaps other changes were made to those other copies that we expect to be saved, but Hibernate doesn\u2019t know about them, because it wasn\u2019t managing them at the time.Rather than save possibly bad data, Hibernate tells us about the problem via the NonUniqueObjectException.So what are we to do? In Hibernate 3, we have merge() (in Hibernate 2, use saveOrUpdateCopy()). This method will force Hibernate to copy any changes from other detached instances onto the instance you want to save, and thus merges all the changes in memory before the save.It\u2019s important to note that merge returns a reference to the newly updated version of the instance. It isn\u2019t reattaching item to the Session. If you test for instance equality (item == item3), you\u2019ll find it returns false in this case. You will probably want to work with item3 from this point forward.It\u2019s also important to note that the Java Persistence API (JPA) doesn\u2019t have a concept of detached and reattached objects, and uses EntityManager.persist() and EntityManager.merge().I\u2019ve found in general that when using Hibernate, saveOrUpdate() is usually sufficient for my needs. I usually only need to use merge when I have objects that can have references to objects of the same type. Most recently, the cause of the exception was in the code validating that the reference wasn\u2019t recursive. I was loading the same object into my session as part of the validation, causing the error.Where have you encountered this problem? Did merge work for you or did you need another solution? Do you prefer to always use merge, or prefer to use it only as needed for specific casesActually the difference between hibernate  and  methods is depends on generator class we are using.If our generator class is assigned, then there is no difference between  and ) methods. Because generator \u2018assigned\u2019 means, as  a programmer we need to give the primary key value to save in the database right [ Hope you know this generators concept ]\nIn case of other than assigned generator class, suppose if our generator class name is Increment means hibernate it self will assign the primary key id value into the database right [ other than assigned generator, hibernate only used to take care the primary key id value remember  ], so in this case if we call  or  method then it will insert the record into the database normally\nBut hear thing is,   method can return that primary key id value which is generated by hibernate and we can see it byIn this same case,  will never give any value back to the client.Be aware that if you call an update on an detached object, there will always be an update done in the database whether you changed the object or not. If it is not what you want you should use Session.lock() with LockMode.None. You should call update only if the object was changed outside the scope of your current session (when in detached mode).None of the following answers are right.\nAll these methods just seem to be alike, but in practice do absolutely different things.\nIt is hard to give short comments. Better to give a link to full documentation about these methods:\nI found a good example showing the differences between all hibernate save methods:In brief, according to the above link:Also for practical examples of all these, please refer to the link I mentioned above, it shows examples for all these different methods.
Java

I'm trying to test some legacy code, using Mockito.I want to stub a  that is used in production as follows:I can write:But the obvious problem is that  is never called with the same  object that I stubbed the method for. (Curse that  operator!)I would love it if I could stub the method in a way that it returns  regardless of the argument. Failing that, I'll listen to other workaround suggestions, but I'd really like to avoid changing the production code until there is reasonable test coverage.or (to avoid s):Don't forget to import matchers (many others are available):Use like this:Before you need to import anyObject should fit your needs.Also, you can always consider implementing hashCode and equals for the Bazoo class. This would make your code example work the way you want.
Java

How do you make  2.0 wait for the page to load?You can also check pageloaded using following codeUse class Also see You can expect to show some element. something like in C#:If you set the implicit wait of the driver, then call the  method on an element you expect to be on the loaded page, the WebDriver will poll for that element until it finds the element or reaches the time out value.source: In general, with Selenium 2.0 the web driver should only return control to the calling code once it has determined that the page has loaded. If it does not, you can call , which cycles round calling  until it is found or times out (time out can be set).Ruby implementation:You may remove the  line. It is added for debug purposes.You can also use the class:  to explicitly wait for an element to show up on the webpage before you can take any action further actionsYou can use the  class to determine if an element is visible:See  for list of all conditions you are able to check.This seems to be a serious limitation of WebDriver. Obviously waiting for an element will not imply the page being loaded, in particular the DOM can be fully build (onready state) whereby JS is still executing and CSS and images are still loading.I believe the simplest solution is to set a JS variable upon the onload event after everything is initialized and check and wait for this JS variable in Selenium.If you want to wait for a specific element to load, you can use the  method on a  :(Example from )All of these solutions are OK for specific cases, but they suffer from at least one of a couple of possible problems:Here's my attempt at a generic solution that avoids this problem (in Python):First, a generic \"wait\" function (use a WebDriverWait if you like, I find them ugly):Next, the solution relies on the fact that selenium records an (internal) id-number for all elements on a page, including the top-level  element.  When a page refreshes or loads, it gets a new html element with a new ID.So, assuming you want to click on a link with text \"my link\" for example:For more Pythonic, reusable, generic helper, you can make a context manager:And then you can use it on pretty much any selenium interaction:I reckon that's bulletproof!  What do you think?  More info in a Imran's answer rehashed for Java 7:I'm surprised that predicates weren't the first choice as you typically know what element(s) you will next interact with on the page you're waiting to load. My approach has always been to build out predicates/functions like  and , etc. and then use and reuse these wherever I need them, be it for a page load or page content change I'm waiting on.For example,In my test class:In my test class parent:Though this seems like a lot, it takes care of checking repeatedly for you\nand the interval for how often to check can be set along with the ultimate\nwait time before timing out. Also, you will reuse such methods.In this example, the parent class defined and initiated the  and the .I hope this helps.Use implicitly wait for wait of every element on page till given time.this wait for every element on page for 30 sec.Another wait is Explicitly wait or conditional wait in this wait until given condition.In id give static element id which is diffidently display on the page, as soon as page is load.You can change from the document to an element, in the case of where only part of a document is being changed.This technique was inspired by the answer from sincebasic.You can explicitly wait for an element to show up on the webpage before you can take any action (like element.click())This is what I used for a similar scenario and it works fine.My simple way::And to you :The best way to wait for page loads when using the Java bindings for WebDriver is to use the Page Object design pattern with PageFactory. This allows you to utilize the  which to put it simply acts as a global wait for all of your elements. It has limitations on elements such as drop-boxes or complex javascript transitions but it will drastically reduce the amount of code needed and speed up test times. A good example can be found in this blogpost. Basic understanding of Core Java is assumed.You can use this snippet of code for the page to load:Or you can use waiter for any element to be loaded and become visible/clickable on that page, most probably which is going to be load at the end of loading like:In  you can get it via promises...If you write this code, you can be sure that the page is fully loaded when you get to the then...If you write this code, you will navigate, and selenium will wait 3 seconds...From Selenium documentation:this.get( url ) \u2192 ThenableSchedules a command to navigate to the given URL.Returns a promise that will be resolved when the document has .You can use the below existing method to set the time for pageeLoadTimeout \nin below example if the page is taking more than 20 seconds to load , then it will throw an exception of page reload Explicitly wait or conditional wait in this wait until given condition.  This will wait for every web element for 60 seconds.Use implicitly wait for wait of every element on page till given time.This will wait for every web element for 60 seconds.\nThe easiest way is just wait for some element which will appear on loaded page.If you would like to click on some button already after page is loaded you could use await and click: provides the following interesting approach:Sample code:use a if condition and for any of the element present You can try this code to let the page load completely until element is found.The best way I've seen is to utilize the  ExpectedCondition, to wait for the old page to become stale.Example:It'll wait for ten seconds for the old HTML tag to become stale, and then throw an exception if it doesn't happen.use following code it's very easy and simple for page load. i hope this helps you. 
Java

Please  tell with a code example why is SimpleDateFormat not threadsafe. What is the problem in this class?\n? \nPlease give a code which demonstrates this fault in class.FastDateFormat is threadsafe. Why?\nwhat is the difference b/w the SimpleDateFormat and FastDateFormat?Please explain with a code which demonstrates this issue? stores intermediate results in instance fields. So if one instance is used by two threads they can mess each other's results.Looking at the  reveals that there is a  instance field, which is used by operations on  / For example  calls  initially and then . If another thread invokes  before the completion of the first invocation, it will clear the calendar, but the other invocation will expect it to be populated with intermediate results of the calculation.One way to reuse date formats without trading thread-safety is to put them in a  - some libraries do that. That's if you need to use the same format multiple times within one thread. But in case you are using a servlet container (that has a thread pool), remember to clean the thread-local after you finish.To be honest, I don't understand why they need the instance field, but that's the way it is. You can also use   which is threadsafe. is a concrete class for formatting and parsing dates in a locale-sensitive manner.   From the ,  To make the SimpleDateFormat class thread-safe, look at the  :ThreadLocal + SimpleDateFormat =  SimpleDateFormatThreadSafe  in Java 8 is immutable and thread-safe alternative to .Release 3.2 of  will have  class that is a thread-safe substitute of  for Gregorian calendar. See  for more information.Here is a  that proves the fault in the class. I've checked: the problem occurs when using parse and also when you are only using format.Here is the example which results in a strange error. Even Google gives no results:And result :If you want to use the same date format among multiple threads, declare it as a static and synchronize on the instance variable when using it...Here\u2019s an example defines a SimpleDateFormat object as a static field. When two or more threads access \u201csomeMethod\u201d concurrently with different dates, they can mess with each other\u2019s results.You can create a service like below and use jmeter to simulate concurrent users using the same SimpleDateFormat object formatting different dates and their results will be messed up.}The code and jmeter script can be downloaded  .
Java

I was looking at the Java code for  and noticed that it made use of a static nested class, .What is the reason for using a static nested class, rather than an normal inner class?The only reason I could think of, was that Entry doesn't have access to instance variables, so from an OOP point of view it has better encapsulation. But I thought there might be other reasons, maybe performance. What might it be?Note. I hope I have got my terms correct, I would have called it a static inner class, but I think this is wrong: The Sun page you link to has some key differences between the two:There is no need for  to be  top-level class as it is  used by  (there are some other interfaces that also have static nested classes named , such as  - same concept). And since it does not need access to LinkedList's members, it makes sense for it to be static - it's a much cleaner approach.As , I think it is a better idea if you are using a nested class is to start off with it being static, and then decide if it really needs to be non-static based on your usage.To my mind, the question ought to be the other way round whenever you see an inner class - does it  need to be an inner class, with the extra complexity and the implicit (rather than explicit and clearer, IMO) reference to an instance of the containing class?Mind you, I'm biased as a C# fan - C# doesn't have the equivalent of inner classes, although it does have nested types. I can't say I've missed inner classes yet :)There are non-obvious memory retention issues to take into account here. Since a non-static inner class maintains an implicit reference to it's 'outer' class, if an instance of the inner class is strongly referenced, then the outer instance is strongly referenced too. This can lead to some head-scratching when the outer class is not garbage collected, even though  that nothing references it.Well, for one thing, non-static inner classes have an extra, hidden field that points to the instance of the outer class.  So if the Entry class weren't static, then besides having access that it doesn't need, it would carry around four pointers instead of three.As a rule, I would say, if you define a class that's basically there to act as a collection of data members, like a \"struct\" in C, consider making it static.static nested class is just like any other outer class, as it doesn't have access to outer class members.Just for packaging convenience we can club static nested classes into one outer class for readability purpose. Other than this there is no other use case of static nested class.Example for such kind of usage, you can find in Android R.java (resources) file.\nRes folder of android contains layouts (containing screen designs), drawable folder (containing images used for project), values folder (which contains string constants), etc..Sine all the folders are part of Res folder, android tool generates a R.java (resources) file which internally contains lot of static nested classes for each of their inner folders.\nHere they are using only for packaging convenience. One of the reasons for static vs. normal have to do with classloading. You cannot instantiate an inner class in the constructor of it's parent.PS: I've always understood 'nested' and 'inner' to be interchangeable. There may be subtle nuances in the terms but most Java developers would understand either.Simple example : If non-static the class cannot be instantiated exept in an instance of the upper class (so not in the example where main is a static function)From :Static inner class is used in the builder pattern. Static inner class can instantiate it's outer class which has only private constructor. So you can use static inner class to instantiate the outer class which only has private constructor.  This will output x: 1As per Oracle site below are key benefits using nested class (static or non-static) refer: Why Use Nested Classes?Compelling reasons for using nested classes include the following:It is a way of logically grouping classes that are only used in one \n    place: If a class is useful to only one other class, then it is\n    logical to embed it in that class and keep the two together. Nesting\n    such \"helper classes\" makes their package more streamlined. It increases encapsulation: Consider two top-level classes, A and B,\n    where B needs access to members of A that would otherwise be\n    declared    private. By hiding class B within class A, A's members\n    can be    declared private and B can access them. In addition, B\n    itself can be    hidden from the outside world. It can lead to more readable and    maintainable code: Nesting small classes within\n    top-level classes    places the code closer to where it    is usedNon static inner classes can result in memory leaks while static inner class will protect against them. If the outer class holds considerable data, it can lower the performance of the application.Using a static nested class rather than non-static one may save spaces in some cases. For example: implementing a  inside a class, say Student.Then the  ensures that the Student class has only one Comparator, rather than instantiate a new one every time a new student instance is created. I don't know about performance difference, but as you say, static nested class is not a part of an instance of the enclosing class. Seems just simpler to create a static nested class unless you really need it to be an inner class.It's a bit like why I always make my variables final in Java - if they're not final, I know there's something funny going on with them. If you use an inner class instead of a static nested class, there should be a good reason.Adavantage of inner class--Without existing of outer class inner class will not exist.There are four types of inner class.point --- 10.inner class inside static method then we can access only static  field of outer class.
Java

Is there a way to set my own custom test case names when using parameterized tests in JUnit4?I'd like to change the default \u2014  \u2014 to something meaningful.To use change the name of parameterized tests, you say: is a string, which can have the following special placeholders:The final name of the test will be the name of the test method, followed by the  in brackets, as shown below.For example (adapted from the unit test for the  annotation):will give names like  and .  (The  part of the name is the method name of the ).Looking at JUnit 4.5, its runner clearly doesn't support that, as that logic is buried inside a private class inside the Parameterized class. You could not use the JUnit Parameterized runner, and create your own instead which would understand the concept of names (which leads to the question of how you might set a name ...).From a JUnit perspective, it would be nice if instead of (or in addition to) just passing an increment, they would pass the comma delimited arguments. TestNG does this. If the feature is important to you, you can comment on the yahoo mailing list referenced at www.junit.org.I recently came across the same problem when using JUnit 4.3.1. I implemented a new class  which extends Parameterized called LabelledParameterized. It has been tested using JUnit 4.3.1, 4.4 and 4.5. It reconstructs the Description instance using the String representation of the first argument of each parameter array from the @Parameters method. You can see the code for this at:and an example of its use at:The test description formats nicely in Eclipse which is what I wanted since this makes failed tests a lot easier to find! I will probably further refine and document the classes over the next few days/weeks. Drop the '?' part of the URLs if you want the bleeding edge. :-)To use it, all you have to do is copy that class (GPL v3), and change @RunWith(Parameterized.class) to @RunWith(LabelledParameterized.class) assuming the first element of your parameter list is a sensible label.I don't know if any later releases of JUnit address this issue but even if they did, I can't update JUnit since all my co-developers would have to update too and we have higher priorities than re-tooling. Hence the work in the class to be compilable by multiple versions of JUnit. there is some reflection jiggery-pokery so that it runs across the different JUnit versions as listed above. The version specifically for JUnit 4.3.1 can be found  and, for JUnit 4.4 and 4.5, .With  as a model, I wrote my own custom test runner / suite -- only took about half an hour. It's slightly different from darrenp's  in that it lets you specify a name explicitly rather than relying on the first parameter's .It also doesn't use arrays because I hate arrays. :)And an example:from junit4.8.2, you can create your own MyParameterized class by simply copy Parameterized class. change the getName() and testName() methods in TestClassRunnerForParameters. You may also want to try JUnitParams: You can create a method likeWhile I wouldn't use it all the time it would be useful to figure out exactly which test number 143 is.I make extensive use of static import for Assert and friends, so it is easy for me to redefine assertion:For example, you could add a \"name\" field to your test class, initialized in the constructor, and display that on test failure.  Just pass it in as the first elements of your parameters array for each test.  This also helps label the data:None of it was working for me, so I got the source for Parameterized and modified it create a a new test runner. I didn't have to change much but IT WORKS!!!A workaround would be to catch and nest all Throwables into a new Throwable with a custom message that contains all information about the parameters. The message would appear in the stack trace.\nMy code looks like this:The stack trace of the failed test is:Check out JUnitParams as dsaff mentioned, works using ant to build parameterized test method descriptions in the html report. This was after trying LabelledParameterized and finding that it although it works with eclipse it does not work with ant as far as the html report is concerned.Cheers,Since the parameter accessed (e.g. with  always returns the  representation, one workaround would be to make an anonymous implementation and override  in each case. For example:
Java

I'm trying to generate Java classes from the FpML (Finanial Products Markup Language) version 4.5. A ton of code is generated, but I cannot use it. Trying to serialize a simple document I get this:In fact  classses have the @XmlRootElement annotation, so what can I be doing wrong?. I'm pointing xjc (JAXB 2.1) to fpml-main-4-5.xsd, which then includes all types.To tie together what others have already stated or hinted at, the rules by which JAXB XJC decides whether or not to put the  annotation on a generated class are non trivial (). exists because the JAXB runtime requires certain information in order to marshal/unmarshal a given object, specifically the XML element name and namespace. You can't just pass any old object to the Marshaller.  provides this information.The annotation is just a convenience, however - JAXB does not require it. The alternative to is to use  wrapper objects, which provide the same information as , but in the form of an object, rather than an annotation. However,  objects are awkward to construct, since you need to know the XML element name and namespace, which business logic usually doesn't. Thankfully, when XJC generates a class model, it also generates a class called . This is partly there for backwards compatibility with JAXB v1, but it's also there as a place for XJC to put generated factory methods which create  wrappers around your own objects. It handles the XML name and namespace for you, so you don't need to worry about it. You just need to look through the  methods (and for large schema, there can be hundreds of them) to find the one you need.This is mentioned at the bottom of the blog post already linked above but this works like a treat for me:As hinted at in one of the above answers, you won't get an XMLRootElement on your root element if in the XSD its type is defined as a named type, since that named type could be used elsewhere in your XSD. Try mking it an anonymous type, i.e. instead of:you would have:@XmlRootElement is not needed for unmarshalling - if one uses the 2 parameter form of Unmarshaller#unmarshall.So, if instead of doing:one should do:The latter code will not require @XmlRootElement annotation at UserType class level.Joe's answer (Joe Jun 26 '09 at 17:26) does it for me. The simple answer is that absence of an @XmlRootElement annotation is no problem if you marshal a JAXBElement. The thing that confused me is the generated ObjectFactory has 2 createMyRootElement methods - the first takes no parameters and gives the unwrapped object, the second takes the unwrapped object and returns it wrapped in a JAXBElement, and marshalling that JAXBElement works fine. Here's the basic code I used (I'm new to this, so apologies if the code's not formatted correctly in this reply), largely cribbed from :You can fix this issue using the binding from .Here is an example with MavenHere is the  file contentIt's not working for us either. But we did find a widely-quoted article that adds SOME background... I'll link to it here for the sake of the next person: With a Maven build, you can add the  annotation with the \"\" plug-in.See more information : see and Did you try to change your xsd like this?As you know the answer is to use the ObjectFactory(). Here is a sample of the code that worked for me :)To soluction it you should configure a xml binding before to compile with wsimport, setting generateElementProperty as false.In case my experience of this problem gives someone a Eureka! moment.. I'll add the following:I was also getting this problem, when using an xsd file that I had generated using IntelliJ's \"Generate xsd from Instance document\" menu option.When I accepted all the defaults of this tool, it generated an xsd file that when used with jaxb, generated java files with no . At runtime when I tried to marshal I got the same exception as discussed in this question.I went back to the IntellJ tool, and saw the default option in the \"Desgin Type\" drop down (which of course I didn't understand.. and still don't if I'm honest) was:Desgin Type:I changed this to , now it generated a (substantially) different xsd, that produced the  when used with jaxb.  Can't say I understand the in's and out's of it, but it worked for me.
Java

I have two sets, A and B, of the same type.I have to find if A contains any element from the set B.What would be the best way to do that without iterating over the sets?\nThe Set library has  and , but not .Wouldn't  work? From the documentation:Thus, the method returns  if the collections contains any common elements.Since Java 8: A good way to implement containsAny for sets is using the Guava . would return a , so the call looks like:This returns true iff the sets are disjoint, otherwise false. The time complexity of this is likely slightly better than retainAll because you dont have to do any cloning to avoid modifying your original set. Apache Commons has a method .Use  in the Set interface. This method provides an intersection of elements common in both sets. See the API docs for more information.You can use  method and get the intersection of your two sets.I would recommend creating a  from set A, and then iterating through set B and checking if any element of B is in A. This would run in  time (as there would be no collisions), whereas  must run in  time.There's a bit rough method to do that. \nIf and only if the A set contains some B's element than the callwill modify the A set. In this situation removeAll will return true (As stated at ). But probably you don't want to modify the A set so you may think to act on a copy, like this way:and the returning value will be true if the sets are not distinct, that is they have non-empty intersection.  Also see I use  \nReturns  if at least one element is in both collections.Simple to use, and the name of the function is more suggestive.
Java

I'm using Ubuntu Gnome 14.04, and I have Java 8 installed (both the JDK and the JRE).When I was installing Android Studio everything worked, but a message appeared saying:How can I install Android Studio correctly, or how do I fix this ?Presuming that you are running the 64bit Ubuntu, the fix suggested for \"Issue \" should solve your problem.Update:\nFor Ubuntu 15.10 & 16.04\n @warsong is right. Installing only  solved the problem.For next uses I rewrite @warsongs comment in answer area. For Ubuntu 15.04,15.10,16.04 LTS & Debian 8For Fedora (tested for Fedora 23/24) runI understand the question is regarding UBUNTU, but I had similar problem in Debian Jessie 64bit and warsongs suggestion worked for it also.\nWhen I ran studio.sh android studio would start, but when I tried to configure the android SDK I got the error\n\nWHen I tried\n\nGot error\n\nSo took warsongs suggestion and only tried to install lib32stdc++6.\n\nAfter this was able to add the Android SDK into Android Studio. The Problem is caused by mksdcard not being installed correctly.if you are running 64 bit, do this to fix the mksdcard problem.and 32 bit:In SDK 6.0, the error message is different but means the same thing.None of these options worked for me on Ubuntu 12.10 (yeah, I need to upgrade).  However, I found an easy solution.  Download the source from here: .  Then simply compile with \"gcc mksdcard.c -o mksdcard\". Backup mksdcard in the SDK tools subfolder and replace with the newly compiled one.  Android Studio will now be happy with your SDK.For Linux Mint runIf you run \nand got a message like: \"\".You can do something like this tut: This issue arises when your 64 bit os tries to install the Android SDK which in turns tries to install some 32 bit binaries and thus is the issue of compatibility. Open an additional terminal and typewould help to install all the required binaries. After this, start the afresh the Android SDK installation process.
Java

In Java, there is a practice of declaring every variable (local or class), parameter final \nif they really are.\nThough this makes the code a lot more verbose, \nthis helps in easy reading/grasping of the code and also prevents mistakes\nas the intention is clearly marked.What are your thoughts on this and what do you follow?I think it all has to do with good coding style. Of course you can write good, robust programs without using a lot of  modifiers anywhere, but when you think about it... Adding  to all things which  change simply narrows down the possibilities that you (or the next programmer, working on your code) will misinterpret or misuse the thought process which resulted in your code. At least it should ring some bells when they now want to change your previously immutable thing.At first, it kind of looks awkward to see a lot of  keywords in your code, but pretty soon you'll stop noticing the word itself and will simply think,  (you can take it from me ;-)I think it's good practice. I am not using it all the time, but when I can and it makes sense to label something  I'll do it.Obsess over:Consider but use judiciously:Ignore unless feeling anal:You really need to understand the full use of the final keyword before using it.  It can apply to and has differing affects on variables, fields, methods and classes I\u2019d recommend checking out the article linked to below for more details.The  modifier, especially for variables, is a means to have the compiler enforce a convention that is generally sensible: make sure a (local or instance) variable is assigned exactly once (no more no less). By making sure a variable is definitely assigned before it is used, you can avoid common cases of a :By preventing a variable from being assigned more than once, you discourage overbroad scoping. Instead of this:You are encouraged to use this:Some links:I'm pretty dogmatic about declaring every possible variable . This includes method parameters, local variables, and rarely, value object fields. I've got three main reasons for declaring final variables everywhere:However, I do think that final classes and methods are not nearly as useful as final variable references. The  keyword, when used with these declarations simply provide roadblocks to automated testing and the use of your code in ways that you could have never anticipated.Effective Java has an item that says \"Favour immutable objects\". Declaring fields as final helps you take some small steps towards this, but there is of course much more to truly immutable objects than that.If you know that objects are immutable they can be shared for reading among many threads/clients without synchronization worries, and it is easier to reason about how the program runs.I have never been in a situation where having a final keyword on a variable has stopped me from making a mistake, so for the moment I think it's a giant waste of time.Unless there is a real reason for doing it (as in you want to make a specific point about that variable being final) I would rather not do it since I find it makes the code less readable.If, however, you don't find it makes the code harder to read or longer to write then by all means go for it. As a clarification (and an attempt to win back down-votes), I'm not saying don't mark constants as final, I'm saying don't do stuff like:It just makes code (in my opinion) harder to read.It's also worth remembering that  final does is prevent you from reassigning a variable, it doesn't make it immutable or anything like that.Final should always be used for constants.  It's even useful for short-lived variables (within a single method) when the rules for defining the variable are complicated.For example:I use  all the time for object attributes.The  keyword has visibility semantics when used on object attributes. Basically, setting the value of a final object attribute happens-before the constructor returns. This means that as long as you don't let the  reference escape the constructor and you use  for  you attributes, your object is (under Java 5 semantics) guarenteed to be properly constructed, and since it is also immutable it can be safely published to other threads.Immutable objects is not just about thread-safety. They also make it a lot easier to reason about the state transitions in your program, because the space of what  change is deliberately and, if used consistently, thoroughly limited to only the things that  change.I sometimes also make methods final, but not as often. I seldomly make classes final. I generally do this because I have little need to. I generally don't use inheritance much. I prefer to use interfaces and object composition instead - this also lends itself to a design that I find is often easier to test. When you code to interfaces instead of concrete classes, then you don't  to use inheritance when you test, as it is, with frameworks such as jMock, much easier to create mock-objects with interfaces than it is with concrete classes.I guess I should make the majority of my classes final, but I just haven't gotten into the habbit yet.I have to read a lot of code for my job. Missing final on instance variables is one of the top things to annoy me and makes understanding the code unnecessarily difficult. For my money, final on local variables causes more clutter than clarity. The language should have been designed to make that the default, but we have to live with the mistake. Sometimes it is useful particularly with loops and definite assignment with an if-else tree, but mostly it tends to indicate your method is too complicated. should obviously be used on constants, and to enforce immutability, but there is another important use on methods. has a whole item on this (Item 15) pointing out the pitfalls of unintended inheritance. Effectively if you didn't design and document your class for inheritance, inheriting from it can give unexpected problems (the item gives a good example). The recommendation therefore is that you use  on any class and/or method that wasn't intended to be inherited from. That may seem draconian, but it makes sense. If you are writing a class library for use by others then you don't want them inheriting from things that weren't designed for it - you will be locking yourself into a particular implementation of the class for back compatibility. If you are coding in a team there is nothing to stop another member of the team from removing the  if they really have to. But the keyword makes them think about what they are doing, and warns them that the class they are inheriting from wasn't designed for it, so they should be extra careful.Sounds like one of the biggest argument  using the final keyword is that \"it's unnecessary\", and it \"wastes space\".If we acknowledge the many benefits of \"final\" as pointed out by many great posts here, while admitting it takes more typing and space, I would argue that Java should have made variables \"final\" by default, and require that things be marked \"mutable\" if the coder wants it to be.Another caveat is that many people confuse final to mean that the contents of the instance variable cannot change, rather than that the reference cannot change. Choosing to type  for each parameter in each method will produce so much irritation both for coders and code readers.Once irritation goes beyond reasonable switch to Scala where arguments are final by default.Or, you can always use code styling tools that will do that automatically for you. All IDEs have them implemented or as plugins.Final when used with  variables in Java provides a substitute for constant in C++. So when final and static is used for a variable it becomes immutable. At the same time makes migrated C++ programmers pretty happy ;-)When used with reference variables it does not allow you to re-reference the object, though the object can be manipulated.When final is used with a method, it does not allow the method to be over-ridden by the subclasses.Once the usage is very clear it should be used with care. It mainly depends on the design as using final on the method would not help polymorphism. One should only use it for variables when you are damn sure that the value of the variable will/should never be changed. Also ensure that you follow the coding convention encouraged by SUN.for eg: final int  COLOR_RED   = 1; (Upper case seperated by underscore)With a reference variable, use it only when we need a an immutable reference to a particular object.Regarding the readability part, ensue that comments play a very important role when using the final modifier.I never use them on local variables, there is little point for the added verbosity.  Even if you don't think the variable should be reassigned, that will make little difference to the next person altering that code that thinks otherwise, and since the code is being changed, any original purpose for making it final may no longer be valid.  If it is just for clarity, I believe it fails due to the negative effects of the verbosity.Pretty much the same applies to member variables as well, as they provide little benefit, except for the case of constants.It also has no bearing on immutability, as the best indicator of something being immutable is that it is documented as such and/or has no methods that can alter the object (this, along with making the class final is the only way to guarantee that it is immutable).But hey, that's just my opinion  :-)I set up Eclipse to add final on all fields and attributes which are not modified. This works great using the Eclipse \"save actions\" which adds these final modifiers (among other things) when saving the file.Highly recommended. Check out  of Eclipse Save Actions.I hardly use final on methods or classes because I like allowing people to override them.Otherwise, I only use finally if it is a Even for local variables, knowing that it is declared final means that I don't need to worry about the reference being changed later on. This means that when debugging and I see that variable later on, I am confident that it is referring to the same object. That is one less thing I need to worry about when looking for a bug.\nA bonus is that if 99% of variables are declared final, then the few variables which really are variable stand out better.\nAlso, the final lets the compiler find some more possible stupid mistakes that might otherwise go unnoticed.For arguments I'm think they're not needed. Mostley they just hurt readabillity. Rreassigning an argument variable is so insanely stupid that I should be pretty confident that they can be treated as constants anyway.The fact that Eclipse colors final red makes it easier to spot variable declarations in the code which I think improves readbillity most of the time.I try to enforce the rule that any and all variables should be final it there isn't an extremley valid reason not to. It's so much easier to answer the \"what is this variable?\" question if you just have to find the initilization and be confident that that is it.I actually get rather nervous around non-final variables now a days. It's like the differnce between having a knife hanging in a thread abouve your head, or just having it you kitchen drawer...A final variable is just a nice way to lable values.A non-final variable is bound to part of some bug-prone algorithm.One nice feature is that when the option to use a variable in out of the question for an algorithm most of the time the sollution is to write a method instead, which usually improves the code significantly.I've been coding for a while now and using final whenever I can. After doing this for a while (for variables, method parameters and class attributes), I can say that 90% (or more) of my variables are actually final. I think the benefit of NOT having variables modified when you don't want to (I saw that before and it's a pain sometimes) pays for the extra typing and the extra \"final\" keywords in your code.That being said, if I would design a language, I would make every variable final unless modified by some other keyword.I don't use final a lot for classes and methods, thought. This is a more or less complicated design choice, unless your class is a utility class (in which case you should have only one private constructor).I also use Collections.unmodifiable... to create unmodifiable lists when I need to.Using anonymous local classes for event listeners and such is a common pattern in Java.\nThe most common use of the final keyword is to make sure that variables in scope are accessible to the even listener.However, if you find yourself being required to put a lot of final statements in your code. That might be a good hint you're doing something wrong.The article posted above gives this example:I use it for constants inside and outside methods.I only sometimes use it for methods because I don't know if a subclass would NOT want to override a given method(for whatever reasons).As far as classes, only for some infrastructure classes, have I used final class.IntelliJ IDEA warns you if a function parameter is written to inside a function. So, I've stopped using final for function arguments. I don't see them inside java Runtime library as well.Using final  is strongly encouraged. However, I wouldn't use it for methods or classes (or at least think about it for a while), because it makes  harder, if not impossible. If you absolutely must make a class or method final, make sure this class implements some interface, so you can have a  implementing the same interface.Marking the class final can also make some method bindings happen at compile time instead of runtime. \nConsider \"v2.foo()\" below - the compiler knows that B cannot have a subclass, so foo() cannot be overridden so the implementation to call is known at compile time.  If class B is NOT marked final, then it's possible that the actual type of v2 is some class that extends B and overrides foo().
Java

I'm using Spring to define stages in my application. It's configured that the necessary class (here called ) is injected with the stages.\nNow I need the List of Stages in another class, named . The  doesn't offer access to his List of Stages.I cannot change the class .My Idea:\nDefine a new bean called Stages and inject it to  and .\nMy problem with this idea is that I don't know how to transform this property:into a bean.Something like this does not work:Can anybody help me with this?Import the spring util namespace. Then you can define a list bean as follows:The value-type is the generics type to be used, and is optional. You can also specify the list implementation class using the attribute .Here is one method:Another option is to use JavaConfig. Assuming that all stages are already registered as spring beans you just have to:and spring will automatically inject them into this list. If you need to preserve order (upper solution doesn't do that) you can do it in that way:The other solution to preserve order is use a  annotation on beans. Then list will contain beans ordered by ascending annotation value.And in SomeClass:Stacker posed a great answer, I would go one step farther to make it more dynamic and use Spring 3 EL Expression. I was trying to figure out how I could do this with the util:list but couldn't get it work due to conversion errors. I think you may be looking for .You declare a ListFactoryBean instance, providing the list to be instantiated as a property withe a  element as its value, and give the bean an  attribute.  Then, each time you use the declared  as a  or similar in some other bean declaration, a new copy of the list is instantiated.  You can also specify the  class to be used.Use the util namespace, you will be able to register the list as a bean in your application context. You can then reuse the list to inject it in other bean definitions.As an addition to Jakub's answer, if you plan to use JavaConfig, you can also autowire that way:And this is how to inject set in some property in Spring:
Java

Can anyone tell me how to get the filename without the extension?\nExample:If you, like me, would rather use some library code where they probably have thought of all special cases, such as what happens if you pass in  or dots in the path but not in the filename, you can use the following:The easiest way is to use a regular expression.The above expression will remove the last dot followed by one or more characters.  Here's a basic unit test.See the following test program:which outputs:If your project uses  (14.0 or newer), you can go with .(Essentially the same as  from Apache Commons IO, as the  suggests. Just wanted to point out Guava does this too. Personally I didn't want to add dependency to Commons\u2014which I feel is a bit of a relic\u2014just because of this.)Here is the consolidated list order by my preference.While I am a big believer in reusing libraries, the  is 174KB, which is noticably large for a mobile app.  If you download the source code and take a look at their FilenameUtils class, you can see there are a lot of extra utilities, and it does cope with Windows and Unix paths, which is all lovely.However, if you just want a couple of static utility methods for use with Unix style paths (with a \"/\" separator), you may find the code below useful.  The  method preserves the rest of the path along with the filename.  There is also a similar .Below is reference from If you don't like to import the full apache.commons, I've extracted the same functionality:Try the code below. Using core Java basic functions. It takes care of s with extension, and without extension (without the  character). The case of multiple  is also covered.You can adapt it to work with  strings.?indexOfExtension or indexOfDOT?
Java

Searching SO and Google, I've found that there are a few Java HTML parsers which are consistently recommended by various parties. Unfortunately it's hard to find any information on the strengths and weaknesses of the various libraries. I'm hoping that some people have spent some comparing these libraries, and can share what they've learned.Here's what I've seen:And if there's a major parser that I've missed, I'd love to hear about its pros and cons as well.Thanks!Almost all known HTML parsers implements the  (part of the JAXP API, Java API for XML processing) and gives you a  back which is ready for direct use by JAXP API. The major differences are usually to be found in the features of the parser in question. Most parsers are to a certain degree forgiving and lenient with non-wellformed HTML (\"tagsoup\"), like , ,  and . You usually use this kind of HTML parsers to \"tidy\" the HTML source (e.g. replacing the HTML-valid  by a XML-valid ), so that you can traverse it \"the usual way\" using the W3C DOM and JAXP API.The only ones which jumps out are  and .  provides a completely own API which gives you the possibility to act like a webbrowser programmatically. I.e. enter form values, click elements, invoke JavaScript, etcetera. It's much more than alone a HTML parser. It's a real \"GUI-less webbrowser\" and HTML unit testing tool. also provides a completely own API. It gives you the possibility to select elements using -like  and provides a slick API to traverse the HTML DOM tree to get the elements of interest. Particularly the traversing of the HTML DOM tree is the major strength of Jsoup. Ones who have worked with  know what a hell of pain it is to traverse the DOM using the verbose  and  APIs. True,  makes the life easier, but still, it's another learning curve and it can end up to be still verbose. Here's an example which uses a \"plain\" W3C DOM parser like JTidy in combination with XPath to extract the first paragraph of your question and the names of all answerers (I am using XPath since without it, the code needed to gather the information of interest would otherwise grow up 10 times as big, without writing utility/helper methods).And here's an example how to do exactly the same with Jsoup:Do you see the difference? It's not only less code, but Jsoup is also relatively easy to grasp if you already have moderate experience with CSS selectors (by e.g. developing websites and/or using jQuery).The pros and cons of each should be clear enough now. If you just want to use the standard JAXP API to traverse it, then go for the first mentioned group of parsers. There are pretty  of them. Which one to choose depends on the features it provides (how is HTML cleaning made easy for you? are there some listeners/interceptors and tag-specific cleaners?) and the robustness of the library (how often is it updated/maintained/fixed?). If you like to unit test the HTML, then HtmlUnit is the way to go. If you like to extract specific data from the HTML (which is more than often the real world requirement), then Jsoup is the way to go. compares certain aspects of the following parsers:It is by no means a complete summary, and it is from 2008.  But you may find it helpful.Add , an implementation of the HTML5 parsing algorithm in Java, to your list. On the plus side, it's specifically designed to match HTML5, and at the heart of the HTML5 validator, so highly likely to match future browser's parsing behaviour to a very high degree of accuracy.On the minus side, no browsers' legacy parsing works exactly like this, and as HTML5 is still in draft, subject to change. In practice, such problems only affect obscure corner cases, and is for all practical purposes, an excellent parser.I found  HTML Parser to be very well written, kept up to date (which many of the parsers are not), no dependencies, and easy to use.I'll just add to @MJB answer after working with most of the HTML parsing libraries in Java, there is a huge pro/con that is omitted: parsers that preserve the formatting and incorrectness of the HTML on input and output.That is most parsers when you change the document will blow away the whitespace, comments, and incorrectness of the DOM particularly if they are an XML like library. is the only parser I know that allows you to manipulate nasty HTML while preserving whitespace formatting and the incorrectness of the HTML (if there is any).Two other options are  and . I have tried most of the parsers here for a crawler / data extraction framework I have been developing. I use HTMLCleaner for the bulk of the data extraction work. This is because it supports a reasonably modern dialect of HTML, XHTML, HTML 5, with namespaces, and it supports DOM, so it is possible to . It's a lot easier to do this with HTMLCleaner than some of the other parsers: JSoup for example supports a DOM like interface, rather than DOM, so . Jericho has a SAX-line interface so again it is requires some work although  but in the end HTMLCleaner just worked better.I also use HTMLParser and Jericho for a table extraction task, which replaced some code written using Perl's . I use HTMLParser to filter the HTML for the table, then use Jericho to parse it. I agree with MJB's and Adam's comments that Jericho is good in some cases because it preserves the underlying HTML. It has a kind of non-standard SAX interface, so for XPath processing HTMLCleaner is better.Parsing HTML in Java is a surprisingly hard problem as all the parsers seem to struggle on certain types of malformed HTML content.
Java

I cannot for the life of me find a definition of what the Java VM flag  actually does, other than some very fuzzy high-level definitions such as \"gets rid of your PermGen problems\" (, btw).I have looked on Sun's/Oracle's site, and even  doesn't actually say what it does.Based upon the name of the flag, I'm guessing that the CMS Garbage Collector doesn't by default unload classes, and this flag turns it on - but I can't be sure.The standard Oracle/Sun VM look on the world is: Classes are forever. So once loaded, they stay in memory even if no one cares anymore. This usually is no problem since you don't have that many purely \"setup\" classes (= used once for setup and then never again). So even if they take up 1MB, who cares.But lately, we have languages like Groovy, that define classes at runtime. Every time you run a script, one (or more) new classes are created and they stay in PermGen forever. If you're running a server, that means you have a memory leak.If you enable  the GC will sweep PermGen, too, and remove classes which are no longer used. You will also have to enable  (thanks to ). See this answer: According to the blog post , it determines if class unloading is enabled under the CMS garbage collector.  The default is .  There is another option called  that is  by default which (presumably) affects the other garbage collectors.The idea is that if the GC detects that a previously loaded class is no longer used anywhere in the JVM, it can reclaim the memory used to hold the classes bytecode and/or native code.Setting CMSClassUnloadingEnabled  help with your permgen problem .  But the chances are that you are not using the CMS, or that you have a genuine classloader related memory leak.  In the latter case, your class will never appear to the GC to be unused ... and will therefore never be unloaded.Aaron Digulla says \"classes are for ever\".  This is not strictly true, even in the purely Java world.  In fact, the lifetime of a class is tied to its classloader.  So if you can arrange that a classloader is garbage collected (and that is not always an easy thing to do) the classes that it loaded will also be garbage collected.In fact, this is what happens when you do a hot redeploy of a webapp.  (Or at least, that's what should happen, if you can avoid the problems that lead to a permgen storage leak.)An example where this is useful:Setting  on our Weblogic 10.3 JVM helped resolving a problem where the JAX-WS implementation created a new proxy class for every web service call, eventually leading to out of memory errors. It wasn't trivial to trace. The following code always returned the same proxy class for Internally, this proxy delegated to an instance of , which again delegated to a new  class where  was incremented at every call. When adding the flags,  was still incremented, but at least those temporary classes were removed from memory.On a more general note, this can be very useful when making heavy use of Java reflection and proxies through 
Java

Continuing from Stack Overflow question :What is the most efficient way to get a Date object without the time? Is there any other way than these two?:Do you absolutely  to use ? I would  recommend that you use  or the  package from Java 8 instead. In particular, while Date and Calendar  represent a particular instant in time, with no such concept as \"just a date\", Joda Time  have a type representing this (). Your code will be much clearer if you're able to use types which represent what you're actually trying to do.There are many, many other reasons to use Joda Time or  instead of the built-in  types - they're generally far better APIs. You can always convert to/from a  at the boundaries of your own code if you need to, e.g. for database interaction.Here is what I used to get today's date with time set to :You can use the  from Apache Commons library.Example: Yes, there is. Java 8 and later comes with the new  built-in. See . Much of the java.time functionality is back-ported to Java 6 & 7 in  and further adapted to Android in .Similar to , java.time offers a  class to represent a date-only value without time-of-day and without time zone.Note that  to determining a particular date. At the stroke of midnight in Paris, for example, the date is still \u201cyesterday\u201d in Montr\u00e9al. By default, java.time uses the  standard in generating a string representation of a date or date-time value. (Another similarity with Joda-Time.) So simply call  to generate text like .The most straightforward way:The standard answer to these questions is to use . The API is better and if you're using the formatters and parsers you can avoid the non-intuitive lack of thread safety of . Using Joda means you can simply do: Using java 8 this can be acheived using It does not make sense to talk about a date without a timestamp with regards to the Date routines in the standard java runtime, as it essentially maps down to a specific millisecond and not a date.  Said millisecond intrinsically has a time of day attached to it which makes it vulnerable to timezone problems like Daylight Savings Time and other calendar adjustments.    See  for an interesting example.If you want to work with dates instead of milliseconds, you need to use something else.  For Java 8 there is a new set of methods providing exactly what you ask for.  For Java 7 and earlier use Well, as far as I know there is no easier way to achieve this if you only use the standard JDK.You can, of course, put that logic in method2 into a static function in a helper class, like done Then you can shorten the second method to:Or, if you really need the current day in this format so often, then you can just wrap it up in another static helper method, thereby making it a one-liner.Definitely not the most correct way, but if you just need a quick solution to get the date without the time and you do not wish to use a third party library this should doI only needed the date for visual purposes and couldn't Joda so I substringed.If you need the date part just for echoing purpose, thenIf all you want is to see the date like so \"YYYY-MM-DD\" without all the other clutter e.g. \"Thu May 21 12:08:18 EDT 2015\" then just use .  This example gets the current date:Also  is a subclass of .If you just need the current date, without time, another option is:This is a simple way of doing it:Check out . It is a simple and efficient alternative to both java.util and Joda-time. It has an intuitive API and classes that represent dates alone, without timestamps.The most straigthforward way that makes full use of the huge TimeZone Database of Java and is correct:Here is a clean solution with no conversion to string and back, and also it doesn't re-calculate time several times as you reset each component of the time to zero. It also uses  (modulus) rather than divide followed by multiply to avoid the double operation.It requires no third-party dependencies, and it RESPECTS THE TIMEZONE OF THE Calender object passed in. This function returns the moment in time at 12 AM in the timezone of the date (Calendar) you pass in.Prefer not to use third-party libraries as much as possible. I know that this way is mentioned before, but here is a nice clean way:Well, not using GregorianCalendar is maybe an option!
Java

we are in the planning stage of migrating a large website which is built on a custom developed mvc framework to a java based web framework which provides built-in support for ajax, rich media content, mashup, templates based layout, validation, maximum html/java code separation. Grails looked like a good choice, however, we do not want to use a scripting language. We want to continue using java. Template based layout is a primary concern as we intend to use this web application with multiple web sites with similar functionality but radically different look and feel. Is portal based solution a good fit to this problem? Any insights on using \"Spring Roo\" or \"Play\" will be very helpful.I did find similar posts like , but it is more than a year old. Things have surely changed in the mean time! Thanks for the great answers! This site is turning to be the best single source for in-the-trenches programmer info. However, I was expecting more info on using a portal-cms duo. Jahia looks goods. Anything similar?Personally, I would stay away from big fat Portal solutions (they are often productivity killers). I've heard good things about  though but I don't have any real experience with it.About Spring Roo, I've read previous answers like  and other things over the Internet but I'm still not convinced (maybe I don't get it), I'm not sure of its maturity, and, more important, I'm really wondering what SpringSource is doing with Grails and Roo (no,  doesn't convince me that they will both survive).I can't say much about Play. I've seen the demo like everybody but I would like to read real life feedback. Until then, I'll wait.Yes and no :) But let's enter the presentation frameworks hell: there is no single answer to your question (like one year ago), there are dozen of frameworks around there and no clear winner. Just to cite a  few:Actually, I'd suggest to take a look at Matt Raible's , he really did a great job at comparing web frameworks, showing their strengths and weakness, gathering facts and numbers, showing trends... I recommend:Really, have a look at these presentations, they will help you to find an appropriate framework (there is no unique answer but you can restrict the choice by elimination) and might change your point of view.I've been using Spring 3 and Jquery for a while but heard about Play and gave it a shot. I really like it, Play is a great fit between something like PHP and the heavy duty Java frameworks like Spring.The things I like most about play are:Things I don't like about PlayTop choice for me is . Clear separation of markup and java code. Very easy to write and use components. Simple to use Ajax, testability. You can debug right into your pages / components and don't get cryptic error messages from your JSF implementation ;)There is also a good comparison wicket <--> JSF in The top three choices for me are (alphabetically):They:Play is closely similar to ROR, a ROR version in javaIn contrast to other answers, I'd like to highlight the disadvantages (IMHO) of popular web frameworks: - Released and already aged. Still only a few news/articles/blog posts/experiences out. I am skeptical. Still waiting for the next major release of Richfaces/Icefaces which fully supports jsf 2 -  currently only alpha builds can be downloaded. - Seems to be only a good thing if you're still relying on struts and want to refactor most of your code. Otherwise: Don't. - I do not like the single-page and the java->javascript approach. I am not sure if one session - multiple views/windows can be easily achieved. For me, this framework should be used for massive-users single-window rich internet applications. - Nice approach, but a little bit verbose and too less documentation available (except the good wicket in action book, but this covers only 1.3). Also, for me it lacks of big projects which are built on top on it. And I currently cannot see where the road of wicket is traveling or if it has already been driven to a dead end. - Did not tried this yet, but you have to include many jars (spring mess) in your classpath to work with this framework properly. And it relies on JSP (in most projects), which I consider already dead. And you get only a pure MVC framework - all other things (ajax and others) have to be implemented/integrated. - A small and nice designed MVC framework, but too less documentation, too less commits/committers, too few releases, too less industry support, too less mailing list activity.I am also curious if I missed a major framework out there (I left Tapestry out intentionally) which might be an option for you (and also for me, too).I have had great success with . It is the only Java Web Framework that has some sort of JSR spec and multiple implementations other than the servlet and portlet spec (although this can be a bad thing).One thing that is bad and good about Java is that you can pick and match frameworks (python also has this feature/problem). Its nice because you don't have to put all your eggs in one basket.Here is a general Java Web Application Stack Recipe: JQuery, Prototype, Dojo Spring MVC, Stripes, and my favorite JAX-RS (Jersey, Apache CXF) Spring, Guice JPA (Hibernate, Google App storage), Hibernate, JDO and more.I also have had great success in using AspectJ to make Java \"suck less\". By using Spring's @Configurable and AspectJ's ITD mixins you can get Rails like Domain objects (this is infact what Roo does but you don't need Roo to do this).I've found  to be really effective and surprisingly lightweight....it aims to be more lightweight than . I've heard from friends that are fulltime web developers that JSF is not worth bothering with, although I have no firsthand experience, and can't back that up with examples (!).Have a look to , that follow the same principles that Play! but implemented by reusing some enterprise grade frameworks/tools like Maven 3/Spring 3/Jersey/jQuery.RESThub is very disruptive comparing to other frameworks since it is a full stack toolkit, but without any serverside MVC or servlet based framworks. Instead, it use a jQuery UI based GUI that use JAX-RS (REST) webservices and a Javascript templating system based on embeddedJs.Servers are stateless, and we use HTML5 sessionStorage to keep session on client side. This approach is design for RIA and scalability.Some demo applications are provided (even if under construction).I would second the Spring recommendation.  I'm not a huge fan GWT, I don't think the Java -> Javascript crosscompiler is quite there yet.  I am working on an AJAX app that uses spring on the server and jQuery on the client. Although there is technically not \"out-of-the-box\" support for jQuery, implementing a spring-MVC AjaxView is dead simple and took about 25 lines of code.  JSF is a nice framewrok, but JSF 1.2 lacked vision for years to come from its release. JSF 2.0 looks promising and has many new things added fro m JSF 1.2 like ajax support, facelets, Annotation support and default conventions (less XML),easy component building than 1.2.It integrates well with Spring also, if you are concerned for DI support.Maybe a little bit late to the show, but I  to mention . Programming is done in Java exclusively, with a component-based approach. Client-Server communication is more about user interaction than data transport, all business logic resides on server. Ext GWT + SpringI think what you are looking for is something close to Jahia. It supports GWT, Mashups, Media Content etc. \nCouple of years back have used portal software \"\" this was not very matured then.\nBut was good and easy for development.Something that deserves more than just a bullet are player based RIA frameworks. Ex. Adobe Flex + Java (Of course this can hinge somewhat on whether your \"site\" is really a \"site\" or more like an \"application\", you wouldn't do a blog site in Flex.)In the AJAX-as-a-buzzword sense, Flex typically uses AMF (a binary protocol that's  than protocols used by AJAX apps), although you can also do strictly AJAX stuff with Flex too. So Flex supports AJAX, but also supports \"better than AJAX\".Being that Flex runs on the Flash 'virtual machine' platform, I think little needs to be added.Not sure what this is getting at exactly, but it sounds like Flex mxml.Supported of course, although you may decide to do some custom stuff if you want to get fancy. (Not that you have to.) The nice thing is that you can get as sophisticated as you want--or not.You can't get more separated by using a 'virtual machine' development approach like Flex/Silverlight/JavaFX. This doesn't just enable you to keep your presentation code separated from your server-side logic and data access layer--it  that they're separated. 'Virtualizing' your development environment gets you cross-browser compatibility, a consistent target platform, no worries about new browsers or new browser releases breaking your application, top of the line java-like debugging capabilities, and a more professional/impressive looking end product.Take a look to ItsNat is basically a Java W3C browser in server, amazingly simple (DHTML in server), promoting AJAX intensive  applications
Java

I am trying to split the Value using a separator.\nBut I am finding the surprising resultsI am expecting to get 8 values. \nBut I am getting only 6 values.Any idea and how to fix. No matter EMPTY value comes at anyplace, it should be in array. by default removes trailing empty strings from result array. To turn this mechanism off we need to use overloaded version of  with  set to negative value likeLittle more details:\n internally returns result of  and in  of this method you can find (emphasis mine):It is worth mentioning that removing trailing empty string makes sense . So for  since we can't split  farther we will get as result  array.\nIt happens because split didn't happen here, so  despite being empty and trailing represents  string, not empty string which was  by splitting process.From the documentation of :So you will have to use the two argument version  with a negative value:Doc:This will not leave out any empty elements, including the trailing ones.From :Overloaded  is more appropriate for your case.Another option is to use Guava's Splitter. It not does have the overhead of a regular expression (which you don't need in this case) and by default does not discard empty trailing strings. For example:For further information, see wiki:\n
Java

I've found the  pretty awesome for keeping hardcoded strings out of my code, and I'd like to keep using it in a utility class that works with models in my application to generate output. For instance, in this case I am generating an email from a model outside of the activity. ? I suppose I could pass in the current activity, but it seems unnecessary. Please correct me if I'm wrong!Edit: Can we access the resources  using ?You can use:... everywhere in your application, even in static constants declarations.\nUnfortunately, it supports .For local resources use . It is not trivial, but it works.Unfortunately, the only way you can access any of the string resources is with a  (i.e. an  or ).  What I've usually done in this case, is to simply require the caller to pass in the context.in MyApplication, which extends :in MyApplication's onCreate:Ta-da!!!! Now you can use this field from anywhere in your application.BTW, one of the reason of  error may be that your IDE imported android.R; class instead of yours one. Just change  to So 2 basic things to get string visible in the different class:If you have a class that you use in an activity and you want to have access the ressource in that class, I recommend you to define a context as a private variable in class and initial it in constructor:Making an instant of class in your activity:I have a utility class Util that wants to call , so I've added a static Context variable with setter:so from each Activity's onCreate, I have to make sure I've initialized the static, i.e.and then from anywhere in my Util I can say reference , such asThis should get you access to  from anywhere allowing you to get  anywhere that can use it; , , , etc.The Singleton:Initialize the Singleton in your  subclass:If I\u00b4m not wrong, this gives you a hook to applicationContext everywhere, call it with \nYou shouldn\u00b4t need to clear this at any point, as when application closes, this goes with it anyway.Remember to update  to use this  subclass:Please let me know if you see anything wrong here, thank you. :)I used \n\nIt works for me.
Java

I'm using Eclipse to generate  and , and there is an option labeled \"Use 'instanceof' to compare types\".  The default is for this option to be unchecked and use  to compare types.  Is there any reason I should prefer  over ?Without using :Using :I usually check the  option, and then go in and remove the \"\" check. (It is redundant since null objects will always fail .)  Is there any reason that's a bad idea?If you use , making your  implementation  will preserve the symmetry contract of the method: . If  seems restrictive, carefully examine your notion of object equivalence to make sure that your overriding implementations fully maintain the contract established by the  class. favors your approach:See also .Effective Java  also covers this.Angelika Langers  gets into that with a long and detailed discussion for a few common and well-known examples, including by Josh Bloch and Barbara Liskov, discovering a couple of problems in most of them. She also gets into the  vs . Some quote from itThe reason to use  is to ensure the symmetric property of the  contract. From equals' JavaDocs:By using instanceof, it's possible to not be symmetric. Consider the example:\nDog extends Animal.\nAnimal's  does an  check of Animal.\nDog's  does an  check of Dog.\nGive Animal  and Dog  (with other fields the same):This violates the symmetric property.To strictly follow equal's contract, symmetry must be ensured, and thus the class needs to be the same.This is something of a religious debate. Both approaches have their problems. has another relevant piece of advice in :Correct me if I am wrong, but getClass() will be useful when you want to make sure your instance is NOT a subclass of the class you are comparing with. If you use instanceof in that situation you can NOT know that because:It depends if you consider if a subclass of a given class is equals to its parent.here I would use 'instanceof', because I want a LastName to be compared to FamilyNamehere I would use 'getClass', because the class already says that the two instances are not equivalent.If you want to ensure only that class will match then use .  If you want to match subclasses then  is needed.Also, instanceof will not match against a null but is safe to compare against a null.  So you don't have to null check it. works for instences of the same class  its subclassesArryaList and RoleList are both  ListWhile  will be  true only if both objects ( this and o ) belongs to exactly the same class.So depending on what you need to compare you could use one or the other. If your logic is: \"One objects is equals to other only if they are both the same class\" you should go for the \"equals\", which I think is most of the cases. Both methods have their problems.  If the subclass changes the identity, then you need to compare their actual classes.  Otherwise, you violate the symmetric property.  For instance, different types of s should not be considered equivalent, even if they have the same name.However, some subclasses don't change identity and these need to use .  For instance, if we have a bunch of immutable  objects, then a  with length and width of 1 should be equal to the unit .In practice, I think the former case is more likely to be true.  Usually, subclassing is a fundamental part of your identity and being exactly like your parent except you can do one little thing does not make you equal.Actually instanceof check where an object belongs to some hierarchy or not. ex: Car object belongs to Vehical class. So \"new Car() instance of Vehical\" returns true. And \"new Car().getClass().equals(Vehical.class)\" return false, though Car object belongs to Vehical class but it's categorized as a separate type.
Java

I want to write a new file with the . I use it like this:Now  and  currently don't exist. I want Java to create them automatically if they aren't already there. Actually Java should set up the whole file path if not already existing.How can I achieve this?Something like:Since Java 1.7 you can use Files.createFile:Use :Use .Use  to handle all these headaches. Edit: For example, use below code to write to a file, this method will 'checking and creating the parent directory if it does not exist'. 
Java

I want to do something like this in Java but I don't know the way:When event \"object 1 say 'hello'\" happens,\nthen object 2 responds to that event by saying \"hello\".Can somebody give me a hint or sample code?You probably want to look into the .Here's some sample code to get yourself started:Related article: What you want is an implementation of the . You can do it yourself completely, or use java classes like  and There are 3 different ways you may wish to set this up: Defaults to Option 3, to try the others simply uncomment the \"\" code block of the class you want to be main, and set that class as the  variable in the  file:
Java

Is there a good tool that can help to reverse engineer Java classes to UML that will show an overview of how my classes are related to each other? It doesn't need to decompile from JAR file because I have the sources. I know there are quite a few out there but most of those can only generate individual class. I hope there is a tool that can generate class diagram that shows an overview of how all my current classes and packages work together, so that I can analyse my current architecture design. Of course, analysing is one thing. The other is for documentation purposes. I know of a few so far. But they cannot do an overview class diagram. Here's a list of Java UML tool that I have tried and is capable of doing reverse engineer but cannot do an overview class diagram of my whole project:Are there any other recommendations to add to this list? And hopefully, can generate an overview Java class diagram. I am using Eclipse, by the way.I use  plugin from Soyatec, under Eclipse and it works fine for the generation of UML giving the source code. does it.\nIt's free tool which has all the mentioned functionality - I personally use it for the same purposes, as described in this post.\nFor each browsed class it shows 2 instantly generated class diagrams: class relations and class UML view.\nClass relations diagram allows to traverse through the whole structure.\nIt has full support for annotations and generics plus special support for JPA entities.\nWorks very well with big projects (thousands of classes).I\u00b4d say  is by far the most powerful one (though probably not the easiest one to work with).MoDisco is a generic reverse engineering framework (so that you can customize your reverse engineering project, with MoDisco you can even reverse engineer the behaviour of the java methods, not only the structure and signatures) but also includes some predefined features like the generation of class diagrams out of Java code that you need.How about the  Plugin for Eclipse. I have used it and I find it to be quite useful. Although if you are generating diagrams for large sources, you might have to start Eclipse with more memory.
Java

Does somebody know of a tutorial or an example of how to implement the standard  with s? In other words, is it possible to put a standard search with a  in a Fragment?In short, you can't. There are a couple of reasons why creating a search interface within a  is not possible.That being said, it doesn't seem like it would be too difficult to achieve something similar to what you are describing. For instance, you might consider implementing your searchable-Activity so that it will accept the  intent and (instead of immediately displaying the results in a , for example) will pass the search query to your s. For instance, consider the following searchable Activity:When a search-request is made, the system will launch your searchable activity, perform the query, and will pass the results to some container Activity (based on your implementation of ). The container Activity will then pass these results to the contained searchable , in which the results will be displayed. The implementation requires a bit more work than what you were probably hoping for, but I'm sure there are ways that you can make it more modular, and it seems like this might be the best that you can do.p.s. If you use this approach, you might have to pay special attention to which Activitys are added/removed to the backstack. See this  for some more information on how this might be done.p.p.s. You might also forget about the standard search interface completely and just implement a simple search within a  as described in .Here is the example to search something using fragments. Hope it helps and this is what you are looking for:It is quite possible to search in a fragment using the standard ActionBar SearchView ActionView API. This will work back to Android 2.1 (API level 7) too using AppCompat support classes v7. In your fragment:In your menu XMLUsing AppCompat support classes v7. Just adding something to  's solution from  solution to get it work properly in a simple manner, here is my fragment code::I added the , cuz without calling  the system will not know that this fragment needs to interact with the menu.then I removed the line  because it doubled the menu items since Activity inflated a menu, then Fragment inflated another menuThanks to @David and @Rookie When working with  you still need to use an  to control and assign the .\nThis  can have search functionality as before.I've recently switched from a 'normal'  based app, to a  based app and the search functionality worked just the same for me.Have you tried working on it, and didn't succeed? If so give some more detail in your question.EDIT:If you want to have a fragment specific search, have all your  extend an interface  with a  method, and have your 's  method call the current fragment's  method.I think I achieved it : you can actually use fragments and add a search icon to an action bar so that a search is possible inside the fragments. The trick is to use an action bar, an action view, a listener for it, a loader and an adapter of course. This works pretty well although it completely bypasses the android platform search mechanism (but it could be completed with some work to find what @Alex Lockwood describes and pass the search to fragments). It would not react to an intent as expected in the case of an activity, but it works : users can search inside fragments. Here is the code : The xml file for the menu of the search fragments res/menu/menu_search.xml: And the xml layout file res/layout/search_in_fragments.xmlUse the  and . You will be able to handle searches without any connection to Activity. Just set an  to the SearchView.See  post for more details on custom search.A  cannot exist outside an , nor can a  be linked to a  or any other .So without using an  to wrap the the , what you're asking is not possible.In case of Fragments into a ViewPager, I could do it by blocking the search button when I'm not on the fragment where I want to give a search bar. Into the activity: And in case of no physical search button, I added an action item into the fragment, which trigger this code:yes its  possible, please implements Search view on your Activity ,'onQueryTextChange' in  Activity will also listen the  search in  fragment, you can check the fragment    visibility in  'onQueryTextChange' , if it visible you  can call  your search method for fragment, its  working  perfect in  my  codei found a work around :)\nyou can override this method (startActivity(Intent) ) in your BaseActivity and then check if the action is ACTION_SEARCH then do your special job :Dothers solution..... i dont like that.\nThis more easy for me.But its  my idea.Im waiting yours opinion
Java

How can I use a servlet filter to change an incoming servlet request url fromto?: according to BalusC's steps below, I came up with the following code:The relevant entry in  look like this:I tried both server-side and client-side redirect with the expected results. It worked, thanks BalusC!Don't forget to add a check in the code if the URL  to be changed and if , then just call , else it will call itself in an infinite loop.Alternatively you can also just use an existing 3rd party API to do all the work for you, such as  which can be configured the way as you would do with Apache's .You could use the ready to use  with a rule like this one:Check the  for more... examples.Please note that if your original URL contains parameters, i.e. ? then these parameters will be also forwarded to next servlet/jsp.\nI didn't find a way to get rid of or replace original parameters (only by using HttpServletRequestWrapper). Any ideas?..Update: it seems that  addresses this problem.A simple JSF Url Prettyfier filter based in the steps of . The filter forwards all the requests starting with the /ui path (supposing you've got all your xhtml files stored there) to the same path, but adding the xhtml suffix.
Java

I have a loop that looks something like this:This is the main content of a method whose sole purpose is to return the array of floats. I want this method to return  if there is an error, so I put the loop inside a  block, like this:But then I also thought of putting the  block inside the loop, like this:Is there any reason, performance or otherwise, to prefer one over the other? The consensus seems to be that it is cleaner to put the loop inside the try/catch, possibly inside its own method. However, there is still debate on which is faster. Can someone test this and come back with a unified answer?PERFORMANCE:There is absolutely no performance difference in where the try/catch structures are placed. Internally, they are implemented as a code-range table in a structure that is created when the method is called. While the method is executing, the try/catch structures are completely out of the picture unless a throw occurs, then the location of the error is compared against the table.Here's a reference: The table is described about half-way down.: as  said in his reply, in Java it doesn't make much difference., for readability of the code, your choice of where to catch the exception depends upon whether you want the loop to keep processing or not.  In your example you returned upon catching an exception.  In that case, I'd put the try/catch around the loop.  If you simply want to catch a bad value but carry on processing, put it inside.  : You could always write your own static ParseFloat method and have the exception handling dealt with in that method rather than your loop.  Making the exception handling isolated to the loop itself!All right, after  that there was no performance difference (as of 1997), I went and tested it. I ran this small benchmark:I checked the resulting bytecode using javap to make sure that nothing got inlined.The results showed that, assuming insignificant JIT optimizations, ; there is absolutely  (I did not have access to other versions). The total time difference is on the order of a few milliseconds over the entire test.Therefore, the only consideration is what looks cleanest. I find that the second way is ugly, so I will stick to either the first way or .I agree with all the performance and readability posts.  However, there are cases where it really does matter.  A couple other people mentioned this, but it might be easier to see with examples.Consider this slightly modified example:If you want the parseAll() method to return null if there are any errors (like the original example), you'd put the try/catch on the outside like this:In reality, you should probably return an error here instead of null, and generally I don't like having multiple returns, but you get the idea.On the other hand, if you want it to just ignore the problems, and parse whatever Strings it can, you'd put the try/catch on the inside of the loop like this:As already mentioned, the performance is the same.  However, user experience isn't necessarily identical.  In the first case, you'll fail fast (i.e. after the first error), however if you put the try/catch block inside the loop, you can capture all the errors that would be created for a given call to the method.  When parsing an array of values from strings where you expect some formatting errors, there are definitely cases where you'd like to be able to present all the errors to the user so that they don't need to try and fix them one by one.If its an all-or-nothing fail, then the first format makes sense.  If you want to be able to process/return all the non-failing elements, you need to use the second form.  Those would be my basic criteria for choosing between the methods.  Personally, if it is all-or-nothing, I wouldn't use the second form.As long as you are aware of what you need to accomplish in the loop you could put the try catch outside the loop. But it is important to understand that the loop will then end as soon as the exception occurs and that may not always be what you want. This is actually a very common error in Java based software. People need to process a number of items, such as emptying a queue, and falsely rely on an outer try/catch statement handling all possible exceptions. They could also be handling only a specific exception inside the loop and not expect any other exception to occur.\nThen if an exception occurs that is not handled inside the loop then the loop will be \"preemted\", it ends possibly prematurely and the outer catch statement handles the exception.If the loop had as its role in life to empty a queue then that loop very likely could end before that queue was really emptied.  Very common fault.While performance might be the same and what \"looks\" better is very subjective, there is still a pretty big difference in functionality. Take the following example:The while loop is inside the try catch block, the variable 'j' is incremented until it hits 40, printed out when j mod 4 is zero and an exception is thrown when j hits 20.Before any details, here the other example:Same logic as above, only difference is that the try/catch block is now inside the while loop. Here comes the output (while in try/catch):And the other output (try/catch in while):There you have quite a significant difference: while in try/catch breaks out of the looptry/catch in while keeps the loop activeIn your examples there is no functional difference.  I find your first example more readable.You should prefer the outer version over the inner version. This is just a specific version of the rule, move anything outside the loop that you can move outside the loop. Depending on the IL compiler and JIT compiler your two versions may or may not end up with different performance characteristics.On another note you should probably look at float.TryParse or Convert.ToFloat.If you put the try/catch inside the loop, you'll keep looping after an exception.  If you put it outside the loop you'll stop as soon as an exception is thrown.setting up a special stack frame for the try/catch adds additional overhead, but the JVM may be able to detect the fact that you're returning and optimize this away.depending on the number of iterations, performance difference will likely be negligible.However i agree with the others that having it outside the loop make the loop body look cleaner.If there's a chance that you'll ever want to continue on with the processing rather than exit if there an invalid number, then you would want the code to be inside the loop.If it's inside, then you'll gain the overhead of the try/catch structure N times, as opposed to just the once on the outside.Every time a Try/Catch structure is called it adds overhead to the execution of the method. Just the little bit of memory & processor ticks needed to deal with the structure.  If you're running a loop 100 times, and for hypothetical sake, let's say the cost is 1 tick per try/catch call, then having the Try/Catch inside the loop costs you 100 ticks, as opposed to only 1 tick if it's outside of the loop.The whole point of exceptions is to encourage the first style: letting the error handling be consolidated and handled once, not immediately at every possible error site.put it inside.  You can keep processing (if you want) or you can throw a helpful exception that tells the client the value of myString and the index of the array containing the bad value. I think NumberFormatException will already tell you the bad value but the principle is to place all the helpful data in the exceptions that you throw.  Think about what would be interesting to you in the debugger at this point in the program.  Consider: In the time of need you will really appreciate an exception like this with as much information in it as possible.I's like to add my own  about two competing considerations when looking at the general problem of where to position exception handling:That depends on the failure handling. If you just want to skip the error elements, try inside:In any other case i would prefer the try outside. The code is more readable, it is more clean. Maybe it would be better to throw an IllegalArgumentException in the error case instead if returning null.I'll put my $0.02 in.  Sometimes you wind up needing to add a \"finally\" later on in your code (because who ever writes their code perfectly the first time?).  In those cases, suddenly it makes more sense to have the try/catch outside the loop.  For example:Because if you get an error, or not, you only want to release your database connection (or pick your favorite type of other resource...) once.Another aspect not mentioned in the above is the fact that every try-catch has  impact on the stack, which can have implications for recursive methods.If method \"outer()\" calls method \"inner()\" (which may call itself recursively), try to locate the try-catch in method \"outer()\" if possible.  A simple \"stack crash\" example we use in a performance class fails at about 6,400 frames when the try-catch is in the inner method, and at about 11,600 when it is in the outer method.In the real world, this can be an issue if you're using the Composite pattern and have large, complex nested structures.
Java

Consider the following example.Now, in Java, String objects are immutable. Then how come the object  can be assigned value \"Help!\". Isn't this contradicting the immutability of strings in Java? Can anybody please explain me the exact concept of immutability?Edit:Ok. I am now getting it, but just one follow-up question. What about the following code: Does this mean that two objects are created again (\"Mississippi\" and \"M!ss!ss!pp!\") and the reference  points to a different object after  method?  is not an object, it's a reference to an object.  and  are two distinct  objects. Thus,   a string. You can change what it , but not that which it .Take this code, for example:Now, there is nothing we could do to  that would affect the value of . They refer to the same object - the string  - but that object is immutable and thus cannot be altered. If we do something like this:Here we see the difference between mutating an object, and changing a reference.  still points to the same object as we initially set  to point to. Setting  to  only changes the , while the  object it originally referred to remains unchanged. If strings  mutable, we could do something like this: If you look at the  (also available in src.zip in your JDK installation directory -- a pro tip is to look there whenever you wonder how something really works) you can see that what it does is the following:So yes,  creates a new  object. Again, the following holds:Your homework for now is to see what the above code does if you change  to  :) Actually, it  possible to mutate strings (and other immutable objects). It requires reflection and is very, very dangerous and should never ever be used unless you're actually interested in destroying the program.The object that  references can change, but the actual  objects themselves cannot.The  objects containing the string  and  cannot change their values, hence they are immutable.The immutability of  objects does not mean that the references pointing to the object cannot change.One way that one can prevent the  reference from changing is to declare it as :Now, trying to assign another  to  will cause a compile error.Light_handle I recommend you take a read of  and . This will help a lot when reading the posts above. Have you read them? Yes. Good. This creates a new \"remote control\" called \"\" and sets that to the value  (or ).e.g. in memory this creates:This then changes the remote control \"\" but does not modify the original string .e.g. in memory this creates:This then changes the remote control \"\" but does not modify the original string  or the object that the remote control currently points to.e.g. in memory this creates:The string object that was first referenced by  was not altered, all that you did was make  refer to a new string object.Lets break it into some partsThis Statement creates string containing  and occupy space in memory i.e. in  and and assigned it to reference object This statement assigns the same string  to new reference Both references are pointing to the same string so output the same value as follows.Though  is , assignment can be possible so the  will now refer to new value .But what about  object which is pointing to  it will be as it is.Since String is immutable  by its method. It will create all new String object in pool as follows.Note if String would be mutable then the output would have been Now you might be surprised why String has such methods like  to modify. Following snippet will clear your confusion.    Here we are assigning modified value of string back to  reference.That's why Java decided  Otherwise anyone can modify and change the value of string.\nHope this will help little bit.The String will not change, the reference to it will.  You are confusing immutability with the concept of  fields.  If a field is declared as , once it has been assigned, it cannot be reassigned.Regarding the replace part of your question, try this:Immutability implies that the value of an instantiated object cannot change, you can never turn \"Hello\" into \"Help!\".The variable str is a reference to an object, when you assign a new value to str you aren't changing the value of the object it references, you are referencing a different object.Though java tries to ignore it,  is nothing more than a pointer. This means that when you first write , you create an object that  points to. When you reassign  by writing , a new object is created and the old  object gets garbage collected whenever java feels like it.String class is immutable, and you can not change value of immutable object.\nBut in case of String, if you change the value of string than it will create new string in string pool and than your string reference to that value not the older one. so by this way string is immutable.\nLets take your example,it will create one string  and will add it to String pool\nso now str is pointing to Mississippi.But after above operation,\none another string will be created \nand it will be add to String pool. and \nnow str is pointing to M!ss!ss!pp!, not Mississippi.so by this way when you will alter value of string object it will create one more object and will add it to string pool.Lets have one more example this above three line will add three objects of string to string pool.\n1) Hello\n2) World\n3) HelloWorldUse:If you see here I use the  method to change the original string, that is, \"New String\" with a string \" Added String\", but still I got the output as previous, hence it proves that you can not change the reference of object of String class, but if you do this thing by StringBuilder class it will work. It is listed below.Like Linus Tolvards said:Take a look at this:The output isSo, remember two things:For those wondering how to break String immutability in Java... is . Which means that we can only change the .In Java, objects are generally accessed by references. In your piece of code str is a reference which is first assigned to \"Hello\" (an automatic created object or fetched from ) and then you assigned another object \"Help!\" to same reference. A point to note is the reference is the same and modified, but objects are different. One more thing in your code you accessed three objects,Calling new String() creates a new object even if it exists in string pool, so generally it should not be used. To put a string created from new String () into string pool you can try the  method.I hope this helps.Immutability I can say is that you cannot change the String itself. Suppose you have String x, the value of which is \"abc\". Now you cannot change the String, that is, you cannot change any character/s in \"abc\".If you have to change any character/s in the String, you can use a character array and mutate it or use StringBuilder.Output:Or you can try:This will show how the hashcode changes.
Java

What is the difference between  and  while handling special characters?  was accepted by  as space. In case of ,  was accepted as .If URL  gets the invoices for user 1234 on December 5th, 2013, the controller method would look like:Also, request parameters can be optional, but path variables cannot--if they were, it would change the URL path hierarchy and introduce request mapping conflicts. For example, would  provide the invoices for user  or details about a user with ID \"invoices\"? annotation used for accessing the query parameter values from the request. Look at the following request URL:In the above URL request, the values for param1 and param2 can be accessed as below:The following are the list of parameters supported by the @RequestParam annotation:@ identifies the pattern that is used in the URI for the incoming request. Let\u2019s look at the below request URL:The above URL request can be written in your Spring MVC as below:The @ annotation has only one attribute value for binding the request URI template. It is allowed to use the multiple @ annotation in the single method. But, ensure that no more than one method has the same pattern.Also there is one more interesting annotation:\nAnd the Controller method for itBut you must enable:it may be that the application/x-www-form-urlencoded midia type convert space to , and the reciever will decode the data by converting the  to space.check the url for more info.
Java

How do you define Global variables in Java  ? To define Global Variable you can make use of static Keywordnow you can access a and b from anywhere\nby callingYou don't. That's by design. You shouldn't do it even if you could. That being said you could create a set of public static members in a class named Globals. but you really shouldn't :). Seriously .. don't do it. Another way is to create an interface like this:Any class that needs to use them only has to implement the interface:You are better off using dependency injection:Truly speaking there is not a concept of  in a java OO programNevertheless there is some truth behind your question because there will be some cases where you want to run a method at any part of the program.\nFor example---random() method in Phrase-O-Matic app;it is a method should be callable from anywhere of a program.So in order to satisfy the things like Above \"We need to have Global-like variables and methods\".Because I declared global variables and method as static you can call them anywhere you wish by simply with the help of following codeClassName.X: X can be either method name or variable name as per the requirement and ClassName is the name of the class in which you declared them.Nothing should be global, except for constants.Put this within your main class.  In other .java files, use it through:Make sure when you move your code off the cutting room floor and into release you remove or comment out this functionality.If you have a workhorse method, like a randomizer, I suggest creating a \"Toolbox\" package!  All coders should have one, then whenever you want to use it in a .java, just import it!Lots of good answers, but I want  to give this example as it's considered the more proper way to access variables of a class by another class using getters and setters. The reason why you use getters and setters this way instead of just making the variable public is as follows. Lets say your var is going to be a global parameter that you NEVER want someone to change during the execution of your program(in the case when you are developing code with a team), something like maybe the URL for a website. In theory this could change and may be used many times in your program, so you want to use a global var to be able to update it all at once. But you do not want someone else to go in and change this var(possibly without realizing how important it is). In that case you simply do not include a setter method, and only include the getter method.There is no such thing as a truly global variable in Java.  Every static variable must belong to some class (like System.out), but when you have decided which class it will go in, you can refer to it from everywhere loaded by the same classloader.Note that static variables should always be protected when updating to avoid race conditions.One, There is no global variable in JavaTwo, What we do have is a 'static' keyword and that is all what we need.\nNothing exists outside of class in Java. The static keyword represents a class variable that on the contrary to instance variable only has one copy and that transcends across all the instances of that class created, which means that its value can be changed and accessed across all instances at any point. If you need a global variable which can be accessed beyond scopes, then this is the variable that you need, but its scope exists only where the class is, and that will be all.This way you can access them with  and you can call anywhere you want:As you probably guess from the answer there is no global variables in Java and the only thing you can do is to create a class with static members:You can use it with  elsewhere. However if you use Java 1.5 or better you can use the  magic to make it look even more as a real global variable:And !Now this is far from a best practice so as you can see in the commercials: There are no global variables in Java, but there are global classes with public fields. You can use static import feature of java 5 to make it look almost like global variables.Going by the concept, global variables, also known as instance variable are the class level variables,i.e., they are defined inside a class but outside methods. In order to make them available completely and use them directly provide the static keyword. \nSo if i am writing a program for simple arithmetical operation and it requires a number pair then two instance variables are defined as such:Moreover using static keyword prior to the instance variables enable us not to specify datatypes for same variables again and again. Just write the variable directly.Generally Global variable (I assume you are comparing it with C,Cpp) define as likeENUMs are also useful in such scenario :For Example  )In general,the Java programming doesn't have any global variables .Since other than the local variables all are comes under the scope of any class defined in the program.\nWe can have the static variable to have the scope of global variables.Creating an independent file, eg. Example.java to use the 1st solution, is just fine. You can do that also within the app, if e.g. the global variables are special to your current app, etc.:Create a class at the beginning and declare your variables in there:You can then access these variables -- using them as 'Globals.month_number', etc. -- from averywhere in your app.To define Global Variable you can make use of static Keywordnow you can access a and b from anywhere by callingYoy are right...specially in J2ME...\n  You can avoid NullPointerException by putting inside your MidLet constructor\n(proggy initialization) this line of code:This ensures that Tools will be allocated before any instruction\nthat uses it.That's it!
Java

In an attempt to fully understand how to solve Java's multiple inheritance problems I have a classic question that I need clarified.Lets say I have class  this has sub classes  and  and I need to make a class  that extends from  and  since  is both a bird and a horse.I think this is the classic diamond problem. From what I can understand the classic way to solve this is to make the ,  and  classes interfaces and implement  from them. I was wondering if there was another way to solve the problem in which I can still create objects for birds and horses. If there was a way to be able to create animals also that would be great but not necessary.You could create interfaces for animal classes (class in the biological meaning), such as  for horses and  for birds (I'm no biologist, so the terms may be wrong).Then you can still create a and and alsoIn order to reduce duplicate code, you could create an abstract class that contains most of the common code of the animals you want to implement.I'd like to add one more detail. As , this is something the OP already knew. However, I want to emphasize, that I suggest to bypass the \"multi-inheritance\" problem with interfaces and that I don't recommend to use interfaces that represent already a concrete type (such as Bird) but more a behavior (others refer to duck-typing, which is good, too, but I mean just: the biological class of birds, Avialae). I also don't recommend to use interface names starting with a capital 'I', such as , which just tells nothing about why you need an interface. That's the difference to the question: construct the inheritance hierarchy using interfaces, use abstract classes when useful, implement concrete classes where needed and use delegation if appropriate.There are two fundamental approaches to combining objects together:The way this works is that you have an Animal object. Within that object you then add further objects that give the properties and behaviors that you require.For example:Now  just looks like this:So  looks like this:Now you have all the advantages of Inheritance. You can re-use code. You can have a collection of IFliers, and can use all the other advantages of polymorphism, etc.However you also have all the flexibility from Composition. You can apply as many different interfaces and composite backing class as you like to each type of  - with as much control as you need over how each bit is set up.An alternative approach depending on what and how you are doing is to have the  base class contain an internal collection to keep the list of different behaviors. In that case you end up using something closer to the Strategy Pattern. That does give advantages in terms of simplifying the code (for example  doesn't need to know anything about  or ) but if you don't also do the interface approach you lose a lot of the advantages of polymorphism, etc.I have a stupid idea:May I suggest the concept of ?Most likely you would tend to make the Pegasus extend a Bird and a Horse interface but duck typing actually suggests that you should rather inherit . As already stated in the comments, a pegasus is not a bird but it can fly. So your Pegasus should rather inherit a -interface and lets say a -interface.This kind of concept is utilized in the . The given example actually shows you how a duck inherits the  and  and still there can be ducks, e.g. the , which can't fly. They could have also made the  extend a -class but then they would have given up some flexibility, because every  would be able to fly, even the poor .Technically speaking, you can only extend one class at a time and implement multiple interfaces, but when laying hands on software engineering, I would rather suggest a problem specific solution not generally answerable. By the way, it is good OO practice,  to extend concrete classes/only extend abstract classes to prevent unwanted inheritance behavior - there is no such thing as an \"animal\" and no use of an animal object but only concrete animals.It is safe to keep a horse in a stable with a half door, as a horse cannot get over a half door.   Therefore I setup a horse housing service that accepts any item of type horse and puts it in a stable with a half door.So is a horse like animal that can fly even a horse?I used to think a lot about multiple inheritance, however now that I have been programming for over 15 years, I no longer care about implementing multiple inheritance.More often than not, when I have tried to cope with a design that pointed toward multiple inheritance, I have later come to release that I had miss understood the problem domain.ORIn Java 8, which is still in the development phase as of February 2014, you could use  to achieve a sort of C++-like multiple inheritance.\nYou could also have a look at  which shows a few examples that should be easier to start working with than the official documentation.Java does not have a Multiple inheritance problem, since it does not have multiple inheritance. This is by design, in order to solve the real multiple inheritance problem (The diamond problem).There are different strategies for mitigating the problem. The most immediately achievable one being the Composite object that Pavel suggests (essentially how C++ handles it). I don't know if multiple inheritence via C3 linearization (or similar) is on the cards for Java's future, but I doubt it.If your question is academic, then the correct solution is that Bird and Horse are more concrete, and it is false to assume that a Pegasus is simply a Bird and a Horse combined. It would be more correct to say that a Pegasus has certain intrinsic properties in common with Birds and Horses (that is they have maybe common ancestors). This can be sufficiently modeled as Moritz' answer points out.I think it depends very much on your needs, and how your animal classes are to be used in your code.If you want to be able to make use of methods and features of your Horse and Bird implementations inside your Pegasus class, then you could implement Pegasus as a  of a Bird and a Horse:Another possibility is to use an  approach instead of inheritance for defining your animals. Of course this means, that you will not have individual Java classes of the animals, but instead they are only defined by their components.Some pseudo code for an Entity-Component-System approach could look like this:you can have an interface hierarchy and then extend your classes from selected interfaces :and then define your classes as needed,  by extending a specific interface :Ehm, your class can be the subclass for only 1 other, but still, you can have as many interfaces implemented, as you wish. A Pegasus is in fact a horse (it is a special case of a horse), which is able to fly (which is the \"skill\" of this special horse). From the other hand, you can say, the Pegasus is a bird, which can walk, and is 4legged - it all depends, how it is easier for you to write the code.Like in your case you can say:Interfaces don't simulate multiple inheritance. Java creators considered multiple inheritance wrong, so there is no such thing in Java.If you want to combine the functionality of two classes into one - use object composition. I.e.And if you want to expose certain methods, define them and let them delegate the call to the corresponding controller.Here interfaces may come handy - if  implements interface  and  implements , you can defineSo that you can use objects interchangeably where the context allows it.So in my point of view, you can't get into diamond problem.As you will already be aware, multiple inheritance of classes in Java is not possible, but it's possible with interfaces. You may also want to consider using the composition design pattern.I wrote a very comprehensive article on composition a few years ago...To reduce the complexity and simplify the language, multiple inheritance is not supported in java.Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B classes have same method and you call it from child class object, there will be ambiguity to call method of A or B class.Since compile time errors are better than runtime errors, java renders compile time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error now.To solve the problem of mutiple inheritance in Java \u2192 interface is usedHave a look at below example for better understanding
Java

I want to print something in console, so that I can debug it.  But for some reason, nothing prints in my Android application.  How do I debug then?\nOn the emulator and most devices  gets redirected to LogCat and printed using . This may not be true on very old or custom Android versions. \nThere is no console to send the messages to so the  messages get lost.  In the same way this happens when you run a \"traditional\" Java application with .Instead, you can use the :You can then view the log either in the  view in Eclipse, or by running the following command:It's good to get in to the habit of looking at logcat output as that is also where the Stack Traces of any uncaught Exceptions are displayed.The first Entry to every logging call is the log tag which identifies the source of the log message.  This is helpful as you can filter the output of the log to show just your messages.  To make sure that you're consistent with your log tag it's probably best to define it once as a  somewhere.There are five one-letter methods in  corresponding to the following levels:The :Use the  . Output visible with LogCatYes it does. If you're using the emulator, it will show in the Logcat view under the  tag. Write something and try it in your emulator.Of course, to see the result in logcat, you should set the Log level at least to \"Info\" (); otherwise, as it happened to me, you won't see your output.There is no place on your phone that you can read the Instead, if you want to see the result of something either look at your  window or make a  or a  (if you're on a newer device) appear on the device's screen with the message :) \nThat's what i do when i have to check for example where it goes in a  code! Have fun coding! :)if you really need System.out.println to work(eg. it's called from third party library). you can simply use reflection to change out field in System.class:RedirectLogOutputStream class:
Java

I have a very big program that is currently using SWT. The program can be run on both Windows, Mac and Linux, and it is a big desktop application with many elements.\nNow SWT being somewhat old I would like to switch to either Swing or JavaFX. And I would like to hear your thoughts on three things.My main concern is what will be better for a desktop GUI application? (I looked online and a lot of people suggest that JavaFX is just as good as Swing, but I didn't see many valid arguments except simple opinion flame wars). It has to work on both Windows, Mac and some popular Linux distributions.I am using MVC methology in my application, if that is of any help.All things being equal, probably JavaFX - the API is much more consistent across components. However, this depends much more on  rather than .Highly dependent on what you're building. Swing has more components around for it (3rd party as well as built in) and not all of them have made their way to the newer JavaFX platform yet, so there may be a certain amount of re-inventing the wheel if you need something a bit custom. On the other hand, if you want to do transitions / animations / video stuff then this is orders of magnitude easier in FX.One other thing to bear in mind is (perhaps) look and feel. If you absolutely must have the default system look and feel, then JavaFX (at present) can't provide this. Not a big must have for me (I prefer the default FX look anyway) but I'm aware some policies mandate a restriction to system styles.Personally, I see JavaFX as the \"up and coming\" UI library that's not  there yet (but more than usable), and Swing as the borderline-legacy UI library that's fully featured and supported for the moment, but probably won't be so much in the years to come (and therefore chances are FX will overtake it at some point.)As stated by Oracle, JavaFX is the next step in their Java based rich client strategy.\nAccordingly, this is what I recommend for your situation:For more info, please take a look these FAQ post by Oracle regarding JavaFX here.I am using javafx for the first time in a non-production recreational app, and there it is fine. It has not production quality IMHO.Example: one needs tricks, work-arounds in some cases, like right-alignment of a column in a TableView may take an extra effort. The usage of callbacks using callbacks is a bit overdone.On the other hand, there are nice effects and extras like HTMLEditor. Switching the application language is easier (simply rebuild the scene). In Java 8 javafx should be more pallatable (callbacks), and ripened.If you cannot wait, go for swing. It is rock-solid.\nYou could opt for the NetBeans Platform RCP, but that takes learning or commercial support. There is effort to port part of the NetBeans Platform to javafx, also in a hybrid version.Last but not least, one may combine both, running javafx inside a swing app.No one has mentioned it, but JavaFX does not compile or run on certain architectures deemed \"servers\" by Oracle (e.g. Solaris), because of the missing \"jfxrt.jar\" support. Stick with SWT, until further notice.I don't think there's any one right answer to this question, but my advice would be to stick with SWT unless you are encountering severe limitations that require such a massive overhaul. Also, SWT is actually newer and more actively maintained than Swing. (It was  as a replacement for Swing using native components).I'd look around to find some (3rd party?) components that do what you want. I've had to create custom Swing components for an agenda view where you can book multiple resources, as well as an Excel-like grid that works well with keyboard navigation and so on. I had a terrible time getting them to work nicely because I needed to delve into many of Swing's many intricacies whenever I came upon a problem. Mouse and focus behaviour and a lot of other things can be very difficult to get right, especially for a casual Swing user. I would hope that JavaFX is a bit more future-orientated and smooth out of the box.On older notebooks with integrated video Swing app starts and works much faster than JavaFX app. As for development, I'd recommend switch to Scala - comparable Scala Swing app contains 2..3 times less code than Java.\nAs for Swing vs SWT: Netbeans GUI considerably faster than Eclipse...
Java

I have this little crazy method that converts BigDecimal values into nice and readable Strings.It however, also produces a so called grouping separator  that makes all my values come out like this:I do need the separator to be a dot or a point and not a comma. \nDoes anybody have a clue of how to accomplish this little feat?I have read  and in particular  to death now but I cannot find a way to get this done.\nAm I approaching this the wrong way? Is there a much more elegant way of doing this? Maybe even a solution that accounts for different local number representations, since the comma would be perfect by European standards.You can change the separator either by setting a locale or using the .If you want the grouping separator to be a point, you can use an european locale:Alternatively you can use the DecimalFormatSymbols class to change the symbols that appear in the formatted numbers produced by the format method. These symbols include the decimal separator, the grouping separator, the minus sign, and the percent sign, among others:Europe is quite huge. I'm not if they use the same format all over. However  or  answer will be of helpi.e use the correct locale BigDecimal does not seem to respect Locale settings.Slovenian locale should have a decimal comma. Guess I had strange misconceptions regarding numbers.I have edited a part of my message that made no sense since it proved to be due the human error (forgot to commit data and was looking at the wrong thing).Same as BigDecimal can be said for any Java .toString() functions. I guess that is good in some ways. Serialization for example or debugging. There is an unique string representation.Also as others mentioned using formatters works OK. Just use formatters, same for the JSF frontend, formatters do the job properly and are aware of the locale.
Java

Could you explain what  does when invoked? sets the interrupted status/flag of the target thread.  Then code running in that target thread MAY poll the interrupted status and handle it appropriately.  Some methods that block such as  may consume the interrupted status immediately and throw an appropriate exception (usually )Interruption in Java is not pre-emptive.  Put another way both threads have to cooperate in order to process the interrupt properly.  If the target thread does not poll the interrupted status the interrupt is effectively ignored.Polling occurs via the  method which returns the current thread's interrupted status AND clears that interrupt flag.  Usually the thread might then do something such as throw InterruptedException.EDIT (from Thilo comments):  Some API methods have built in interrupt handling.  Of the top of my head this includes.EDIT (from 's answer to  for completeness)Thread interruption is a gentle way to nudge a thread. It is used to give threads a chance to exit , as opposed to  that is more like shooting the thread with an assault rifle.Check this out for complete understanding about same :If the targeted thread has been waiting (by calling , or some other related methods that essentially do the same thing, such as ), it will be interrupted, meaning that it stops waiting for what it was waiting for and receive an InterruptedException instead.It is completely up to the thread itself (the code that called ) to decide what to do in this situation. It does not automatically terminate the thread.It is sometimes used in combination with a termination flag. When interrupted, the thread could check this flag, and then shut itself down. But again, this is just a convention.For completeness, in addition to the other answers, , as the following example shows.Output:Implication: if you loop like the following, and the interrupt occurs at the exact moment when control has left  and is going around the loop, the exception is still going to occur. :Interrupts this thread.Unless the current thread is interrupting itself, which is always permitted, the checkAccess method of this thread is invoked, which may cause a SecurityException to be thrown.If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a ClosedByInterruptException.If this thread is blocked in a Selector then the thread's interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector's wakeup method were invoked.If none of the previous conditions hold then this thread's interrupt status will be set.Interrupting a thread that is not alive need not have any effect.Throws:\n    SecurityException - if the current thread cannot modify this thread sets the interrupted status/flag of the target thread to true which when checked using  can help in stopping the endless thread. Refer An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate.\nA very good referance: 
Java

I'm a web developer at day and thinking about building my first real desktop application. The idea is to build a tool that automates a very repetitive task in a web application where no API is available.I know I want to use Java. I used it before for web stuff, know the syntax pretty well  and want the application to be cross plattform as easy as possible. Where I'm not so sure is if I should use SWT or Swing. As my main audience uses Windows, I want to look it as native as possible there. Linux and Mac should work, but the looks are not so important here.So what are the arguments for and against each UI Framework, Swing or SWT?Thanks.PS: I develop on Windows using Eclipse. But was thinking about playing with Netbeans.An important thing to consider is that some users and some resellers (Dell) install a 64 bit VM on their 64 bit Windows, and you can't use the same SWT library on 32 bit and 64 bit VMs.This means you will need to distribute and test different packages depending on whether users have 32-bit or a 64-bit Java VM. See  with Azureus, for instance, but you also have it with Eclipse, where as of today the builds on the front download page do not run on a 64 bit VM. pro swing:But at the bottom line I wouldn't suggest to use 'pure' swing or swt ;-)\nThere are several application frameworks for swing/swt out. .\nThe biggest players are netbeans (swing) and eclipse (swt). Another nice framework could be griffon and a nice 'set of components' is pivot (swing). Griffon is very interesting because it integrates a lot of libraries and ; also pivot, swt, etcI would use Swing for a couple of reasons.If you want to build a very feature-rich application, you might want to check out the  (Rich Client Platform). There's a learning curve, but you can put together nice applications quickly with a little practice. I don't have enough experience with the Eclipse platform to make a valid judgment.If you don't want to use the entire RCP, NetBeans also has many useful components that can be pulled out and used independently.One other word of advice, look into different layout managers. They tripped me up for a long time when I was learning. Some of the best aren't even in the standard library. The  (for both Swing and SWT) and  Forms tools are two of the best in my opinion.I whould choose swing just because it's \"native\" for java.Plus, have a look at .For your requirements it sounds like the bottom line will be to use Swing since it is slightly easier to get started with and not as tightly integrated to the native platform as SWT.Swing usually is a safe bet.Interesting question. I don't know SWT too well to brag about it (unlike Swing and AWT) but here's the comparison done on SWT/Swing/AWT.And here's the site where you can get tutorial on basically anything on SWT ()Hope you make a right decision (if there are right decisions in coding)... :-)If you plan to build a full functional applications with more than a handful of features, I will suggest to jump right to using Eclipse RCP as the framework.If your application won't grow too big or your requirements are just too unique to be handled by a normal business framework, you can safely jump with Swing.At the end of the day, I'd suggest you to try both technologies to find the one suit you better. Like Netbeans vs Eclipse vs IntelliJ, there is no the absolute correct answer here and both frameworks have their own drawbacks.Pro Swing:Pro SWT:One thing to consider: ScreenreadersFor some reasons, some Swing components do not work well when using a screenreader (and the Java AccessBridge for Windows). Know that different screenreaders result in different behaviour. And in my experience the SWT-Tree performs a lot better than the Swing-Tree in combination with a screenreader. Thus our application ended up in using both SWT and Swing components.For distributing and loading the proper SWT-library, you might find this link usefull:\nSWT was created as a response to the sluggishness of Swing around the turn of the century. Now that the differences in performance are becoming negligable, I think Swing is a better option for your standard applications. SWT/Eclipse has a nice framework which helps with a lot of boiler plate code.
Java

Is there a way to compile multiple java source directories in a single maven project? You can add a new source directory with build-helperI naively do it this way :This worked for meto make it work in intelliJ, you can also addto maven-compiler-pluginThis also works with maven by defining the resources tag. You can name your src folder names whatever you like.Used the build-helper-maven-plugin from the post - and update src/main/generated.  And mvn clean compile works on my ../common/src/main/java, or on ../common, so kept the latter.  Then yes, confirming that IntelliJ IDEA (ver 10.5.2) level of the compilation failed as David Phillips mentioned.\nThe issue was that IDEA did not add another source root to the project.  Adding it manually solved the issue.  It's not nice as editing anything in the project should come from maven and not from direct editing of IDEA's project options.  Yet I will be able to live with it until they support build-helper-maven-plugin directly such that it will auto add the sources.Then needed another workaround to make this work though.  Since each time IDEA re-imported maven settings after a pom change me newly added source was kept on module, yet it lost it's Source Folders selections and was useless.  So for IDEA - need to set these once:Now keeping those folders on import is not the best practice in the world either, ..., but giving it a try.This can be done in two steps:If you work with started jetty (jetty:run), then recompilation of any class in any module (with Maven, IDEA or Eclipse) will lead to jetty's restart. The same behavior you'll get for modified resources.
Java

With Mockito, I want to  a method call with  in its argument list, but I didn't find how to write this.I just want something like , how to do that with Mockito ?I would try  Try this:    I would rather use . This worked for me.I agree with Mutanos and Alecio.\nFurther, one can check as many identical method calls as possible (verifying the subsequent calls in the production code, the order of the verify's does not matter).\nHere is the code:Or..You can use Mockito.any()  when arguments are arrays also.\nI used it like this:
Java

How do I get a  3.0 controller to trigger a 404?I have a controller with  and for some  accessing the controller, I want the container to come up with a 404.Since Spring 3.0 you also can throw an Exception declared with  annotation:Rewrite your method signature so that it accepts  as a parameter, so that you can call  on it.I would like to mention that there's exception (not only) for 404 by default provided by Spring. See  for details. So if you do not need your own exception you can simply do this:you can use the  to handle your Exceptions ,\nThe default behavior the @ControllerAdvice annotated class will assist all known Controllers.so it will be called when any Controller you have throws 404 error .like the following : and map this 404 response error in your web.xml , like the following : Hope that Helps . Since Spring 3.0.2 you can return  as a result of the controller's method:(ResponseEntity<T> is a more flexible than @ResponseBody annotation - see )If your controller method is for something like file handling then  is very handy:I'd recommend throwing , like thisYou must remember that this can be done only before anything is written to servlet output stream.While the marked answer is correct there is a way of achieving this without exceptions. The service is returning  of the searched object and this is mapped to  if found and to  404 if empty. Simply you can use web.xml to add error code and 404 error page. But make sure 404 error page must not locate under WEB-INF.This is the simplest way to do it but this have some limitation. Suppose if you want to add the same style for this page that you added other pages. In this way you can't to that. You have to use the Configure web.xml with settingCreate new controller 
Java

I keep finding both on here and Google people having troubles going from  to  and not the other way around. Yet I'm sure I'm not the only one that has run into this scenario before going from  to .The only other answers I've found were \"Just set it as Long in the first place\" which really doesn't address the question.Can someone help me out here? I initially tried casting but I get a \"\"As you can imagine I'm a little perplexed, I'm stuck using int since some content is coming in as an ArrayList and the entity for which I'm storing this info requires the sequence number as a Long.Thanks!Note that there is a difference between a cast to  and a cast to . If you cast to  (a primitive value) then it should be automatically boxed to a  (the reference type that wraps it).You could alternatively use  to create an instance of , initializing it with the  value.Use the following: .If you already have the int typed as an Integer you can do this:use orI have this little toy, that also deals with non generic interfaces.\nI'm OK with it throwing a ClassCastException if feed wrong (OK and happy)In Java you can do:in your case it would be: We shall get the long value by using  reference.It works for all number types, here is a test:I had a great deal of trouble with this. I just wanted to:Where IntervalCount is a Long, and the JSpinner was set to return a Long.  Eventually I had to write this function:which seems to do the trick.  No amount of simple casting, none of the above solutions worked for me.  Very frustrating.How About// Will not compile// Compiles, and retains the non-NULL spirit of int. The best  is .  Of course, your use case may require Long and possible NULL values.  But if the int, or other longs are your only input, and your method can be modified, I would suggest this approach. // Compiles, is the most efficient way, and makes it clear that the source value, is and will never be NULL. 
Java

I would like to be able to write a Java class in one package which can access non-public methods of a class in another package without having to make it a subclass of the other class. Is this possible?Lets say I have a class  and another class . They are in different packages (family) for hatred reasons. wants to   and  wants to only let   her.In C++,  would declare  as a (lover)  but there are no such things in java.Here are the classes and the trick :Ladies first :So the method  is  but you need a  to call it. It uses this  as a \"signature security\" to ensure that only  can call this method and simply calls  on it so the runtime will throw a  if it is .Now boys :The class  is public, but its constructor is . Therefore anyone can see it, but only  can construct it. I use a static reference so the  that is never used is only constructed once and does not impact optimization.Therefore,  can   and only he can because only he can construct and access a  instance, which is required by  to  her (or else she'll slap you with a ).The designers of Java explicitly rejected the idea of friend as it works in C++. You put your \"friends\" in the same package.  Private, protected, and packaged security is enforced as part of the language design.  James Gosling wanted Java to be C++ without the mistakes. I believe he felt that friend was a mistake because it violates OOP principles. Packages provide a reasonable way to organize components without being too purist about OOP.NR pointed out that you could cheat using reflection, but even that only works if you aren't using the SecurityManager. If you turn on Java standard security, you won't be able to cheat with reflection unless you write security policy to specifically allow it.The 'friend' concept is useful in Java, for example, to separate an API from its implementation. It is common for implementation classes to need access to API class internals but these should not be exposed to API clients. This can be achieved using the 'Friend Accessor' pattern as detailed below:The class exposed through the API:The class providing the 'friend' functionality:Example access from a class in the 'friend' implementation package:There are two solutions to your question that don't involve keeping all classes in the same package.  The first is to use the Friend Accessor/ pattern described in (Practical API Design, Tulach 2008).The second is to use OSGi.  There is an article  explaining how OSGi accomplishes this.  Related Questions: , , and .As far as I know, it is not possible.Maybe, You could give us some more details about Your design. Questions like these are likely the result of design flaws.Just considerI think that friend classes in C++ are like inner-class concept in Java. Using inner-classes\nyou can actually define an enclosing class and an enclosed one. Enclosed class has full access to the public and private members of it's enclosing class.\nsee the following link:\neirikma's answer is easy and excellent.  I might add one more thing:  instead of having a publicly accessible method, getFriend() to get a friend which cannot be used, you could go one step further and disallow getting the friend without a token: getFriend(Service.FriendToken).  This FriendToken would be an inner public class with a private constructor, so that only Service could instantiate one.Using ideas from the other answers, here I detail a clear use case example, ending with the reusable  class. The benefit of this mechanism is that only the friend class itself is allowed to be a friend, and not any sub-classes of it. Potentially making it safer.To begin, here is an example of how to use the  class.Then in another package you can do this:The  class is as follows. (You only need to write this code once, no need to copy it around.)The provided solution was perhaps not the simplest. Another approach is based on the same idea as in C++: private members are not accessible outside the package/private scope, except for a specific class that the owner makes a friend of itself. The class that needs friend access to a member should create a inner public abstract \"friend class\" that the class owning the hidden properties can export access to, by returning a subclass that implement the access-implementing methods. The \"API\" method of the friend class can be private so it is not accessible outside the class that needs friend access. Its only statement is a call to an abstract protected member that the exporting class implements. Here's the code:First the test that verifies that this actually works:Then the Service that needs friend access to a package private member of Entity:Finally: the Entity class that provides friendly access to a package private member only to the class application.service.Service. Okay, I must admit it is a bit longer than \"friend service::Service;\" but it might be possible to shorten it while retaining compile-time checking by using annotations. If you want to access protected methods you could create a subclass of the class you want to use that exposes the methods you want to use as public (or internal to the namespace to be safer), and have an instance of that class in your class (use it as a proxy).As far as private methods are concerned (I think) you are out of luck. I prefer delegation or composition or factory class (depending upon the issue that results in this problem) to avoid making it a public class. If it is a \"interface/implementation classes in different packages\" problem, then I would use a public factory class that would in the same package as the impl package and prevent the exposure of the impl class.If it is a \"I hate to make this class/method public just to provide this functionality for some other class in a different package\" problem, then I would use a public delegate class in the same package and expose only that part of the functionality needed by the \"outsider\" class.Some of these decisions are driven by the target server classloading architecture (OSGi bundle, WAR/EAR, etc.), deployment and package naming conventions. For example, the above proposed solution, 'Friend Accessor' pattern is clever for normal java applications. I wonder if it gets tricky to implement it in OSGi due to the difference in classloading style.See \nfor more info.In Java it is possible to have a \"package-related friendness\". \nThis can be userful for unit testing.\nIf you do not specify private/public/protected in front of a method, it will be \"friend in the package\".\nA class in the same package will be able to access it, but it will be private outside the class.This rule is not always known, and it is a good approximation of a C++ \"friend\" keyword.\nI find it a good replacement.I agree that in most cases the friend keyword is unnecessary.And finally, if it really is necessary, there is the friend accessor pattern mentioned in the other answers.Not using a keyword or so.You could \"cheat\" using reflection etc., but I wouldn't recommend \"cheating\".A method I've found for solving this problem is to create an accessor object, like so:The first code to call  \"claims ownership\" of the accessor. Usually, this is code that creates the object.This also has an advantage over C++'s friend mechanism, because it allows you to limit access on a  level, as opposed to a  level. By controlling the accessor reference, you control access to the object. You can also create multiple accessors, and give different access to each, which allows fine-grained control over what code can access what:Finally, if you'd like things to be a bit more organized, you can create a reference object, which holds everything together. This allows you to claim all accessors with one method call, as well as keep them together with their linked instance. Once you have the reference, you can pass the accessors out to the code that needs it:After much head-banging (not the good kind), this was my final solution, and I very much like it. It is flexible, simple to use, and allows very good control over class access. (The  access is very useful.) If you use protected instead of private for the accessors/references, sub-classes of Foo can even return extended references from . It also doesn't require any reflection, so it can be used in any environment.I think, the approach of using the friend accessor pattern is way too complicated. I had to face the same problem and I solved using the good, old copy constructor, known from C++, in Java:In your application you could write the following code:The advantage of this method is that only your application has access to the protected data. It's not exactly a substitution of the friend keyword. But I think it's quite suitable when you write custom libraries and you need to access protected data.Whenever you have to deal with instances of ProtectedContainer you can wrap your ProtectedAccessor around it and you gain access.It also works with protected methods. You define them protected in your API. Later in your application you write a private wrapper class and expose the protected method as public. That's it.I once saw a reflection based solution that did \"friend checking\" at runtime using reflection and checking the call stack to see if the class calling the method was permitted to do so. Being a runtime check, it has the obvious drawback.
Java

i am trying to integrate google sign in , in my app,i added these libraries:also add this to project build gradle:also add plugin to app build gradle:then add required permissions\nbut when i try to run my app , received this error:Try adding  to your app  file.Try Steve's  first. In case it happens frequently or first step didn't help  might help. For those who love to dig deeper here is couple similar issues (with more answers):  Another thing to watch for, is that you don't use That will import ALL the play services, and it'll only take little more than a hello world to exceed the 65535 method limit of a single dex APK.Always specify only the services you need, for instance: I just had to Clean my project and then it built successfully afterwards.This error began appearing for me when I added some new methods to my project. I knew that I was nowhere near the 65k method limit and did not want to enable multiDex support for my project if I could help it.I resolved it by increasing the memory available to the  task. I did this by specifying  in .I tried this after having had no success with other common solutions to this problem:Note: increasing the memory available to the DEX task can cause performance problems on systems with lower memory - . I also faced similar issue in Android Studio 1.5.1 and gradle 1.5.0.\nI just have to remove unwanted libraries from dependencies which may be automatically added in my app's build.gradle file.\nOne was :  compile 'com.google.android.gms:play-services:8.4.0'.\nSo for best practices try to only include specific play services library like for ads include onlyAlthoughthis will also solve the issue, but provides with a lot of Notes in gradle console, making it confusing to find the other real issues during buildI'm using AS 1.5.1 and encountered the same problem. But just cleaning the project just wont do, so I tried something.This worked with me, so I hope this helps.you can see the documentation of Manifest.xmlAt my case change buildToolsVersion from \"24\" to \"23.0.2\", solve the problem.I had same problem when i rolled back to old version via git, and that version had previous .jar library of one 3rd party api, and for some reason turned out that both jar of the same sdk, just different versions were in /libs folder. First Delete intermediates files\n  YOUR APP FOLDER\\app\\build\\intermediates\nOR\n  Clean your project and then rebuild.Thent add    i.e. It's work for meIn my case the Exception occurred because all google play service extensions are not with same version as followsIt worked when I changed this to  In build.gradle you need to add the next one.  Add the next one in local.properties  After that into Application class you need to add the Multidex too.  Don't forget add the line code into Manifest.xml That's it with this was enough for resolve the bug:\nExecution failed for task ':app:transformClassesWithDexForDebug. \n\nCheck very well into build.gradle with javaMaxHeapSize \"2g\" and the local.properties org.gradle.jvmargs=-Xmx2048m are of 2 gigabyte.If you are using the latest gradle version ie  , then try updating the latest support respository from the SDK manager and rebuild the entire project.If you need add this reference for cordova plugin add next line in your plugin.xml file.If the different dependencies have a same jar also cause this build error.For example:If \"library1\" and \"library2\" has a same jar named , this will make such an error.It happened to me because of Eclipse memory leak. I had to restart my computer.I changed a couple of pngs and the build number in the gradle and now I get this.  No amount of cleaning and restarting helped.  Disabling Instant Run fixed it for me.  YMMVI had the same option and as soon as I turned off Instant run, it worked fine on my API16 device, but on the API24 device it worked fine with Instant run. Hope this helps someone having the same issueSimply go to Build - Edit Build Types - Properties Tab - Build Type Version and downgrade it to ver 23.0.1. Click ok.\nThis works for android studio 1.5.\nIt worked for me.this code solved problemFor easiest way to implement google sign in visit: Also tryAlso keep same version number for different services.the write answer is in  put\ndefaultConfig {\n        multiDexEnabled true\n}\nthen  \nandroid:name=\"android.support.multidex.MultiDexApplication\"\nwish this answer is hellpful to some one
Java

I'm very new to Java EE and I'm trying to understand the concept of Local interfaces and Remote interfaces. I've been told that one of the big advantages of Java EE is that it is easy to scale (which I believe means you can deploy different components on different servers). Is that where Remote and Local interfaces come in? Are you supposed to use Remote interfaces if you expect your application to have different components on different servers? And use Local interfaces if your application is only going to reside on one server?If my assumptions above are correct, how would you go about choosing whether to use Local or Remote interfaces for a new application, where your unsure of what the volume of traffic would be? Start off by using Local interfaces, and gradually upgrade to Remote interfaces where applicable?Thanks for any clarification and suggestions.In the initial versions of the EJB specification, EJBs were \"assumed\" to be remote components and the only way to invoke them was to make a remote call, using RMI semantics and all the overhead it implies (a network call and object serialization for every method call). EJB clients had to pay this performance penalty even when collocated in the same virtual machine with the EJB container. Later, Sun realized most business applications were actually not distributing EJBs on a different tier and they fixed the spec (in EJB 2.0) by introducing the concept of Local interfaces so that clients collocated in the same virtual machine with the EJB container can call EJBs using direct method invocation, totally bypassing RMI semantics (and the associated overhead).Java EE can scale, but this doesn't necessarily means  components. You can run a Web+EJB application on a cluster without separating the Web tier and the EJB tier. I would phrase it like this: use remote interfaces if the client are not in the same JVM (this doesn't mean using only one server/JVM).I would probably start by using Local interfaces. And as already hinted, switching to remote interfaces is not always mandatory (you can cluster a  structure). I suggest to check the resources mentioned below (the 2 first ones are quite old but still relevant, the 2 others are more recent). While I agree with most of what is written above, I would like to refine the \"how to start\" ideas a bit.My suggestion to you is to never  program directly to EJB interfaces within your code. Always use a regular, business-oriented interface, program to it (meaning, have your code call methods on the business-oriented interface) and provide the EJB \"glue\" code as a pluggable implementation. Your program should be focused on business logic, and not on implementation details such as EJB.That way, you can easily switch between remote and local implementations - and if you use an IoC container such as Spring, you can do it by means of configuration only.A special note about switching from local to remote: note that there are a few semantic differences between the two. For example, calling an EJB method via its \"remote interface\" results in arguments being passed by-value, while calling through the \"local interface\" results in arguments being passed by-reference. This is a  difference; so if you \"start with local\", make sure that you design your system in a way that it takes \"remote\" semantics into consideration as well.If your design relies on EJB methods changing passed-in objects, then it would be tricky for you to \"switch to remote\" later; perhaps even impossible.Good luck.This may answers your concerns :Source: According to EJB Spec 3.2 an EJB can be either be  or . \nA business interface cannot be both local and remote at the same time.  annotated beans can only be accessed if they are in the same application. annotated beans can be accessed across different applications, residing in different jvms or across application servers.So the important things to keep in mind are:
Java

How do I pick a random element from a set?\nI'm particularly interested in picking a random element from a\nHashSet or a LinkedHashSet, in Java.\nSolutions for other languages are also welcome. A somewhat related Did You Know: There are useful methods in  for shuffling whole collections:  and .Fast solution for Java using an  and a : [element -> index].Motivation: I needed a set of items with  properties, especially to pick a random item from the set (see  method). Random navigation in a binary tree is not accurate: trees are not perfectly balanced, which would not lead to a uniform distribution.If you want to do it in Java, you should consider copying the elements into some kind of random-access collection (such as an ArrayList).  Because, unless your set is small, accessing the selected element will be expensive (O(n) instead of O(1)). [ed: list copy is also O(n)]Alternatively, you could look for another Set implementation that more closely matches your requirements.  The  from Commons Collections looks promising.This is faster than the for-each loop in the accepted answer:The for-each construct calls  on every loop, but since , that check is unnecessary overhead. I saw a 10-20% boost in speed, but YMMV. (Also, this compiles without having to add an extra return statement.)Note that this code (and most other answers) can be applied to any Collection, not just Set. In generic method form:Clojure solution:Can't you just get the size/length of the set/array, generate a random number between 0 and the size/length, then call the element whose index matches that number? HashSet has a .size() method, I'm pretty sure.In psuedocode -Perl 5Here is one way to do it.C++. This should be reasonably quick, as it doesn't require iterating over the whole set, or sorting it. This should work out of the box with most modern compilers, assuming they support . If not, you may need to use Boost.The  are helpful here to explain this, even if you don't use Boost.The trick is to make use of the fact that the data has been divided into buckets, and to quickly identify a randomly chosen bucket (with the appropriate probability).Solution above speak in terms of latency but doesn't guarantee equal probability of each index being selected.\nIf that needs to be considered, try reservoir sampling. . Collections.shuffle() (as suggested by few) uses one such algorithm.PHP, assuming \"set\" is an array:The Mersenne Twister functions are better but there's no MT equivalent of array_rand in PHP. has a set type and a random-element operator, unary \"?\", so the expressionwill produce a random number between 1 and 5.The random seed is initialized to 0 when a program is run, so to produce different results on each run use Javascript solution ;)Or alternatively:In lispIn Mathematica:Or, in recent versions, simply:This received a down-vote, perhaps because it lacks explanation, so here one is: generates a pseudorandom float between 0 and 1.  This is multiplied by the length of the list and then the ceiling function is used to round up to the next integer.  This index is then extracted from .Since hash table functionality is frequently done with rules in Mathematica, and rules are stored in lists, one might use:How about justThis is identical to accepted answer (Khoth), but with the unnecessary  and  variables removed.Though doing away with the two aforementioned variables, the above solution still remains random because we are relying upon random (starting at a randomly selected index) to decrement itself  toward  over each iteration.Unfortunately, this cannot be done efficiently (better than O(n)) in any of the Standard Library set containers.This is odd, since it is very easy to add a randomized pick function to hash sets as well as binary sets. In a not to sparse hash set, you can try random entries, until you get a hit. For a binary tree, you can choose randomly between the left or right subtree, with a maximum of O(log2) steps. I've implemented a demo of the later below:I got [995, 975, 971, 995, 1057, 1004, 966, 1052, 984, 1001] as output, so the distribution seams good.I've struggled with the same problem for myself, and I haven't yet decided weather the performance gain of this more efficient pick is worth the overhead of using a python based collection. I could of course refine it and translate it to C, but that is too much work for me today :)Since you said \"Solutions for other languages are also welcome\", here's the version for Python:PHP, using MT:For fun I wrote a RandomHashSet based on rejection sampling. It's a bit hacky, since HashMap doesn't let us access it's table directly, but it should work just fine.It doesn't use any extra memory, and lookup time is O(1) amortized. (Because java HashTable is dense).you can also  transfer the set to array use array \nit will probably work on small scale i see the for loop in the most voted answer is O(n) anyway If you really just want to pick \"any\" object from the , without any guarantees on the randomness, the easiest is taking the first returned by the iterator.The easiest with Java 8 is:where  is a random integer. Of course it is of less performance than that with the A generic solution using Khoth's answer as a starting point.If set size is not large then by using Arrays this can be done.With  we can do a little better than Khoth's answer:
Java

I have a Java project in Eclipse with ~10 packages and ~10 class files per package.  Is there a way to determine total lines of code for the whole project from within Eclipse?  I am familiar with other tools (e.g., Code Analyzer, wc, etc.) but I want to know if there is a way to do this within Eclipse (or get confirmation that there is no way to do it).Here's a good metrics plugin that displays number of lines of code and much more:It says it requires Eclipse 3.1, although I imagine they mean 3.1+Here's another metrics plugin that's been tested on Ganymede:  > Check the  box.Use this expression: Select whatever file types (, , etc..) and working sets are appropriate for you.   Under linux, the simpler is:To resume, just do:Are you interested in counting the executable lines rather than the total file line count?\nIf so you could try a code coverage tool such as .\nAs a side effect of the code coverage stats you get stats on the number of executable lines and blocks (and methods and classes). These are rolled up from the method level upwards, so you can see line counts for the packages, source roots and projects as well.For eclipse(Indigo), install ().After installation:\n- Right click on your project\n- Choose  tools --> compute metrics\n- And you will get your answer in a Metrics tab as Number of Lines.You could use a batch file with the following script:I think if you have MyEclipse, it adds a label to the Project Properties page which contains the total number of source code lines. Might not help you as MyEclipse is not free though.Unfortunately, that wasn't enough in my case so I wrote a source analyzer to gather statistics not gathered by other solutions (for example the metrics mentioned by AlbertoPL).You could use former Instantiations product . This eclipse plugin provides you suchlike statistics in code metrics view. This is provided by Google free of charge.A very simple plugin for counting actual lines of source code is  eclipse plugin. Please download and try.Place the downloaded jar file under eclipse\\plugin folder and restart eclipse.\n\n
Java

I'm essentially looking for a \"@Ignore\" type annotation with which I can stop a particular field from being persisted. How can this be achieved? complies with your needs.To ignore a field, annotate it with  so it will not be mapped by hibernate.\nSource: .To ignore a field, annotate it with  so it will not be mapped by hibernate.but then  the field when converting to JSON.(omit by JPA but still include in Jackson) use  :You can also use  and hide fields in JSON during deserialization when :This answer comes a little late, but it completes the response.In order to avoid a field from an entity to be persisted in DB one can use one of the two mechanisms: - the JPA annotation marking a field as not persistable keyword in java. Beware - using this keyword, will prevent the field to be used with any serialization mechanism from java. So, if the field must be serialized you'd better use just the  annotation.To complete the above answers, I had the case using an XML mapping file where neither the  nor  worked...\nI had to put the transient information in the xml file:
Java

I'm a beginner in Java.  Please suggest which collection(s) can/should be used for maintaining a sorted list in Java. I have tried  and , but they weren't what I was looking for.This comes very late, but there is a class in the JDK just for the purpose of having a sorted list. It is named (somewhat out of order with the other  interfaces) \"\". It can sort either s or using a .The difference with a  sorted using  is that this will maintain a partial order at all times, with O(log(n)) insertion performance, by using a heap data structure, whereas inserting in a sorted  will be O(n) (i.e., using binary search and move).However, unlike a ,  does not support indexed access (),  (thus the name ).TreeMap and TreeSet will give you an iteration over the contents in sorted order. Or you could use an ArrayList and use Collections.sort() to sort it. All those classes are in java.utilIf you want to maintain a  which you will  (i.e. a structure which, in addition to being sorted, allows duplicates and whose elements can be efficiently referenced by index), then use an ArrayList but when you need to insert an element, always use  at which you add a given element. The latter method tells you the index you need to insert at to keep your list in sorted order.Use Google Guava's TreeMultiset.  Guava is a spectacular collections API.Guava: TreeMultiset: One problem with providing an implementation of List that maintains sorted order is the promise made in the Javadocs of the 'add' method.There are a few options. I'd suggest TreeSet if you don't want duplicates and the objects you're inserting are comparable.You can also use the static methods of the Collections class to do this.See  and  for more info.You want the  implementations, namely .If you just want to sort a list, use any kind of  and use . If you want to make sure elements in the list are unique and always sorted, use a .What I have done is implement List having a internal instance with all the methods delegated.After, I have implemented a new method \"putOrdered\" which insert in the proper position if the element doesn't exist or replace just in case it exist.If you want to allow repeated elements just implement addOrdered instead (or both).If you want to avoid inserts you can also throw and unsupported operation exception on  \"add\" and \"set\" methods. ... and also You have to be careful with ListIterator methods because they could modify your internal list. In this case you can return a copy of the internal list or again throw an exception.TreeSet would not work because they do not allow duplicates plus they do not provide method to fetch element at specific position. PriorityQueue would not work because it does not allow fetching elements at specific position which is a basic requirement for a list.\nI think you need to implement your own algorithm to maintain a sorted list in Java with O(logn) insert time, unless you do not need duplicates.\nMaybe a solution could be using a TreeMap where the key is a subclass of the item overriding the equals method so that duplicates are allowed. You can try solving these tasks with  if you are using prior versions to java 8. You can find it here: Here you have an example:Of course, having this kind of beauty impacts in the performance (an average of 2 times), but can you find a more readable code?The problem with PriorityQueue is that it's backed up by an simple array, and the logic that gets the elements in order is done by the \"queue[2*n+1] and queue[2*(n+1)]\" thingie. It works great if you just pull from head, but makes it useless if you are trying to call the .toArray on it at some point. I go around this problem by using com.google.common.collect.TreeMultimap, but I supply a custom Comparator for the values, wrapped in an Ordering, that never returns 0. ex. for Double:This way I get the values in order when I call .toArray(), and also have duplicates.The most efficient way to implement a sorted list like you want would be to implement indexable skiplist as in here: . \nIt would allow to have inserts/removals in O(log(n)) and would allow to have indexed access at the same time. And it would also allow duplicates.Skiplist is a pretty interesting and, I would say, underrated data structure.\nUnfortunately there is no skiplist implementation in Java base library, but you can use one of open source implementations or implement it yourself.What you want is a binary search tree. It maintains sorted order while offering logarithmic access for searches, removals and insertions (unless you have a degenerated tree - then it's linear). It is quite easy to implement and you even can make it implement the List interface, but then the index-access gets complicated.Second approach is to have an ArrayList and then a bubble sort implementation. Because you are inserting or removing one element at a time, the access times for insertions and removals are linear. Searches are logarithmic and index access constant (times can get different for LinkedList). The only code you need is 5, maybe 6 lines of bubble sort.You can use Arraylist and Treemap, as you said you want repeated values as well then you cant use TreeSet, though it is sorted as well, but you have to define comparator. Use sort() method to sort the list as below:For reference see the link:\nUse  which gives elements in sorted order. OR use  for external sorting with .
Java

What is the most efficient Java Collections library?A few years ago, I did a lot of Java and had the impression back then that  is the best (most efficient) Java Collections implementation. But when I read the answers to the question \"\" I noticed that  is hardly mentioned. So which Java Collections library is best now?  To clarify, I mostly want to know what library to use when I have to store millions of entries in a hash table etc. (need a small runtime and memory footprint).From inspection, it looks like Trove is just a library of collections for primitive types - it's not like it's meant to be adding a lot of functionality over the normal collections in the JDK.Personally (and I'm biased) I love  (including the former Google Java Collections project). It makes various tasks (including collections) a lot easier, in a way which is at least reasonably efficient. Given that collection operations rarely form a bottleneck in my code (in my experience) this is \"better\" than a collections API which may be more efficient but doesn't make my code as readable.Given that the overlap between Trove and the Guava is pretty much nil, perhaps you could clarify what you're actually looking for from a collections library.The question is (now) about storing lots of data, which can be represented using primitive types like , in a Map. Some of the answers here are very misleading in my opinion. Let's see why.I modified the benchmark from  to measure both runtime and memory consumption. I also added  to this benchmark, which is another collections library for primitive types (I use that one extensively). The 'official' trove benchmark does not compare IntIntMaps to Java Collection's , probably storing  and storing  is not the same from a technical point of view. But a user might not care about this technical detail, he wants to store data representable with  efficiently.First the relevant part of the code:I assume the data comes as primitive , which seems sane. But this implies a runtime penalty for java util, because of the auto-boxing, which is not neccessary for the primitive collections frameworks. The runtime results (without  calls, of course) on WinXP, jdk1.6.0_10:While this might already seem drastic, this is not the reason to use such a framework. The reason is memory performance. The results for a Map containing 100000  entries:Java Collections needs  the memory compared to the primitive collection frameworks. I.e. you can keep three times as much data in memory, without resorting to disk IO which lowers runtime performance by magnitudes. And this matters. Read  to find out why.In my experience high memory consumption is the biggest performance issue with Java, which of course results in worse runtime performance as well. Primitive collection frameworks can really help here.So: No, java.util is not the answer. And \"adding functionality\" to Java collections is not the point when asking about efficiency. Also the modern JDK collections do  \"out-perform even the specialized Trove collections\".Disclaimer: The benchmark here is far from complete, nor is it perfect. It is meant to drive home the point, which I have experienced in many projects. Primitive collections are useful enough to tolerate fishy API -  you work with lots of data.I know this is an old post and there are a ton of answers here. \nBut, The answers above are superficial and over simplified in terms of suggesting a library. There is no one library that does well across the various benchmarks presented here. The only conclusion I derive is if you care about performance and memory and specifically dealing with primitive types, its more than worth looking at the non jdk alternatives.Here is a more sound analysis, in terms of benchmark mechanics and the libraries covered.\n is a thread in the mahout dev list. The libraries covered are:\nUnfortunately, the original benchmarks are no longer available and besides its a bit outdated. \n is a fairly recent (Jan 2015) benchmarks done by someone else. It is not as comprehensive nor does it have the interactive exploratory tools as the original link.As other commentators have noticed, the definition of \"efficient\" casts a wide net. However no one has yet mentioned the . Some of the highlights:The Javolution distribution includes a benchmark suite so you can see how they stack up against other libraries/the built-in collections.Some collection libs to consider:I would first and foremost reach for the JDK collection library.  It covers most common things you need to do and is obviously already available to you.Google Collections is probably the best high-quality library outside the JDK.  It's heavily used and well supported.Apache Commons Collections is older and suffers a bit from the \"too many cooks\" problem but has a lot of useful stuff as well.Trove has very specialized collections for cases like primitive keys/values.  These days we find that on modern JDKs and with the Java 5+ collections and concurrent use cases, the JDK collections out-perform even the specialized Trove collections.If you have really high concurrency use cases, you should definitely check out stuff like the NonBlockingHashMap in the high-scale lib, which is a lock-free implementation and can stomp on ConcurrentHashMap if you have the right use case for it.Sorry for the obvious answer, but for most uses, the default  are more than sufficient.To store millions of  in a map, take a look at I'm developer of happy-collections from Depends on how we define \"efficient\".Every data structure has its own Big-Oh behavior for reading, writing, iterating, memory footprint, etc.  A linked list in one library is likely to be the same as any other.  And a hash map will be faster for reading O(1) than a linked list O(n).This doesn't sound like \"most efficient\".  It sounds like \"most popular\" to me.Just some feedback - I've never heard of it, and I don't know anyone who has used it.  Collections built into the JDK, Google, or Apache Commons are well-known to me.Trove offers a few advantages.That said, a lot has been done to improve jdk collections since trove was written.It's the hashing strategies that make it appealing to me though... Google for trove and read their overview.  as well as the  package should be mentioned, if you plan to use the HashMap in multiple threads. small memory footprint is assued, since this is part of standard java.If you want to store millions of records in a hash table, chances are that you will run into memory problems. This happened to me when I tried creating a map with 2.3 million String objects, for example. I went with , which is very mature and performs well. They have a Java API that wraps the Collections API, so you can easily create arbitrarily large maps with very little memory footprint. Access will be slower though (as it is stored on disk). : is there a decent (and efficient), well maintained, library for immutable collections? Clojure has excellent support for this, and it would be nice to have something similar for Java.
Java

Upcasting is allowed in Java, however downcasting gives a compile error. The compile error can be removed by adding a cast but would anyway break at the runtime. In this case why Java allows downcasting if it cannot be executed at the runtime?\nIs there any practical use for this concept? Downcasting is allowed when there is a possibility that it suceeds at run time:In some cases this will not succeed:In others it will work:Note that some casts will be disallowed at compile time, because they will never succeed at all:Using your example, you could do:I believe this applies to all statically typed languages:The typecast effectively says: assume this is a reference to the cast class and use it as such.  Now, lets say o is  an Integer, assuming this is a String makes no sense and will give unexpected results, thus there needs to be a runtime check and an exception to notify the runtime environment that something is wrong.In practical use, you can write code working on a more general class, but cast it to a subclass if you know what subclass it is and need to treat it as such.  A typical example is overriding Object.equals().  Assume we have a class for Car:We can all see that the code you provided won't work at run time. That's because we know that the expression  can  be an object of type .But that's not how the compiler sees it. By the time the compiler is checking whether the cast is allowed, it just sees this:And as others have demonstrated, that sort of cast is perfectly legal. The expression on the right could very well evaluate to an object of type . The compiler sees that  and  have a subtype relation, so with the \"expression\" view of the code, the cast might work.The compiler does not consider the special case when it knows  what object type  will really have. It just sees the static type as  and considers the dynamic type could be  or any descendant of , including .@ Original Poster - see inline comments.I believe this is because there is no way for the compiler to know at compile-time if the cast will succeed or not. For your example, it's simple to see that the cast will fail, but there are other times where it is not so clear. For instance, imagine that types B, C, and D all extend type A, and then a method  returns an instance of either B, C or D depending on a randomly generated number. The compiler cannot know which exact run-time type will be returned by this method, so if you later cast the results to , there is no way to know if the cast will succeed (or fail). Therefore the compiler has to assume casts will succeed.Downcast works in the case when we are dealing with an upcasted object.\nUpcasting:So now this  variable can always be downcasted to  because the object which was cast is an ,but because  is an Object it cannot be cast to  because  cannot be cast to .Downcasting is very useful in the following code snippet I use this all the time. Thus proving that downcasting is useful. I store String in the Linked List. \nWhen I retrieve the elements of Linked List, Objects are returned. To access the elements as Strings(or any other Class Objects), downcasting helps me. Java allows us to compile downcast code trusting us that we are doing the wrong thing. \nStill if humans make a mistake, it is caught at runtime.Consider the below examplehere we create the object of subclass Bone and assigned it to super class AOne reference and now superclass reference does not know \nabout the method method2 in the subclass i.e Bone  during compile time.therefore we need to downcast this reference of superclass to subclass reference so as the resultant reference can know about the presence of methods in the subclass i.e Bone
Java

We know that it is expensive to catch exceptions. But, is it also expensive to use a try-catch block in Java even if an exception is never thrown? I found the Stack Overflow question/answer , but it is for . has almost no expense at all. Instead of doing the work of setting up the  at runtime, the code's metadata is structured at compile time such that when an exception is thrown, it now does a relatively expensive operation of walking up the stack and seeing if any  blocks exist that would catch this exception. From a layman's perspective,  may as well be free. It's actually throwing the exception that costs you - but unless you're throwing hundreds or thousands of exceptions, you still won't notice the cost. has some minor costs associated with it. Java cannot do some optimizations on code in a  block that it would otherwise do. For example, Java will often re-arrange instructions in a method to make it run faster - but Java also needs to guarantee that if an exception is thrown, the method's execution is observed as though its statements, as written in the source code, executed in order up to some line.Because in a  block an exception can be thrown (at any line in the try block! Some exceptions are thrown asynchronously, such as by calling  on a Thread (which is deprecated), and even besides that OutOfMemoryError can happen almost anywhere) and yet it can be caught and code continue to execute afterwards in the same method, it is more difficult to reason about optimizations that can be made, so they are less likely to happen. (Someone would have to program the compiler to do them, reason about and guarantee correctness, etc. It'd be a big pain for something meant to be 'exceptional') But again, in practice you won't notice things like this.Let's measure it, shall we?On my computer, this prints something like:At least in this trivial example, the try statement had no measurable impact on performance. Feel free to measure more complex ones.Generally speaking, I recommend not to worry about the performance cost of language constructs until you have evidence of an actual performance problem in your code. Or as Donald Knuth  it: \"premature optimization is the root of all evil\"./ may have some impact on performance. This is because it prevents JVM from doing some optimizations. Joshua Bloch, in \"Effective Java,\" said the following: Yep, as the others have said, a  block inhibits some optimizations across the  characters surrounding it.  In particular, the optimizer must assume that an exception could occur at any point within the block, so there's no assurance that statements get executed.For example:Without the , the value calculated to assign to  could be saved as a \"common subexpression\" and reused to assign to .  But because of the  there is no assurance that the first expression was ever evaluated, so the expression must be recomputed.  This isn't usually a big deal in \"straight-line\" code, but can be significant in a loop.It should be noted, however, that this applies ONLY to JITCed code.  javac does only a piddling amount of optimization, and there is zero cost to the bytecode interpreter to enter/leave a  block.  (There are no bytecodes generated to mark the block boundaries.)And for bestsss:Output:javap output:No \"GOTO\".To understand why the optimizations cannot be performed, It is useful to understand the underlying mechanisms.  The most succinct example I could find was implemented in C macros at:  Compilers often have difficulty determining if a jump can be localized to X, Y and Z so they skip optimizations that they can't guarantee to be safe, but the implementation itself is rather light.Yet another microbenchmark ().I created a test in which I measure try-catch and no-try-catch code version based on an exception percentage. 10% percentage means that 10% of the test cases had division by zero cases. In one situation it is handled by a try-catch block, in the other by a conditional operator. Here is my results table:Which says that there is no significant difference between any of these cases.
Java

How can I create a concurrent List instance, where I can access elements by index? Does the JDK have any classes or factory methods I can use?There is a concurrent list implementation in .  in particular.You can very well use  if all you need is simple invocation synchronization:If you don't care about having index-based access and just want the insertion-order-preserving characteristics of a List, you could consider a . Since it implements Iterable, once you've finished adding all the items, you can loop over the contents using the simplified for-each syntax:Because the act of acquiring the position and getting the element from the given position naturally requires some locking (you can't have the list have structural changes between those two operations).The very idea of a concurrent collection is that each operation on its own is atomic and can be done without explicit locking/synchronization.Therefore getting the element at position  from a given  as an atomic operation doesn't make too much sense in a situation where concurrent access is anticipated.
Java

I just learned about Java's Scanner class and now I'm wondering how it compares/competes with the StringTokenizer and String.Split. I know that the StringTokenizer and String.Split only work on Strings, so why would I want to use the Scanner for a String? Is Scanner just intended to be one-stop-shopping for spliting?They're essentially horses for courses.You'll note from my timings that  can still tokenize  on a typical machine. In addition, it has the advantage over  that it gives you the output as a string array, which is usually what you want. Using an , as provided by , is too \"syntactically fussy\" most of the time. From this point of view,  is a bit of a waste of space nowadays, and you may as well just use .Let's start by eliminating . It is getting old and doesn't even support regular expressions. Its documentation states:So let's throw it out right away. That leaves  and . What's the difference between them?For one thing,  simply returns an array, which makes it easy to use a foreach loop: is built more like a stream:or(It has a rather , so don't think that it's always restricted to such simple things.)This stream-style interface can be useful for parsing simple text files or console input, when you don't have (or can't get) all the input before starting to parse.Personally, the only time I can remember using  is for school projects, when I had to get user input from the command line. It makes that sort of operation easy. But if I have a  that I want to split up, it's almost a no-brainer to go with .StringTokenizer was always there. It is the fastest of all, but the enumeration-like idiom might not look as elegant as the others.split came to existence on JDK 1.4. Slower than tokenizer but easier to use, since it is callable from the String class.Scanner came to be on JDK 1.5. It is the most flexible and fills a long standing gap on the Java API to support an equivalent of the famous Cs scanf function family.Split is slow, but not as slow as Scanner.  StringTokenizer is faster than split. However, I found that I could obtain double the speed, by trading some flexibility, to get a speed-boost, which I did at JFastParser Testing on a string containing one million doubles:If you have a String object you want to tokenize, favor using String's  method over a StringTokenizer.  If you're parsing text data from a source outside your program, like from a file, or from the user, that's where a Scanner comes in handy.I recently did some experiments about the bad performance of String.split() in highly performance sensitive situations. You may find this useful.  The gist is that String.split() compiles a Regular Expression pattern each time and can thus slow down your program, compared to if you use a precompiled Pattern object and use it directly to operate on a String.String.split seems to be much slower than StringTokenizer. The only advantage with split is that you get an array of the tokens. Also you can use any regular expressions in split. \n    org.apache.commons.lang.StringUtils has a split method which works much more faster than any of two viz. StringTokenizer or String.split. \n    But the CPU utilization for all the three is nearly the same. So we also need a method which is less CPU intensive, which I am still not able to find. For the default scenarios I would suggest Pattern.split() as well but if you need maximum performance (especially on Android all solutions I tested are quite slow) and you only need to split by a single char, I now use my own method:Use \"abc\".toCharArray() to get the char array for a String. For example:One important difference is that both String.split() and Scanner can produce empty strings but StringTokenizer never does it.For example:Output:This is because the delimiter for String.split() and Scanner.useDelimiter() is not just a string, but a regular expression. We can replace the delimiter \" \" with \" +\" in the example above to make them behave like StringTokenizer.String.split() works very good but has its own boundaries, like if you wanted to split a string as shown below based on single or double pipe (|) symbol, it doesn't work. In this situation you can use StringTokenizer.ABC|IJK
Java

I want to start a server which listen to a port. I can specify port explicitly and it works. But I would like to find a port in an automatic way. In this respect I have two questions.If you don't mind the port used, specify a port of 0 to the  and it will listen on any free port.If you want to use a specific set of ports, then the easiest way is probably to iterate through them until one works. Something like this:Could be used like so:If you pass 0 as the port number to the constructor of ServerSocket, It will allocate a port for you.Starting from Java 1.7 you can use try-with-resources like this: If you need to find an open port on a specific interface check  documentation for alternative constructors.  Any code using the port number returned by this method is subject to a race condition - a different process / thread may bind to the same port immediately after we close the ServerSocket instance. According to , you should use ports  to  if you don't need a 'well known' port.AFAIK the only way to determine wheter a port is in use is to try to open it.If you need in  use:The Eclipse SDK contains a class , that does what you want. You may have a look into the git .If you use Spring you may try See This works for me on Java 6If you want to create your own server using a , you can just have it pick a free port for you:Other server implementations typically have similar support.  for example picks a free port unless you explicitly set it:I have recently released a tiny library for doing just that with tests in mind.\nMaven dependency is:Once installed, free port numbers can be obtained via:It may not help you much, but on my (Ubuntu) machine I have a file /etc/services in which at least the ports used/reserved by some of the apps are given. These are the standard ports for those apps. No guarantees that these are running, just the default ports these apps use (so you should not use them if possible).There are slightly more than 500 ports defined, about half UDP and half TCP.The files are made using information by IANA, see .If your server starts up, then that socket was not used. Something like: 
Java

What is lazy loading in Java? I don't understand the process. Can anybody help me to understand the process of lazy loading?Say you have a parent and that parent has a collection of children. Hibernate now can \"lazy-load\" the children, which means that it does not actually load all the children when loading the parent. Instead, it loads them when requested to do so. You can either request this explicitly or, and this is far more common, hibernate will load them automatically when you try to access a child.Lazy-loading can help improve the performance significantly since often you won't need the children and so they will not be loaded.Also beware of the n+1-problem. Hibernate will not actually load all children when you access the collection. Instead, it will load each child individually. When iterating over the collection, this causes a query for every child. In order to avoid this, you can trick hibernate into loading all children simultaneously, e.g. by calling parent.getChildren().size().\"Lazy loading\" means that an entity will be loaded  when you  accesses the entity for the  time.The  is like this:This saves the cost of preloading/prefilling  the entities in a large dataset beforehand while you after all actually don't need  of them.In Hibernate, you can configure to lazily load a collection of child entities. The  lazy loading is then done inside the methods of the  which Hibernate uses \"under the hoods\" to assign the collection of entities as .E.g..Martin Fowler defines the  pattern in  as such:So, when loading a given object, the idea is to not  the related object(s) that you may not use immediately to save the related performance cost. Instead, the related object(s) will be loaded only when used. This is not a pattern specific to data access and Hibernate but it is particularly useful in such fields and Hibernate supports lazy loading of one-to-many associations and single-point associations (one-to-one and many-to-one) also under certain conditions. \nLazy interaction is discussed in more detail in  of the Hibernate 3.0 Reference Documentation. Bydefault lazy loading is true.Lazy loading means when the select query is executed it will not hit the database. It will wait for getter function i.e when we required then ,it will fetch from the datbase.\nfor example:\nYou are a parent who has a kid with a lot of toys. But the current issue is whenever you call him (we assume you have a boy), he comes to you with all his toys as well. Now this is an issue since you do not want him carrying around his toys all the time.\nSo being the rationale parent, you go right ahead and define the toys of the child as LAZY. Now whenever you call him, he just comes to you without his toys.Lazy fetching decides whether to load child objects while loading the Parent Object. \nYou need to do this setting respective hibernate mapping file of the parent class. \n (means not to load child) \nBy default the lazy loading of the child objects is true. This make sure that the child objects are not loaded unless they are explicitly invoked in the application by calling  method on parent.In this case hibernate issues a fresh database call to load the child when  is actully called on the Parent object.But in some cases you do need to load the child objects when parent is loaded. \nJust make the lazy=false and hibernate will load the child when parent is loaded from the database.Example : \nIf you have a TABLE ? EMPLOYEE mapped to Employee object and contains set of Address objects. \nParent Class : Employee class,\nChild class : Address Class In the Employee.hbm.xml file In the above configuration. \nIf  : - when you load the Employee object that time child object Address is also loaded and set to setAddresss() method. \nIf you call employee.getAdress() then loaded data returns.No fresh database call. If  :- This the default configuration. If you don?t mention then hibernate consider lazy=true. \nwhen you load the Employee object that time child object Adress is not loaded. You need extra call to data base to get address objects. \nIf you call  then that time database query fires and return results. Fresh database call.In layman's language it is like you are making a cake and you will need 5-10 ingredients from fridge. You have two options get all ingredients from fridge and put it on your kitchen platform or bring the item you want when you need..\nSimilarly in eager loading you fetch all information about bean and its related classes (not  child or is-a relation but has a relationship, i.e. cake has flour, has milk, has cream etc) and in case of lazy loading first you bring only its identifier and values that are coming from same table (necessary ingredients that first you will need in your bowl in case of cake)..all information that is coming from other tables will be fetched as and when required/used.Hope this helps :)Lazy Loading? Well, it simply means that child records are not fetched immediately, but automatically as soon as you try to access them.WikipediaLink of  from hibernate.orgLazy setting decides whether to load child objects while loading the Parent Object.You need to do this setting respective hibernate mapping file of the parent class.Lazy = true (means not to load child)By default the lazy loading of the child objects is true. This make sure that the child objects are not loaded unless they are explicitly invoked in the application by calling getChild() method on parent.In this case hibernate issues a fresh database call to load the child when getChild() is actully called on the Parent object.But in some cases you do need to load the child objects when parent is loaded. Just make the lazy=false and hibernate will load the child when parent is loaded from the database.Exampleslazy=true (default)Address child of User class can be made lazy if it is not required frequently.lazy=falseBut you may need to load the Author object for Book parent whenever you deal with the book for online bookshop.Lazy initialization is a performance optimization. It's used when data is deemed to be 'expensive' for some reason.\nFor example:\nif the hashCode value for an object might not actually be needed by its caller, always calculating the hashCode for all instances of the object may be felt to be unnecessary.\nsince accessing a file system or network is relatively slow, such operations should be put off until they are absolutely required.Lazy initialization has two objectives :\ndelay an expensive operation until it's absolutely necessary\nstore the result of that expensive operation, such that you won't need to repeat it againHiberante supports the feature of lazy initialization for both entities and collections.\nHibernate engine loads only those objects that we are querying for does not other entites or collections.\n\n\n lazy=\"false\" by default loading initialization mention for the only child is lazy.in case of true that is parent is loading does not support childLazy setting decides whether to load child objects while loading the Parent Object.You need to do this setting respective hibernate mapping file of the parent class.Lazy = true (means not to load child)By default the lazy loading of the child objects is true.Lazy loading allows you to defer the association retrieval or to have a better control over the fetching strategy.When you use EAGER loading, you define a global fetch plan which cannot be overridden at query time, meaning you are limited to a decision you took while designing your entity model. The , because the fetching strategy is a query-time policy and it might differ from a business use case to another.The  is a very important aspect, as too much EAGER fetching can cause serious performance related issues.Well it simply means loading data you need currently instead of loading whole bunch of data at once which you won't use now. Thereby making application load time faster than usual. 
Java

Let's say I have an application that utilizes the  framework as suchWhen I run this application in the debugger, a thread is created with the following (default) name: . As you can see, this isn't terribly useful and as far as I can tell, the  framework does not provide an easy way to name the created threads or thread-pools.So, how does one go about providing names for the threads/thread-pools? For instance, .You could supply a  to . The factory will be responsibe for creating threads, and will be able to name them.To quote the :Guava almost always has what you . and pass it off to your .You can try to provide your own thread factory, which will create thread with appropriate names.  Here's one example:The  from apache commons-lang is also useful to provide the naming behavior. Instead of writing an anonymous inner class, you can use the Builder to name the threads as you want. Here's the example from the javadocs:You can also change the name of your thread afterwards, while the thread is executed:That could be of interest if for instance you're using the same ThreadFactory for different type of tasks.There's an  for this with Oracle. From the comments from the Oracle employee it seems they don't understand the issue and won't fix. It's one of these things that is dead simple to support in the JDK (without breaking backwards compatibility) so it is kind of a shame that the RFE gets misunderstood.As pointed out you need to implement your own . If you don't want to pull in Guava or Apache Commons just for this purpose I provide here a  implementation that you can use. It is exactly similar to what you get from the JDK except for the ability to set the thread name prefix to something else than \"pool\".When you want to use it you simply take advantage of the fact that all  methods allow you to provide your own . Thiswill give an ExecutorService where threads are named  but by using you'll get an ExecutorService where threads are named . Voila!Pass the ThreadFactory to an executorservice and you are good to go A quick and dirty way is to use  in the  method.If you are using Spring, there is  for which you can set a thread name prefix.Extend  Sample code:output:....etc  You can write your own implementation of ThreadFactory, using for example some existing implementation (like defaultThreadFactory) and change the name at the end.Example of implementing ThreadFactory: And usage:
Java

Is there a way to set the  attribute of a  programmatically? There doesn't appear to be a  method.To be clear, I am not talking about View / Widget styles! I am talking about the following:setTypeface is the Attribute textStyle.As Shankar V added, to preserve the previously set typeface attributes you can use:Let's say you have a style called RedHUGEText on your values/styles.xml:Just create your TextView as usual in the XML layout/your_layout.xml file, let's say:And in the java code of your Activity you do this:It worked for me! And it applied color, size, gravity, etc. I've used it on handsets and tablets with Android API Levels from 8 to 17 with no problems.Remember... this is useful only if the style of the text really depends on a condition on your Java logic or you are building the UI \"on the fly\" with code... if it doesn't, it is better to just do:You can always have it your way!Hope it helps!Search for  or also . There is similar question on stackoverflow: So many way to achieve this task some are below:-This question is asked in a lot of places in a lot of different ways. I originally answered it here but I feel it's relevant in this thread as well (since i ended up  when I was searching for an answer).There is no one line solution to this problem, but this worked for my use case. The problem is, the 'View(context, attrs, defStyle)' constructor does not refer to an actual style, it wants an attribute. So, we will:In 'res/values/attrs.xml', define a new attribute:In res/values/styles.xml' I'm going to create the style I want to use on my custom TextViewIn 'res/values/themes.xml' or 'res/values/styles.xml', modify the theme for your application / activity and add the following style:Finally, in your custom TextView, you can now use the constructor with the attribute and it will receive your styleIt's worth noting that I repeatedly used customTextView in different variants and different places, but it is in no way required that the name of the view match the style or the attribute or anything. Also, this technique should work with any custom view, not just TextViews.This worked for meor I\u00b4ve resolved it with two simple methods.Follow the explanation.My existing style declaration:My Android Java code:Regards.Take a look at this.This feature is not currently supported.
Java

I am trying to build an application, but it gives some error. My JDK version is given below:Here is my Error Log: happens because of a higher JDK during compile time and lower JDK during runtime.These guys gave you the reason why is failing but not how to solve it. This problem may appear even if you have a jdk which matches JVM which you are trying it into.Project -> Properties -> Java CompilerEnable project specific settings.Then select Compiler Compliance Level to 1.6 or 1.5, build and test your app.Now, it should be fine.Version 51 is Java 7, you probably use the wrong JDK. Check JAVA_HOME.I encountered the same issue, when jdk 1.7 was used to compile then jre 1.4 was used for execution. My solution was to set environment variable PATH by adding pathname C:\\glassfish3\\jdk7\\bin in front of the existing PATH setting. The updated value is \"C:\\glassfish3\\jdk7\\bin;C:\\Sun\\SDK\\bin\". After the update, the problem was gone. It means that you compiled your classes under a , but then try to run them under  of JDK.Make sure you're using the correct SDK when compiling/running and also, make sure you use source/target 1.7.Use Maven and use the  to explicitly call the actual correct version JDK javac.exe command, because Maven could be running any version; this also catches !  This later part could have easily been fixed in Java 1.5+ by adding versioning attributes to new classes, methods, and properties, or separate compiler versioning data, so is a quite stupid oversight by Sun and Oracle.
Java

According to the JLS, an  array should be filled by zeros just after initialization. However, I am faced with a situation where it is not. Such a behavior occurs first in JDK 7u4 and also occurs in all later updates (I use 64-bit implementation). The following code throws exception:The exception occurs after the JVM performs compilation of the code block and does not arise with  flag. Additionally, the  statement (as all other statements in this code) is necessary, and the exception does not occurs if it is absent. It is clear that this possible bug is bounded with some JVM optimization. Any ideas for the reason of such a behavior?\nI see this behavior on HotSpot 64-bit server VM, Java version from 1.7.0_04 to 1.7.0_10 on Gentoo Linux, Debian Linux (both kernel 3.0 version) and MacOS Lion. This error can always be reproduced with the code above. I did not test this problem with a 32-bit JDK or on Windows. I already sent a bug report to the Oracle (bug id 7196857) and it will appear in public Oracle bug database in few days.\nOracle published this bug at their public bug database:  Here we are faced with a bug in the JIT-compiler. Compiler determines that the allocated array is filled after allocation in , but the check for uses between the allocation and the fill is faulty. So, compiler performs an illegal optimization - it skips zeroing of allocated array.This bug is placed in Oracle bug tracker (). Unfortunately, I did not wait for any clarifications from Oracle about the following points. As I see, this bug is OS-specific: it absolutely reproducible on 64-bit Linux and Mac, but, as I see from comments, it reproduces not regularly on Windows (for similar versions of JDK). Additionally it would be nice to know when this bug will be fixed.There is only advice at the moment: do not use JDK1.7.0_04 or later if you depend on JLS for newly declared arrays.In the new  of the JDK 7u10 (early access) released at October 04, 2012, this bug was fixed at least for Linux OS (I did not test for other). Thanks to @Makoto, who found that this bug is no longer available for public access in Oracle bug database. Unfortunately, I do not know for the reasons Oracle removed it from public access, but it is available in Google . Also, this bug has caught the attention of Redhat: the CVE identifiers   () and  () were assigned to this flaw.I made some change in your code.\nIt's not a problem of Integer overflow. See the code, it throws an exception at runtime 
Java

I declare an enum as : And then, iterate enum as shown below :I checked the Java API but can't find the values() method? I'm curious as to where this method comes from? API link : \nYou can't see this method in javadoc because it's added by the compiler.Documented in three places : The  function simply list all values of the enumeration.The method is implicitly defined (i.e. generated by the compiler).From the :Run this you will see These are all public methods that \"sex\" class has. They are not in the source code, javac.exe added themNotes: 
Java

 API provides a class called as , which would basically serialize the control in order to access the critical resource. It gives method such as  and .  We can do similar things if we can use  keyword and using  and  methods.  I am wondering which one of these is better in practice and why?If you're simply locking an object, I'd prefer to use Example:You have to explicitly do  everywhere.Whereas with synchronized, it's super clear and impossible to get wrong:That said, s may be more useful for more complicated things where you can't acquire and release in such a clean manner.  I would honestly prefer to avoid using bare s in the first place, and just go with a more sophisticated concurrency control such as a  or a , if they meet your needs.I've never had a reason to use  or  but there may be some good ones.I've found that  and  (and other new  classes) are just more tools for the toolbox. I could do most everything I needed with my old claw hammer (the  keyword), but it was awkward to use in some situations. Several of those awkward situations became much simpler once I added more tools to my toolbox: a rubber mallet, a ball-peen hammer, a prybar, and some nail punches. , my old claw hammer still sees its share of use.I don't think one is really \"better\" than the other, but rather each is a better fit for different problems.  In a nutshell, the simple model and scope-oriented nature of  helps protect me from bugs in my code, but those same advantages are sometimes hindrances in more complex scenarios. Its these more complex scenarios that the concurrent package was created to help address. But using this higher level constructs requires more explicit and careful management in the code.===I think the  does a good job of describing the distinction between  and  (the emphasis is mine):You can achieve everything the utilities in   do with the low-level primitives like , , or  / However, concurrency is tricky, and most people get at least some parts of it wrong, making their code either incorrect or inefficient (or both).The concurrent API provides a higher-level approach, which is easier (and as such safer) to use. In a nutshell, you should not need to use  directly anymore. The   class itself is on the lower-level side of this toolbox, you may not even need to use that directly either (you can use  and  and stuff, etc, most of the time).There are 4 main factors into why you would want to use  or .Note: Synchronized locking is what I mean when I say intrinsic locking. Brian Goetz's \"Java Concurrency In Practice\" book, section 13.3:\n\"...Like the default ReentrantLock, intrinsic locking offers no deterministic fairness guarantees, but the\nstatistical fairness guarantees of most locking implementations are good enough for almost all situations...\"The main difference is fairness, in other words are requests handled FIFO or can there be barging?  Method level synchronization ensures fair or FIFO allocation of the lock.  Using ordoes not assure fairness.If you have lots of contention for the lock you can easily encounter barging where newer requests get the lock and older requests get stuck.  I've seen cases where 200 threads arrive in short order for a lock and the 2nd one to arrive got processed last.  This is ok for some applications but for others its deadly.See Brian Goetz's \"Java Concurrency In Practice\" book, section 13.3 for a full discussion of this topic.I would like to add some more things on top of   answer. support various methods for finer grained lock control, which are more expressive than implicit monitors ( locks)Advantages of  from documentation : In simple terms as per my understanding,  allows an object to re-enter from one critical section to other critical section . Since you already have lock to enter one critical section, you can other critical section on same object by using current lock.  key features as per this You can use   to further acquire control on granular locking on read and write operations.Apart from these three ReentrantLocks, java 8 provides one more LockYou can use these stamps to either release a lock or to check if the lock is still valid. Additionally stamped locks support another lock mode called optimistic locking.Have a look at this  on usage of different type of  and  locks.Lock makes programmers life easier. Here are few situations that can be achieved easier with lock.While, the lock, and conditions are build on the synchronized. So certainly you can achiever the same goal with that. However, that might make your life difficult and can deviate you from solving the actual problem. 
Java

I write a little command-line-application in Java. This application should work with a mix of parameters and commands, similar to .I'm a fan of .You can set it to understand commands, flags (with short and long names), whether or not certain commands/switches are required, or if they have default values. It even has functionality to print out a useful  type  message.The  page has some good examples of how it can be used. I prefer  to Commons CLI. (And I\u2019ve used both.)With , you don\u2019t need to call any functions. Everything\u2019s done for you!  (Parameters are set to object fields via reflection.)Here's a relatively up to date (As of Oct 2013) list of libraries that answer your question.If you're looking for a recommendation, I recommend JOpt Simple or JewelCli.JewelCLI is a .  It uses Proxied Interfaces Configured with Annotations to dynamically build a type-safe API for your command-line parameters.An example parameter interface :An example usage of the parameter interface :Save copies of the files above to a single directory and download the  to that directory as well.Compile and run the example in Bash on Linux/Mac OS X/etc.:Compile and run the example in the Windows Command Prompt:Running the example should yield the following output:For completeness sake let's add JCommander and an example usageIt's also worth looking at . It 'attempts to honor the command line option syntaxes of POSIX getopt() and GNU getopt_long().' \nIt seems to have some community traction, notably being the command line parsing lib of choice for the  (and Minecraft!). is annotation based, allows complex rules for combining arguments (sequences,nesting,arguments,types,...) and is reasonably well documented.To use it, add to your pom, and declare the available options as follows:and then to actually parse the command line, donote that it does not (yet) contain an auto generated help text. This was prototyped, but aborted. It is easy to generate a basic help text for simple cases, but for more complex configurations (a.e. the available options for an application like \"find\" or \"gcc\"), the result will not be pretty, and you will likely rather want to control the layout yourself.JSAP looks pretty good to me.I'm using airlift for a project I'm working on, seems to work quite nicely:Simple Maven dependency that you need to add:And after that it's annotation based and has a pretty neat way of displaying help text as well.Can see an example here if it's helpful:There is also a java getopt 
Java

What is a JavaBean and why do I need it? Since I can create all apps with the class and interface structure? Why do I need beans? And can you give me some examples where beans are essential instead of classes and interfaces?Please explain the essentiality of a bean in the below context:They often just represents real world data. Here's a simple example of a Javabean:Implementing  is not per se mandatory, but very useful if you'd like to be able to persist or transfer Javabeans outside Java's memory, e.g. in harddisk or over network. In for example a DAO class you can use it to create a list of users wherein you  the data of the  table in the database:In for example a Servlet class you can use it to  data from the database to the UI:In for example a JSP page you can  it by , which follows the Javabean conventions, to display the data:Does it make sense? You see, it's kind of a  which you can use everywhere to ,  and  data. are everywhere, they're a convention and just about every single slightly larger library out there uses those conventions to automate things. Just a few reasons why JavaBeans should be used:Also there's of course  which are a whole another matter and shouldn't be mixed with plain JavaBeans. I just wanted to mention EJB:s because the names are similar and it's easy to get those two confused.If you consider \"normal\" JavaBeans in web app context, they make more sense than wearing shoes in your legs. Since the Servlet specification requires for sessions to be serializable, it means you should store your data in session as something that's serializable - why not make it a bean then! Just throw your SomeBusinessDataBean into the session and you're good to go, laughably easy, specification-compliant and convenient.Also transferring that data around the application is easy too since JavaBeans help you to decouple parts of your application completely. Think JavaBeans as a letter and various subsystems of the application as departments within a very large corporation: Dept.A mails a bunch of data to Dept.B, Dept.B doesn't know -- where the data came from just as it should be and can just open the letter, read stuff from it and do its thing based on that data.Actually what's above applies to standalone apps too, the only difference is that you can mess up with the UI a bit more since standalone applications have stateful UI:s while web applications have statelss UI:s which in some cases only simulate stateful UI:s. Because of this difference, it's easier to make a mess with standalone application but that's worth a whole another topic and isn't directly related to JavaBeans at all.A bean is nothing much, really. For a class to be a \"bean\", all it requires is:To that, you can add getters and setters for properties of the class that conform to a specific naming convention if you want the fields to be discoverable in certain circumstances (e.g. making that class some object you can drag and drop from a visual editor in your IDE, for example).You can find more directly from Sun .A Java Bean is a software component that has been designed to be reusable in a variety of different environments. There is no restriction on the capability of a Bean. It may perform a simple function, such as checking the spelling of a document, or a complex function, such as forecasting the performance of a stock portfolio. A Bean may be visible to an end user. One example of this is a button on a graphical user interface. A Bean may also be invisible to a user. Software to decode a stream of multimedia information in real time is an example of this type of building block. Finally, a Bean may be designed to work autonomously on a user's workstation or to work in cooperation with a set of other distributed components. Software to generate a pie chart from a set of data points is an example of a Bean that can execute locally. However, a Bean that provides real-time price information from a stock or commodities exchange would need to work in cooperation with other distributed software to obtain its data.We will see shortly what specific changes a software developer must make to a class so that it is usable as a Java Bean. However, one of the goals of the Java designers was to make it easy to use this technology. Therefore, the code changes are minimal.A software component architecture provides standard mechanisms to deal with software building blocks. The following list enumerates some of the specific benefits that Java technology provides for a component developer:This is a real Bean named MyBean that has state (the variable theValue) that will automatically be saved and restored by the JavaBeans persistence mechanism, and it has a property named MyValue that is usable by a visual programming environment. This Bean doesn't have any visual representation, but that isn't a requirement for a JavaBean component. 
Java

What is this \"Execute Around\" idiom (or similar) I've been hearing about? \nWhy might I use it, and why might I not want to use it?Basically it's the pattern where you write a method to do things which are always required, e.g. resource allocation and clean-up, and make the caller pass in \"what we want to do with the resource\". For example:The calling code doesn't need to worry about the open/clean-up side - it will be taken care of by .This was frankly painful in Java because closures were so wordy, starting with Java 8 lambda expressions can be implemented like in many other languages (e.g. C# lambda expressions, or Groovy), and this special case is handled since Java 7 with  and  streams.Although \"allocate and clean-up\" is the typical example given, there are plenty of other possible examples - transaction handling, logging, executing some code with more privileges etc. It's basically a bit like the  but without inheritance.The Execute Around idiom is used when you find yourself having to do something like this:In order to avoid repeating all of this redundant code that is always executed \"around\" your actual tasks, you would create a class that takes care of it automatically:This idiom moves all of the complicated redundant code into one place, and leaves your main program much more readable (and maintainable!)Take a look at  for a C# example, and  for a C++ example.See also , which surveys this construct across many programming languages and offers some interesting research\u2019y ideas.  Concerning the specific question of why one might use it, the above paper offers some concrete examples:And later:The paper does not explore why  to use this idiom, but it does describe why the idiom is easy to get wrong without language-level help:I see you have a Java tag here so I'll use Java as an example even though the pattern isn't platform-specific.The idea is that sometimes you have code that always involves the same boilerplate before you run the code and after you run the code.  A good example is JDBC.  You always grab a connection and create a statement (or prepared statement) before running the actual query and processing the result set, and then you always do the same boilerplate cleanup at the end--closing the statement and connection.The idea with execute-around is that it's better if you can factor out the boilerplate code. That saves you some typing, but the reason is deeper. It's the don't-repeat-yourself (DRY) principle here--you isolate the code to one location so if there's a bug or you need to change it, or you just want to understand it, it's all in one place.The thing that's a little tricky with this kind of factoring-out though is that you have references that both the \"before\" and \"after\" parts need to see. In the JDBC example this would include the Connection and (Prepared)Statement.  So to handle that you essentially \"wrap\" your target code with the boilerplate code.You may be familiar with some common cases in Java. One is servlet filters. Another is AOP around advice. A third is the various xxxTemplate classes in Spring.  In each case you have some wrapper object into which your \"interesting\" code (say the JDBC query and result set processing) is injected. The wrapper object does the \"before\" part, invokes the interesting code and then does the \"after\" part.An  is where you pass arbitrary code to a method, which may perform setup and/or teardown code and execute your code in between.Java isn't the language I'd choose to do this in.  It's more stylish to pass a closure (or lambda expression) as the argument.  Though objects are arguably .It seems to me that the Execute Around Method is sort of like  (Dependency Injection) that you can vary ad hoc, every time you call the method.But it could also be interpreted as an example of Control Coupling (telling a method what to do by its argument, literally in this case).This reminds me of the .  Notice that the link I pointed to includes Java code for the pattern.Obviously one could perform \"Execute Around\" by making initialization and cleanup code and just passing in a strategy, which will then always be wrapped in initialization and cleanup code.As with any technique used to reduce code repetition, you should not use it until you have at least 2 cases where you need it, perhaps even 3 (a la the YAGNI principle).  Keep in mind that the removing code repetition reduces maintenance (fewer copies of code means less time spent copying fixes across each copy), but also increases maintenance (more total code).  Thus, the cost of this trick is that you are adding more code.This type of technique is useful for more than just initialization and cleanup.  It's also good for when you want to make it easier to call your functions (e.g. you could use it in a wizard so that the \"next\" and \"previous\" buttons don't need giant case statements to decide what to do to go to the next/previous page.I'll try to explain, as I would to a four year old:Santa's coming to town. His elves code whatever they want behind his back, and unless they change things get a little repetitive:Or this:....ad nauseam a million times with a million different presents: notice that the only thing different is step 2. If step two is the only thing that is different, then why is Santa duplicating the code, i.e. why is he duplicating steps 1 and 3 one million times? A million presents means that he is needlessly repeating steps 1 and 3 a million times. Execute around helps to solve that problem. and helps eliminate code. Steps 1 and 3 are basically constant, allowing for step 2 to be the only part that changes.If you still don't get it, here is another example: think of a sandwhich: the bread on the outside is always the same, but what's on the inside changes depending on the type of sandwhich you choose (.e.g ham, cheese, jam, peanut butter etc). Bread is always on the outside and you don't need to repeat that a billion times for every type of sandwhich you are creating.Now if you read the above explanations, perhaps you will find it easier to understand. I hope this explanation helped you.If you want groovy idioms, here it is:
Java

I want to invoke the  method which is static. I got the object of type , but I am not able to create an instance of that class and also not able to invoke the  method .In case the method is private use  instead of . And call  on the method object.Fromthe Javadoc of Method.invoke():What happens when you 
Java

I have this piece of code, which is not working:The sum variable is always 0. What am I doing wrong? is immutable.  The javadocs stat that  \"[r]eturns a BigInteger whose value is (this + val).\" Therefore, you can't change , you need to reassign the result of the  method to .The  class is immutable, hence you can't change its state. So calling \"add\" creates a new , rather than modifying the current.Other replies have nailed it; BigInteger is immutable.  Here's the minor change to make that code work. is an  class so we can not assign new object in the location of already assigned object. But you can create new object to assign new value like:BigInteger is an immutable class. So whenever you do any arithmetic, you have to reassign the output to a variable. Yes it's Immutable    so the method add() of BigInteger class does not add new BigIntger value to its own value ,but  without changing the current BigInteger and   is an immutable class. \nYou need to explicitly assign value of your output to sum like this:Actually you can use,for creating object for BigInteger class.But the problem here is,you cannot give a variable in the double quotes.So we have to use the  method and we have to store the answer in that sum again.So we will write,Since you are summing up some int values together, there is no need to use BigInteger.  is enough for that.  is 32 bits, while  is 64 bits, that can contain the sum of all int values.
Java

What's the difference between and in Java? When should I use them?The first form is called .  You use this when you're writing formal APIs for your code, which are generated by the  tool.  For an example,  uses Javadoc and was generated by that tool.Some common elements you'd see in Javadoc include:As an example, here's Javadoc for the  method of :The second form is a block (multi-line) comment.  You use this if you want to have multiple lines in a comment.I will say that you'd only want to use the latter form ; that is, you don't want to overburden your code with block comments that don't describe what behaviors the method/complex function is supposed to have.Since Javadoc is the more descriptive of the two, and you can generate actual documentation as a result of using it, using Javadoc would be more preferable to simple block comments.For the Java , there is  between the two. Java has two types of comments: traditional comments () and end-of-line comments (). See the . So, for the Java programming language, both  and  are instances of traditional comments, and they are both treated exactly the same by the Java compiler, i.e., they are ignored (or more correctly: they are treated as white space).However, as a Java programmer, you do not only use a Java compiler. You use a an entire tool chain, which includes e.g. the compiler, an IDE, a build system, etc. And some of these tools interpret things differently than the Java compiler. In particular,  comments are interpreted by the Javadoc tool, which is included in the Java  and generates documentation. The Javadoc tool will scan the Java source file and interpret the parts between  as documentation.This is similar to tags like  and : if you include a comment like  or , most IDEs will highlight such comments so that you don't forget about them. But for Java, they are just comments.  The first is Javadoc comments. They can be processed by the  tool to generate the API documentation for your classes. The second is a normal block comment.Reading the section  well explain all you need to know about comments in Java.The first oneis used to declare .For more information on  refer to the .The second one, as explained clearly in JLS, will ignore all the text between  and  thus is used to create multiline comments.Thus, the following text is a single complete comment:I don't think the existing answers adequately addressed this part of the question:If you're writing an API that will be published or reused within your organization, you should write comprehensive Javadoc comments for every  class, method, and field, as well as  methods and fields of non- classes.  Javadoc should cover everything that  be conveyed by the method signature, such as preconditions, postconditions, valid arguments, runtime exceptions, internal calls, etc.If you're writing an internal API (one that's used by different parts of the same program), Javadoc is arguably less important.  But for the benefit of maintenance programmers, you should still write Javadoc for any method or field where the correct usage or meaning is not immediately obvious.The \"killer feature\" of Javadoc is that it's closely integrated with Eclipse and other IDEs.  A developer only needs to hover their mouse pointer over an identifier to learn everything they need to know about it.  Constantly referring to the documentation becomes second nature for experienced Java developers, which improves the quality of their own code.  If your API isn't documented with Javadoc, experienced developers will not want to use it.First one is for Javadoc you define on the top of classes, interfaces, methods etc. You can use Javadoc as the name suggest to document your code on what the class does or what method does etc and generate report on it.Second one is code block comment.\nSay for example you have some code block which you do not want compiler to interpret then you use code block comment.another one is //\nthis you use on statement level to specify what the proceeding lines of codes are supposed to do.There are some other also like //TODO, this will mark that you want to do something later on that place//FIXME you can use when you have some temporary solution but you want to visit later and make it better.Hope this helpsComments in the following listing of Java Code are the greyed out characters:The Java language supports three kinds of comments:The compiler ignores everything from  to .This indicates a documentation comment (doc comment, for short). The compiler ignores this kind of comment, just like it ignores comments that use  and . The JDK javadoc tool uses doc comments when preparing automatically generated documentation.The compiler ignores everything from  to the end of the line.Now regarding when you should be using them:Use  when you want to comment a single line of code.Use  when you want to comment multiple lines of code.Use   when you would want to add some info about the program that can be used for automatic generation of program documentation. Java supports two types of comments:Some tool such as  use a special multiline comment for their purpose. For example  is a documentation comment used by javadoc when preparing the automatically generated documentation, but for Java it's a simple multiline comment.
Java

In my app I want to save a copy of a certain file with a different name (which I get from user)Do I really need to open the contents of the file and write it to another file?What is the best way to do so?To copy a file and save it to your destination path you can use the method below.Alternatively, you can use  to copy a file. It  be faster than the byte copy method when copying a large file. These worked nice for meIt might be too late for an answer but the most convenient way is using 'se.g. this is what I did``Here is a solution that actually closes the input/output streams if an error occurs while copying. This solution utilizes apache Commons IO IOUtils methods for both copying and handling the closing of streams.If you have root permission you can copy using below code:OR
Java

I have a vertical LinearLayout where one of the items is an  loaded using Picasso. I need to rise the image's width to the full device width, and to display the center part of the image cropped by a fixed height (150dp). I currently have the following code:Which values should I put into  and  (=150dp)?You are looking for:What these mean:Image Resizing with resize(x, y)\nGenerally it's optimal if your server or API deliver the image in the exact dimensions you need, which are a perfect trade-off between bandwidth, memory consumption and image quality.Unfortunately, it's not always in your control to request images in the perfect dimensions. If the images are in a weird size you can use the resize(horizontalSize, verticalSize) call to change the dimensions of your image into a more suitable size. This will resize the image before displaying it in the ImageView.Use of scaleDown()\nWhen using the resize() option Picasso will also upscale your image. Since making a small image bigger without improving the quality of the image can be wasted computing time, call scaleDown(true) to only apply the resize() when the original image has larger dimensions than the target size.Avoiding Stretched Images with Scaling\nNow, as with any image manipulation, resizing images can really distort the aspect ratio and uglify the image display. In most of your use cases, you want to prevent this from happening. Picasso gives you two mitigation choices here, either call centerCrop() or centerInside().CenterCrop() is a cropping technique that scales the image so that it fills the requested bounds of the ImageView and then crops the extra. The ImageView will be filled completely, but the entire image might not be displayed.CenterInside() is a cropping technique that scales the image so that both dimensions are equal to or less than the requested bounds of the ImageView. The image will be displayed completely, but might not fill the entire ImageView.Last, but not least: Picasso's fit()\nThe discussed options should cover your needs for functionality regarding image resizing and scaling. There is one last helper functionality of Picasso, which can be very useful: fit().fit() is measuring the dimensions of the target ImageView and internally uses resize() to reduce the image size to the dimensions of the ImageView. There are two things to know about fit(). First, calling fit() can delay the image request since Picasso will need to wait until the size of the ImageView can be measured. Second, you only can use fit() with an ImageView as the target (we'll look at other targets later).The advantage is that the image is at the lowest possible resolution, without affecting its quality. A lower resolution means less data to be hold in the cache. This can significantly reduce the impact of images in the memory footprint of your app. In summary, if you prefer a lower memory impact over a little faster loading times, fit() is a great tool.
Java

Trying to remove all letters and characters that are not 0-9 and a period.  Im using Character.isDigit() but it also removes decimal, how can I also keep the decimal.Try this code:Now  will contain .I would use a regex.printsYou might like to keep  as well for negative numbers.With guava:see result: 0097-557890-999if you also do not need \"-\" in String you can do like this:result: 0097557890999Adding an extra character check for dot  will solve the requirement:A way to replace it with a java 8 stream:
Java

I was trying to look how my app looks in material design and I would like to use the new cards lib.\nMy Problem is, that it's giving me this error within my gradle file and I need to fix that.I downloaded and installed it. in Terminal is showing me that 1.7 is installed:wellis giving me: doesn't have a . I found the  here:And set the path to the \"SDK location\" Preferences in Android Studio under \"JDK location\". But it's not working -- it seems that it still can't find JDK 7.I'm using Mac OSX 10.9.3 and Android Studio (Beta) 0.8.1.Setting the directory to:\n\nin JDK settings solved my issue. I had the same problem getting started up. Hope this helps!@megapoff answer is correct . But I face little difficulty to fix it . So here is the detail solution step-by-step  The other answers are very correct but I want to be more concise and clear. To prevent others from visiting this page multiple times unnecessarily.Important* Old Path is /System/Library/Java... and New Path is /Library/Java... (Not under the System directory)Replace old path: /System/Library/Java/JavaVirtualMachines/jdk1.6.0_0.jdk/Contents/HomeSet your new path: /Library/Java/JavaVirtualMachines/jdk1.7.0_79.jdk/Contents/HomeI haven't moved over to Android Studio, yet. I've used it for a few tests and really like it. Just haven't been able to switch over yet. I've had this sort of issue in Eclipse and that's obviously a different solution, but looking through one of my test projects, this appears to be how you go about it:Open your project and go to File->Settings.Under the Project Settings, expand Compiler and go to the Java Compiler option. You want to use javac and set the project bytecode version to 1.7.Hopefully that'll do it.For jdk-7u79-macosx-x64.dmg just Setting the directory to\n/Library/Java/JavaVirtualMachines/jdk1.7.0_60.jdk/Contents/HomeNot in \n/System/Library/Java/JavaVirtualMachines/jdk1.7.0_60.jdk/Contents/HomeBoth are differentInstead of looking for the folder inside :\nWe have to look into :
Java

My keystore is corrupt, therefore the Android Market is requiring me to rename the app and resubmit it. However, whenever I go to edit the package names in Manifest and throughout the files, it gives me tons of errors.What's the proper way to change the application name?If you're using Eclipse, you could try  from Android's developer site. They're specifically for the GestureBuilder sample but should apply to any application as far as I can tell:Also, be sure you remembered to rename the package itself along with the references to it in the files. In Eclipse you can see the name of the package in the file explorer window/tree view on the left hand side. In my experience, Eclipse can sometimes be a little finnicky and unreliable with this (leaving behind stray references to the old package name, for example).There is a way to change the package name easily in Eclipse. Right click on your project, scroll down to Android Tools, and then click on Rename Application Package.Here's how you could do this in Eclipse:\nsuper easy way\nright click on your project...\nIn , which, quite honestly, you should be using, change the package name by  on the package name in the It then gives the option of renaming the directory or the package. Select the package. The directory should follow suit. Type in your new package name, and click Refactor. It will change all the imports and remove redundant imports for you. You can even have it fix it for you in comments and strings, etc., change the package name accordingly in your AndroidManifest.xml towards the top. Otherwise you will get errors everywhere complaining about R.whatever.First create a new package with the desired namejava folder -> new -> package.`Then, select and drag all your classes to the new package. AndroidStudio will re-factor the package name everywhere.After that: in your app's  add/edit applicationId with the new one. i.e. ( in my case):  Original post and more comments Without Eclipse:The above 6 steps are what I did to get my package name changed and get a successful* build. There may be a better way to handle steps 5 and 6 via dex commands to update paths, or perhaps by editing classes.dex.d in the root directory of the project. I'm not familiar with dex or if it's ok to delete/edit classes.dex.d so I went with the method of deleting .class files that I know will be regenerated in the build. I then checked classes.dex.d to see what still needed to be updated.*No errors or warnings left in my build EXCEPT dex and apkbuilder both state \"Found Deleted Target File\" with no specifics about what that file is. Not sure if this shows up in every build, if it was there before I messed with my package name, or if it's a result of my deletions and I'm missing a step.Follow these steps:-Changing package name is a pain in the ass. It looks like different methods work for different people. My solution is quick and error free. Looks like no cleaning or resetting eclipse is needed.:P.S. If you will not follow this order you can end up changing all the java files one by one with new imports and a bunch of compile time errors, so the order is very important.Bernstein has the method, use the Eclipse tool, \"Rename Application Package\", you may have to do some clean-up even after the fact. \nAlso, Eclipse sometimes loses track of things when you make changes to a project. You may have to use the \"Clean Project\" tool (under the \"Project\" menu.) If that doesn't work, you may have to close and restart Eclipse. Voo-doo solutions, but Eclipse can be that way. I found the easiest solution was to use  to replace \"com.package.name\" with \"com.newpackage.name\", then rename the directories properly. Super easy, super fast.There is also another solution for users without Eclipse, simply change the package attribute in  <manifest> tag in AndroidManifest.xml, by replacing the the old package name used with a new one.  You have to adjust the all the related import statements and related folders manually in your project than, too.Alternative: I just lost few hours trying all solutions. I was sure, problem is in my code - apk starting but some errors when working with different classes and activities.Only way working with my project:For me it works, only solution.In Android Studio 1.2.2\nSay if you want to change  to \nYou can follow the steps in each of the directories as displayed in the below screen shot. It will give you the preview option so that you can preview before making any changes. Go to  and give your new name. You have to do it for each of the folders, say for com, example and myapp. It will automatically update the imports so that you don't have to worry about it.\nAlso update the file  which is not updated automatically.After that it will ask for  do it. Then everything will be fine. I'm able to upload my APK to google store after this. Make sure you have signed your app to upload it to the store.So, using IntelliJ with Android (Studio) plugin was: I went to  on top and changed package name by right-clicking -> Refactor -> rename.\nOur then package name had four parts , the new one only .\nSo I renamed the first three. Then I went to the directory of generated sources (), right-clicked  class and Refactor->Move[d] it to one package higher. Same with  in .By using Refactor->Move, IntelliJ updates all references to  and . Finally I updated all applicationId[s] I found in gradle.build I found. I hit Clean Project, Make and Rebuild Project. Deleted the app from my phone and hit \"Play\". It all worked out so refactoring was easy and quite fast.
Java

For new applications written in Java 7, is there any reason to use a  object any more or can we consider it deprecated? I believe a  can do everything a  can do and more.  will most likely  be deprecated / unsupported. That said,  is part of the more modern  lib, and does everything  can, but generally in a better way, and then some. For new projects, use .And if you ever need a  object for legacy, just call Not unless and until it is so marked in the Javadoc.Check this article about more info - Basically file.Path will be the way to go from now on but as is widely known Java people tend to keep back-compatibility so I guess that's why they have left it. Yes, but many existing APIs, including Java7's own standard APIs, still work only with  type.Am I missing something? Problem for me is that Path doesn't give you attributes as easily as File. For example, you want to use Java 8 streams to get the last modified file in a directory, where it's tempting to do the following:To do this with Path would require a lot of messy stuff retrieving .This is a bit like saying: \"should Napoleon invade Russia,  are these Brussels sprouts really tasty?\"As to the second part of the question, you can indeed consider it deprecated. As of March 2017, it isn't deprecated.  But there's nothing to stop you  it so.  Whether that will procure you any advantage in this life or the next is impossible to say.
Java

I'm trying to hold a list of items in a collection with a key of my choice. In Java, I would simply use Map as follows:Is there an equivalent way of doing this in C#?\n doesn't uses hash and I cannot define a custom type key\n isn't a generic class\n doesn't have a  methodYou can index Dictionary, you didn't need 'get'.An efficient way to test/get values is  (thanx to  Earwicker):With this method you can fast and exception-less get values (if present).Resources:Dictionary<,> is the equivalent.  While it doesn't have a Get(...) method, it does have an indexed property called Item which you can access in C# directly using index notation:If you want to use a custom key type then you should consider implementing IEquatable<> and overriding Equals(object) and GetHashCode() unless the default (reference or struct) equality is sufficient for determining equality of keys.  You should also make your key type immutable to prevent weird things happening if a key is mutated after it has been inserted into a dictionary (e.g. because the mutation caused its hash code to change).
Java

My question is very basic, but I didn't find an answer on a Google search.In , what is the maximum size a  object may have, referring to the  method call?I know that  return the size of a  as a ;Considering the  class'  method returns an , the maximum length that would be returned by the method would be , which is  (or approximately 2 billion.)In terms of lengths and indexing of arrays, (such as , which is probably the way the internal data representation is implemented for s),  of  says the following:Furthermore, the indexing must be by  values, as mentioned in :Therefore, it appears that the limit is indeed , as that is the maximum value for a nonnegative  value.However, there probably are going to be other limitations, such as the maximum allocatable size for an array.Since arrays must be indexed with integers, the maximum length of an array is  (2-1, or 2\u00a0147\u00a0483\u00a0647). This is assuming you have enough memory to hold an array of that size, of course. and  say that a  object is represented by  of length information and the  representation of every character in the string. This concludes that the length of String is limited by the number of bytes of the modified UTF-8 representation of the string when used with  and .In addition,  found in the Java virtual machine specification defines the structure as follows.You can find that the size of 'length' is .That the return type of a certain method (e.g. ) is  does not always mean that its allowed maximum value is . Instead, in most cases,  is chosen just for performance reasons. The Java language specification says that integers whose size is smaller than that of  are converted to  before calculation (if my memory serves me correctly) and it is one reason to choose  when there is no special reason.The maximum length at compilation time is at most 65536. Note again that the length is the number of bytes of the  representation, not the number of characters in a  object. objects may be able to have much more characters at runtime. However, if you want to use  objects with  and  interfaces, it is better to avoid using too long  objects. I found this limitation when I implemented Objective-C equivalents of  and .apparently it's bound to an int, which is 0x7FFFFFFF (2147483647).The Return type of the length() method of the String class is .Refer So the maximum value of int is .String is considered as char array internally,So indexing is done within the maximum range.\nThis means we cannot index the 2147483648th member.So the maximum length of String in java is 2147483647.Primitive data type int is 4 bytes(32 bits) in java.As 1 bit (MSB) is used as a ,The range is constrained within  (-2147483648 to 2147483647).\nWe cannot use negative values for indexing.So obviously the range we can use is from 0 to 2147483647.I have a 2010 iMac with 8GB of RAM, running Eclipse Neon.2 Release (4.6.2) with Java 1.8.0_25. With the VM argument -Xmx6g, I ran the following code:This prints:So, it seems that the max array size is ~1,207,959,549. Then I realized that we don't actually care if Java runs out of memory: we're just looking for the maximum array size (which seems to be a constant defined somewhere). So:Which prints:So, it seems the max is Integer.MAX_VALUE - 2, or (2^31) - 3P.S. I'm not sure why my  maxed out at  while my  maxed out at (2^31)-3. It seems that  doubles the size of its internal  to grow it, so that probably causes the issue.
Java

i am executing simple Dependency Injection program of spring & getting this exception. \nI have already included common-logging1.1.1.jar and spring.jar file. Could you please help to out?I have also faced the same issues, to fix, download the jar files from the below urland copy to your lib folder, will resolve your issue.If you're using maven for managing dependencies, add the following line in your pom.xml:You just download  and then copy this file in to libsfinally, it works.I had the same problem, and solved it by just adding the  to the class path.commons-logging-1.1.1.jar or jcl-over-slf4j-1.7.6.jar alIf you are using maven, use the below code.Setting the scope to compile did it for meAre you sure you spelled the name of the JAR file exactly right? I think it should probably be  (note the extra  in the name). Also check if the directory name is correct. always means that a class cannot be found, so most likely your class path is not correct.Issue solved by adding commons-logging.jarImp files are ,Two options (at least):Note: linking the jar can lead to problems with the server and maybe the reason why it's added to the build path but not solving the server startup problem.So don't point the jar to an external folder.OR...If you're using a tc server instance, then you need to add the jar as an external jar to the server instance run configurations.go to run as, run configurations..., {your tc server instance}, and then the Class Path tab.Then add the commons-logging jar.Adding commons-logging.jar or commons-logging-1.1.jar will solve this...Try doing a complete clean of the target/deployment directory for the app to get rid of any stale library jars. Make a fresh build and check that commons-logging.jar is actually being placed in the correct lib folder. It might not be included when you are building the library for the application. use this url to download jar files and include them in your class path, issue will be solvedI got the same trouble than you.\nFinally I checked the version of apache possessing the class. \nI found that the version 1.0.4 has the class.Try to use the version 1.0.4 instead of 1.1.X or 1.2.XMy dependencies : My Java Code My Result : Double check also that your maven dependencies are well imported.I generally assign the classpath to a variable and then verify it.  I've written a small ruby script which I include in a my startup scripts which .  Validating the classpath before the JVM starts has saved me lots of time troubleshooting these types of problems.Hey I was following the tutorial on tutorialpoint.com. Add after you complete  You must  libraries to the project from the files downloaded at this step. For me the file name was \"\".  If you're running this on Android then note that apparently  package is not complete on Android. To attempt to fix it on Android try the following:, I apologise as I realise this is not exactly answering the question, though this SO page comes up a lot when searching for android-generated  errors.Just check whether the commons-logging.jar has been added to your libs and the classpath.. I had the same issue and that was because of this. \ndhammikas-try to include:into your WEB-INF/lib folder.I tried, it works.Check whether the jars are imported properly. I imported them using build path. But it didn't recognise the jar in WAR/lib folder. Later, I . It works fine now. You can refresh / clean your project.try adding this dependency\n    \n        org.apache.commons\n        commons-exec\n        1.3\n    Hello friends if your getting any not class found exception in hibernate code it is the problem of jar files.here mainly two problems\n1.I mean to say your working old version of hibernate may be 3.2 bellow.So if u try above 3.6 it will works fine2.first checkes database connection.if it database working properly their was a mistake in ur program or jar file.  please check these two prioblems if it also not working you tried to IDE . I am using netbeanside 6.9 version.here hibernate working fine.you dont get any error from class not founnd exception..I hope this one helps moreSolution is to Add  jar fileIf all else fails, as it had for me, try putting the commons-logging-x.y.z.jar in your Tomcat lib directory.  It solved the problem!  BTW, I am using Tomcat 6.
Java

How can I change the current working directory from within a Java program? Everything I've been able to find about the issue claims that you simply can't do it, but I can't believe that that's really the case.I have a piece of code that opens a file using a hard-coded relative file path from the directory it's normally started in, and I just want to be able to use that code from within a different Java program without having to start it from within a particular directory. It seems like you should just be able to call , but as far as I can figure out, calling that line just silently fails and does nothing.I would understand if Java didn't allow you to do this, if it weren't for the fact that it allows you to  the current working directory, and even allows you to open files using relative file paths....There is no reliable way to do this in pure Java. Setting the  property via  or  does seem to affect subsequent creations of , but not e.g. .The  constructor can help if you build up your directory path separately from your file path, allowing easier swapping.An alternative is to set up a script to run Java from a different directory, or use JNI native code . was closed in 2008 as \"will not fix\".If you run your legacy program with , you will be able to specify its working .There  a way to do this using the system property \"user.dir\".  The key part to understand is that getAbsoluteFile() must be called (as shown below) or else relative paths will be resolved against the  \"user.dir\" value.It is possible to change the PWD, using JNA/JNI to make calls to libc. The JRuby guys have a handy java library for making POSIX calls called  Here's You can see an example of its use  (Clojure code, sorry). Look at the function chdirToRootIf I understand correctly, a Java program starts with a  of the current environment variables. Any changes via  are modifying the copy, not the original environment variables. Not that this provides a thorough reason as to why Sun chose this behavior, but perhaps it sheds a little light...As mentioned you can't change the CWD of the JVM but if you were to launch another process using Runtime.exec() you can use the overloaded method that lets you specify the working directory. This is not really for running your Java program in another directory but for many cases when one needs to launch another program like a Perl script for example, you can specify the working directory of that script while leaving the working dir of the JVM unchanged.See  javadocsSpecifically,where  is the working directory to run the subprocess inThe working directory is a operating system feature (set when the process starts). \nWhy don't you just pass your own System property () and use that in your code as the parent of your File:The smarter/easier thing to do here is to just change your code so that instead of opening the file assuming that it exists in the current working directory (I assume you are doing something like , just build the path to the file yourself.Let the user pass in the base directory, read it from a config file, fall back to  if the other properties can't be found, etc. But it's a whole lot easier to improve the logic in your program than it is to change how environment variables work.I have tried to invokeIt seems to work. But throws a  thoughshows the correct path. \nI have . I think the problem is:The solution may be: It creates a file Object as absolute one with the current directory which is known by the JVM. But that code should be existing in a used class, it needs changing of reused codes.~~~~JcHartmutThe other possible answer to this question may depend on the reason you are opening the file.  Is this a property file or a file that has some configuration related to your application?If this is the case you may consider trying to load the file through the classpath loader, this way you can load any file Java has access to.If you run your commands in a shell you can write something like \"java -cp\" and add any directories you want separated by \":\" if java doesnt find something in one directory it will go try and find them in the other directories, that is what I do.You can use after Will printUse FileSystemView 
Java

So, normally  would return a type of ....but supposed it's an \n of object , how do I make  to return a type of  rather than ?Like this:It's tempting to do it like:but the internal implementation will realloc a properly sized array anyway so you are better doing it upfront.If your list is not properly typed you need to do a cast before calling toArray. Like this:It doesn't really need to return , for example:-Here's my  class:-I got the answer...this seems to be working perfectly fineSamples:
Java

In eclipse, when your cursor is placed on a method (or other things), other places the method exists are highlighted. I'd like to change the color of this highlight, but after scouring the eclipse preferences many times in all 3 places, I have yet to find it.Any of you Eclipse gurus know where to find this option?Thank you!After running around in the Preferences dialog, the following is the location at which the highlight color for \"occurrences\" can be changed:Look for  from the  list.Then, be sure that  is selected, then choose the desired color.And, a picture is worth a thousand words...For those working in Titanium Studio, the item is a little different:  It's under the \"Titanium Studio\" Themes tab.The color to change is the \"Selection\" one in the top right.1 - right click the highlight whose color you want to change2 - select \"Properties\" in the popup menu3 - choose the new color (as  suggested)This solution is easy because you dont have to search for the highlight by its name (\"Ocurrence\" or \"Write Ocurrence\" etc), just right click and the appropriate window is shown.If you're using eclipse with PHP package and want to change highlighted colour then there is slight difference to above answer.
Java

Does creating an object using reflection rather than calling the class constructor result in any significant performance differences? Looking up a class via reflection is, , more expensive.Quoting :Here's a simple test I hacked up in 5 minutes on my machine, running Sun JRE 6u10:With these results:Bear in mind the lookup and the instantiation are done together, and in some cases the lookup can be refactored away, but this is just a basic example.Even if you just instantiate, you still get a performance hit:Again, YMMV.Yes, it's slower.But remember the damn #1 rule--PREMATURE OPTIMIZATION IS THE ROOT OF ALL EVIL(Well, may be tied with #1 for DRY)I swear, if someone came up to me at work and asked me this I'd be very watchful over their code for the next few months.You must never optimize until you are sure you need it, until then, just write good, readable code.Oh, and I don't mean write stupid code either.  Just be thinking about the cleanest way you can possibly do it--no copy and paste, etc.  (Still be wary of stuff like inner loops and using the collection that best fits your need--Ignoring these isn't \"unoptimized\" programming, it's \"bad\" programming)It freaks me out when I hear questions like this, but then I forget that everyone has to go through learning all the rules themselves before they really get it.  You'll get it after you've spent a man-month debugging something someone \"Optimized\".EDIT:An interesting thing happened in this thread.  Check the #1 answer, it's an example of how powerful the compiler is at optimizing things.  The test is completely invalid because the non-reflective instantiation can be completely factored out.Lesson?  Don't EVER optimize until you've written a clean, neatly coded solution and proven it to be too slow.You may find that A a = new A() is being optimised out by the JVM.\nIf you put the objects into an array, they don't perform so well. ;)\nThe following prints...This suggest the difference is about 150 ns on my machine.There is some overhead with reflection, but it's a lot smaller on modern VMs than it used to be.If you're using reflection to create every simple object in your program then something is wrong. Using it occasionally, when you have good reason, shouldn't be a problem at all.\"Significant\" is entirely dependent on context.If you're using reflection to create a single handler object based on some configuration file, and then spending the rest of your time running database queries, then it's insignificant. If you're creating large numbers of objects via reflection in a tight loop, then yes, it's significant.In general, design flexibility (where needed!) should drive your use of reflection, not performance. However, to determine whether performance is an issue, you need to profile rather than get arbitrary responses from a discussion forum.If there  is need for something faster than reflection, and it's not just a premature optimization, then bytecode generation with  or a higher level library is an option. Generating the bytecode the first time is slower than just using reflection, but once the bytecode has been generated, it is as fast as normal Java code and will be optimized by the JIT compiler.Some examples of applications which use code generation:Reflection is slow, though object allocation is not as hopeless as other aspects of reflection.  Achieving equivalent performance with reflection-based instantiation requires you to write your code so the jit can tell which class is being instantiated.  If the identity of the class can't be determined, then the allocation code can't be inlined.  Worse, escape analysis fails, and the object can't be stack-allocated.  If you're lucky, the JVM's run-time profiling may come to the rescue if this code gets hot, and may determine dynamically which class predominates and may optimize for that one.Be aware the microbenchmarks in this thread are deeply flawed, so take them with a grain of salt.  The least flawed by far is Peter Lawrey's: it does warmup runs to get the methods jitted, and it (consciously) defeats escape analysis to ensure the allocations are actually occurring.  Even that one has its problems, though: for example, the tremendous number of array stores can be expected to defeat caches and store buffers, so this will wind up being mostly a memory benchmark if your allocations are very fast.  (Kudos to Peter on getting the conclusion right though: that the difference is \"150ns\" rather than \"2.5x\".  I suspect he does this kind of thing for a living.)Yes there is a performance hit when using Reflection but a possible workaround for optimization is caching the method:will result in:Yes, it is significantly slower. We were running some code that did that, and while I don't have the metrics available at the moment, the end result was that we had to refactor that code to not use reflection. If you know what the class is, just call the constructor directly.Interestingly enough, settting setAccessible(true), which skips the security checks, has a 20% reduction in cost.Without setAccessible(true)With setAccessible(true)In the doReflection() is the overhead because of Class.forName(\"misc.A\") (that would require a class lookup, potentially scanning the class path on the filsystem), rather than the newInstance() called on the class. I am wondering what the stats would look like if the Class.forName(\"misc.A\") is done only once outside the for-loop, it doesn't really have to be done for every invocation of the loop.Yes, always will be slower create an object by reflection because the JVM cannot optimize the code on compilation time. See the Sun/Java  for more details.See this simple test:Often you can use Apache commons BeanUtils or PropertyUtils which introspection (basically they cache the meta data about the classes so they don't always need to use reflection).I think it depends on how light/heavy the target method is. if the target method is very light(e.g. getter/setter), It could be 1 ~ 3 times slower. if the target method takes about 1 millisecond or above,  then the performance will be very close. here is the test I did with Java 8 and  :The complete test code is available at GitHub:
Java

What is the maximum number of parameters that a method in Java can have and why?I am using Java 1.8 on a 64-bit Windows system.All the answers on StackOverflow about this say that the technical limit is 255 parameters without specifying why.To be precise, 255 for static and 254 for non-static ( will be the 255th in this case) methods.I thought this could be described in some sort of specification and that there is simply a statically defined maximum number of parameters allowed. But this was only valid for .\nI did some tests with  parameters, and I was only able to declare 127 parameters in that case.With  parameters, the allowed number I deduced from testing is 255 (it may be because the reference size is 4 bytes in Java?).But since I am using a 64-bit system, references size should be 8 bytes wide and so with  parameters the maximum allowed number should be 127, similar to  types.How does this limit is exactly applied? Does the limit have anything to do with the  of the method?Note: I am not really going to use these many parameters in any method, but this question is only to clarify the exact behavior.That limit is defined in the :Section  gives some additional information:Your observations were spot on, double word primitives (/) need twice the size of usual 4 bytes variables .Regarding the last part of your question related to 64bit systems, the specification defines how many ,  that part of the specification  even on a 64bit platform,  the 64bit JVM will accomodate 255 instance parameters (like your 255 ) regardless of the internal object's pointer size. of the JVM specification has the information you are looking for:Therefore it appears that whether the host-machine is 32-bit or 64-bit has no effect on the number of parameters. If you notice, the documentation speaks in terms of \"units\", where the length of one \"unit\" is a function of the word-size. If the number of parameters directly proportional to word-size, there would be portability issues; you wouldn't be able to compile the same Java program on different architectures (assuming that at least one method used the maximum-number of parameters on the architecture with the larger word-size). I found an interesting issue from a newsletter about this, 
Java

What are the pros and cons of each  (BDD) framework for Java?I've found some of them , for example.Does it make sense to use a BDD framework if I already use a mocking library (e.g. )?I've just finished comparing three BDD frameworks for Java. Obviously my findings have a fairly short use-by date.I didn't have the chance to try out Cuke4Duke of JDave as I would have liked, but will probably push for JBehave at this time.\"pros and cons\" might be different things for different people. I usually have a look atAnd from some frameworks I had a look atConcerning the mocks: You definitely need a mocking framework as well. The BDD frameworks just help you in writing the specs, but some tests will need mocks or stubs, esp. when you design top down (from overview to detail).Here is an interesting link about Really, look at the one mentioned above.Short answer: yes, definitely. Actually, acceptance testing using a BDD framework and unit testing in isolation using mock objects are so different that I don't really get the question. Acceptance testing is black box testing, tests are used to verify that a business feature is working and are ideally written by business analyst. Unit tests in isolation using mocks is white box testing, tests are used to verify that a unit is working and are written by developers. Both are useful buty they have totally different purposes. In other words, using Mockito doesn't replace a BDD framework at all and the inverse is also true.I originally did my BDD with plain jUnit but I've been looking at  lately because it's almost 1:1 to what I was doing with jUnit. It also runs on top of jUnit so it already works on Eclipse and is also easy to configure to work on continuous integration systems such as Hudson. Can't really compare it with others but my experiences with JDave have been good so far.Oh and it's never a stupid idea to use mocks! They're not tied to TDD/BDD specifically, their purpose is to ease the burden of testing in general.Wow, I see the topic is hot, lot of good answers...Irony aside, I recently discovered BDD and found the concept interesting. Hey, it forces to write both tests... and specifications! As surprising as it might seem, the latter can be also missing in some projects... Or just lacking the precision that BDD forces to introduce.The  article summarizes the concept and links to some good articles (like the one written by Andrew Glover). Moreover, to the topic of this thread, it gives a rather comprehensive (I suppose) listing of BDD frameworks, a good number of them being for Java.\nIt doesn't solve the problem of choosing the framework but at least it will ease the search...Since BDD relies heavily on readability of test code, I suppose a good criterion of choice is to look at the quick tours/tutorial and see which one seems the more fitting your style.\nOther criteria could be the fact a framework leverage tools you are familiar with (unit test, mocking), usage with IDE, and so on.My team have been using  for some time. It uses plain text files to store specifications. Every step (Given, When, Then) is then executed by a certain method which can extract parameters from the step. Scenarios can be indented and well formatted which helps a lot if clients want to verify them.There are some problems, too. We have switched to Java 6. Sometimes some scenario steps are ignored during execution. It may cause a lot of trouble figuring out where's the bug.My team have used JBehave with success - we moved to it after using EasyB and found the plain text scenario files easier to deal with.I tried  (previously developed as Cuke4Duke).\nIt uses Gherkin DSL for specification, stored as plain text.It can be run as JUnit test. So the only problem to start using is to make business people or Product Manager to read/write .features in Sources.Results
Java

I've seen some interesting claims on SO re Java hashmaps and their  lookup time. Can someone explain why this is so? Unless these hashmaps are vastly different from any of the hashing algorithms I was bought up on, there must always exist a dataset that contains collisions.In which case, the lookup would be  rather than . Can someone explain whether they  O(1) and, if so, how they achieve this?A particular feature of a HashMap is that unlike, say, balanced trees, its behavior is probabilistic.  In these cases its usually most helpful to talk about complexity in terms of the probability of a worst-case event occurring would be.  For a hash map, that of course is the case of a collision with respect to how full the map happens to be.  A collision is pretty easy to estimate.  So a hash map with even a modest number of elements is pretty likely to experience at least one collision.  Big O notation allows us to do something more compelling. Observe that for any arbitrary, fixed constant k.We can use this feature to improve the performance of the hash map.  We could instead think about the probability of at most 2 collisions.This is much lower.  Since the cost of handling one extra collision is irrelevant to Big O performance, we've found a way to improve performance without actually changing the algorithm!  We can generalzie this to And now we can disregard some arbitrary number of collisions and end up with vanishingly tiny likelihood of more collisions than we are accounting for.  You could get the probability to an arbitrarily tiny level by choosing the correct k, all without altering the actual implementation of the algorithm.We talk about this by saying that the hash-map has O(1) access You seem to mix up worst-case behaviour with average-case (expected) runtime. The former is indeed O(n) for hash tables in general (i.e. not using a perfect hashing) but this is rarely relevant in practice.Any dependable hash table implementation, coupled with a half decent hash, has a retrieval performance of O(1) with a very small factor (2, in fact) in the expected case, within a very narrow margin of variance.In Java, HashMap works by using hashCode to locate a bucket.  Each bucket is a list of items residing in that bucket.  The items are scanned, using equals for comparison.  When adding items, the HashMap is resized once a certain load percentage is reached.So, sometimes it will have to compare against a few items, but generally it's much closer to O(1) than O(n).  For practical purposes, that's all you should need to know.Remember that o(1) does not mean that each lookup only examines a single item - it means that the average number of items checked remains constant w.r.t. the number of items in the container. So if it takes on average 4 comparisons to find an item in a container with 100 items, it should also take an average of 4 comparisons to find an item in a container with 10000 items, and for any other number of items (there's always a bit of variance, especially around the points at which the hash table rehashes, and when there's a very small number of items).So collisions don't prevent the container from having o(1) operations, as long as the average number of keys per bucket remains within a fixed bound.O(1+n/k) where k is the number of buckets. If implementation sets k = n/alpha then it is O(1+alpha) = O(1) since alpha is a constant.I know this is an old question, but there's actually a new answer to it.  You're right that a hash map isn't really O(1), strictly speaking, because as the number of elements gets arbitrarily large, eventually you will not be able to search in constant time (and O-notation is defined in terms of numbers that can get arbitrarily large).  But it doesn't follow that the real time complexity is O(n)--because there's no rule that says that the buckets have to be implemented as a linear list.  In fact, Java 8 implements the buckets as  once they exceed a threshold, which makes the actual time O(log n).If the number of buckets (call it b) is held constant (the usual case), then lookup is actually O(n).\n As n gets large, the number of elements in each bucket averages n/b. If collision resolution is done in one of the usual ways (linked list for example), then lookup is O(n/b) = O(n).The O notation is about what happens when n gets larger and larger. It can be misleading when applied to certain algorithms, and hash tables are a case in point. We choose the number of buckets based on how many elements we're expecting to deal with. When n is about the same size as b, then lookup is roughly constant-time, but we can't call it O(1) because O is defined in terms of a limit as n \u2192 \u221e.We've established that the standard description of hash table lookups being O(1) refers to the average-case expected time, not the strict worst-case performance. For a hash table resolving collisions with chaining (like Java's hashmap) this is technically O(1+\u03b1) with , where \u03b1 is the table's load factor. Still constant as long as the number of objects you're storing is no more than a constant factor larger than the table size.It's also been explained that strictly speaking it's possible to construct input that requires O() lookups for any deterministic hash function. But it's also interesting to consider the worst-case  time, which is different than average search time. Using chaining this is O(1 + the length of the longest chain), for example \u0398(log  / log log ) when \u03b1=1.If you're interested in theoretical ways to achieve constant time expected worst-case lookups, you can read about  which resolves collisions recursively with another hash table!It is O(1) only if your hashing function is very good. The Java hash table implementation does not protect against bad hash functions.Whether you need to grow the table when you add items or not is not relevant to the question because it is about lookup time.This basically goes for most hash table implementations in most programming languages, as the algorithm itself doesn't really change. If there are no collisions present in the table, you only have to do a single look-up, therefore the running time is O(1). If there are collisions present, you have to do more than one look-up, which drives down the performance towards O(n).It depends on the algorithm you choose to avoid collisions. If your implementation uses separate chaining then the worst case scenario happens where every data element is hashed to the same value (poor choice of the hash function for example). In that case, data lookup is no different from a linear search on a linked list i.e. O(n). However, the probability of that happening is negligible and lookups best and average cases remain constant i.e. O(1).Academics aside, from a practical perspective, HashMaps should be accepted as having an inconsequential performance impact (unless your profiler tells you otherwise.)Elements inside the HashMap are stored as an array of linked list (node), each linked list in the array represent a bucket for unique hash value of one or more keys.\nWhile adding an entry in the HashMap, the hashcode of the key is used to determine the location of the bucket in the array, something like:Here the & represents bitwise AND operator.For example: During get operation it uses same way to determine the location of bucket for the key. Under the best case each hashcode is unique and results in a unique bucket for each key, in this case the get method spends time only to determine the bucket location and retrieving the value which is constant O(1). Under the worst case, all the keys have same hashcode and stored in same bucket, this results in traversing through the entire list which leads to O(n).In the case of java 8, the Linked List bucket is replaced with a TreeMap if the size grows to more than 8, this reduces the worst case search efficiency to O(log n).Only in theoretical case, when hashcodes are always different and bucket for every hash code is also different, the O(1) will exist. Otherwise, it is of constant order i.e. on increment of hashmap, its order of search remains constant.Of course the performance of the hashmap will depend based on the quality of the hashCode() function for the given object. However, if the function is implemented such that the possibility of collisions is very low, it will have a very good performance (this is not strictly O(1) in  possible case but it is in  cases).For example the default implementation in the Oracle JRE is to use a random number (which is stored in the object instance so that it doesn't change - but it also disables biased locking, but that's an other discussion) so the chance of collisions is very low.
Java

What is a synthetic class in Java? Why should it be used? How can I use it?For example, When you have a switch statement, java creates a variable that starts with a $.  If you want to see an example of this, peek into the java reflection of a class that has a switch statement in it.  You will see these variables when you have at least one switch statement anywhere in the class. To answer your question, I don't believe you are able to access(other than reflection) the synthetic classes.If you are analyzing a class that you don't know anything about (via reflection) and need to know very specific and low-level things about that class, you may end up using Java reflection methods that have to do with synthetic classes. The only \"use\" here is get more information about the class in order to use it appropriately in your code. (If you're doing this, you're probably building a framework of some sorts that other developers could use. )Otherwise, if you are not using reflection, there are no practical uses of synthetic classes that I know of. Java has the ability to create classes at runtime. These classes are known as Synthetic Classes or Dynamic Proxies.See  for more information.Other open-source libraries, such as  and  also allow you to generate synthetic classes, and are more powerful than the libraries provided with the JRE.Synthetic classes are used by AOP (Aspect Oriented Programming) libraries such as Spring AOP and AspectJ, as well as ORM libraries such as Hibernate. Well I found the answer to the first question on google:This is just a basic definition but I found it in a forum thread and there was no explanation. Still looking for a better one...synthetic classes / methods / fields:These things are important for the VM. Have a look at following code snippet:According to , though the language specification describes an \"isSynthetic\" proprty for classes, this is pretty much ignored by implementations and not used for either dynamic proxies or anonymous classes. Synthetic fields and constructors are used to implement nested classes (there is not concept of nested classes in byte code, only in source code).I think that the concept of synthetic classes has simply proven to be not useful, i.e. nobody cares whether a class is synthetic. With fields and methods, it's probably used in exactly one place: to determine what to show in an IDE class structure view - you want normal methods and fields to show up there, but not the synthetic ones used to simulate nested classes. OTOH, you DO want anonymous classes to show up there.They are created by JVM at run time when they invoke private members of inner class for  debugging purposeThe methods,fields,class created by JVM during run time for its execution purpose are called SyntheticAlso Synthetic Classes or Dynamic Proxies are used by EasyMock to create implementations of interfaces or abstract classes at runtime.If I get it right, a synthetic class is one generated on the fly, without having to give it an explicit name. For example:This creates a synthetic subclass of Thread and overrides its run() method, then instantiates it and starts it.When the Java compiler compiles certain constructs, such as inner classes, it creates ; these are classes, methods, fields, and other constructs that do not have a corresponding construct in the source code. \n\nSynthetic constructs enable Java compilers to implement new Java language features without changes to the JVM. However, synthetic constructs can vary among different Java compiler implementations, which means that .class files can vary among different implementations as well.reference:Synthetic constructs are classes, methods, fields etc that do not have a corresponding construct in the source code. Synthetic constructs enable Java compilers to implement new Java language features without changes to the JVM. However, synthetic constructs can vary among different Java compiler implementations, which means that .class files can vary among different implementations as well.I saw a synthetic class in a disassembled java 5+ project. Turns out it was a compiler hack to implement switching on enums.Synthetic class does not appear in your code, but made up by compiler. \nE.g. Bridge method made up by compiler in java is typically synthetic.Using  instruction, u can see a bridge method it is made up by compiler, however does not appear in your code.
Java

I was surprised recently to find that it's possible to have a return statement in a finally block in Java.It seems like lots of people think it's a bad thing to do as described in ''. Scratching a little deeper, I also found '' which shows some pretty horrible examples of other types of flow control in finally blocks.So, my question is, can anyone give me an example where a return statement (or other flow control) in a finally block produces better / more readable code?The examples you provided are reason enough to  use flow-control from finally.Even if there's a contrived example where it's \"better,\" consider the developer who has to maintain your code later and who might not be aware of the subtleties.  That poor developer might even be you....I had a REALLY hard time to track down a bug years ago that was caused by this. The code was something like:What happened is that the exception was thrown down in some other code. It was being caught and logged and rethrown within the  method. But the exception wasn't being propagated up past . After a LONG time of looking at this we finally tracked it down to the return method. The return method in the finally block was basically stopping the exception that happened in the try block from propagating up even though it wasn't caught.Like others have said, while it is legal to return from a finally block according to the Java spec, it is a BAD thing and shouldn't be done.javac will warn of return in finally if you use the -Xlint:finally. Originally javac emitted no warnings - if something is wrong with the code, it should fail to compile. Unfortunately backwards compatibility means that unanticipated ingenious foolishness cannot be prohibited.Exceptions can be thrown from finally blocks, but in that case the exhibited behaviour is almost certainly what you want.Adding control structures and returns to finally{} blocks are just another example of \"just because you can\" abuses which are scattered throughout virtually all development languages.  Jason was right in suggesting it could easily become a maintenance nightmare - the arguments against early returns from functions apply more-so to this case of \"late returns\".Finally blocks exist for one purpose, to allow you to completely tidy up after yourself, no matter what happened in all the preceeding code. Principally this is closing / releasing file pointers, database connections etc., though I could see it being stretched to say adding in bespoke auditing.Anything that affects the return of the function should lie in the try{} block.  Even if you had a method whereby you checked an external state, did a time consuming operation, then checked that state again in case it became invalid, you would still want the second check inside the try{} - if it sat inside finally{} and the long operation failed, you would then be checking that state a second time needlessly.One interesting point for me was to see how Groovy deals with implicit returns. In Groovy it is possible to \"return\" from a method simply leaving a value at the end (without return). What do you think happens, if you uncomment the  line in the finally statement - will this overwrite the regular return value (\"OK\") and cover the exception?!
Java

Is there any difference betweenand?If there is no difference, what is the benefit of using ?The difference is that, for example, ais abut not aSo:You would think a  of s should be a  of s, but there's a good reason why it isn't:Suppose you could do:So this is why a  of s shouldn't be a  of s.You cannot assign expressions with types such as  to the first.(If you want to know why you can't assign  to  see a  other questions on SO.)What I'm missing in the other answers is a reference to how this relates to co- and contravariance and sub- and supertypes (that is, polymorphism) in general and to Java in particular. This may be well understood by the OP, but just in case, here it goes:If you have a class , then  and  are their subtypes. Any Car can be assigned to a variable of type Automobile, this is well-known in OO and is called polymorphism. Covariance refers to using this same principle in scenarios with generics or delegates. Java doesn't have delegates (yet), so the term applies only to generics.I tend to think of covariance as standard polymorphism what you would expect to work without thinking, because:The reason of the error is, however, correct:   inherit from  and thus cannot be assigned to each other. Only the generic type parameters have an inherit relationship. One might think that the Java compiler simply isn't smart enough to properly understand your scenario there. However, you can help the compiler by giving him a hint:The reverse of co-variance is contravariance. Where in covariance the parameter types must have a subtype relationship, in contravariance they must have a supertype relationship. This can be considered as an inheritance upper-bound: any supertype is allowed up and including the specified type:This can be used with :You could even call it with a comparer that compares objects and use it with any type.A bit OT perhaps, you didn't ask, but it helps understanding answering your question. In general, when you  something, use covariance and when you  something, use contravariance. This is best explained in .You use , so the rules for  applies. Here you have a list of maps and each item you store in the list must be a  or derive from it. The statement  cannot derive from , but must be  .Hence, the following will work, because  inherits from :but this will not:and this will not work either, because it does not satisfy the covariance constraint:This is probably obvious, but you may have already noted that using the  keyword only applies to that parameter and not to the rest. I.e., the following will not compile:Suppose you want to allow any type in the map, with a key as string, you can use  on each type parameter. I.e., suppose you process XML and you want to store AttrNode, Element etc in a map, you can do something like:Today, I have used this feature, so here's my very fresh real-life example. (I have changed class and method names to generic ones so they won't distract from the actual point.)I have a method that's meant to accept a  of  objects that I originally wrote with this signature:But it want to actually call it with s of subclasses of . But this is not allowed! (The reason for that is,  could add objects to  that are of type , but not of the subtype that 's objects are declared to be at the caller's site. So this could break the type system if it were possible.)Now here come generics to the rescue, because it works as intended if I use this method signature instead:or shorter, if you don't need to use the actual type in the method body:This way, 's type becomes a collection of objects of the actual subtype of , so it becomes possible to use this with subclasses without endangering the type system.As you mentioned, there could be two below versions of defining a List:2 is very open. It can hold any object type. This may not be useful in case you want to have a map of a given type. In case someone accidentally puts a different type of map, for example, . Your consumer method might break.In order to ensure that  can hold objects of a given type, Java generics introduced . So in #1, the  can hold any object which is derived from  type. Adding any other type of data would throw an exception.
Java

From my understanding, garbage collection in Java cleans up some object if nothing else is 'pointing' to that object.My question is, what happens if we have something like this:, , and  should be garbage collected, but they are all being referenced by other objects.How does the Java garbage collection deal with this? (or is it simply a memory drain?)Java's GC considers objects \"garbage\" if they aren't reachable through a chain starting at a garbage collection root, so these objects will be collected.  Even though objects may point to each other to form a cycle, they're still garbage if they're cut off from the root.See the section on unreachable objects in Appendix A: The Truth About Garbage Collection in  (free ebook, also available on ) for the gory details.yes Java Garbage collector handles circular-reference!There are special objects called called garbage-collection roots (GC roots). These are always reachable and so is any object that has them at its own root.A simple Java application has the following GC roots:To determine which objects are no longer in use, the JVM intermittently runs what is very aptly called a . It works as followsSo if any object is not reachable from the GC roots(even if it is self-referenced or cyclic-referenced) it will be subjected to garbage collection.Ofcourse sometimes this may led to memory leak if programmer forgets to dereference an object.Source : A garbage collector starts from some \"root\" set of places that are always considered \"reachable\", such as the CPU registers, stack, and global variables. It works by finding any pointers in those areas, and recursively finding everything they point at. Once it's found all that,  else is garbage.There are, of course, quite a few variations, mostly for the sake of speed. For example, most modern garbage collectors are \"generational\", meaning that they divide objects into generations, and as an object gets older, the garbage collector goes longer and longer between times that it tries to figure out whether that object is still valid or not -- it just starts to assume that if it has lived a long time, chances are pretty good that it'll continue to live even longer.Nonetheless, the basic idea remains the same: it's all based on starting from some root set of things that it takes for granted could still be used, and then chasing all the pointers to find what else could be in use.Interesting aside: may people are often surprised by the degree of similarity between this part of a garbage collector and code for marshaling objects for things like remote procedure calls. In each case, you're starting from some root set of objects, and chasing pointers to find all the other objects those refer to...You are correct. The specific form of garbage collection you describe is called \"\". The way it works (conceptually, at least, most modern implementations of reference counting are actually implemented quite differently) in the simplest case, looks like this:And this simple strategy has exactly the problem you decribe: if A references B and B references A, then both of their reference counts can  be less than 1, which means they will never get collected.There are four ways to deal with this problem:By the way, the  major way to implement a garbage collector (and I have already hinted at that a couple of times above), is . A tracing collector is based on the concept of . You start out with some  that you know is  reachable (global constants, for example, or the  class, the current lexical scope, the current stack frame) and from there you  all objects that are reachable from the root set, then all objects that are reachable from the objects reachable from the root set and so on, until you have the transitive closure. Everything that is  in that closure is garbage.Since a cycle is only reachable within itself, but not reachable from the root set, it will be collected.The Java GCs don't actually behave as you describe.  It's more accurate to say that they start from a base set of objects, frequently called \"GC roots\", and will collect any object that can not be reached from a root.\nGC roots include things like:So, in your case, once the local variables a, b, and c go out of scope at the end of your method, there are no more GC roots that contain, directly or indirectly, a reference to any of your three nodes, and they'll be eligible for garbage collection.TofuBeer's link has more detail if you want it. goes into depth about the garbage collector (conceptually... there are several implementations).  The relevant part to your post is \"A.3.4 Unreachable\".Garbage collection doesn't usually mean \"clean some object iff nothing else is 'pointing' to that object\" (that's reference counting). Garbage collection roughly means finding objects that can't be reached from the program.So in your example, after a,b, and c go out of scope, they can be collected by the GC, since you can't access these objects anymore.Bill answered your question directly. As Amnon said, your definition of garbage collection is just reference counting. I just wanted to add that even very simple algorithms like mark and sweep and copy collection easily handle circular references. So, nothing magic about it!
Java

What is the difference between  and ?I do not understand the significant difference (I have read something about them!). Could you please help me?Maybe an example demonstrating how both methods are used will help you to understand things better. So, consider the following class:As explained in its javadoc, calling   i.e. it returns  which is affected to the  variable of type .Then, calling   In other words, this is here actually equivalent to a  and returns a new instance of .And running this  class thus prints the following output:The big difference with the traditional  is that  allows to instantiate a class that you don't know until runtime, making your code more dynamic. A typical example is the JDBC API which loads, at runtime, the exact driver required to perform the work. EJBs containers, Servlet containers are other good examples: they use dynamic runtime loading to load and create components they don't know anything before the runtime.Actually, if you want to go further, have a look at Ted Neward paper  that I was paraphrasing in the paragraph just above. (answering a question from the OP posted as comment): The case of JDBC drivers is a bit special. As explained in the  chapter of :To register themselves during initialization, JDBC driver typically use a static initialization block like this:Calling  causes the initialization of the  class and thus the execution of the static initialization block. And   will indeed \"create\" an instance but this is just a consequence of how (good) JDBC Driver are implemented.As a side note, I'd mention that all this is not required anymore with JDBC 4.0(added as a default package since Java 7) and the new auto-loading feature of JDBC 4.0 drivers. See .Class.forName() gives you the class object, which is useful for reflection. The methods that this object has are defined by Java, not by the programmer writing the class. They are the same for every class. Calling newInstance() on that gives you an instance of that class (i.e. calling  it is equivalent to calling ), on which you can call the methods that the class defines, access the visible fields etc.  In JDBC world, the  practice (according the JDBC API) is that you use  to load a JDBC driver. The JDBC driver should namely register itself in  inside a static block:Invoking  will execute all . This way the  can find the associated driver among the registered drivers by connection URL during  which roughly look like follows:But there were also  JDBC drivers, starting with the  as well known example, which incorrectly registers itself inside the  instead of a static block:The only way to get it to work dynamically is to call  afterwards! Otherwise you will face at first sight unexplainable \"SQLException: no suitable driver\". Once again, this is a  in the JDBC driver, not in your own code. Nowadays, no one JDBC driver should contain this bug. So you can (and should) leave the  away.1 : if you are interested only in the static block of the class , the loading the class only would do , and would execute static blocks then all you need is:2 : if you are interested in loading the class , execute its static blocks and also want to access its its non static part , then you need an instance and then you need:Class.forName() gets a reference to a Class, Class.forName().newInstance() tries to use the no-arg constructor for the Class to return a new instance.\"Class.forName()\" returns the Class-Type for the given name. \"newInstance()\" does return an instance of this class.On the type you can't call directly any instance methods but can only use reflection for the class. If you want to work with an object of the class you have to create an instance of it (same as calling \"new MyClass()\").Example for \"Class.forName()\"Example for \"Class.forName().newInstance()\"just adding to above answers, when we have a static code (ie code block is instance independent) that needs to be present in memory, we can have the class returned so we'll use Class.forname(\"someName\") else if we dont have static code we can go for Class.forname().newInstance(\"someName\") as it will load object level code blocks(non static) to memoryClass.forName()-->forName() is the static method of Class class it returns Class class object used for reflection not user class object so you can only call Class class methods on it like getMethods(),getConstructors() etc. If you care about only running static block of your(Runtime given) class and only getting information of methods,constructors,Modifier etc of your class you can do with this object which you get using Class.forName()But if you want to access or call your class method (class which you have given at runtime) then you need to have its object so newInstance method of Class class do it for you.It create new instance of the class and return it to you .You just need to type-cast it to your class.ex-:  suppose Employee is your class thenClass a=Class.forName(args[0]); //args[0]=cmd line argument to give class at  runtime. Employee ob1=a.newInstance();a.newInstance() is similar to creating object using new Employee().now you can access all your class visible fields and methods.
Java

Where can I view Tomcat log files in Eclipse?For some reason my Tomcat installation/log folder is always empty.BTW, does Tomcat dump to the log file after a while or is it immediate?Go to the \"Server\" view, then double-click the Tomcat server you're running. The  log files are stored relative to the path in the \"Server path\" field, which itself is relative to the workspace path.I'm not sure if you were after catalina.out or one of the other logs produced by Tomcat.But, if you're after the catalina.out log file then follow the directions below:Another forum provided this answer:Looks like the logs are scattered? I found access logs under\nDouble click and open the server.\nGo to 'Arguments'.\n-Dcatalina.base= .. something.\nGo to that something.\nYour logs are there.:Since the path field is uneditable, you can also \"Open Launch Configuration\", click Arguments tab, copy the VM argument for catalina.base (within quotes). This is the full path of your WTP webapp directory. Copying the value to the clipboard can save you the laborious task of browsing the file system to the path.Also note you should be seeing the output to the log file in your Console view as you run or debug.If you want logs in a separate file other than the console: \nDouble click on the server--> Open Launch Configuration--> Arguments --> add \n-Dlog.dir = \"Path where you want to store this file\" and restart the server. Tip: Make sure that the server is not running when you are trying to add the argument.\nYou should have log4j or similar logging framework in place. 
Java

How do you return a JSON object form a Java servlet.Previously when doing AJAX with a servlet I have returned a string. Is there a JSON object type that needs to be used, or do you just return a String that looks like a JSON object e.g. I do exactly what you suggest (return a ).You might consider setting the MIME type to indicate you're returning JSON, though (according to  it's \"application/json\").Write the JSON object to the response object's output stream.You should also set the content type  as follows, which will specify what you are returning:          First convert the JSON object to . Then just write it out to the response writer along with content type of  and character encoding of UTF-8.Here's an example assuming you're using  to convert a Java object to a JSON string:That's all.Just write a string to the output stream. You might set the MIME-type to  (:  is apparently officialer) if you're feeling helpful. (There's a small but nonzero chance that it'll keep something from messing it up someday, and it's a good practice.)There might be a JSON object for Java coding convenience. But at last the data structure will be serialized to string. Setting a proper MIME type would be nice.I'd suggest  from .Gson is very  usefull for this. easier even.\nhere is my example:}Have to say people if yours vars are empty when using gson it wont build the json for you.Just theI used  to convert Java Object to JSON string and send as follows.response.setContentType(\"text/json\");//create the JSON string, I suggest using some framework.String your_string;out.write(your_string.getBytes(\"UTF-8\"));Close to BalusC answer in 3 simple lines using Google Gson lib. Add this lines in the servlet method:`Good luck!
Java

I am using Java to get a  input from the user. I am trying to make the first letter of this input capitalized. I tried this:which led to these compiler errors:With your example:  from the value of  is What you want to do is probably this:(converts first char to uppercase and adds the remainder of the original string)Also, you create an input stream reader, but never read any line. Thus  will always be .This should work: from .Use .Set the string to lower case, then set the first Letter to upper like this:then to capitalise the first letter:substring is just getting a piece of a larger string, then we are combining them  back together.Shortest too:Worked for me.This is just to show you, that you were not that wrong. Add this dependency to your Now you can useYou can also try this:This is better(optimized) than with using substring. (but not to worry on small string)You can use  to do this.  But there are two different cases:If the  you are capitalizing is meant to be human-readable, you should also specify the default locale:If the  you are capitalizing is meant to be machine-readable, avoid using  because the string that is returned will be inconsistent across different regions, and in this case always specify the same locale (for example, ).  This will ensure that the strings you are using for internal processing are consistent, which will help you avoid difficult-to-find bugs.Note: You do not have to specify  for , as this is done automatically.What about ?try this oneWhat this method does is that consider the work \"hello world\" this method turn it into \"Hello World\" capitalize the beginning of each word .This will workHave a look at ACL WordUtils.WordUtils.capitalize(\"your string\") == \"Your String\"Many of the answers are very helpful so I used them to create a method to turn any string to a title (first character capitalized):You can use the following code:example test with JUnit: Following example also capitalizes words after special characters such as [/-]thanks I have read some of the comments and I came with the following I hope its helps \ngood luck You can use the following code:The answer from Ameen Mahheen is good but if we have some string with double space, like \"hello  world\" then sb.append gets IndexOutOfBounds Exception. Right thing to do is teste before this line, doing:You may try thisYou can use Class WordUtils.Suppose your String is \"current address\" then use ****strong text\noutput : Current AddressRefer: Try this, it worked for me.
Java

I installed Android Studio, but when I edit my layout files, I can't find live preview! I just see an XML file. How can I see my layout in graphical view?Update:\nThis is how it looks like in my case:You should have a  button next to the  button under the xml text editor:Or you can use the  button in the upper right corner to add a preview window next to the XML code:If you dont have it, then do this:  ->  -> Several people seem to have the same problem. The issue is that the IDE only displays the preview if editing a layout file in the  directory of an Android project.In particular, it won't show if editing a file in  since those are not  directory but  directory. In your case, you are editing a file in the  directory...The Resource folder is set automatically, and can be viewed (and changed) in Project Structure > Modules > [Module name] > Android > Resources directory.In case that helps anyone, I had the same issue today where the 'design / text' tabs were missing. I had switched to the dark theme and thought maybe that was the issue, so went back to Preferences / Appearance (under IDE settings) switched back to Default Theme, and that reset everything correctly for me. I could also then switch again to Darcula theme and the tabs were still there, so seems like switching themes is a way to reset the IDE windows/tabs.The following worked for me:-> file -> settings -> plugins -> disable the android support plugin -> you will be prompted to restart -> once restarted re-enable the plugin and other dependency plugins that might have been disabled in the process-> you will be prompted to restart once again. Hopefully when android studio restarts the second time the preview should render. Got the same problem after importing my Eclipse ADT project to Android Studio. Text and Desing tabs where missing. Found my Event Log windows reads \n\"Frameworks detected: Android framework is detected in the project Configure\"I click the hyperlink provided and everything was fixed, Text and Desing tabs became visible and functionalNavigate to file -> Project structure -> modules -> click on green plus button to add a module.Select new module -> select Application Module in Android option -> give a module name -> next -> next -> finishSelect project that to be include in module -> click apply -> okayNow you will be able to see the full project structure; then open the module form project window (the left panel), select res then select layout -> your layout name(.xml).Now you will be able to see the design view and text view both...Guys everything is very simple... \n1. Just input in search \"Preview\" and it will show you a single result. Just click on it and preview appears again :)\n2. Pull the right-side line and window will appear. It's kinda resize.Happy coding!Go to File->Invalidate Caches / Restart.This will solve the issue.As etienne said be sure that the XML file you are looking at is in I had the same issue. If you're in a layout file in  directory, you won't see a preview, nor will you have it as an option to enable. I wish Google had a slight warning for it.If you want to see the , in the right part of the screen you should have a button call  that show/hide the live preview. If what you want is to use the WYSISYG editor mode, in the bottom of the editor there is a tab that switch between  mode and  mode.This works in the same way both in IntelliJ and Android Studio.I had the same issue and resolved by editing the t file in src>main>res>layout. You can choose between Test and Design mode at the bottom of editor. Quite simple if we know where to look for !!! spend few hours figuring it out!!!  File>>setting>>Compiler>>JavaCompiler At \"Project bytecode version(leave blank for jdk default):\" choose your jdk.I had this problem a couple hours ago when I exported my projects from Eclipse to Android Studio. Unfortunately, the top answers here didn't work for me. Anyway, creating a new project instead of opening an old one did the trick for me as what Thomas Kaliakos mentioned on his comment In case you want docked mode, (it still visible while editing the xml file), and you, by mistake, clicked and unmarked docked mode. In order to get it back you have focus on preview and click .If you see a message at the bottom saying something like, \"Android Framework detected. Click to configure\", DO IT.After doing this, my Text and Design bottom-tabs appeared.
Java

I'm trying to compile my android project and I'm getting this errorI've been reading in other post that try to compile with java 8 might cause that error but not my case, I have the following Java version:OS: Linux Mint\n(I'm not have Java 8 installed.)\nBuild: MAVENCan anyone help me with this?\nThanks in advance!I face this problem too when making new project from android studio.I've been able to resolve this by downgrading buildToolsVersion in app gradle  setting:\nchange {module-name}/build.gradle lineto \n@Edit: \nIn Android Studio 2.1 Go to File-> Project Structure->App -> Build Tool Version. Change it to 23.0.3Do the method above, only when you are using java version 7 and for some reason do not want to upgrade to java 8 yet. Hope this helps >> Change  to source : experienceInitially I had downgraded  from  to , as specified in Rudy Kurniawan's answer. Then I have noticed that I have jdk 7 specified in my project settings. I have changed it to jdk 8 and now build tools  work.It's also important to have compile options set to :I installed Android Studio alongside to Xamarin Visual Studio (was already installed). After the installation (excluded SDK, because they were already installed) I started Android Studio and it downloaded, installed and added missing SDKs (after giving the path to the SDK location). As a result I got the error message on buildAs a solution I installed  without JRE (because it was already installed). Before I tried the x64 version, but it disappeared ... Then you have to change the .This is done in Visual Studio by clicking Tools > Options > Xamarin > Android Settings. Here you can navigate to the correct location. In my case it was .Finally, clean your project and make a new build :-)The problem specified:. To solve this problem we have to change from  from 24 to maximum 23:Java 8 must be required in the future for , so we have to start using Java 8.I had the same problem with my IntelliJ Maven build. My \"solution\" was to go into the build tools and remove the build tools 24.0.0 folder. I found it in the  directory. This is not a long term fix, but this should at least get your project building again. Upgrading to Java 8 as many have suggested will be better long term.What no one here is saying is that with Build Tools 24.0.0, Java 8 is required and most people have either 1.6 or 1.7. So yeah, setting the build tool to 23.x.x would 'solve' the problem but the root cause is the Java version on your system. On the long term, you might want to upgrade your dev environment to use JDK8 to make use the new language enhancements and the jack compiler.I am on Android Studio 2.0 and facing the same problem. \nThe solution provided by Rudy Kurniawan sorted out this issue. The affected file can be located by:The  \"\" pane is default on the left. To find it, inspect the name of the side tabs, click it, then use the top pull down box to get to \"\". Expand the tree in the pane to find the target file. Double-click it to edit. Sorry for the late reply.Hope it helps someone elseThis problem is related with your SDK, not with your JDK.\nYou can check your version information from You will get something like If you are using preview tools for building ,then you will get similar errors all over.gotoBack to your code   and \n(In rare cases, you have to select build-tools from project settings page)I also faced this problem when making a new project in eclipse.Hope this helps is the code for JDK 8.  You can see that here: .  So Gradle is expecting you to have JDK 8 as the default Java version on your machine.  Newest versions of Gradle for Android won't work with Java 7.The solution is simple: make Java 8 the default jdk version on your machine.SOLUTION FOUND TO ALL USERS HAVE THIS PROBLEM.THE SOLUTION TO THE PROBLEM WITH ECLIPSE IS WRITE THIS IN YOUR project.properties FILE:THE SOLUTION TO THE PROBLEM WITH ANDROID IS STUDIO VERSION 2.1 FILE write this in BUESTRO project.properties:Thanks everyone for solution.I could solve my same problem using below solution.In my project, I added jar which were created in Java8. And my project was referring to JRE 7. When i changed project JRE to 8. My problem solved.Steps: In eclipse, right click on project name in project explorer > build path > Libraries > click on jre version > click edit > installed JRE > add > standerd VM > select JRE home click-path (path should be localePath\\java\\jdk1.8.0_25\\jre) > provide name > save > select same JRE for project > finish > ok Refresh/build project once > try to run your java file. it should work.Get this error message on the travis build server?I fixed my  build with \nbuildToolsVersion  using this In my case the default jdk was 1.7 then I changed it to 1.8 by browsing to the exact folder where the updated jdk is found in.I had the same problem and tried to change the version, sometimes is for the version of Android Studio in Project> Gradle Scripts> build.gradle(Module:app) you can change the version. For example:From  question.You can try to change your compiler level back to 1.7 in the IDE you're using.If this doesn't help, try checking other's answer in the link mentioned above and let us know what helped you.Your Android build tools are not properly installed. Try installing some other version of build tools and give that version in the gradle file.\nor you can go to this directoryC:\\Users\\\\AppData\\Local\\Android\\sdk\\build-tools and see which build tools is installed. Try changing the build tool version in the gradle file and compile the app to see if it is working.i had 22.0.1,23.0.02 and 24.0.0 versions of build tools and only the old 22.0.1 version worked.source: i tried it myself and it worked for me.This problem stems from the fact that your build tool version and JDK won't work together. I was using JDK version 7 with build tool 24.0.1. Of course lowering build tool version may fix the problem but it is not a real fix, as upgrading your build tools in future will break it again.You should make sure build tool version and JDK work together. I upgraded my build tool to latest (24.0.1) and installed jdk8. Make sure to set your JAVA_HOME to latest and then try clean build. Got the same issue outside of Android Studio, when trying to build for Cordova using the sdk from command line (cordova build android). The solution provided by Rudy works in this case too. You just don't downgrade the version of Build Tools from Android Studio but you do it using the android sdk manager ui.I just encountered this problem.Reverting from the \"Preview Channel\" versions of the SDK tools and build tools to the latest stable version fixed it.I had two versions of java jdk installed. Once I pointed to right version of java jdk in File->Project Structure -> SDK Location to the latest version which I had in JAVA_HOME environment variable, the issue went away.Changing  to  fixed it for me.My Android Studio version is 2.1.2, perhaps that's whyThe Simplest  solution is you have to update your JDK to latest, version . Because  Cordova supports only latest JDK .  First of all you have to update your Android SDK. Then, If you are not  able to update through your terminal ,  Got to your  of Linux destro and  search the Latest (which one you want to install) and install  that one .Then again run  .  It will  solve the problem .In ,my case it worked.You need to go into your SDK installation directory, and make sure that the  sub-directory matches the  in your app's build.gradle file:\nCheck that you have the latest version of the SDK installed in either  or Then go to VS2015 and follow the path tools - options - Xamarin - Android settings and in the section JDK location select change and go to look for the version you have either x64 or x32.I am on cordova, here's what I've done:-\u00a0rename your android project, so that there's space for new one\n-\u00a0update JAVA Development Kit to 1.8 (latest one in time of writing this)\n-\u00a0run    Should work without problems now. Your app hash will change, so if you are using it f.e. for facbeook login, you will need to update itI'd had this issue for too long (SO etc hadn't helped) and only just solved it (using sdk 25).-The local.properties file proguard.dir var was not applying with ant; I'd specified 5.3.2, but a command line call and signed export build (eclipse) was using 4.7, from the sdk dir(only 5+ supports java 8)My solution was to replace the proguard jars (android-sdk/tools/proguard/libs directory) in the sdk with a current (5+) version of proguard.unsupported-major-minor-version error can be because of unsupported JDK version. Update JDK, Go to Module Settings and change the JDK path to the new one. In most of the cases, it fixes the error.
Java

I am building an android app that needs to download and synchronise with an online database, I am sending my query from the app to a php page which returns the relevant rows from a database in JSON format. can someone please tell me the best way to iterate through a JSON array?I receive an array of objects:What is the simplest piece of code I could use to access the JSONObjects in the array?EDIT: now that I think of it the method I used to iterate the loop was:So I guess I had was somehow able to turn the returned Json into and iterable array. Any Ideas how I could achieve this?I apologise for my vaguness but I had this working from an example I found on the web and have since been unable to find it.I have done it two different ways,I think this code is short and clear:Is that what you were looking for?This article helped me when I got started with JSON and Android:On Arrays, look for:Use the , it's also available for Android.There are several ways to parse JSON with it:Take org.json classes, there are  the android API.If you're using the , which is open source, you can just make JSONArray implement the  interface and add the following method to the class:This will make all instances of JSONArray iterable, meaning that the  syntax will now work with it (note that foo has to be an Object, because JSONArrays do not have a declared type). All this works because the JSONArray class is backed by a simple ArrayList, which is already iterable. I imagine that other open source implementations would be just as easy to change.unfortunately , JSONArray doesn't support for each statement, like:You are using the same Cast object for every entry.\nOn each iteration you just changed the same object instead creating a new one.This code should fix it:While iterating over a JSON array (org.json.JSONArray, built into Android), watch out for  objects; for example, you may get  instead of a  string.A check may look like:When I tried @vipw's suggestion, I was faced with this exception:\nThis worked for me instead:
Java

In my code I need to find all my things that happened today.  So I need to compare against dates from today at 00:00am (midnight early this morning) to 12:00pm (midnight tonight).I know ...... gets me right now.  And ...... gets me zero time on Jan 1, 1970.  But what's an easy way to get zero time today and zero time tomorrow?Any help is greatly appreciated!UPDATE; I did this, but surely there's an easier way??If you're using a JDK < 8, I recommend , because the API is really nice:\nSince version 2.3 of Joda Time  is , so use this:Pass a time zone if you don't want the JVM\u2019s current default time zone.Remember,  is not used to represent  (!). To represent date you need a calendar. This:will create a  instance representing present date in your current time zone. Now what you need is to truncate every field below day (hour, minute, second and millisecond) by setting it to . You now have a midnight today.Now to get midnight next day, you need to add one day:Note that adding  seconds or 24 hours is incorrect due to summer time that might occur in the meantime.UPDATE: However my favourite way to deal with this problem is to use  class from :It uses  behind the scenes...The easiest way to find a midnight:Next day:As of JodaTime 2.3, the  is deprecated.From Here is a sample code without  method. ()For sake of completeness, if you are using  you can also use the  method of the  class to get midnight in .As written in the JavadocHope it helps.This appears to be an option:to add a day to it, eitherorI have a hunch the latter is preferred in case of something weird like daylight savings causing adding 24 hours to not be enough (see  and its other answers).If you are using Java 8 and later, you can try the  ():these methods will help you-and Other answers are correct, especially the . As some mentioned, you should avoid the old java.util.Date/.Calendar classes as they are poorly designed, confusing, and troublesome. They have been supplanted by the java.time classes.Let me add notes about strategy around  and .In date-time work, spans of time are often defined using the \u201cHalf-Open\u201d approach. In this approach the beginning is  while the ending is . This solves problems and if used consistently makes reasoning about your date-time handling much easier. One problem solved is defining the end of the day. Is the last moment of the day  ()? Perhaps, in the java.util.Date class (from earliest Java; troublesome \u2013 avoid this class!) and in the highly successful  library. But in other software, such as database like Postgres, the last moment will be  (). But in other software such as the  framework (built into Java 8 and later, successor to Joda-Time) and in some database such the , the last moment might be  (). Rather than splitting hairs, think in terms of first moment only, not last moment.In Half-Open, a day runs from the first moment of one day and goes up to but  the first moment of the following day. So rather than think like this:\u2026think like this\u2026In database work, this approach means  using the  in SQL.Furthermore, the first moment of the day is  always the time-of-day .  in some time zones, and possibly other anomalies, can mean a different time starts the day. So let the  classes do the work of determining the start of a day with a call to . So we have to detour through  and back to  as you can see in this example code.Note the passing of the optional . If omitted your JVM\u2019s current default time zone is applied implicitly. Better to be explicit.Time zone is crucial to date-time work. The Question and some other Answers are potentially flawed because the do not consciously handle time zone.If you  use a java.util.Date or .Calendar, look for new conversion methods added to those old classes.By the way, if you are doing much work with spans of time take a look at:I did this differently than everyone else here did.  I'm new to Java, so maybe my solution is poor.  I'm not sure this works yet, but either way, I'd appreciate any feedback on this solution.  I'm confused by the statement above that you can calculate tomorrow by calling:If you add 1 to the day of the month and it's the 31st day, don't you get the 32nd day of the month?Why are times/dates not all based on UTC in Java?  I would think Timezones should only be needed when used with i/o, but internally should always be used in UTC.  However, the classes seem to include Timezone info which seems not only wasteful, but prone to coding errors.   Apache Commons Lang, java.util.Date)The simplest way with JodaTime  Because of one day is  ms, \nthe midnight of this day can be calculate as...I know this is very old post. I thought to share my knowledge here ! For the date Mid night today with exact Time zone you can use following Where    is being subtracted i.e. actually related to time zone for example Indian time zone i.e. kolkata differs +5:30hrs from actual . So subtracting  that with converting into milliseconds. So change last substracted number according  to you. I m creating a product i.e. only based in India So just used specific timestamp. 
Java

I have an  and I want to copy it exactly. I use utility classes when possible on the assumption that someone spent some time making it correct. So naturally, I end up with the  class which contains a copy method.Suppose I have the following:This fails because basically it thinks  isn't big enough to hold . Yes I know  has size 0, but it should be big enough now shouldn't it? If I have to fill  first, then  becomes a completely useless function in my mind. So, except for programming a copy function (which I'm going to do now) is there a proper way to do this?Callingcreates a shallow copy of  within . All elements will exist within  in the exact same order that they were within  (assuming it had an order).Similarly, callingalso creates a shallow copy of  within . If the first parameter, , does not have enough  (not size) to contain all of 's elements, then it will throw an . The expectation is that no allocations will be required by  to work, and if any are, then it throws that exception. It's an optimization to require the copied collection to be preallocated (), but I generally do not think that the feature is worth it due to the required checks given the constructor-based alternatives like the one shown above that have no weird side effects.To create a deep copy, the , via either mechanism, would have to have intricate knowledge of the underlying type. In the case of s, which are immutable in Java (and .NET for that matter), you don't even need a deep copy. In the case of , you need to know how to make a deep copy of it and that is not a generic operation.Note: The originally accepted answer was the top result for  in Google, and it was flat out wrong as pointed out in the comments. has a  of 3, but a  of 0. The fact that  has some sort of buffer capacity is an implementation detail - it's not part of the  interface, so  doesn't use it. It would be ugly for it to special-case .As MrWiggles has indicated, using the ArrayList constructor which takes a collection is the way to in the example provided.For more complicated scenarios (which may well include your real code), you may find the  useful.Just do:ArrayList has a constructor that will accept another Collection to copy the elements fromThe answer by Stephen Katulka (accepted answer) is wrong (the second part).\nIt explains that  does a deep copy, which it does not. Both,  and  only do a shallow copy. The difference is, that the constructor allocates new memory, and  does not, which makes it suitable in cases where you can reuse arrays, as it has a performance advantage there.The Java standard API tries to discourage the use of deep copies, as it would be bad if new coders would use this on a regular basis, which may also be one of the reason why  is not public by default.The source code for  can be seen on line 552 at:\nIf you need a deep copy, you have to iterate over the items manually, using a for loop and clone() on each object.the simplest way to copy a List is to pass it to the constructor of the new list: will be a shallow copy of Looking at the source of  (I'd never seen it before) it seems to be for coping the elements index by index. using  thus element 0 will over write element 0 in the target list etc etc. Not particularly clear from the javadocs I'd have to admit.doesn't set the size. It sets the initial capacity (being how many elements it can fit in before it needs to resize).  A simpler way of copying in this case is:As hoijui mentions. The selected answer from Stephen Katulka contains a comment about Collections.copy that is incorrect. The author probably accepted it because the first line of code was doing the copy that he wanted. The additional call to Collections.copy just copies again. (Resulting in the copy happening twice).Here is code to prove it.Most answers here do not realize the problem, the user wants to have a COPY of the elements from first list to the second list, destination list elements are new objects and not reference to the elements of original list.\n(means changing an element of second list should not change values for corresponding element of source list.)\nFor the mutable objects we cannot use ArrayList(Collection) constructor because it will simple refer to the original list element and will not copy.\nYou need to have a list cloner for each object when copying.Why dont you just use  method:even if you have existing items in b or you want to pend some elements after it, such as:If you want to copy an ArrayList, copy it by using:Strings can be deep copied withbecause they are immutable. Every other Object not --> you need to iterate and do a copy by yourself.Every other Object not --> you need to iterate and do a copy by yourself.To avoid this implement Cloneable.....The following output illustrates results of using copy constructor and Collections.copy():The source of full program is here: . But the output is enough to see how java.util.Collections.copy() behaves.And if you are using google guava, the one line solution would be This creates a mutable array list instance.Copy isn't useless if you imagine the use case to copy some values into an existing collection. I.e. you want to overwrite existing elements instead of inserting.An example: a = [1,2,3,4,5] b = [2,2,2,2,3,3,3,3,3,4,4,4,] a.copy(b) = [1,2,3,4,5,3,3,3,3,4,4,4]However I'd expect a copy method that would take additional parameters for the start index of the source and target collection, as well as a parameter for count.See Java BUG To understand why Collections.copy() throws an IndexOutOfBoundsException although you've made the backing array of the destination list large enough (via the size() call on the sourceList), see the answer by Abhay Yadav in this related question:\n
Java

So I installed the beta of JDK 8 a while ago to look at some of the examples. I thought for sure by now, it's easy to change between versions. Doing some Play development with IntelliJ. For some reason, IntelliJ is compiling with 8 even though:If I go to the Java Preferences page, it does show 8 installed, but there is no option to uninstall it and it doesn't see any of the other versions.When I do , it tells me  and I do  and it returns 1.6.Note: with a  little fiddling, you can use IntelliJ and JDK7, see .I was able to unistall jdk 8 in mavericks successfully doing the following steps:Make it really simple...Managing Java versions on Mac OSX is a nightmare.  I recently switched over to using JDK 1.7, deleting JDK 6 from my MacBook entirely (I also had traces of JDK 5 - this laptop has been updated a few times).Here's what I did to move to JDK 7.1) download the latest from Oracle () and install it.2) Remove (using rm - if you've got backups, you can revert if you make a mistake) all the JDK6 and JRE6 files.At this stage, you should see:(and nothing else)3) In the folder /Library/Java/Extensions/, you'll need to remove all the old jar files, the ones that correspond to other releases of Java.  If you don't, you'll get the infamous message about the wrong version of tools.jar (see ).  It is not enough to rename the jar files, because Java will open every jar in that folder - I moved mine into a sub-directory.  It's safe to remove them once you know everything else works.I haven't found I need to set JAVA_HOME for simple things.: I just tried running IntelliJ and it  start unless you have Apple's JDK 6 installed (see ).  Same is true for Eclipse. Netbeans works fine.Use  ; I found these alias and function to be pretty useful in my :Here is the official document about uninstalling the JDK.I nuked everything Java, JDK, and oracle. I was running Java 8 on OSX El CapitanOther answers were missing tons of stuff. This answer covers a lot more bases.Good bye, shovelware.If you have installed jdk8 on your Mac but now you want to remove it, just run below command \"sudo rm -rf /Library/Java/JavaVirtualMachines/jdk1.8.0.jdk\"If you uninstall all the files but it still fails, use this line:For yosomite imac OS x:This worked perfectly for me:
Java

I have an  that I'd like to return a copy of.   has a clone method has the following signature:After I call this method, how do I cast the returned Object back to ?Why would you want to clone? Creating a new list usually makes more sense.Job done.This is the code I use for that:Hope is usefull for youBe advised that Object.clone() has some major problems, and its use is discouraged in most cases. Please see Item 11, from \"\" by Joshua Bloch for a complete answer. I believe you can safely use Object.clone() on primitive type arrays, but apart from that you need to be judicious about properly using and overriding clone. You are probably better off defining a copy constructor or a static factory method that explicitly clones the object according to your semantics.I think this should do the trick using the Collections API:: the copy method runs in linear time.    With Java 8 it can be cloned with a stream....I find using addAll works fine.parentheses are used rather than the generics syntaxBe very careful when cloning ArrayLists. Cloning in java is shallow. This means that it will  only clone the Arraylist itself and not its members. So if you have an ArrayList X1 and clone it into X2 any change in X2 will also manifest in X1 and vice-versa. When you clone you will only generate a new ArrayList with pointers to the same elements in the original. My function to clone a List with type:This should also work:If you want this in order to be able to return the List in a getter it would be better to do:To clone a generic interface like  you will just need to cast it. here you are an example:It is a bit tricky, but it works, if you are limited to return a  interface, so anyone after you can implement your list whenever he wants.I know this answer is close to the final answer, but my answer answers how to do all of that while you are working with  -the generic parent- not I am not a java professional, but I have the same problem and I tried to solve by this method. (It suppose that T has a copy constructor).
Java

Is there any Utils help reader a textfile in resource into a String. I suppose this is a popular requirement, but I couldn't found any Utils after Googling.ThanksYes,  provides this in the  class. For example:You can use the old  oneliner to do that without any additional dependency like guava:Guys, don't use 3rd party stuff unless you really need that. There is a lot of functionality in the JDK already. has a \"toString\" method for reading a file into a String:This method does not require the file to be in the classpath (as in  previous answer).For java 7: has a utility name : has found a :I often had this problem myself. To avoid dependencies on small projects, I often\nwrite a small utility function when I don't need commons io or such. Here is\nthe code to load the content of the file in a string buffer :Specifying the encoding  important in that case, because you might have\nedited your file in UTF-8, and then put it in a jar, and the computer that opens\nthe file may have CP-1251 as its native file encoding (for example); so in\nthis case you never know the target encoding, therefore the explicit\nencoding information is crucial.\nAlso the loop to read the file char by char seems inefficient, but it is used on a\nBufferedReader, and so actually quite fast.You can use the following code  form Java If you want to get your String from a project resource like the file\ntestcase/foo.json in src/main/resources in your project, do this:Note that the getClassLoader() method is missing on some of the other examples.Use Apache commons's FileUtils. It has a method Here is my approach worked fine Guava also has  if you want a return value as  line-by-line:Please refer to  to compare 3 ways ( vs. Guava's  vs. Guava's ) to get  from a text file.With set of static imports, Guava solution can be very compact one-liner:The following imports are required:I'm using the following for reading resource files from the :No third party dependencies required.
Java

 Sun's JVM source doesn't contain this exact message, but I think the text  is from the native implementation of :My guess is that it is caused when the client has terminated the connection, before getting the full response (e.g. sent a request, but before getting the full response, it got closed / terminated / offline)I need to have a proof that this stack trace is the socket client's \"fault\", and there is nothing that the server could have done to avoid it. (except catching the exception, or using a non Sun JVM SocketOutputStream, though both don't really avoid the fact the client has terminated)\"This error can occur when the local network system aborts a connection, such as when WinSock closes an established connection after data retransmission fails (receiver never acknowledges data sent on a datastream socket).\". See . See also .I have seen this most often when a corporate firewall on a workstation/laptop gets in the way, it kills the connection.eg. I have a server process and a client process on the same machine. The server is listening on all interfaces (0.0.0.0) and the client attempts a connection to the public/home interface (note not the loopback interface 127.0.0.1).If the machine is has its network disconnected (eg wifi turned off) then the connection is formed. If the machine is connected to the corporate network (directly or vpn) then the connection is formed.However, if the machine is connected to a public wifi (or home network) then the firewall kicks in an kills the connection. In this situation connecting the client to the loopback interface works fine, just not to the home/public interface.Hope this helps.I was facing the same issue.\nCommonly This kind of error occurs due to client has closed its connection and server still trying to write on that client.\nSo make sure that your client has its connection open until server done with its outputstream.\nAnd one more thing, Don`t forgot to Hope this helps. \nAnd if still facing issue than brief your problem here in details.To prove which component fails I would monitor the TCP/IP communication using  and look who is actaully closing the port, also timeouts could be relevant.Have you checked the Tomcat source code  the JVM source ? That may give you more help.I think your general thinking is good. I would expect a  in the scenario that you couldn't connect. The above looks very like it's client-driven.For anyone using simple Client Server programms and getting this error, it is a problem of unclosed (or closed to early) Input or Output Streams.The  is thrown when there is an error creating or accessing  (such as ). This usually can be caused when the server has terminated the connection (without properly closing it), so before getting the full response. In most cases this can be caused either by the timeout issue (e.g. the response takes too much time or server is overloaded with the requests), or the client sent the SYN, but it didn't receive ACK (acknowledgment of the connection termination). For timeout issues, you can consider increasing the timeout value.The Socket Exception usually comes with the specified detail message about the issue.Example of detailed messages:This error happened to me while testing my soap service with SoapUI client, basically I was trying to get a very big message (>500kb) and SoapUI closed the connection by timeout....and put a large value, such as 180000 (3 minutes), this won't be the perfect fix for your issue because the file is in fact to large, but at least you will have a response.I was facing the same problem with wireMock while mocking the rest API calls.\nEarlier I was defining the server like this:But it should be defined like as shown below:In my case, the error was:It was received in eclipse while debugging a java application accessing a H2 database. The source of the error was that I had initially opened the database with SQuirreL to check manually for integrity. I did use the flag to enable multiple connections to the same DB (i.e. ), so there was no problem connecting to the DB from java.The error appeared when, after a while --it is a long java process-- I decided to close SQuirreL to free resources. It appears as if SQuirreL were the one \"owning\" the DB server instance and that it was shut down with the SQuirreL connection.Restarting the Java application did not yield the error again.My server was throwing this exception in the pass 2 days and I solved it by moving the disconnecting function with: To the end of the  listing thread.\nif it will helped anyone.
Java

Is there an open-source Java library for parsing SQL statements?If possible, it should be customizable or flexible enough to also be able to parse (or at least ignore) vendor-specific syntax (such as Oracle tablespace definitions or MySQL's LIMIT clause).If not, strict adherence to the SQL standard is also fine. I need this for two things:  has an ANSI SQL grammar available.  You can use that to create your own parser.ANTLR4 has a .If you need a parser there should be a parser in the code base of .You may want to look at the  method on the jdbc Connection object which you can pass it vendor neutral queries that will get postprocessed into vendor specific queries. is not open source, but is exactly what you are looking after.Try Hibernate uses ANTLR for sql and hql parsing.JSqlParser is also a good option.although it has some bugs(or some features not implemented) while parsing oracle pl/sql.\nsee its forum for detail.so if you're parsing oracle pl/sql, ANTLR is recommended.What you want to do with the parsed SQL? I can recommend a few Java implementation of Lex/Yacc (, ) that you can use an existing SQL grammar with. If you want to actually do something with the resulting parsed grammar, I might suggest looking at , an open source SQL database written in Java. 
Java

Having been using  now for 6+ months or so, I'm pretty happy with the new API changes. One area I'm still not confident in is when to use . I seem to swing between wanting to use it everywhere something may be , and nowhere at all.There seem to be a lot of situations when I could use it, and I'm never sure if it adds benefit (IE readability / null safety) or just causes additional overhead. So, I have a few examples, and I'd be interested in the community's thoughts on whether  adds benefit. 1 - As a public method return type when the method could return :2 - As a method parameter when the param may be :3 - As an optional member of a bean:4 - In : In general I don't think:adds anything - especially since one can use  to remove  values etc, but are there any good uses for  in collections?Any cases I've missed?The main point of  is to provide a means for a function returning a value to indicate the absence of a return value. See . This allows the caller to continue a chain of fluent method calls.This most closely matches use case  in the OP's question. Although,  is a more precise formulation than  since something like  could never return null.For use case , passing an optional argument to a method, this could be made to work, but it's rather clumsy. Suppose you have a method that takes a string followed by an optional second string. Accepting an  as the second arg would result in code like this:Even accepting null is nicer:Probably the best is to have an overloaded method that accepts a single string argument and provides a default for the second:This does have limitations, but it's much nicer than either of the above.Use cases  and , having an  in a class field or in a data structure, is considered a misuse of the API. First, it goes against the main design goal of  as stated at the top. Second, it doesn't add any value.There are three ways to deal with the absence of a value in an : to provide a substitute value, to call a function to provide a substitute value, or to throw an exception. If you're storing into a field, you'd do this at initialization or assignment time. If you're adding values into a list, as the OP mentioned, you have the additional choice of simply not adding the value, thereby \"flattening\" out absent values.I'm sure somebody could come up with some contrived cases where they really want to store an  in a field or a collection, but in general, it is best to avoid doing this.I'm late to the game but for what it's worth, I want to add my 2 Cents. They go against the , which is well summarized by , but I'm still convinced of their validity (obviously).I wrote an entire  but it basically comes down to this:The first two exceptions can reduce the perceived overhead of wrapping and unwrapping references in . They are chosen such that a null can never legally pass a boundary from one instance into another.Note that this will almost never allow s in collections which is almost as bad as s. Just don't do it. ;)Doing this reduces the presence of s in your code base, although it does not eradicate them. But that is not even the main point. There are other important advantages:Using  clearly expresses that the variable is, well, optional. Any reader of your code or consumer of your API will be beaten over the head with the fact that there might be nothing there and that a check is necessary before accessing the value.Without  the meaning of a  occurrence is unclear. It could be a legal representation of a state (see ) or an implementation error like a missing or failed initialization.This changes dramatically with the persistent use of . Here, already the occurrence of  signifies the presence of a bug. (Because if the value were allowed to be missing, an  would have been used.) This makes debugging a null pointer exception much easier as the question of the meaning of this  is already answered.Now that nothing can be  anymore, this can be enforced everywhere. Whether with annotations, assertions or plain checks, you never have to think about whether this argument or that return type can be null. It can't!Of course, there is no silver bullet...Wrapping values (especially primitives) into an extra instance can degrade performance. In tight loops this might become noticeable or even worse.Note that the compiler might be able to circumvent the extra reference for short lived lifetimes of s. In Java 10  might further reduce or remove the penalty. but a  is not overly complicated.Due to the invariance of generic types in Java, certain operations become cumbersome when the actual value type is pushed into a generic type argument. An example is given .Personally, I prefer to use  to use  and  checks as these are largely compile time (can have some runtime checks) This has lower overhead in terms of code readability and runtime performance.  It is not as rigorous as using Optional, however this lack of rigour should be backed by decent unit tests.This works with Java 5 and no need to wrap and unwrap values. (or create wrapper objects)I think the Guava Optional and their wiki page puts it quite well: adds some overhead, but I think its clear advantage is to make it  \nthat an object might be absent and it enforces that programmers handle the situation. It prevents that someone forgets the beloved  check.Taking the example of , I think it is far more explicit code to write:than For me, the  better captures the fact that there is no soundcard present.My 2\u00a2 about your points:In general, I would try to minimize passing around s. (Once burnt...) \nI think it is worth to find the appropriate abstractions and indicate to the fellow programmers what a certain return value actually represents.From :There are already several resources about this feature:Here is an interesting usage (I believe) for... Tests.I intend to heavily test one of my projects and I therefore build assertions; only there are things I have to verify and others I don't.I therefore build things to assert and use an assert to verify them, like this:In the NodeAssert class, I do this:Which means the assert really only triggers if I want to check the label!Seems  is only useful if the type T in Optional is a primitive type like , , , etc. For \"real\" classes, it does not make sense to me as you can use a  value anyway.I think it was taken from here (or from another similar language concept).In C# this  was introduced long ago to wrap value types.I do not think that Optional is a general substitute for methods that potentially return null values.The basic idea is: The absence of a value does not mean that it potentially is available in the future. It's a difference between findById(-1) and findById(67).The main information of Optionals for the caller is that he may not count on the value given but it may be available at some time. Maybe it will disappear again and comes back later one more time. It's like an on/off switch. You have the \"option\" to switch the light on or off. But you have no option if you do not have a light to switch on.So I find it too messy to introduce Optionals everywhere where previously null was potentially returned. I will still use null, but only in restricted areas like the root of a tree, lazy initialization and explicit find-methods.Java SE 8 introduces a new class called java.util.Optional,You can create an empty Optional or Optional with null value.And here is an Optional with a non-null value:Now that you have an Optional object, you can access the methods available to explicitly deal with the presence or absence of values. Instead of having to remember to do a null check, as follows:You can use the ifPresent() method, as follows:
Java

What are good reasons to prohibit inheritance in Java, for example by using final classes or classes using a single, private parameterless constructor? What are good reasons of making a method final?Your best reference here is Item 17 (15 in the first edition) of Joshua Bloch's excellent book \"Effective Java\", called \"Design and document for inheritance or else prohibit it\". You should really read it, but I'll summarize.The interaction of inherited classes with their parents can be surprising and unpredicatable if the ancestor wasn't designed to be inherited from. Classes should therefore come in two kinds :If you are writing purely internal code this may be a bit of overkill. However the extra effort involved in adding five characters to a class file is very small. If you are writing only for internal comsumption then a future coder can always remove the 'final' - you can think of it as a warning saying \"this class was not designed with inheritance in mind\".You might want to make a method final so that overriding classes can't change behavior that is counted on in other methods.  Methods called in constructors are often declared final so you don't get any unpleasant surprises when creating objects.One reason to make a class final would be if you wanted to force composition over inheritance. This is generally desirable in avoiding tight coupling between classes.you might want to make immutable objects (), you might want to create a singleton (), or you might want to prevent someone from overriding the method for reasons of efficiency, safety, or security.So that no body can extend those classes and change their behavior.Eg: Wrapper class Integer is a final class. If that class is not final, then any one can extend Integer into his own class and change the basic behavior of integer class. To avoid this, java made all wrapper classes as final classes.Inheritance is like a chainsaw - very powerful, but awful in the wrong hands. Either you design a class to be inherited from (which can limit flexibility and take a lot longer) or you should prohibit it.See Effective Java 2nd edition items 16 and 17, or my blog post .Hmmm... I can think of two things:You might have a class that deals with certain security issues. By subclassing it and feeding your system the subclassed version of it, an attacker can circumvent security restrictions. E.g. your application might support plugins and if a plugin can just subclass your security relevant classes, it can use this trick to somehow smuggle a subclassed version of it into place. However, this is rather something Sun has to deal with regarding applets and the like, maybe not such a realistic case.A much more realistic one is to avoid an object becomes mutable. E.g. since Strings are immutable, your code can safely keep references to itinstead of copying the string first. However, if you can subclass String, you can add methods to it that allow the string value to be modified, now no code can rely anymore that the string will stay the same if it just copies the string as above, instead it must duplicate the string.To stop people from doing things that could confuse themselves and others. Imagine a physics library where you have some defined constants or calculations. Without using the final keyword, someone could come along and redefine basic calculations or constants that should NEVER change.Also, if you are writing a commercial closed source class, you might not want people to be able to change the functionality down the line, especially if u need to give support for it and people have overridden your method and are complaining that calling it gives unexpected results.If you mark classes and methods as final, you may notice a small performance gain, since the runtime doesn't have to look up the right class method to invoke for a given object. Non-final methods are marked as virtual so that they can be properly extended if needed, final methods can be directly linked or compiled inline in the class.You want to make a method final so that overriding classes does not change its behavior. When you want to be able to change the behavior make the method public. When you override a public method it can be changed. 
Java

If you have a jar file called  located in  and you want to use the class called  from it, how do you go about doing it from the command line?I thought it would be to go into the directory and say  but that isn't working. Any help would be appreciated.Use .You want:The  gives the following example:Their are two types of JAR file available in javaAssuming you are in the directory where  file is and that  has a  method on it:You use the following command line:Where:
Java

Say you catch an exception and get the following on the standard output (like, say, the console) if you do a  :Now I want to send this instead to a logger like, say, log4j to get the following:How can I do this?You pass the exception directly to the logger, e.g.It's up to log4j to render the stack trace.If you want to log a stacktrace without involving an exception just do this: You can also get stack trace as string via ExceptionUtils.getStackTrace.\nI use it only for log.debug, to keep log.error simple.This answer may be not related to the question asked but related to title of the question. ORORJust because it happened to me and can be useful.\nIf you do thisyou will get the header of the exception and not the whole stacktrace. Because the logger will think that you are passing a String.\nDo it without  as skaffman saidCreate this : Call this in your code
Java

I would like to know if there is such a method in Java. Take this snippet as example :To quote a :If you want it back as a string later, you can call getPath(). Indeed, if you really wanted to mimic Path.Combine, you could just write something like:You can just do One way is to get system properties that give you the path separator for the operating system,  explains how.  You can then use a standard string join using the .This is a start, I don't think it works exactly as you intend, but it at least produces a consistent result.
Java

I am working with a rather large app written in .\nJSF 1.2 is around 6 years old now. I need to upgrade to JSF 2.0. How painful will this be? I noticed that some attributes in custom tags have been changed etc. Painfulness of upgrading JSF 1.2 to 2.0 depends on the view technology which you are currently using and which you want to use.Regardless of the view technology switch,  the following steps should be done:If you're using  and want to  using it, then you basically don't need to change anything else. If you're already using a suffix  for the , like , then it's good to know that the  will first scan for  file and if it is not present, then scan for  file. This provides you room to gradually convert from JSP to Facelets behind the scenes without changing the URL's. But if you're using a prefix , like  and you want to gradually upgrade from JSP to Facelets, then you really have to change it to  and possibly also all links in the existing JSP pages.You only need to keep in mind that the new JSF 2.0 provided implicit navigation doesn't scan for the presence of the file, it will go to  anyway. So if you want to come from or go to , then you still need to include it in the viewid the JSF 1.x way.If you're using  as view technology and want to use the JSF 2.0 supplied , then you need to do the following additional steps:That should basically be it.If you're using  as view technology and you want to upgrade to  immediately, then you need to do a lot of changes before the site can go live. You're basically changing the view technology here. On every master page, you need to change the following basic JSP template....to the following basic Facelets template:If your existing JSP pages are well designed, you should not have any line of  code and you should also have only the  as the sole JSP-specific tag. Any of those needs to be changed from:toThe basic JSP include page template of....should be changed to the following basic Facelets include page template:You need to change the JSP TLD files to Facelets TLD files as described in this .Regardless of the migration approach, you can gradually  the  by the new JSF 2.0 annotations. Any  can be annotated by :Next to , there are also ,  and  available. If you omit the  attribute of the , then it will default to classname with the 1st char lowercased. In this particular example, it will be .Any  can be annotated using :Any  can be annotated using :Any  can be annotated using Any  can be annotated using Any  which uses the filename of the XHTML page as both  and  can be removed since this will be  done. This can be gradually done by changing all outcome values to match the filename of the target view.Finally, any session scoped bean which was been put in the session with the sole reason to retain the bean data in subsequent requests in the same tab/window can better be marked , because this way the bean won't be affected when the enduser opens the same page in different tabs/windows.Note that I don't take any 3rd party componant libraries like PrimeFaces/RichFaces/IceFaces into account in this answer, it would then be impossible to write a reliable answer since it basically boils down to \"it depends\". In general it's sufficient to just upgrade the component library to a -by themselves verified- JSF 2.0 compatible version as per their instructions. Best is to just write unit tests, run them before and after the upgrade and fix any issues individually. Here are at least some useful links with regard to migration of the specific component library:PrimeFaces has no migration guide for PrimeFaces 1.x to 2.x as PrimeFaces 1.x requires Facelets 1.x already, so you just have to follow Facelets 1.x to 2.x migration steps. However, there's a PrimeFaces  which might apply as well on migrating from PrimeFaces 1.x to 3.x. Tomahawk has also no migration guide. Basically the only which you need to change are the JARs and if necessary get rid of all  references on a request scoped bean by making the bean view scoped.One thing to mention is that if anyone is using JSTL with JSF 1.2 then when upgrading to JSF2 you should change the namespace from:to:JSF 2.0 have many new features and components and I don't feel migration will be painful.  Only area you will find difficult is in using thrid party libraries.  If your application is heavily dependant upon libraries like Richfaces then you will face problem.  Not all the components from Richfaces 3 is ported to Richfaces 4.This also might help\nAlso check this Web.xmlStep 1: Change web.xmlStep 2: webmvc-config.xmlStep3:facess-config.xmlIf you are using Apache Trinidad you'll also have to upgrade it to version 2.0 so that it will support JSF 2.0.  There's more info at .
Java

I know how to work out the index of a certain character or number in a string, but is there any predefined method I can use to give me the character at the  position? So in the string \"foo\", if I asked for the character with index 0 it would return \"f\".Note - in the above question, by \"character\" I don't mean the char data type, but a letter or number in a string. The important thing here is that I don't receive a char when the method is invoked, but a string (of length 1). And I know about the substring() method, but I was wondering if there was a neater way.The method you're looking for is . Here's an example:For more information, see the . If you want another simple tutorial,  or .If you don't want the result as a  data type, but rather as a string, you would use the  method:If you want more information on the  class and the  method, I pulled my info from .You want returns If you're hellbent on having a string there are a couple of ways to convert a char to a string:Or Or evenFor example.You're pretty stuck with , given your requirements.  The standard way would be , but you said you won't accept a char data type.You could use  method result as parameter for . A hybrid approach combining  with your requirement of not getting  char could beBut that's not really \"neater\" than  to be honest.simple as,None of the proposed answers works for surrogate pairs used to encode characters outside of the .Here is an example using 3 different techniques to iterate over the \"characters\" of a string (incl. using Java 8 stream API). Please notice this example includes characters of the Unicode Supplementary Multilingual Plane (SMP). You need a proper font to display this example and the result correctly.The First solution is a simple loop over all  of the string:The Second solution uses an explicit loop too, but accessing individual \ncode points with  and incrementing the loop index accordingly to :The third solution is basically the same as the second, but using the :When you run that test program, you obtain:As you can see (if you're able to display hieroglyphs properly), the first solution does not handle properly characters outside of the Unicode BMP. On the other hand, the other two solutions deal well with surrogate pairs.Here's the correct code. if you're using zybooks this will answer all the problems.Like this:
Java

I'm trying to read a text file line by line using InputStream from the assets directory in Android.I want to convert the InputStream to a BufferedReader to be able to use the readLine().I have the following code:The third line drops the following error:What I'm trying to do in C would be something like:What am I doing wrong or how should I do that? Thanks! can't wrap an  directly. It wraps another . In this case you'd want to do something like:A BufferedReader constructor takes a  as argument, not an InputStream. You should first create a Reader from your stream, like so:Preferrably, you also provide a Charset or character encoding name to the StreamReader constructor. Since a stream just provides bytes, converting these to text means the encoding must be known. If you don't specify it, the system default is assumed.
Java

In a few large projects i have been working on lately it seems to become increasingly important to choose one or the other (XML or Annotation). As projects grow, consistency is very important for maintainability. My question is, what do people prefer.  Do you prefer XML based or Annotation based? or Both? Everybody talks about XML configuration hell and how annotations are the answer, what about Annotation configuration hell?Annotations have their use, but they are not the one silver bullet to kill XML configuration.  I recommend mixing the two!For instance, if using Spring, it is entirely intuitive to use XML for the dependency injection portion of your application.  This gets the code's dependencies away from the code which will be using it, by contrast, using some sort of annotation in the code that needs the dependencies makes the code aware of this automatic configuration.However, instead of using XML for transactional management, marking a method as transactional with an annotation makes perfect sense, since this is information a programmer would probably wish to know.  But that an interface is going to be injected as a SubtypeY instead of a SubtypeX should not be included in the class, because if now you wish to inject SubtypeX, you have to change your code, whereas you had an interface contract before anyways, so with XML, you would just need to change the XML mappings and it is fairly quick and painless to do so.I haven't used JPA annotations, so I don't know how good they are, but I would argue that leaving the mapping of beans to the database in XML is also good, as the object shouldn't care where its information came from, it should just care what it can do with its information.  But if you like JPA (I don't have any expirience with it), by all means, go for it.In general:\nIf an annotation provides functionality and acts as a comment in and of itself, and doesn't tie the code down to some specific process in order to function normally without this annotation, then go for annotations.  For example, a transactional method marked as being transactional does not kill its operating logic, and serves as a good code-level comment as well.  Otherwise, this information is probably best expressed as XML, because although it will eventually affect how the code operates, it won't change the main functionality of the code, and hence doesn't belong in the source files.There is a wider issue here, that of externalised vs inlined meta-data. If your object model is only ever going to persisted in one way, then inlined meta-data (i.e. annotations) are more compact and readable.If, however, your object model was reused in different applications in such a way that each application wanted to persist the model in different ways, then externalising the meta-data (i.e. XML descriptors) becomes more appropriate.Neither one is better, and so both are supported, although annotations are more fashionable. As a result, new hair-on-fire frameworks like JPA tend to put more emphasis on them. More mature APIs like native Hibernate offer both, because it's known that neither one is enough.I always think about annotations as some kind of indicator of  a class is capable of, or  it interacts with others.Spring XML configuration on the other hand to me is just that, For instance, information about the ip and port of a proxy, is definetly going into an XML file, it is the runtime configuration.Using , to indicate the framework what to do with the class is good use of annotations.Putting the URL into the  annotation is bad style.But this is just my opinion.\nThe line between interaction and configuration is not always clear.I've been using Spring for a few years now and the amount of XML that was required was definitely getting tedious.  Between the new XML schemas and annotation support in Spring 2.5 I usually do these things:I think that visibility is a big win with an XML based approach.  I find that the XML isn't really that bad, given the various tools out there for navigating XML documents (i.e. Visual Studio + ReSharper's File Structure window).You can certainly take a mixed approach, but that seems dangerous to me if only because, potentially, it would make it difficult for new developers on a project to figure out where different objects are configured or mapped.I don't know; in the end XML Hell doesn't seem all that bad to me.It depends on what everything you want to configure, because there are some options that cannot be configured with anotations. If we see it from the side of annotations:It's up to you what is more important...In general I would recommend to choose one way and use it all over some closed part of product...(with some exceptions: eg if you choose XML based configurations, it's ok to use @Autowire annotation. It's mixing, but this one helps both readability and maintainability)An important part in using an annotation-only approach is that the concept of a \"bean name\" more or less goes away (becomes insignificant).The \"bean names\" in Spring form an additional level of abstraction over the implementing classes. With XML beans are defined and referenced relative to their bean name. With annotations they are referenced by their class/interface. (Although the bean name exists, you do not need to know it) I strongly believe that getting rid of superfluous abstractions simplifies systems and improves productivity. For  projects I think the gains by getting rid of XML can be substantial.I also think a mix is the best thing, but it also depends on the type of configuration parameters.\nI'm working on a Seam project which also uses Spring and I usually deploy it to different development and test servers. So I have split:The key difference is that you don't have to recompile the code for all changing server-specific configurations, just edit the xml file.\nThere's also the advantage that some configuration changes can be done by team members who don't understand all the code involved.There are other aspect to compare like refactoring and other code changes. when using XML it takes serous effort to make refactoring because you have to take care of all the XML content. But it is easy when using Annotations.My preferred way is the Java based configuration without (or minimal) annotations. I might be wrong, but I thought Annotations (as in Java's @Tag and C#'s [Attribute]) were a compile-time option, and XML was a run-time option. That to me says the are not equivalent and have different pros and cons.In the scope of DI container, I consider annotation based DI is abusing the use of Java annotation. By saying that, I don't recommend to use it widely in your project. If your project does really needs the power of DI container, I would recommend to use Spring IoC with Xml based configuration option.If it is just for a sake of Unit-test, developers should apply Dependency Inject pattern in their coding and take advantages from mocking tools such as EasyMock or JMock to circumvent dependencies.You should try to avoid using DI container in its wrong context.Configuration information that is always going to be linked to a specific Java component (class, method, or field) is a good candidate to be represented by annotations. Annotations work especially well in this case when the configuration is core to the purpose of the code. Because of the limitations on annotations, it's also best when each component can only ever have one configuration. If you need to deal with multiple configurations, especially ones that are conditional on anything outside the Java class containing an annotation, annotations may create more problems than they solve. Finally, annotations cannot be modified without recompiling the Java source code, so anything that needs to be reconfigurable at run time can't use annotations.Please refer following links. They might be useful too.This is the classic 'Configuration versus Convention' question.  Personal taste dictates the answer in most cases.  However, personally I prefer Configuration (i.e. XML based) over Convention.  IMO IDE's are sufficiently robust enough to overcome some of the XML hell people often associate w/ the building and maintaining an XML based approach.  In the end, I find the benefits of Configuration (such as building utilities to build, maintain and deploy the XML config file) outweighs Convention in the long run.  I use both. Mostly XML, but when I have a bunch of beans that inherit from a common class and have common properties, I use annotations for those, in the superclass, so I don't have to set the same properties for each bean. Because I'm a bit of a control freak, I use @Resource(name=\"referredBean\") instead of just autowiring stuff (and save myself a lot of trouble if I ever need another bean of the same class as the original referredBean).There are some pros and cons of annotation configuration from my experience:I prefer combining both approaches - java annotations and essential xml minimum that minimize configuration hell.For Spring Framework I like the idea of being able to use the @Component annotation and setting the \"component-scan\" option so that Spring can find my java beans so that I do not have to define all of my beans in XML, nor in JavaConfig.  For example, for stateless singleton java beans that simply need to be wired up to other classes (via an interface ideally) this approach works very well.  In general, for Spring beans I have for the most part moved away from Spring XML DSL for defining beans, and now favor the use of JavaConfig and Spring Annotations because you get some compile time checking of your configuration and some refactoring support that you don't get with Spring XML configuration.  I do mix the two in certain rare cases where I've found that JavaConfig/Annotations can't do what is available using XML configuration. For Hibernate ORM (haven't used JPA yet) I still prefer the XML mapping files because annotations in domain model classes to some degree violates  which is a layering architectural style I have adopted over the past few years.  The violation occurs because it requires the Core Layer to depend on persistence related things such as Hibernate or JPA libraries and it makes the domain model POJOs a bit less persistence ignorant.  In fact the Core Layer is not supposed to depend on any other infrastructure at all.However, if The Clean Architecture is not your \"cup of tea\" then I can see there are definitely advantages (such as convenience and maintainability) of using Hibernate/JPA annotations in domain model classes over separate XML mapping files.
Java

I have an INTELIJ(v12) android project successfully imported to AndroidStudio(v0.4.0). It works perfectly if I don't change anything in manifest. When I want to change the launcher activity and run, it outputs with the following error:When I click  it outputs:Anyone has faced this problem? Any ideas?Run settings:\nI faced a similar problem after refactoring.\nThis is what i did to resolve this issue:And everything worked fine!\nI think the key is to .  Hope this helps you or anyone else!\nIf above steps doesn't work for you, then  seems be a solution, as pointed out by @Yasitha.  When running Android Studio 2.1 and up you can also encounter this issue when you have the instant run option enabled in your preferences (is enabled by default). To disable this option go to  option in the  top menu and look for  so you can uncheck the first checkbox on that screen.Anyway that fixed it for me. Originally pointed out by user @yusufonder. I discovered this was the issue since gradle install still worked.This happens when you do the followingAS thinks you still have the app in your device.tl;dr - To resolve this, you can simply disconnect your device after uninstalling the app and reconnect it.Right now it says:Try either  to the beginning of the Activity's name:Or  to the beginning of the Activity's name:May be helpful for someone:--Sometimes when testing on a device, . To verify and fix this:For me, the problem was that   that the app was still on the device.To fix it:make sure the  of the  is added to your !I had the same error after renaming/refactoring. What I did was add the  property attribute to my build.gradle file, and set its value to the application package. I would face this problem when uninstalling the app via the device (i.e. dragging the app to the \"Uninstall\" option). But here is the proper way to uninstall:Use the  command. This will prevent the  error.I had the same issue and I solved it refactoring my activity launcher, just change the class name and it works.Even I had the same problem but none of the above solutions worked for me.\nThe problem was that, I had froze the particular app which I was trying to run via Titanium Backup due to which I got the above error. I tried both in Eclipse and Android Studio.After the realization I just unistalled the app and then ran it again.Problem Solved :-)I also faced the same problem somewhere in the past.  Renaming and Moving files require changes in the gradle file so whenever you rename or move some file just clean the project:Cleaning the project just removes the  files and recompiles the project. Basically, it forces a project rebuild. Sometimes such types of errors did not cleaned on cleaning project then try to uninstall the app from the device (either it is emulator or physical one) and run the app again. Hope this will help you, it helps me 50% times. I face the similar Problem please follow the below steps.\nit will help you:1- Clean your Project\n2- Delete your build directory\n3- Restart your Android Studio\n4- Rebuild the project\n5- it will run successfully.  Thanksfor me, on android 6 when i uninstalled the app it actually went to disabled instead of being removed from device.Settings > Apps > click on your app and uninstallthis fixed it for mei just go to Build > Rebuild Project and my problem is solvedNone of the above worked for me.  I had a version of the app on the device that could not be uninstalled as it was corrupt somehow.  I had to factory reset the device.  Not too bothered cause it was a just a dev deviceI'd like to share the trick that helped in my case. I uninstalled the application from the device and nothing of  operations didn't help. Since Android Studio thinks that the application is still installed on the device and doesn't deploy it, you can force the installation using the ADB:where  means reinstall the app, keeping its data.As others have noted, this problem can be caused by an attached device/emulator while uninstalling the app and AS connection still exists.  On my end, I just delete all the  folders (under app and project dirs) in the project, and relaunch the application on the device/emulator.I took reference from @jayeffkay's comment.It works for me after I deleted the gradle cache files located in 2.10 is the gradle version used in my case.I had same issue. My problem fixed when I disabled instant run for Android Studio 2.1.1I had Error type 3. I managed to fix it by adding the following code below in AndroidMainfest.xml.I faced this problem lately, and tried all suggestions above, and problem was not saved. Finally I changed a NDK, and problem was solved...For me it was a very specific problem, I've got a  to test my application on, and to reset my apps data I uninstalled it on the phone, but the phone has a \"nice\" feature to don't uninstall apps immediatly so you might can reinstall them within one day.\nSo the app was installed but not usable() after removing the app from the phone completely it worked.I think another reason that issue happen is that it is not fully deleted for all users on the device.Go to Settings -> Apps - > Your Apps -> Click to the 3 dots on the top right -> Uninstall for all usersIt works for me. It happen especially you change the icons of the app or messing around with the AndroidManifest.xml file.If you're not careful and you're trying to disable something in your app manifest make sure you don't disable the app...I accidentally set  to \"false\" instead of . Wasted 2 hours searching for a solution. \"instant run\" can be found with the following steps:\nPreferences -> Build,Execution,Deployment -> Instant Run and then uncheck the checkbox \"Enable Instant Run to hot swap....\" Check if you are building hidden version. That\u2019s intended behavior for hidden app.If you want to build regular version, you need to change Build Variant in Android Studio , change it to regular.I have LG Stylus and in my test phone, application isn't remove permanently. In Settings -> Application I found debug app (which I try install and debug by AS) with adnotation turn-off. When I remove app from my phone, error disappeard.
Java

I'd like to know if I can get the first element of a list or set.  Which method to use?(This is the closest you'll get to having the \"first\" element of a .  You should realize that it has absolutely no meaning for most implementations of .  This may have meaning for LinkedHashSet and TreeSet, but not for HashSet.)See the javadoc of or and check the size before using the above methods by invoking In Java >=8 you could also use the Streaming API:(Useful if the Set/List may be empty.)SortedSet has a first() method:The sorted objects must implement the Comparable interface (like String does)SetListYou can use the get(index) method to access an element from a List. Sets, by definition, simply contain elements and have no particular order. Therefore, there is no \"first\" element you can get, but it is possible to iterate through it using iterator (using the for each loop) or convert it to an array using the toArray() method. I'm surprised that nobody suggested guava solution yet:or if you expect single element:A less polished solution can even be
Java

I want to return an age in years as an int in a Java method.\nWhat I have now is the following where getBirthDate() returns a Date object (with the birth date ;-)):But since getYear() is deprecated I'm wondering if there is a better way to do this? I'm not even sure this works correctly, since I have no unit tests in place (yet).Check out , which simplifies date/time calculations (Joda is also the basis of the new standard Java date/time apis, so you'll be learning a soon-to-be-standard API). EDIT: Java 8 has  and is worth checking out.e.g. which is as simple as you could want. The pre-Java 8 stuff is (as you've identified) somewhat unintuitive.JDK 8 makes this easy and elegant:A JUnit test to demonstrate its use: Everyone should be using JDK 8 by now. All earlier versions have passed the end of their support lives.Note that the expression  is implicitly related to the system timezone (which is often overlooked by users). For clarity it is generally better to use the overloaded method  specifying an explicit timezone (here \"Europe/Paris\" as example). If the system timezone is requested then my personal preference is to write  to make the relation to the system timezone clearer. This is more writing effort but makes reading easier.Please note that the proposed and accepted Joda-Time-solution yields a different computation result for the dates shown above (a rare case), namely:I consider this as a small bug but the Joda-team has a different view on this weird behaviour and does not want to fix it (weird because the day-of-month of end date is smaller than of start date so the year should be one less). See also this closed .For comparison see the various other answers. I would not recommend using these outdated classes at all because the resulting code is still errorprone in some exotic cases and/or way too complex considering the fact that the original question sounds so simple. In year 2015 we have really better libraries.The proposed solution is simple but will sometimes fail in case of leap years. Just evaluating the day of year is not reliable.:This works similar to Java-8-solution. Just replace  by  and  by . However, getting \"today\" requires an explicit timezone reference.If you are using GWT you will be limited to using java.util.Date, here is a method that takes the date as integers, but still uses java.util.Date:I simply use the milliseconds in a year constant value to my advantage:The correct answer using  is:You could even shorten it into one line if you like. I copied the idea from , but I believe this is more correct as you see from the comments there (and it answers the question exactly).The fields birth and effect are both date fields:    This basically a modification of John O's solution without using depreciated methods. I spent a fair amount of time trying to get his code to work in in my code. Maybe this will save others that time.This is an improved version of the one above... considering that you want age to be an 'int'. because sometimes you don't want to fill your program with a bunch of libraries.Try to copy this one in your code, then use the method to get the age.With the  library :  has the date of birth. and format is whatever (defined in the following line):Here is how to format:Variable  will have the years.Elegant, , timestamp difference based  variant of Yaron Ronen solution.I am including a . It is impossible due (to possibly) different number of leap days (and seconds) in any timestamp difference. The discrepancy should be max +-1 day (and one second) for this algorithm, see test2(), whereas Yaron Ronen solution based on completely constant assumption of  can differ 10 days for a 40ty year old, nevertheless this variant is incorrect too.It is tricky, because this improved variant, using formula , returns correct results most of the time, as number of leap years in on average same between two dates.It's perhaps surprising to note that you don't need to know how many days or months there are in a year or how many days are in those months, likewise, you don't need to know about leap years, leap seconds, or any of that stuff using this simple, 100% accurate method:What about this one?Here is the java code to calculate age in year, month and days. I use this piece of code for age calculation ,Hope this helps ..no libraries used
Java

I have a situation where the return statement nested in two for loops will always be reached, theoretically. The compiler disagrees and requires a return statement outside of the for loop. I'd like to know an elegant way to optimize this method that's beyond my current understanding, none of my attempted implementations of break seem to work. Attached is a method from an assignment that generates random integers and returns the iterations cycled through until a second random integer is found, generated within a range passed into the method as an int parameter.The compiler's heuristics will never let you omit the last . If you're sure it'll never be reached, I'd replace it with a  to make the situation clear.As  you can make sure the second  statement is semantically unreachable:Compiles & runs fine. And if you ever get an  you'll know the implementation was semantically wrong, without having to explicitly throw anything.Since you asked about breaking out of two  loops, you can use a label to do that (see the example below):While an assert is a good fast solution. In general this kind of problems means that your code is too complicated. When I am looking at your code, it's obvious that you don't really want an array to hold previous numbers. You want a :Now note that what we are returning is actually the size of the set. The code complexity has decreased from quadratic to linear and it is immediately more readable.Now we can realize that we don't even need that  index:As your return value is based on the outer loop's variable you could simply alter the outer loop's condition to  and then return this last value (which you've just omitted) at the end of the function:This way you don't need to introduce code that will never be reached.Use a temp variable, for instance \"result\" , and remove the inner return. \nChange the for loop for a while loop with the proper condition. \nTo me it's always more elegant to have only one return as the last statement of the function.Maybe this is an indication that you should rewrite your code.  For example:Methods that have a return statement and have a loop/loops inside them always require a return statement outside the loop(s). Even if this statement outside the loop is never reached. In such cases, in order to avoid unnecessary return statements, you could define a variable of the respective type, an integer in your case, at the beginning of the method i.e. before and outside the respective loop(s). When the desired result inside the loop is reached, you can ascribe the respective value to this pre-defined variable and use it for the return statement outside the loop. Since you want your method to return the first result when rInt[i] equals rInt[count], implementing only the above-mentioned variable is not enough because the method will return the last result when rInt[i] equals rInt[count]. One options is to implement two \"break statements\" that are called when the we have the desired result. So, the method will look something like this:I agree that one should throw an exception where unreachable statement occurs. Just wanted to show how the same method can do this in more readable way (java 8 streams required).
Java

What is the difference between them? I know that But in sourcecode of LinkedHashSet there are only calling constructors of HashSet. So where is double-linked List and insertion order?The answer lies in  the  uses to construct the base class:And (one example of) a  constructor that takes a boolean argument is described, and looks like this:'s constructors invoke the following base class constructor:As you can see, the internal map is a . If you look inside , you'll discover the following field:This is the linked list in question.You should look at the source of the  constructor it calls... it's a special constructor that makes the backing  a  instead of just a .A HashSet is unordered and unsorted Set. LinkedHashSet is the ordered version of HashSet.The only difference between HashSet and LinkedHashSet is that LinkedHashSet maintains the insertion order. When we iterate through a HashSet, the order is unpredictable while it is predictable in case of LinkedHashSet.\nThe reason why LinkedHashSet maintains insertion order is because the underlying data structure is a doubly-linked list.HashSet:\nUnordered actually.\nif u passing the parameter meansOut Put:\nMay be  not predictable. next time another order. which produce FIFO Order.If you take a look at the constructors called from the LinkedHashSet class you will see that internally it's a LinkedHashMap that is used for backing purpose.I suggest you to use  most of the time, because it has ):You can see source test page here: All Methods and constructors are same but only one difference is LinkedHashset will maintain insertion order but it will not allow duplicates.Hashset will not maintain any insertion order.\nIt is combination of List and Set simple :)
Java

I was wondering what happens when you try to catch an StackOverflowError and came up with the following method:Now my question:Why does this method print '4'?I thought maybe it was because  needs 3 segments on the call stack, but I don't know where the number 3 comes from. When you look at the source code (and bytecode) of , it normally would lead to far more method invocations than 3 (so 3 segments on the call stack would not be sufficient). If it's because of optimizations the Hotspot VM applies (method inlining), I wonder if the result would be different on another VM.:As the output seems to be highly JVM specific, I get the result 4 using\nJava(TM) SE Runtime Environment (build 1.6.0_41-b02)\nJava HotSpot(TM) 64-Bit Server VM (build 20.14-b01, mixed mode)My question is not about why there is a cnt > 0 (obviously because  requires stack size and throws another  before something gets printed), but why it has the particular value of 4, respectively 0,3,8,55 or something else on other systems.I think the others have done a good job at explaining why cnt > 0, but there's not enough details regarding why cnt = 4, and why cnt varies so widely among different settings. I will attempt to fill that void here.Let When we first get into main, the space left over is X-M. Each recursive call takes up R more memory. So for 1 recursive call (1 more than original), the memory use is M + R. Suppose that StackOverflowError is thrown after C successful recursive calls, that is, M + C * R <= X and M + C * (R + 1) > X. At the time of the first StackOverflowError, there's X - M - C * R memory left.To be able to run , we need P amount of space left on the stack. If it so happens that X - M - C * R >= P, then 0 will be printed. If P requires more space, then we remove frames from the stack, gaining R memory at the cost of cnt++. When  is finally able to run, X - M - (C - cnt) * R >= P. So if P is large for a particular system, then cnt will be large. Let's look at this with some examples.  Suppose Then C = floor((X-M)/R) = 49, and cnt = ceiling((P - (X - M - C*R))/R) = 0. Suppose thatThen C = 19, and cnt = 2. Suppose that Then C = 20, and cnt = 3. Suppose that Then C = 19, and cnt = 2.Thus, we see that both the system (M, R, and P) and the stack size (X) affects cnt.As a side note, it does not matter how much space  requires to start. As long as there is not enough space for , then cnt will not increase, so there are no external effects.I take back what I said about . It does play a role. Suppose it requires T amount of space to start. cnt starts to increment when the leftover space is greater than T, and  runs when the leftover space is greater than T + P. This adds an extra step to the calculations and further muddies up the already muddy analysis.I finally found time to run some experiments to back up my theory. Unfortunately, the theory doesn't seem to match up with the experiments. What actually happens is very different.Experiment setup:\nUbuntu 12.04 server with default java and default-jdk. Xss starting at 70,000 at 1 byte increments to 460,000.The results are available at: \nI've created another version where every repeated data point is removed. In other words, only points that are different from the previous are shown. This makes it easier to see anomalies. This is the victim of bad recursive call. As you are wondering why the value of  varies, it is because the stack size depends on the platform. Java SE 6 on Windows has a default stack size of 320k in the 32-bit VM and 1024k in the 64-bit VM. You can read more .You can run using different stack sizes and you will see different values of  before the stack overflows-You don't see the value of  being printed multiple times even though the value is greater than 1 sometimes because your print statement is also throwing error which you can debug to be sure through Eclipse or other IDEs.You can change the code to the following to debug per statement execution if you'd prefer-As this getting a lot more attention, let's have another example to make things clearer-We created another method named  to do a bad recursion and removed the  statement from the catch block so it doesn't start throwing another set of errors while trying to print. This works as expected. You can try putting  statement after  above and compile. Then run multiple times. Depending on your platform, you may get different values of .This is why generally we do not catch errors because mystery in code is not fantasy.The behavior is dependent upon the stack size (which can be manually set using . The stack size is architecture specific. From JDK 7 :So when the  is thrown, the error is caught in catch block. Here  is another stack call which throws exception again. This gets repeated.  - Well it depends on when JVM thinks it is no longer stackoverflow. And that depends on the stack size of each function call (difficult to find) and the . As mentioned above default total size and size of each function call (depends on memory page size etc) is platform specific. Hence different behavior.Calling the  call with  gives me . Hence the correlataion.I think the number displayed is the number of time the  call throws the  exception.It probably depend on the implementation of the  and the number of stacking call it is made in it.As an illustration:The  call trigger the  exception at call i.\nThe i-1 call of main catch the exception and call  which trigger a second .   get increment to 1.\nThe i-2 call of main catch now the exception and call .  In  a method is called triggering a 3rd exception.   get increment to 2.\n  this continue until  can make all its needed call and finally display the value of .This is then dependent of the actual implementation of .For the JDK7 either it detect cycling call and throws the exception earlier either it keep some stack resource and throw the exception before reaching the limit to give some room for remediation logic either the  implementation doesn't make calls either the ++ operation is done after the  call thus is by pass by the exception. After digging around for a while, I can't say that I find the answer, but I think it's quite close now.First, we need to know when a  will be thrown. In fact, the stack for a java thread stores frames, which containing all the data needed for invoking a method and resume. According to , when invoking a method,Second, we should make it clear what is \"\". According to ,So, when a frame is created, there should be enough heap space to create a stack frame and enough stack space to store the new reference which point to the new stack frame if the frame is heap allocated.Now let's go back to the question. From the above, we can know that when a method is execute, it may just costs the same amount of stack space. And invoking  (may) needs 5 level of method invocation, so 5 frames need to be created. Then when  is thrown out, it has to go back 5 times to get enough stack space to store 5 frames' references. Hence 4 is print out. Why not 5? Because you use . Change it to , and then you will get 5.And you will notice that when the size of stack go to a high level, you will get 50 sometimes. That is because the amount of available heap space need to be taken into consideration then. When the stack's size is too large, maybe heap space will run out before stack. And (maybe) the actual size of stack frames of  is about 51 times of , therefore it goes back 51 times and print 50.This is not exactly an answer to the question but I just wanted to add something to the original question that I came across and how I understood the problem:In the original problem the exception is caught where it was possible:For example with jdk 1.7 it is caught at first place of occurence.but in earlier versions of jdk it looks like the exception is not being caught at the first place of occurence hence 4, 50 etc..Now if you remove the try catch block as followingThen you will see all the values of  ant the thrown exceptions (on jdk 1.7).I used netbeans to see the output, as the cmd will not show all the output and exception thrown.
Java

Is there any performance reason to declare method parameters final in Java?As in:Versus:Assuming that  is only read and never modified in .The final keyword does not appear in the class file for local variables and parameters, thus it cannot impact the runtime performance.  It's only use is to clarify the coders intent that the variable not be changed (which many consider dubious reason for its usage), and dealing with anonymous inner classes.There is a lot of argument over whether the final modifier on the method itself has any performance gain since the methods will be inlined by the optimizing compiler at runtime anyway, regardless of the modifier.  In this case it should also only be used to restrict the overriding of the method.The only benefit to a final parameter is that it can be used in anonymous nested classes.  If a parameter is never changed, the compiler will already detect that as part of it's normal operation even without the final modifier.  It's pretty rare that bugs are caused by a parameter being unexpectedly assigned - if your methods are big enough to need this level of engineering, make them smaller - methods you call can't change your parameters.I can't think of a reason why the compiler would care if you declared a method parameter final or not.But the real answer to this question is - write two functions, one with final parameters and one with regular parameters. Run them a million times each and see if there's any noticeable runtime difference. If you're worried about performance, it's very important to do some profiling work on your code and find out exactly what is slowing you down. It's almost certainly not what you would expect it to be :)Compilers that operate after class loading, such as JIT compilers, can take advantage of final methods. Consequently, methods declared final could have some performance benefit. Oh and another good resourceI would suggest you never write micro benchmarks. You do not know which optimization the JIT can do and when, and you would likely get a wrong idea of how it behave just doing a \"simple test case\"I assume the compiler could possibly remove all private static final variables that has a primitive type, such as int, and inline them directly in the code just like with a C++ macro.However, i have no clue if this is done in practice, but it could be done in order to save some memory. Just one more point that to above that using non-final local variables declared within the method\u2014the inner class instance may outlive the stack frame, so the local variable might vanish while the inner object is still aliveparameters (means the object's identity, not its state).
Java

Do interfaces inherit from  class in Java?If no then how we are able to call the method of object class on interface instanceNo, they don't. And there is no common \"root\" interface implicitly inherited by all interfaces either (as in the case with classes) for that matter.An interface implicitly declared one method for each public method in . Thus the  method is implicitly declared as a member in an interface (unless it already inherits it from a superinterface).This is explained in detail in the Java Language Specification, .This post has been rewritten as an article .There is actually a superclass field in every  file, including those that represent interfaces.For an interface it always points to .  But that isn't used for anything.Another way to look at it is:Here the cast  is always valid, which implies that every interface type is a subtype of . is a supertype of any interface [1] However, an interface does not , , or,  .JLS has a special clause to add  methods into interfaces [2][1] [2] \nNo Interface does not inherits Object class,but it provide accessibility to all methods of Object class. \nThe members of an interface are:, . It is a compile-time error if the interface explicitly declares such a method m in the case where m is declared to be final in Object.Now it is clear that all superinterface have abstract member method corresponding to each public instance method declared in Object .\nsource:\n\". Classes, enums, arrays, and \"Quoted from: \nSecond sentence to be clear.You are calling the equals method on the Object which implements the Interface.Any class implementing any interface is also derived from  as well by definition.That's because  reads that there is a class that  , and is assigned to variable . Every class that implements an interface extends Object implicitly, hence when you do , the language knows that you have a class that is a subtype of . The JVM will do runtime checking for your code (i.e. throw ).
Java

Is it possible to do something similar to the following code in JavaSadly - no.  The closest you can do is:Of course, you can wrap this up in library methods if you feel the need to (it's unlikely to cut down on length much), but at the syntax level there isn't anything more succinct available. has a method that does something similar called .This is more helpful when you have something likesince it saves you from either calling the potentially expensive method twice or declaring a local variable in your code to reference twice.Short answer: The best you can do is to create a static utility method (so that it can be imported using  syntax)The above is equivalent to Guava's method  by @ColinD, but that can be extended more in generalNo, and be aware that workaround functions are not exactly the same, a true null coalescing operator short circuits like && and || do, meaning it will only attempt to evaluate the second expression if the first is null., from Apache Commons Lang 3 is another option. I prefer this becuase unlike Guava, this method does not throw an . It will simply return ;Primitives in Java can never be null, so that statement does not make sense conceptually. However, the wrapper classes (Integer, Character, etc.), as well as any other instantiable class can be null.Besides that fact, there isn't any short-hand syntax for a null coalescing operator. You must use the expanded form.
Java

Is it still worth to add the log4j library to a Java 5 project just to log\nlet's say some exceptions to a file with some nice rollover settings.\nOr will the standard util.logging facility do the job as well?What do you think?I'd say you're probably fine with util.logging for the needs you describe.For a good decision tree, have a look at That said, pretty much every project these days seems to wind up including log4j, if only because some other library uses it.I recommend that you use the  (SLF4J). It supports different providers that include Log4J and can be used as a replacement for Apache Commons Logging.Log4j has been around for a long time, and it works very well.  I have no scientific study to back it, but based on what I've seen at a large number of clients, it is easily the logging framework that I see used more than any other.  It has been around for a long time, and not been replaced by the Next Big Logging Framework, which says something.  It is dead simple to set up, and easy to learn the basic appenders (outputs).  There are a whole host appenders that are available, including:Plus others.  It isn't difficult to write your own appender either.  Additionally there is a great deal of flexibility in each of the appenders that allow you to control specifically what is output in your log.One note, I had a series of classloader problems when I used apache commons logging in addition to log4j.  It was only for one specific application, but I found it simpler to use log4j alone, rather than to have the flexibility offered when using an abstraction layer like commons logging.    See this article for\n:Good luck!java.util.logging offers a comprehensive logging package without the excess baggage some of the others provide..log4j is a much nicer package overall, and doesn't have some of the hiccups that java.util.logging contains.  I'd second that using log4j directly is easier than using the commons logging.I recommend using  as your logging interface. That way you have the flexibility to switch logging implementations anytime you want without requiring any code changes on your end.I would go with log4j. The possibilites with log4j is not obsolete at all!
Java

How do you remove a cookie in a Java servlet?I tried this:\nEDIT: The following now works successfully it appears to be the combination of:andBefore I was doing:Which expires the cookie when the browser is closed as per .The full working snippet to expire a cookie is:The MaxAge of -1 signals that you want the cookie to persist for the duration of the session. You want to set MaxAge to 0 instead.From the :In my environment, following code works. Although looks redundant at first glance,  and  are necessary to clear the cookie properly.    Keep in mind that a cookie is actually defined by the tuple of it's name, path, and domain.  If any one of those three is different, or there is more than one cookie of the same name, but defined with paths/domains that may still be visible for the URL in question, you'll still see that cookie passed on the request.  E.g. if the url is \"\", you'll see any cookies defined on bar.com or foo.bar.com, or with a path of \"/\" or \"/baz\".Thus, what you have looks like it should work, as long as there's only one cookie defined in the client, with the name \"SSO_COOKIE_NAME\", domain \"SSO_DOMAIN\", and path \"/\".  If there are any cookies with different path or domain, you'll still see the cookie sent to the client.To debug this, go into Firefox's preferences -> Security tab, and search for all cookies with the SSO_COOKIE_NAME.  Click on each to see the domain and path.  I'm betting you'll find one in there that's not quite what you're expecting.This is code that I have effectively used before, passing  as the strPath parameter.did that not worked? This removes all cookies if response is send back.
Java

I tried searching using Google Search and Stack\u00a0Overflow, but it didn't show up any results. I have seen this in opensource library code:What does \"|=\" (  ) mean? reads the same way as .is the same aswhere  is the bit-wise OR operator.All operators are referenced .A bit-wise operator is used because, as is frequent, those constants enable an int to carry flags.If you  at those constants, you'll see that they're in powers of two :So you can use bit-wise OR to add flagssosimply means we add a flag.And symmetrically, we test a flag is set using  :You have already got sufficient answer for your question. But may be my answer help you more about  kind of binary operators.    I am writing table for :\nFollowing are valid:  note all operators are binary operators.    Also     It's a shortening for this:And  is a bit-wise OR. is the  operator, and it is being applied like . I was looking for an answer on what  does in Groovy and although answers above are right on they did not help me understand a particular piece of code I was looking at.In particular, when applied to a boolean variable \"|=\" will set it to TRUE the first time it encounters a truthy expression on the right side and will HOLD its TRUE value for all |= subsequent calls. Like a latch.Here a simplified example of this:Output::\nWhy is this useful?Consider a situation where you want to know if anything has changed on a variety of objects and if so notify some one of the changes. So, you would setup a  boolean and set it to   and then  etc.\nHere is a brief example:Note: ||= does not exist. (logical or)\nYou can use or
Java

i got a tricky one:I can't set valid breakpoints. Not in Tests, neither in my Java Classes. I searched Stackoverflow and google, but I couldn't find anybody with the same problem.I'm using STS(x86) and Maven. It may seem confusing but I solved it by myself.\nI have to go Run-> Skip all Breakpoints (it was set, and I wonder how it was set, because I didn't do it)There is a menu entry you have discovered for yourself that toggles the skipping of all breakpoints. There is also an icon for this in the \"Breakpoints\" View, and there may be a hot-key defined as well, all of which you may have triggered by accident.Take a look at the .Screenshot of the 'skip all breakpoints' in eclipse.When you click on 'skip all breakpoints'(which is selected), everything will become normal    The shortcut key for placing a breakpoint in Eclipse (Ctrl + Shift + B) is quite similar to the one that skips all the breakpoint (Ctrl + Alt + B). Hence, if a \"skip all breakpoints\" condition is to be cancelled, it can be achieved by pressing \"Ctrl + Alt + B\" again.1) Run => Skip all breakpoints.\n2) Run => remove all break points.and then your debugger wont show cross sign and will keep debugging your app.I followed these steps below to fix this
Java

For example why can you do:But not:And you can do:But not: is a primitive type. Variables of type  store the actual binary value for the integer you want to represent.  doesn't make sense because  is  a class and therefore doesn't have any methods. is a class, no different from any other in the Java language. Variables of type  store  to  objects, just as with any other reference (object) type.  is a call to the static method  from class  (note that this method actually returns an  and not an ).To be more specific,  is a class with a single field of type . This class is used where you need an  to be treated like any other object, such as in generic types or situations where you need nullability.Note that every primitive type in Java has an equivalent  class: Wrapper classes inherit from Object class, and primitive don't. So it can be used in collections with Object reference or with Generics.Since java 5 we have autoboxing, and the conversion between primitive and wrapper class is done automatically.  Beware, however, as this can introduce subtle bugs and performance problems; being explicit about conversions never hurts.Integer is a class and int is a primitive type.Read up on at these links: An Integer is pretty much just a wrapper for the primitive type int. It allows you to use all the functions of the Integer class to make life a bit easier for you.If you're new to Java, something you should learn to appreciate is the Java documentation. For example, anything you want to know about the  is documented in detail.This is straight out of the documentation for the Integer class:  refers to wrapper type in Java whereas  is a primitive type. Everything except primitive data types in Java is implemented just as objects that implies Java is a highly qualified pure object-oriented progamming language. If you need, all primitives types are also available as wrapper types in Java. You can have some performance benefit with primitive types and hence wrapper types should be used only when there is absolutely necessary.In your example as below.the constant  is being  ( and  occurs automatically from  onwards) to  and therefore you can use the statement like that and also . This is actually achieved through the statement Integer is an wrapper class/Object and int is primitive type. This difference plays huge role when you want to store int values in a collection, because they accept only objects as values (until jdk1.4). JDK5 onwards because of autoboxing it is whole different story. is a primitive type that represent an integer. whereas  is an Object that wraps . The  object gives you more functionality, such as converting to hex, string, etc.You can also use OOP concepts with . For example, you can use Integer for generics (i.e. ).int is a primitive type and not an object. That means that there are no methods associated with it. Integer is an object with methods (such as parseInt).With newer java there is functionality for auto boxing (and unboxing). That means that the compiler will insert Integer.valueOf(int) or integer.intValue() where needed. That means that it is actually possible to writewhich is interpreted asAn int variable holds a 32 bit signed integer value. An Integer (with capital I) holds a reference to an object of (class) type Integer, or to null.Java automatically casts between the two; from Integer to int whenever the Integer object occurs as an argument to an int operator or is assigned to an int variable, or an int value is assigned to an Integer variable. This casting is called boxing/unboxing.If an Integer variable referencing null is unboxed, explicitly or implicitly, a NullPointerException is thrown.To optimize the Java code runtime,   has been added including ,  etc. but they come along with there  so that if needed you can convert and use them as standard Java object along with many utility that comes as their member functions (such as ).In Java int is a primitive data type while Integer is a Helper class, it is use to convert for one data type to other.For example:Primitive data types are store the fastest available memory where the Helper class is complex and store in heap memory.reference from \"David Gassner\" Java Essential Training. is a primitive data type while  is a Reference or Wrapper Type (Class) in Java.after  which introduce the concept of  and  you can initialize both  or  like this. is a Class defined in  library and  is a static method belongs to  ClassSo,  is possible in java. but  is primitive type (assume like a keyword) in java. So, you can't call  with .
Java

I am wanting to create an array of arraylist like below:But it's not compiling. How can I do this?As per :Instead, you could do:As suggested by Tom Hawting - tackline, it is even better to do:As the others have mentioned it's probably better to use another list to store the ArrayList in but if you have to use an array:This works:You can create a class extending ArrayListand then create the arrayI totally do not get it, why everyone is suggesting the genric type over the array particularly for this question.What if my need is to index  different arraylists.With declaring  I need to create   objects manually or put a for loop to create  lists or some other way, in any way it will always be my duty to create  lists.Isn't it great if we declare it through casting as . I see it as a good design where one do not have to create all the indexing object (arraylists) by himselfCan anyone enlighten me why this (arrayform) will be a bad design and what are its disadvantages?The problem with this situation is by using a arraylist you get a time complexity of o(n) for adding at a specific position. If you use an array you create a memory location by declaring your array therefore it is constantYou can create Array of ArrayListThis will be help full in scenarios like. You know the size of the outer one . But the size of inner ones varies. Here you can create array of fixed length. which contain size varying Array lists. Hope this will be helpful for youYou can't create array of generic type. Create List of ArrayLists :or if you REALLY need array (WARNING: bad design!):This works, array of ArrayList. Give it a try to understand how.Credits to Kelvincer for some of codes.To declare an array of ArrayLists statically for, say, sprite positions as Points:dynamically:Despite the cautions and some complex suggestions here, I have found an array of ArrayLists to be an elegant solution to represent related ArrayLists of the same type.I find this easier to use...ArrayList[] lists = (ArrayList[])new ArrayList[10]; You can do this ://Create an Array of type ArrayList//For each element in array make an ArrayListyou can create a List[] and initialize them by for loop. it compiles without errors:it works with arrayList[] l as well.
Java

My code here detects if the  is equals to some  type, if it is, it will do a certain conversionI have shortened my code, because it has a lot of  statements, What design pattern is suitable for removing many  and  or  statements?You could have a  interface. Then you could create a class for each Mimetype like:You would need a class like this for each converter. Then you could set up a map like this:Then your  method becomes like this:Using this approach you could easily add different converters in the future.All untested, probably doesn't compile, but you get the ideaIf you use pre-JDK7, you may add an enum for all  types:And have a look at the Stack Overflow question  on how to convert Strings to enums.Consider using the Strategy design pattern and a  to dispatch to the appropriate strategy. Particularly useful if you you will need additional functionality, in addition to a conversion for a particular , or the convertors are large and complicated code and you would want to place each convertor in its own  file.If you run the  you should check If you are using , you can use  construct:See: For prior versions,  is the only choice.It's definitely a Strategy design pattern. But you have a big problem in your general design. It's not a good programming habit to use String to identify a type. Simply because it's easily editable and you can make a grammar mistake and spend all the afternoon looking for a programming mistake. You can avoid using map<>.I suggest the following:This design is scalable and you can add as much as you need FileType and converters.\nThe answer you vote for is misleading!!!!\nThere is a big difference between coding and hacking.If you are not using Java 7 you could create an  and use that value with a  case. You then only need to pass the enum value (rather than a file, I don't why you are doing that). It would look neater too.These should help with what you want to do:
Java

What does  mean in Java?  I'm in the process of learning. In all the examples in the book I'm working from  comes before any method that is being used or created. What does this mean? It's three completely different things: means that the method is visible and can be called from other objects of other types. Other alternatives are private, protected, package and . See  for more details. means that the method is associated with the class, not a specific instance (object) of that class. This means that you can call a static method without creating an object of the class. means that the method has no return value. If the method returned an  you would write  instead of .The combination of all three of these is most commonly seen on the  method which most tutorials will include.The three words have orthogonal meanings. means that the method will be visible from classes in other packages. means that the method is not attached to a specific instance, and it has no \"\". It is more or less a function. is the return type. It means \"this method returns nothing\".The  keyword is an access specifier, which allows the programmer to control the visibility of class members. When a class member is preceded by public, then that member may be accessed by code outside the class in which it is declared. (The opposite of public is private, which prevents a member from being used by code defined outside of its class.) In this case,  must be declared as public, since it must be called by code outside of its class when the program is started. The keyword  allows  to be called without having to instantiate a particular instance of the class. This is necessary since  is called by the Java interpreter before any objects are made. The keyword  simply tells the compiler that  does not return a value. As you will see, methods may also return values.It means that:You'd think that the lack of a return means it isn't doing much, but it might be saving things in the database, for example.It means three things.First  means that any other object can access it. means that the class in which it resides doesn't have to be instantiated first before the function can be called. means that the function does not return a value.Since you are just learning, don't worry about the first two too much until you learn about classes, and the third won't matter much until you start writing functions (other than main that is).Best piece of advice I got when learning to program, and which I pass along to you, is don't worry about the little details you don't understand right away.  Get a broad overview of the fundamentals, then go back and worry about the details.  The reason is that you have to use some things (like ) in your first programs which can't really be explained well without teaching you about a bunch of other stuff first.  So, for the moment, just accept that that's the way it's done, and move on.  You will understand them shortly.Considering the typical top-level class. Only public and no modifier access modifiers may be used at the top level so you'll either see public or you won't see any access modifier at all.  `static`` is used because you may not have a need to create an actual object at the top level \n(but sometimes you will want to so you may not always see/use static. There are other reasons why you wouldn't include static too but this is the typical one at the top level.) is used because usually you're not going to be returning a value from the top level (class). (sometimes you'll want to return a value other than  so void may not always be used either especially in the case when you have declared, initialized an object at the top level that you are assigning some value to).\nI'm a newbie myself so if this answer is wrong in any way please don't hang me. By day I'm a tech recruiter not a developer; coding is my hobby. Also, I'm always open to constructive criticism and love to learn so please feel free to point out any errors. - means that the class (program) is available for use by any other class. - creates a class. Can also be applied to variables and methods,making them class methods/variables instead of just local to a particular instance of the class. - this means that no product is returned when the class completes processing. Compare this with helper classes that provide a return value to the main class,these operate like functions; these do not have void in the declaration. means that the method is associated with the class, not a specific instance (object) of that class. This means that you can call a static method without creating an object of the class.\nBecause of use of a  keyword  is your first method to be invoked..\n doesn't need to any object to instance...\nso, is called by the Java interpreter before any objects are made.
Java

Imagine I'm in a Service that already has a background thread. Can I do a request using volley in that same thread, so that callbacks happen synchronously?There are 2 reasons for this: \n- First, I do not need another thread and it would be a waste to create it.\n- Second, if I'm in a ServiceIntent, the execution of the thread will finish before the callback, and therefor I will have no response from Volley. I know I can create my own Service that has some thread with a runloop I can control, but it would be desirable having this functionality in volley.Thank you!It looks like it is possible with Volley's  class. For example, to create a synchronous JSON HTTP GET request, you can do the following:Note @Matthews answer is correct BUT if you are on another thread and you do a volley call when you have no internet,  (Therefore if that thread is an IntentService, you will never be able to send another message to it and your service will be basically dead).Use the version of  that has a timeout  and catch the error to exit your thread.To match @Mathews answer:Below I wrapped it in a method & use a different request:It is probably recommended to use the Futures, but if for whatever reason you don't want to, instead of cooking your own synchronized blocking thing you should use a . So that would work like this..As a complementary observation to both @Blundells and @Mathews answers, I'm not sure  call is delivered to anything  the main thread by Volley.Having a look at the  it seems the  is using a  to execute the request and a  to deliver the result (the  is injected into the ). The  is in turn created with a  spawn from the main thread (somewhere around line 112 in the  implementation).Somewhere about line 135 in the  it seems like also successful results are delivered through the same  as any errors. Again; a  based on a  spawn from the main thread.For the use-case where a request is to be made from an  it's fair to assume that the thread of the service should block until we have a response from Volley (to guarantee a living runtime scope to handle the result in).One approach would be to override the default way a , where an alternative constructor is used instead, injecting a  which spawns from the  thread rather than the main thread. I haven't investigated the implications of this, however.I use a lock to achieve that effect now im wondering if its correct my way\nanyone want to comment ?I want to add something to Matthew's accepted answer. While  might seem to make a synchronous call from the thread you created it, it does not. Instead, the call is executed on a background thread.\nFrom what I understand after going through the library, requests in the  are dispatched in its  method:Now both  and  classes extend thread. So effectively a new worker thread is spawned for dequeuing the request queue and the response is returned to the success and error listeners implemented internally by .\nAlthough your second purpose is attained but you first purpose is not since a new thread is always spawned, no matter from which thread you execute .\nIn short,  Correct me if I am wrong.
Java

Difference between UTF-8 and UTF-16?\nWhy do we need these?I believe there are a lot of good articles about this around the Web, but here is a short summary.Both UTF-8 and UTF-16 are variable length encodings. However, in UTF-8 a character may occupy a minimum of 8 bits, while in UTF-16 character length starts with 16 bits.Main UTF-8 pros:Main UTF-8 cons:Main UTF-16 pros:Main UTF-16 cons:In general, UTF-16 is usually better for in-memory representation because BE/LE is irrelevant there (just use native order) and indexing is faster (just don't forget to handle surrogate pairs properly). UTF-8, on the other hand, is extremely good for text files and network protocols because there is no BE/LE issue and null-termination often comes in handy, as well as ASCII-compatibility.They're simply different schemes for representing Unicode characters.Both are variable-length - UTF-16 uses 2 bytes for all characters in the basic multilingual plane (BMP) which contains most characters in common use.UTF-8 uses between 1 and 3 bytes for characters in the BMP, up to 4 for characters in the current Unicode range of U+0000 to U+1FFFFF, and is extensible up to U+7FFFFFFF if that ever becomes necessary... but notably all ASCII characters are represented in a single byte each.For the purposes of a message digest it won't matter which of these you pick, so long as everyone who tries to recreate the digest uses the same option.See  for more about UTF-8 and Unicode.(Note that all Java characters are UTF-16 code points within the BMP; to represent characters above U+FFFF you need to use surrogate pairs in Java.)This is unrelated to UTF-8/16 (in general, although it does convert to UTF16 and the BE/LE part can be set w/ a single line), yet below is the fastest way to convert String to byte[]. For instance: good exactly for the case provided (hash code). String.getBytes(enc) is relatively slow. Simple way to differentiate UTF-8 and UTF-16 is to identify commonalities between them.Other than sharing same unicode number for given character, each one is their own format.
Java

I am trying to return 2 values from a Java method but I get these errors. Here is my code:Error:Java Result: 1Instead of returning an array that contains the two values or using a generic  class, consider creating a class that represents the result that you want to return, and return an instance of that class. Give the class a meaningful name. The benefits of this approach over using an array are type safety and it will make your program much easier to understand.Note: A generic  class, as proposed in some of the other answers here, also gives you type safety, but doesn't convey what the result represents.Example (which doesn't use really meaningful names):Java does not support multi-value returns. Return an array of values.You could implement a generic  if you are sure that you just need to return two values:and then have the method return that :You can only return one value in Java, so the neatest way is like this:Here's an updated version of your code:Try this :you have to use collections to return more then one return valuesin your case you write your code asYou don't need to create your own class to return two different values. Just use a HashMap like this:You even have the benefit of type safety.In my opinion the best is to create a new class which constructor is the function you need, e.g.:Then simply use the constructor as you would use the function:and you can use pR.sth1, pR.sth2 as \"2 results of the function\"You also can send in mutable objects as parameters, if you use methods to modify them then they will be modified when you return from the function. It won't work on stuff like Float, since it is immutable.The result is:\nRutgerUse a Pair/Tuple type object , you don't even need to create one if u depend on Apache commons-lang. Just use the  class.
Java

I'm making a Java application with an application-logic-thread and a database-access-thread.\nBoth of them persist for the entire lifetime of the application and both need to be running at the same time (one talks to the server, one talks to the user; when the app is fully started, I need  of them to work).However, on startup, I need to make sure that initially the app thread waits until the db thread is ready (currently determined by polling a custom method ).\nI wouldn't mind if app thread blocks until the db thread was ready. doesn't look like a solution - the db thread only exits at app shutdown. kind of works, but the empty loop consumes a lot of processor cycles.Any other ideas? Thanks.I would really recommend that you go through a tutorial like  before you commence in the magical world of multithreading.There are also a number of good books out (google for \"Concurrent Programming in Java\", \"Java Concurrency in Practice\".In your code that must wait for the , you must have something like this:In your 's method, you would need to do something like this:The  I'm using in these examples is preferably the object that you need to manipulate concurrently from  each thread, or you could create a separate  for that purpose (I would not recommend making the methods themselves synchronized):\nThere are other (sometimes better) ways to do the above, e.g. with , etc. Since Java 5 there are a lot of nifty concurrency classes in the  package and sub-packages. You really need to find material online to get to know concurrency, or get a good book. Use a  with a counter of 1.Now in the app thread do-In the db thread, after you are done, do - Requirement ::  Answer :: Job Done!! See example belowOutput of this program ::You can see that  takes 6sec before finishing its task which is greater than other thread. So Future.get() waits until the task is done.If you don't use future.get() it doesn't wait to finish and executes based time consumption.Good Luck with Java concurrency.Try  class out of the  package, which provides higher level synchronization mechanisms, that are far less error prone than any of the low level stuff.You could do it using an  object shared between the two threads:And in the second thread:As others have said, do not take this light-hearted and just copy-paste code. Do some reading first.Use this class like this then: Create a ThreadEvent:In the method this is waiting for results:And in the method that is creating the results after all the results have been created:(Sorry for editing this post, but this code has a very bad race condition and I don't have enough reputation to comment)You can only use this if you are 100% sure that signal() is called after await(). This is the one big reason why you cannot use Java object like e.g. Windows Events.The if the code runs in this order:then . This is because Object.notify() only wakes up one of the currently running threads. A thread waiting later is not awoken. This is very different from how I expect events to work, where an event is signalled until a) waited for or b) explicitly reset.Note: Most of the time, you should use notifyAll(), but this is not relevant to the \"wait forever\" problem above.The  interface from the  package is designed to provide access to results calculated in another thread.Take a look at  and  for a ready-made way of doing this kind of thing.I'd strongly recommend reading  to anyone interested in concurrency and multithreading. It obviously concentrates on Java, but there is plenty of meat for anybody working in other languages too.This applies to all languages:You want to have an event/listener model.  You create a listener to wait for a particular event.  The event would be created (or signaled) in your worker thread.  This will block the thread until the signal is received instead of constantly polling to see if a condition is met, like the solution you currently have.Your situation is one of the most common causes for deadlocks- make sure you signal the other thread regardless of errors that may have occurred.  Example- if your application throws an exception- and never calls the method to signal the other that things have completed.  This will make it so the other thread never 'wakes up'.I suggest that you look into the concepts of using events and event handlers to better understand this paradigm before implementing your case.Alternatively you can use a blocking function call using a mutex- which will cause the thread to wait for the resource to be free.  To do this you need good thread synchronization- such as: If you want something quick and dirty, you can just add a Thread.sleep() call within your while loop.  If the database library is something you can't change, then there is really no other easy solution.  Polling the database until is ready with a wait period won't kill the performance.Hardly something that you could call elegant code, but gets the work done.In case you can modify the database code, then using a mutex as proposed in other answers is better.You could read from a blocking queue in one thread and write to it in another thread.Since You can consider other alternatives:A lot of correct answers but without a simple example.. Here is an easy and simple way of to use :This idea can apply?. If you use CountdownLatches or Semaphores works perfect but if u are looking for the easiest answer for an interview i think this can apply.
Java

I installed JDK using apt-get install. I dont know where my jdk folder is. I need to set the path for that. Does any one has a clue on the location?This depends a bit from your package system ... if the  command works, you can type  to find the location of the java command. On the OpenSUSE system I'm on now it returns  (but this is not a system which uses ).On Ubuntu, it   for OpenJDK, and in some other subdirectory of  for Suns JDK (and other implementations as well, I think).For any given package you can determine what files it installs and where it installs them by querying dpkg.  For example for the package 'openjdk-6-jdk': will tell you which java implementation is the default for your system and where in the filesystem it is installed. Check the manual for more options.should give you something likeThis question will get moved but you can do the followingorUse find to located it.  It should be under  somewhere:Another best way to find Java folder path is to use  command in Fedora Linux (I know its for Ubuntu but I hit this post from google just by its headline). Just want to share incase people like me looking for answers for fedora flavour.To display all information regarding javaon OpenSUSE 13.1/13.2 its: \nversion-number can be 1.7.x 1.8.x etc. check software manager witch version you have installed...  Andr\u00e9 Simple, try it:It's /
Java

Is there an easy way (aka: not using a proxy) to get access to the raw request/response XML for a webservice published with JAX-WS reference implementation (the one included in JDK 1.5 and better) ?\nBeing able to do that via code is what I need to do.\nJust having it logged to a file by clever logging configurations would be nice but enough.I know that other more complex and complete frameworks exist that might do that, but I would like to keep it as simple as possible and axis, cxf, etc all add considerable overhead that I want to avoid.Thanks!Following options enable logging of all communication to the console (technically, you only need one of these, but that depends on the libraries you use, so setting all four is safer option). You can set it in the code like in example, or as command line parameter using -D or as environment variable as Upendra wrote.See question  for details.Here is the solution in raw code (put together thanks to stjohnroe and Shamik):Where SOAPLoggingHandler is (ripped from linked examples):Before starting tomcat, set  as below in Linux envs. Then start Tomcat. You will see the request and response in the  file.There are various ways of doing this programmatically, as described in the other answers, but they're quite invasive mechanisms. However, if you know that you're using the JAX-WS RI (aka \"Metro\"), then you can do this at the configuration level.  on how to do this. No need to mess about with your application.// This solution provides a way programatically add a handler to the web service clien w/o the XML config// See full doc here: // Create new class that implements SOAPHandler// Programatically add your LogMessageHandlerYou need to implement a javax.xml.ws.handler.LogicalHandler, this handler then needs to be referenced in a handler configuration file, which in turn is referenced by an @HandlerChain annotation in your service endpoint (interface or implementation).\nYou can then either output the message via system.out or a logger in your processMessage implementation. See I am posting a new answer, as I do not have enough reputation to comment on the one provided by  (see: ).In case you want the SOAP message to be printed in a file (e.g. via Log4j), you may use:Please note that under certain circumstances, the method call writeTo() may not behave as expected (see:  or ), therefore the following code will do the trick:You could try to put a  in front of the webservice and inspect request and response going to / returned from the service.Although you specifically did not ask for a proxy, sometimes I find  is enough to see what goes on on a connection. It's a simple tool, no install, it does show the data streams and can write to file too.In  you could simply executeas  is a public var defined in the class as followsam I correct in understanding that you want to change/access the raw XML message?If so, you (or since this is five years old, the next guy) might want to have a look at the Provider interface that is part of the JAXWS. The client counterpart is done using the \"Dispatch\" class. Anyway, you don't have to add handlers or interceptors. You still CAN, of course. The downside is this way, you are COMPLETELY responsible for building the SOAPMessage, but its easy, and if that's what you want(like I did) this is perfect.Here is an example for the server side(bit clumsy, it was just for experimenting)-You publish it like you would an SEI,Or you can use an Endpoint class for it.\nHope that has been helpful.And oh, if you want you needn't deal with headers and stuff, if you change the service mode to PAYLOAD(You'll only get the Soap Body).Inject  to endpoint interface. we can trace the SOAP request and responseImplementing SOAPHandler with    by adding  annotation to your endpoint interface.handlers.xmlSOAPLoggingHandler.java  Set the following system properties, this will enabled xml logging. You can set it in java or configuration file.console logs:One way to do is not using your code but use network packet sniffers like Etheral or WireShark which can capture the HTTP packet with the XML message as payload to it and you can keep logging them to a file or so.But more sophisticated approach is to write your own message handlers. You can have a look at it . Actually. If you look into sources of HttpClientTransport you will notice that it is also writing messages into java.util.logging.Logger. Which means you can see those messages in your logs too.For example if you are using Log4J2 all you need to do is the following:After these steps you start seeing SOAP messages in your logs.
Java

I have a gigantic QuickBooks SDK .XSD schema file which defines XML requests/responses that I can send/receive from QuickBooks.I'd like to be able to easily generate Java classes from these .XSD files, which I could then use to marshal XML to Java objects, and Java objects to XML. Is there an easy way to do this...? Ideally, it would not require any libraries external to the basic Java distro at run-time. But I'm flexible...  does EXACTLY what you want. It's built into the JRE/JDK starting at 1.6To expand on the \"use JAXB\" comments above, In Windows\n    e.g., \n    Wait a bit, and if you had a well-formed XSD file, you will get some well-formed Java classesIf you want to start coding Java to XML and XML to Java in less than 5 minutes, try  Simple XML Serialization.  Don't spend hours learning the JAXB API\nHowever, if you are really keen on learning JAXB, here's an excellent tutorial\nContents of tutorial:There're a number of way to do XML serialization in Java. If you want fine-grained control over parsing and serialization you can go for SAX, DOM, or Stax for better performance. Yet, what I often want to do is a simple mapping between POJOs and XML. However, creating Java classes to do XML event parsing manually is not trivial. I recently found JAXB to be a quick and convenient Java-XML mapping or serialization.JAXB contains a lot of useful features, you can check out the reference implementation here.  is also a good resource to learn more about JAXB. For this blog entry, I'll show you how to do a simple Java-XML serialization with JAXB.Let's say I have an Item Java object. I want to serialize an Item object to XML format. What I have to do first is to annotate this POJO with a few XML annotation from javax.xml.bind.annotation.* package. See code listing 1 for Item.javaFrom the codeMy  is ready. I can then go ahead and create JAXB script for marshaling Item.For complete code Listing please see Code Listing 2 . The output Code Listing 3  file is created. It looks like this:Easy right? You can alternatively channel the output XML as text String, Stream, Writer, ContentHandler, etc by simply change the parameter of the marshal(...) method likeLet's reverse the process. Assume that I now have a piece of XML string data and I want to turn it into Item.java object. XML data (Code listing 3) looks likeI can then unmarshal this xml code to Item object byFor complete code Listing please see Code Listing 2 (main.java). The XML source can come in many forms both from Stream and file. The only difference, again, is the method parameter:Last thing I want to mention here is validating input XML with schema before unmarshalling to Java object. I create an XML schema file called item.xsd. For complete code Listing please see Code Listing 4 (Item.xsd). Now what I have to do is register this schema for validation.When I try to unmarshal XML data to POJO, if the input XML is not conformed to the schema, exception will be caught. For complete code Listing please see Code Listing 5 (invalid_item.xml).Here I change the 'id' attribute to string instead of integer.If XML input is valid against the schema, the XML data will be unmarshalled to Item.java object successfully.Using Eclipse IDE:- will do it.  Specifically the \"scomp\" command.EDIT: XMLBeans has been , check  for more info.Maven can be used for the purpose, you need to add some dependencies and just clean your application. You will get all classes created automatically in your target folder.Just copy them from target to desired place, here is pom.xml that i have used to create classed from xsd files :Just place your xsd files under \"src/main/webapp/schemas/\" and maven will find them at compile time.Hope this will help you, more information can be found at Hope it will help :)If you don't mind using an external library, I've used  to do this in the past.the easiest way is using command line. Just type in directory of your .xsd file: So, the java will generate all Pojos.JAXB Limitation.I worked on JAXB, as per my opinion its a nice way of dealing with data between XML and Java objects. The Positive sides are its proven and better in performance and control over the data during runtime. With a good usage of built tools or scripts it will takes away lot of coding efforts.I found the configuration part is not a straight away task, and spent hours in getting the development environment setup.However I dropped this solution due to a silly limitation I faced. My XML Schema Definition ( XSD ) has a attribute/element with name \"value\" and that I have to use XSD as it is. This very little constraint forced the  my binding step XJC failed with a Error \"Property 'Value' already used.\"This is due to the JAXB implementation, the binding process tries to create Java objects out of XSD by adding few attributes to each class and one of them being a value attribute. When it processed my XSD it complained that there is already a property with that name. Well best option is .I also have a question if we have an option to do reverse engineering here. if yes can we generate xsd from pojo class?Isn't JAXB's XJC is a possible answer to this? I'm trying to achieve the same thing. Still in the \"trying\" phase though. Came across XJC, so thought of sharing.The well-known There is a  that could do this for you at any build phase you want.You could do this stuff in both ways: xsd <-> JavaTalking about JAXB limitation, a solution when having the same name for different attributes is adding inline jaxb customizations to the xsd:  +\n   \n      .\n      .\n      binding declarations\n      .\n      .\n   \nor external customizations...You can see further informations on :\n
Java

I have the following code in Java;What is the best way to write the if condition?Use  instead of :Comparing with the  constant  avoids having to construct a  every execution.FYI,  also has constants  and  for your convenience.The reason you can't use  is that it takes  into consideration:so it's unsuitable for a purely numeric comparison. However,  doesn't consider scale when comparing:Alternatively,  can be used:There is a constant that you can check against:I usually use the following:You would want to use equals() since they are objects, and utilize the built in ZERO instance:Note that  takes scale into account, so unless selectPrice is the same scale (0) as  then this will return false.To take scale out of the equation as it were:I should note that for certain mathematical situations, , which is why I imagine  takes the scale into account.  gives precision to the hundredths place, whereas  is not that precise. Depending on the situation you may want to stick with .Alternatively, I think it is worth mentioning that the behavior of equals and compareTo methods in the class BigDecimal .This basically means that:Therefore, you have to be very careful with the scale in your  variable, otherwise you would get unexpected result.There is a static constant that :You should do this instead of:in order to avoid the case where  is .
Java

Is there a standard idiom for comparing version numbers?  I can't just use a straight String compareTo because I don't know yet what the maximum number of point releases there will be.  I need to compare the versions and have the following hold true:Tokenize the strings with the dot as delimiter and then compare the integer translation side by side, beginning from the left.Another solution for this old post (for those that it might help) :Edit:@daiscog: Thank you for your remark, this piece of code has been developed for the Android platform and as recommended by Google, the method \"matches\" check the entire string unlike Java that uses a regulatory pattern. ( - )It's really easy using Maven:You can get the right dependency string for Maven Artifact from :You need to normalise the version strings so they can be compared. Something likePrintsThe best to reuse existing code,\ntake advantages:Don't include dependency to maven-artifact as that will pull various transitive dependenciesWondering why everybody assumes that the versions is only made up of integers - in my case it was not.Why reinventing the wheel (assuming the version follows the Semver standard)First install  via MavenThen use this libraryfor my projects I use my commons-version library \nit contains two auxiliary classes - to parse version (parsed version can be compared with another version object because it is comparable one) and VersionValidator which allows to check version for some expression like Wrote a little function myself.Simpler Using ListsI created simple  on  using  convention. So it works only for strings in format X.Y.Z (Major.Minor.Patch) where X, Y, and Z are non-negative integers. You can find it on my .Method  compares two version strings. It returns 0 if the versions are equal, 1 if version v1 is before version v2, -1 if version v1 is after version v2, -2 if version format is invalid.Here's an optimized implementation:Result:For Scala you can use a library that I made: This code try to resolve this type of comparison versions.I liked the idea from @Peter Lawrey, And i extended it to further limits : Hope it helps someone. It passed all test cases in interviewbit and leetcode (need to uncomment two lines in compareVersion function). Easily tested !My java Solution
Java

I am trying to add a text field onto my Android app in Eclipse, but then I drag the  option on to the graphical layout, a message at the bottom comes up. It reads\n\nEven when I go to  there is no error log option. The whole designer is useless now, because I can not use it anymore until I delete the  directly from the xml. What is causing this error, and how do I fix it? I am running the latest version (as of today, 6-30-14), and Windows 8 Pro x64.Here is my full layout code:Check the \"Android version to use when rendering layouts\" and make sure you're not using a version that ends in \"W\" for Android Wear ( API 20: Android 4.4W). I don't believe Wear supports .In both Android Studio and Eclipse, it's the dropdown with the green android in the layout preview's toolbar. You may want to set it explicitly and not allow the IDE to choose the Android version automatically.From the Eclipse IDE, just change the API version to use for previewing, as shown in below screenshot.\nInstead of \"Automatically Pick Best\", manually select the one which works for you (API 17 worked for me).I changed my Android version for Android 4.2, but it still not work for me. I tried different solutions found that it only work by deleting Android 4.4W package.Window > Android SDK Manager > check Android 4.4W(API 20) if it was installed > Delete packageIf you are facing this on Android Studio, follow along1) Uninstall Android 4.4W(API 20) from the SDK Manager2) Make sure you have Android SDK Build Tools 19.1 installed from the SDK Manager.3) Edit build.gradle within your app folder. Set the following two values as below4) The IDE will prompt you to sync the Gradle file with your project, click Yes.5) Open your activity file and then change the 'Android version to use when rendering layouts in IDE' to 'API 19'. This is the green colored Android Bot towards the right on the preview windowI deleted 4.4w from my sdk install pile, which must have slipped past me last time I installed an sdk. Once I removed it it was no longer and option, and eclipse picked an sdk I did have that wasn't W and it worked.The W in Android 4.4W suggest wearable devices.\nAndroid Wear is a wrist watch and you cannot type anything in it so you cannot use EditText on 4.4W. Change the API to 19 or less or change it to 4.4LCheck it out @ You can change your previewing API version as Jim suggested if u don't want to develop apps for wearable devices. 
Java

I've just started playing with Guice, and a use-case I can think of is that in a test I just want to override a single binding.  I think I'd like to use the rest of the production level bindings to ensure everything is setup correctly and to avoid duplication.So imagine I have the following ModuleAnd in my test I only want to override InterfaceC, while keeping InterfaceA and InterfaceB in tact, so I'd want something like:I've also tried the following, with no luck:Does anyone know if it's possible to do what I want or am I completely barking up the wrong tree??--- Follow up:\nIt would seem I can achieve what I want if I make use of the @ImplementedBy tag on the interface and then just provide a binding in the test case, which works nicely when there is a 1-1 mapping between the interface and implementation.Also, after discussing this with a colleague it would seem we'd head down the road of overriding an entire module and ensuring we have our modules defined correctly.  This seems like it might cause a problem though where a binding is misplaced in a module and needs to be moved, thus possibly breaking a load of tests as bindings may no longer be available to be overriden.This might not be the answer you're looking for, but if you're writing unit tests, you probably shouldn't be using an injector and rather be injecting mock or fake objects by hand.On the other hand, if you really want to replace a single binding, you could use :See details .But as the javadoc for  recommends, you should design your modules in such a way that you don't need to override bindings. In the example you gave, you could accomplish that by moving the binding of  to a separate module.Why not to use inheritance? You can override your specific bindings in  method, leaving shared implementations in  method.And finally create your injector this way:If you don't want to change your production module and if you have a default maven-like project structure likeYou can just create a new class  in your test directory using the same package as for your original class. Guice will then bind  to  from your test directory whereas all other interfaces will be bound to your production classes. You want to use  where you can declare your custom configuration for each test class.In a different setup, we have more than one activity defined in separate modules.  The activity that's being injected into is in an Android Library Module, with its own RoboGuice module definition in the AndroidManifest.xml file.  The setup looks like this.  In the Library Module there are these definitions:AndroidManifest.xml:Then we have a type being injected:Some default implementation of Foo:MainModule configures the FooThing implementation for Foo:And finally, an Activity that consumes Foo:In the consuming Android Application Module, we would like to use  but, for testing purposes, inject our own .One might argue to expose the module handling to the client application, however, we need to mostly hide the components being injected because the Library Module is an SDK, and exposing pieces has larger implications.(Remember, this is for testing, so we know the internals of SomeActivity, and know it consumes a (package visible) Foo).The way I found that works makes sense; use the the suggested override for :Now, when  is started, it will get  for its injected  instance.It's a very specific situation where, in our case, OtherFooThing was used internally to record test situations, while FooThing was used, by default, for all other uses.Keep in mind, we  using  in our unit tests, and it works flawlessly.
Java

How can I configure  to log different levels for a logger to different destinations?For example, given the following Logback configuration, will Logback record  messages to  and  messages to ?(Note that this example is a variation of example  shown in ).Update: For an all configuration based approach using Groovy see .--You can do some interesting things with . The below configuration will only print warn and error messages to stderr, and everything else to stdout.I believe this would be the simplest solution:okay, here is my favorite xml way of doing it.  I do this for the eclipse version so I can and for some reason SO is not showing this all properly but most seems to be there...Using ThresoldFilter & multiple LevelFilters : This is the configuration that I use, which works fine, it is based on XML + JaninoEventEvaluator (requires the  library to be added to Classpath)I use logback.groovy to configure my logback but you can do it with xml config as well:I think to use GEventEvaluator is simplier because there is no need to create filter classes.\nI apologize for my English!The simplest solution is to use  on the appenders:Full example:Update: As Mike pointed out in the comment, messages with ERROR level are printed here both to STDOUT and STDERR. Not sure what was the OP's intent, though. You can try Mike's answer if this is not what you wanted.I take no credit for this answer, as it's merely a combination of the best two answers above: that of X. Wo Satuk and that of S\u00e9bastien Helbert:  is lovely but you can't configure it to have an upper level as well as a lower level*, but combining it with two  set to \"DENY\"  and  works a treat.: do not forget the  tag in the STDERR appender: my omission of it had me frustrated for a few minutes.* it does however have a method  in the  but I haven't a clue how you'd use it in this context.Example of how to output colored messages of level \"INFO\" or higher to  and messages of level \"WARN\" or higher to .Your  file:Try this. You can just use built-in  and . No need to create your own filters programmically. In this example WARN and ERROR levels are logged to System.err and rest to System.out:\n\n    
Java

What's the equivalent of Java's  in JavaScript?The simple answer is that there is no such function.The closest thing you have is:Note that you  don't want to busy-wait (e.g. in a spin loop), since your browser is almost certainly executing your JavaScript in a single-threaded environment.Here are a couple of other SO questions that deal with threads in JavaScript:And this question may also be helpful:Try with this code. I hope it's useful for you.There's no direct equivalent, as it'd pause a webpage.  However there is a , e.g.:Closure example (thanks Daniel):The second argument is milliseconds before firing, you can use this for time events or waiting before performing an operation.  Updated based on comments for a cleaner result.You can either write a spin loop (a loop that just loops for a long period of time performing some sort of computation to delay the function) or use:This will call 'Func1()' after 3 seconds.Edit:Credit goes to the commenters, but you can pass anonymous functions to setTimeout.This is much more efficient and does not invoke javascript's eval function.This eventually helped me:Or maybe you can use the setInterval function, to call a particular function, after the specified number of milliseconds. Just do a google for the setInterval prototype.I don't quite recollect it.setTimeout would not hold and resume on your own thread however Thread.sleep does. There is no actual equal in Javascript
Java

I am having  called  which contains .When iterating the map, if  is match with specified string, I need to remove the key from map.i.e. contains  but I am unable to remove the key from . Instead getting error :Try:Use To remove specific key and element from hashmap use full source code is likeSource : 
Java

I've met these articles:And that lead me to this Google I/O 2010 video about REST client applicationsSince now, I've been creating REST component as static component in my Application controller class.   From now, I think, I should change the pattern.  pointed out that  application is great sample of how to write REST clients on Android.  told that this ways is too overcomplicated.  So, can anybody please show us what is the best practice? In short and simple way.\nThe IOSched application is too complex for sample use-case.The original answer is more than a year and a half old at the time of this edit. Although the concepts presented in original answer still hold, as other answers point out, there are now libraries out there that make this task easier for you. More importantly, some of these libraries handle device configuration changes for you.The original answer is retained below for reference. But please also take the time to examine some of the Rest client libraries for Android to see if they fit your use cases. The following is a list of some of the libraries I've evaluated. It is by no means intended to be an exhaustive list.Presenting my approach to having REST clients on Android. I do not claim it is the best though :) Also, note that this is what I came up with in response to my requirement. You might need to have more layers/add more complexity if your use case demands it. For example, I do not have local storage at all; because my app can tolerate loss of a few REST responses.My approach uses just s under the covers. In my case, I \"call\" these Tasks from my  instance; but to fully account for cases like screen rotation, you might choose to call them from a  or such.I consciously chose my REST client itself to be an API. This means, that the app which uses my REST client need not even be aware of the actual REST URL's and the data format used. The client would have 2 layers:In addition, I chose to use a Callback mechanism to communicate the result of the s back to the app.Enough of text. Let's see some code now. Lets take a hypothetical REST API URL - The top layer might look like this:Note that the app doesn't use the JSON or XML (or whatever other format) returned by the REST API directly. Instead, the app only sees the bean .Then, the lower layer (AsyncTask layer) might look like this:Here's how an app might use the API (in an  or ):I hope the comments are sufficient to explain the design; but I'd be glad to provide more info.\"Developing Android REST client applications\" by Virgil Dobjanschi led to much discussion, since no source code was presented during the session or was provided afterwards.The only reference implementation I know (please comment if you know more) is available at  (the Google IO session is mentioned under /presentation). It is a library which you can use in your own application.The second link asks for the \"best\" REST framework, which is discussed heavily on stackoverflow. For me the application size is important, followed by the performance of the implementation.Therefore I stick to org.json or GSON for complexer scenarios. For the architecture of an org.json implementation, I am using a static class which represents the server use cases (e.g. findPerson, getPerson). I call this functionality from a service and use utility classes which are doing the mapping (project specific) and the network IO (my own REST template for plain GET or POST). I try to avoid the usage of reflection.Never use AsynTask to perform network request or whatever that need to be persisted. Async Task are strongly tied to your activity and if the user change the orientation of the screen since the App is re created the AsyncTask will be stopped.I suggest you to use Service pattern with Intent Service and ResultReceiver. Take a look to . It's a library that allows you to perform any kind of REST request asynchronously and notify your UI with Request Listeners implementing the Virgil Dobjanschi's service pattern.There is another library with much cleaner API and type-safe data.\nHere is a simple usage exampleOr more complex with callbacksIt is fresh new, but looks very promising.There is plenty of libraries out there and I'm using this one: . This was created by me, and, as you can see in the documentation, it's way cleaner and simpler than the other ones. It's not focused on Android, but I'm using in it and it's working pretty well.It supports HTTP Basic Auth. It does the dirty job of serializing and deserializing JSON objects. You will like it, specially if your API is Rails like.Disclaimer: I am involved in the rest2mobile open source projectAnother alternative as a REST client is to use .The approach is slightly different as it uses concrete  to generate the client code for the REST service. The code replaces the REST URL and JSON payloads with native java methods and POJOs. It also automatically handles server connections, asynchronous invocations and POJO to/from JSON conversions. Note that this tool comes in different flavors (cli, plugins, android/ios/js support) and you can use the  to generate the API directly into your app. All the code can be found on .
Java

In Java, I have just found out that the following code is legal:FYI, receiver is just a helper class with the following signature:I've never seen the  notation before. How does that work?  Is there any way to code that more conventionally?It's the way to instantiate a non-static inner class from outside the containing class body, as described in the . Every inner class instance is associated with an instance of its containing class. When you  an inner class from  its containing class it uses the  instance of the container by default:But if you want to create an instance of Bar outside Foo, or associate a new instance with a containing instance other than  then you have to use the prefix notation.Have a look at this example:Using javap we can view instructions generated for this codeMain method:Inner class constructor:Everything is simple - when invoking TestInner constructor, java passes Test instance as a first argument . Not looking at that TestInner should have a no argument constructor. TestInner in its turn just saves reference to parent object, . When you are invoking inner class constructor from an instance method, reference to parent object  is passes automatically, so you do not have to specify it. Actually its passes every time, but when invoking from outside it should be passed explicitly. - is just a way to specify the first hidden argument to TestInner constructor, not a type is equal to: is equal to:When inner classes were added to Java in version 1.1 of the language they were originally defined as a transformation to 1.0 compatible code. If you look at an example of this transformation, I think it will make it a lot clearer how an inner class actually works.Consider the code from Ian Roberts' answer:When transformed to 1.0 compatible code, that inner class  would become something like this:The inner class name is prefixed with the outer class name so as to make it unique. A hidden private  member is added that holds a copy of the outer . And a hidden constructor is created to initialise that member.And if you look at the  method, it would be transformed into something like this:So let's see what happens when you execute the following code.First we instantiate an instance of  and intialise the  member to 5 (i.e. ).Next we call , which instantiates an instance of  and initialises the  member to the value of  passed in from  (i.e. ).Finally we call  which tries to print  which is  which is 5.Now that was a regular instantiation of an inner class. Let's look at what happens when instantiating  from outside .Applying our 1.0 transformation again, that second line would become something like this:This is almost identical to the  call. Again we're instantiating an instance of  and initialising the  member to f. So again, .And again when you call , you are printing  which is  which is 5.The key thing to remember is that the inner class has a hidden member holding a copy of  from the outer class. When you instantiate an inner class from within the outer class, it it implicitly initialised with the current value of . When you instantiate the inner class from outside the outer class, you explicitly specify which instance of the outer class to use, via the prefix on the  keyword.Think of  as a single token. Kind of like a function name with a space in it.Of course, the class  does not literally have a function named , but I'm guessing the syntax is meant to suggest that. It's meant to look like you're calling a function that creates a new instance of  using a particular instance of  for any accesses to the enclosing class.If a declaration of a type (such as a member variable or a parameter name) in a particular scope (such as an inner class or a method definition) has the same name as another declaration in the enclosing scope, then the declaration shadows the declaration of the enclosing scope. You cannot refer to a shadowed declaration by its name alone. The following example, ShadowTest, demonstrates this:This example defines three variables named x: The member variable of the class ShadowTest, the member variable of the inner class FirstLevel, and the parameter in the method methodInFirstLevel. The variable x defined as a parameter of the method methodInFirstLevel shadows the variable of the inner class FirstLevel. Consequently, when you use the variable x in the method methodInFirstLevel, it refers to the method parameter. To refer to the member variable of the inner class FirstLevel, use the keyword this to represent the enclosing scope:Refer to member variables that enclose larger scopes by the class name to which they belong. For example, the following statement accesses the member variable of the class ShadowTest from the method methodInFirstLevel:
Java

How do you find a memory leak in Java (using, for example, JHat)? I have tried to load the heap dump up in JHat to take a basic look. However, I do not understand how I am supposed to be able to find the root reference () or whatever it is called. Basically, I can tell that there are several hundred megabytes of hash table entries ([java.util.HashMap$Entry or something like that), but maps are used all over the place... Is there some way to search for large maps, or perhaps find general roots of large object trees?[Edit]\nOk, I've read the answers so far but let's just say I am a cheap bastard (meaning I am more interested in learning how to use JHat than to pay for JProfiler). Also, JHat is always available since it is part of the JDK. Unless of course there is no way with JHat but brute force, but I can't believe that can be the case.Also, I do not think I will be able to actually modify (adding logging of  map sizes) and run it for long enough for me to notice the leak.I use following approach to finding memory leaks in Java. I've used jProfiler with great success, but I believe that any specialized tool with graphing capabilities (diffs are easier to analyze in graphical form) will work.Basically analysis should start from greatest positive diff by, say, object types and find what causes those extra objects to stick in memory.For web applications that process requests in several threads analysis gets more complicated, but nevertheless general approach still applies.I did quite a number of projects specifically aimed at reducing memory footprint of the applications and this general approach with some application specific tweaks and trick always worked well.Questioner here, I have got to say getting a tool that does not take 5 minutes to answer any click makes it a lot easier to find potential memory leaks.Since people are suggesting several tools ( I only tried visual wm since I got that in the JDK and JProbe trial ) I though I should suggest a free / open source tool built on the Eclipse platform, the Memory Analyzer (sometimes referenced as the SAP memory analyzer) available on  . What is really cool about this tool is that it indexed the heap dump when I first opened it which allowed it to show data like retained heap without waiting 5 minutes for each object (pretty much all operations were tons faster than the other tools I tried).When you open the dump, the first screen shows you a pie chart with the biggest objects (counting retained heap) and one can quickly navigate down to the objects that are to big for comfort. It also has a Find likely leak suspects which I reccon can come in handy, but since the navigation was enough for me I did not really get into it.A tool is a big help.However, there are times when you can't use a tool: the heap dump is so huge it crashes the tool, you are trying to troubleshoot a machine in some production environment to which you only have shell access, etc.In that case, it helps to know your way around the hprof dump file.Look for SITES BEGIN. This shows you what objects are using the most memory. But the objects aren't lumped together solely by type: each entry also includes a \"trace\" ID. You can then search for that \"TRACE nnnn\" to see the top few frames of the stack where the object was allocated. Often, once I see where the object is allocated, I find a bug and I'm done. Also, note that you can control how many frames are recorded in the stack with the options to -Xrunhprof.If you check out the allocation site, and don't see anything wrong, you have to start backward chaining from some of those live objects to root objects, to find the unexpected reference chain. This is where a tool really helps, but you can do the same thing by hand (well, with grep). There is not just one root object (i.e., object not subject to garbage collection). Threads, classes, and stack frames act as root objects, and anything they reference strongly is not collectible.To do the chaining, look in the HEAP DUMP section for entries with the bad trace id. This will take you to an OBJ or ARR entry, which shows a unique object identifier in hexadecimal. Search for all occurrences of that id to find who's got a strong reference to the object. Follow each of those paths backward as they branch until you figure out where the leak is. See why a tool is so handy?Static members are a repeat offender for memory leaks. In fact, even without a tool, it'd be worth spending a few minutes looking through your code for static Map members. Can a map grow large? Does anything ever clean up its entries?There are tools that should help you find your leak, like JProbe, YourKit, AD4J or JRockit Mission Control. The last is the one that I personally know best. Any good tool should let you drill down to a level where you can easily identify what leaks, and where the leaking objects are allocated. Using HashTables, Hashmaps or similar is one of the few ways that you can acually leak memory in Java at all. If I had to find the leak by hand I would peridically print the size of my HashMaps, and from there find the one where I add items and forget to delete them.Well, there's always the low tech solution of adding logging of the size of your maps when you modify them, then search the logs for which maps are growing beyond a reasonable size.Most of the time, in enterprise applications the Java heap given is larger than the ideal size of max 12 to 16 GB. I have found it hard to make the NetBeans profiler work directly on these big java apps.But usually this is not needed. You can use the jmap utility that comes with the jdk to take a \"live\" heap dump , that is jmap will dump the heap after running GC.  Do some operation on the application, wait till the operation is completed, then take another \"live\" heap dump. Use tools like Eclipse MAT to load the heapdumps, sort on the histogram, see which objects have increased, or which are the highest, This would give a clue.There is only one problem with this approach; Huge heap dumps, even with the live option, may be too big to transfer out to development lap, and may need a machine with enough memory/RAM to open.That is where the class histogram comes into picture. You can dump a live class histogram with the jmap tool. This will give only the class histogram of memory usage.Basically it won't have the information to chain the reference. For example it may put char array at the top. And String class somewhere below. You have to draw the connection yourself. Instead of taking two heap dumps, take two class histograms, like as described above; Then compare the class histograms and see the classes that are increasing. See if you can relate the Java classes to your application classes. This will give a pretty good hint. Here is a pythons script that can help you compare two  jmap histogram dumps. Finally tools like JConolse and VisualVm are essential to see the memory growth over time, and see if there is a memory leak. Finally sometimes your problem may not be a memory leak , but high memory usage.For this enable GC logging;use a more advanced and new compacting GC like G1GC; and you can use jdk tools like jstat to see the GC behaviour liveOther referecences to google for -jhat, jmap, Full GC, Humongous allocation, G1GCYou really need to use a memory profiler that tracks allocations. Take a look at  - their \"heap walker\" feature is great, and they have integration with all of the major Java IDEs. It's not free, but it isn't that expensive either ($499 for a single license) - you will burn $500 worth of time pretty quickly struggling to find a leak with less sophisticated tools.NetBeans has a built-in profiler. you may want to check out .  It's also part of the JDK and I have found it helpful to find memory/reference leaks in conjunction with jhat.  Also take a look at  blog entry.
Java

I'm trying  problem from Sphere Online Judge (SPOJ) where I need to find a palindrome for a integer of up to a million digits. I thought about using Java's functions for reversing Strings, but would they allow for a String to be this long?   You should be able to get a String of length  (always 2147483647 (2 - 1) by the Java specification, the maximum size of an array, which the String class uses for internal storage) or half your maximum heap size (since each character is two bytes), whichever is smaller.I believe they can be up to 2^31-1 characters, as they are held by an internal array, and arrays are indexed by integers in Java.While you can in theory Integer.MAX_VALUE characters, the JVM is limited in the size of the array it can use.on Oracle Java 8 update 92 printsNote: in Java 9, Strings will use byte[] which will mean that multi-byte characters will use more than one byte and reduce the maximum further.  If you have all four byte code-points e.g. emojis, you will only get around 500 million charactersHave you considered using  instead of  to hold your numbers?Integer.MAX_VALUE is max size of string + depends of your memory size but the Problem on sphere's online judge you don't have to use those functions The heap part gets worse, my friends. UTF-16 isn't guaranteed to be limited to 16 bits and can expand to 32Java9 uses byte[] to store String.value, so you can only get about 1GB Strings in Java9. Java8 on the other hand can have 2GB Strings.By character I mean \"char\"s, some character is not representable in BMP(like some of the emojis), so it will take more(currently 2) chars.If you use google's app engine, com.google.appengine.api.datastore.Text can help. It allows a single string to store upto1 megabyte.
Java

How can I elegantly serialize a lambda?For example, the code below throws a . How can I fix it without creating a  \"dummy\" interface?Java 8 introduces the possibility to . In the case of serialization, it is therefore possible to write:And the lambda automagically becomes serializable.The same construction can be used for method references. For example this code:defines a lambda expression and a method reference with a serializable target type.If you are willing to switch to another serialization framework like , you can get rid of the multiple bounds or the requirement that the implemented interface must implement . The approach is to For details and code see this 
Java

Is there a nicer way to write in jUnitIf you add in Hamcrest and JUnit4, you could do:With some static imports, it looks a lot better:The static imports needed would be:use  whenever possible EDIT:  may have more assertions (a fork)Use hamcrest Matcher You can optional add an even more detail error message.Use the new  syntax together with .It is available starting with .Another variant isMoreover in  there are some other interesting matchers, like ,  etc.I've tried out many answers on this page, none really worked:So I stopped trying to make nicely readable code, but used the simple and workable approach mentioned in the question instead.
Java

I'm finally making the voyage back to IntelliJ via Eclipse.  Currently my Eclipse is set up so that if I currently have a statement such as this (where ^ denotes where my cursor currently sits):and I hit the semi-colon (;) key, it will automatically put the semi-colon at the end of the statement:Currently IntelliJ does this:Meaning I will have to explicitly type the closing bracket before typing the semi-colon.Not a huge problem obviously but I have found myself putting the semi-colon in the wrong place a few times today as I make the transition back to IntelliJ and thought that it may be more efficient (for both my fingers and brain) not to have to type the closing bracket.Try ++. That finishes the statement you're currently writing. Try it in a few different situations, like in if statements, for loops etc, and you'll see that it'll complete the line and open some curly braces for you if necessary.You can  a keymap of your own. I added + to my Keymaps for the \"Complete Current Statement\" action. This saved me an extra key stroke and made it a little bit more intuitive.You can opt to remove or keep the existing mapping.  Should look something like this when you're done:
Java

I have the following  condition.What value of  will return  for this condition in Java?I am unable to think of any such value of  considering  notation in Java.I would also love to have algebraic proof of whatever answer this condition has (in context with Java)?The only  value for which it works is  .It's because integers are negated using the .Usingyou see that  isTaking the negative value is done by first swapping  and , which givesand by adding , which givesAs you can see in the link I gave, Wikipedia mentions the problem with the most negative numbers and specifies it's the sole exception :Of course you have the same phenomenon for  if you store it in a  variable.Note that . Another (bad) solution could for example have been to negate by simply changing the most significant bit and letting the other bits unchanged, this would have avoided this problem with MIN_VALUE but would have made 2 different  values and complicated binary arithmetic (how would you have incremented for example ?).The value you are looking for is .That's off-topic for Stack Exchange.  But you could do it starting from the definition of Java integers ()andand the definition of the Java unary '-' operator ():In additional to the answers given so far...There is four values in totalThe wrapped values get unwrapped so they are also true for this expression.  Note: Math.abs documents.andIt is surprising that Math.abs might return a negative number.  This happens either because a) there is no positive values for -MIN_VALUE in these cases b) performing the  calculation results in an overflow.What is also interest is why doesn't Byte.MIN_VALUE, Short.MIN_VALUE do not do this.  This is because the  changes the type to  for these and thus no overflow.Character.MIN_VALUE doesn't have a problem because it is 0.Float.MIN_VALUE and Double.MIN_VALUE have a different meaning.  These are the smallest representable value greater than zero. Thus they have valid negative values which are not themselves.Like the others have mentioned, this is only fulfilled by . As for proof, let me offer an easier to understand explanation other than in binary (although it is still rooted in that).Note that  is equal to  or  and  is equal to  or .  is , which is now too large for an Integer (since it is past ) thus causing an Integer overflow, making it  again. It's the only Integer that does this since  is the only number with no negative equivalent aside from 0.Tentative algebraic proof, using  arithmetic: can be rewritten as  (adding  on both sides), or .This equation has two solutions of the form , namely  and  obtained by shifting in either  or  on the left.The solution  being excluded, there remains the solution .Maybe it's not too educative, but instead of thinking you could run this code:to see that it prints infinitely :)
Java

What does  do?\nFor example in the function:If you launch your program with  (or  for short) then this statementis equivalent toIf you launch your program without this option, the assert statement will have no effect.For example, , as posted in your question, is equivalent to(If you launched with  that is.)Formally, the  says the following:Where  is controlled with the  switch and  means that an  is thrown.You can append  like this:to specify what the error message of the thrown AssertionError should be.This post has been rewritten as an article .If the condition isn't satisfied, an  will be thrown.Assertions have to be enabled, though; otherwise the  expression does nothing. See: is a debugging tool that will cause the program to throw an  exception if the condition is not true.  In this case, the program will throw an exception if either of the two conditions following it evaluate to false.  Although I have read a lot documentation about this one, I'm still confusing on how, when, and where to use it. Make it very simple to understand:When you have a similar situation like this:You might receive warning (displaying yellow line on strB = strA.toLowerCase(); ) that strA might produce a NULL value to strB. Although you know that strB is absolutely won't be null in the end, just in case, you use assert toSometime, when you compile your code, you don't get your result and it's a bug. But the application won't crash, and you spend a very hard time to find where is causing this bug.So, if you put assert, like this:you tell the compiler that strA is absolutely not a null value, it can 'peacefully' turn off the warning. IF it is NULL (worst case happens), it will stop the application and throw a bug to you to locate it.Assertions are generally used primarily as a means of checking the program's expected behavior. It should lead to a crash in most cases, since the programmer's assumptions about the state of the program are false. This is where the debugging aspect of assertions come in. They create a checkpoint that we simply can't ignore if we would like to have correct behavior. In your case it does data validation on the incoming parameters, though it does not prevent clients from misusing the function in the future. Especially if they are not, (and should not) be included in release builds.    It ensures that the expression returns true.  Otherwise, it throws a .Assert does throw an AssertionError if you run your app with assertions turned on.If you run this with, say: It shall throw an 
Java

How do I build a URL or a URI in Java? Is there an idiomatic way, or libraries that easily do this?I need to allow starting from a request string, parse/change various URL parts (scheme, host, path, query string) and support adding and automatically encoding query parameters.As of Apache HTTP Component HttpClient 4.1.3, from the official :Edit: as of v4.2  has been deprecated in favor of :?As the author, I'm probably not the best person to judge if my URL/URI builder is , but here it nevertheless is: I wanted the simplest possible complete solution with zero dependencies outside the JDK, so I had to roll my own.Using HTTPClient worked well.Bug (RFE) 6306820 in the java bug database adresses this.In one of the comments, a  is provided.After being lambasted for suggesting the URL class.  I will take the commenter's advice and suggest the  instead.  I suggest you look closely at the constructors for a URI as the class is very immutable once created.\nI think this constructor allows you to set everything in the URI that you could need.There are plenty of libraries that can help you with URI building (don't reinvent the wheel). Here are three to get you started: It's  and there is a very popular library named  which has been starred  times on GitHub. With this library, you can build an url like below:The  has pretty good methods for constructing a URL.
Java

I can't seem to find the answer I'm looking for regarding a simple question: how do I round up any number to the nearest ?For example, whenever the number is 0.2, 0.7, 0.2222, 0.4324, 0.99999 I would want the outcome to be 1.So far I haveIt doesn't seem to be doing the job, though. is the correct function to call. I'm guessing  is an , which would make  perform integer arithmetic. Try  instead.Outputs:See I don't know why you are dividing by 100 but here my assumption or This seemed to do the perfect job. Worked everytime.Assuming a as double and we need a rounded number with no decimal place . Use Math.round() function.\nThis goes as my solution . 
Java

I wrote a web service project using netbeans 6.7.1 with glassfish v2.1, put log4j.properties to the root dir of project and use:in Constructor:and in functions:but, it is error info(actually, I have tried to put it almost every dir that I could realize):the example project could be get from I know it's a bit late to answer this question, and maybe you already found the solution, but I'm posting the solution I found (after I googled a lot) so it may help a little:Hope this will help.rgdsAs already stated, log4j.properties should be in a directory included in the classpath, I want to add that in a mavenized project a good place can be You have to put it in the root directory, that corresponds to your execution context.Example:If you start executing from a different project, you need to have that file in the project used for starting the execution. For example, if a different project holds some JUnit tests, it needs to have also its log4j.properties file.I suggest using log4j.xml instead of the log4j.properties. You have more options, get assistance from your IDE and so on...You can specify config file location with VM argument -Dlog4j.configuration=\"file:/C:/workspace3/local/log4j.properties\"If you put log4j.properties inside src, you don't need to use the statement - It will be taken automatically as the properties file is in the classpath.For a Maven Based Project keep your log4j.properties in src/main/resources. Nothing else to do!The file should be located in the WEB-INF/classes directory.\nThis directory structure should be packaged within the war file. Try:My IDE is NetBeans. I put log4j.property file as shown in the picturesRootWebWEB-INFTo use this property file you should to write this code:You can define  from another JSP file.\nExample:Now you can use log4j.property file in your projects.A few technically correct specific answers already provided but in general, it can be anywhere on the runtime classpath, i.e. wherever classes are sought by the JVM.This could be the /src dir in Eclipse or the WEB-INF/classes directory in your deployed app, but it's best to be aware of the classpath concept and why the file is placed in it, don't just treat WEB-INF/classes as a \"magic\" directory.I've spent a great deal of time to figure out why the  file is not seen. \nThen I noticed it was visible for the project only when it was in both  and  folders. \nHope it'll be useful to somebody. \nPS: The project was maven-based.I found that Glassfish by default is looking at [Glassfish install location]\\glassfish\\domains[your domain]\\ as the default working directory...  you can drop the log4j.properties file in this location and initialize it in your code using PropertyConfigurator as previously mentioned...I don't know this is correct way.But it solved my problem.\nput log4j.properties file in \"project folder\"/config and use PropertyConfigurator.configure(\"config//log4j.properties\");it will works with IDE but not when run the jar file yourself.\nwhen you run the jar file by yourself just copy the log4j.properties file in to the folder that jar file is in.when the jar and property file in same directory it runs well.
Java

im using Android Studio\nwhy every time I create a new project always comes up when I remove        \napplications in dependencies no problem anymore...I had the same problem. Solved by adding url for missing repository in the  file:That's it.Just remove the \"testCompile 'junit:junit:4.12'\" from build.gradle file:worked for me and I am Happy! :) Go to File -> Project Structure. Following window will open:From there:Hope it works for you too :D It's not able to get junit library.After adding above line inside android block in build.gradle file, it resolved problem.\nThis can be because your Android studio doesn't have junit library.Probably your gradle is incomplete, I recommend you add the following   but in some cases won't work , you can completely delete it from you dependencies in your gradle.add repository in your build.gradle fileHere is what I did to solve the same problem. I am behind a firewall, which is same issue as yours I suppose.\nSo I had tried removing the but that didnt work for me.\nI tried adding below lines of code:Even that did not work for me.I tried removing (-) and readding (+) Junit4.12 from the library dependencies under Module Settings.\nStill that did not work for me.Tried syncing and rebuilding project several times. Still did not work for me.Finally what I did was to manually download the Junit4.12.jar file from mvnrepository website. I put this jar file in the Androids Workspace under the Project folder inside libs folder.\nThen go to Module Settings > Dependencies Tab > (+) > File Dependency >\nunder Sleect path window, expand the 'libs' folder and you will find the Jar file you copied inside there.\nSelect the File and click 'OK'\nNow remove the previous version of junit4.12 from the list of dependencies.You should have one entry  in the Dependencies list.\nNow click 'OK'.Now Gradle will rebuild the project and you should be good to go.Hope this helps!I'll tryed everithing, but the only thing that helps me resolve the problem was delete the line from the app gradel.I received this error after creating a new project. In the build.gradle file, I had this:  I change it to the following and the error went away:  I think this is because I am behind a firewall and specifying the url like so changes it from https to httpProbably you are behind proxy. Happened to me, used my mobile tethering (no proxy) rebuild project and error disappeared. Returned to original connection (with proxy) and rebuild with no errors.It happens HTTPS is blocked by Proxy.\nTry to change from default jcenter (which uses HTTPS) into HTTP. BeforeAfterRepeat the above step for allprojects.? If so, the problem can be in missing network configuration for  in your  file. AndroidStudio puts automatically your default proxy settings to  file in your project, but only for http and forgets https.So basically your  file needs to contain both http and https config:CHANGE your build.gradle like with this, work fine for me:added to Go to File -> Project Structure -> dependency\nThere you will find ->  junit:unit:4.12On the right hand side ..select compile from the drop down.\nSimple.. its done.Reference Image: Reds'\nVVMostly this issue will come when ever you update your SDK, at the time of project creation Gradle build fails. If you add the  and  repositories to your  your problem will solved.These are the two line you have to add after The error is caused by missing jar files. My simple solution is just by copying all the files that does not resolve to the C:\\Program Files\\Android\\Android Studio\\gradle\\m2repository... (your file path may be different). I got around 6 dependencies that cannot be resolved, junit is one of them and the others are com and org and javax. Since I am behind a firewall, even if I added the code for the repository, the Android Studio doesn't seem to access it. I went to the maven repository and downloaded all the files that will not resolve. Problem solved and the Gradle sync without error. But I am a certified newbie with only 1 day experience so I do not not if this is the proper way to do it. Example error: \nCannot resolve com:squareup:javawriter:2.1.1Step 1: I created a path C:\\Program Files\\Android\\Android Studio\\gradle\\m2repository\\com\\squareup\\javawriter\\2.1.1\\ Step 2: I downloaded all the jar files from the maven repository: \nStep 3: I manually downloaded all the .jar files from this directoryStep 4: I copied them to C:\\Program Files\\Android\\Android Studio\\gradle\\m2repository\\com\\squareup\\javawriter\\2.1.1\\ I repeated this to all the files that did not resolve including the junit.For junit, here is the directory I created: \nC:\\Program Files\\Android\\Android Studio\\gradle\\m2repository\\junit\\junit\\4.12\nand then I copied the junit-4.12.jar inside this directory and the junit error disappeared.After that sync the project again.Try this:If you are behind a proxy. Android Studio will add proxy for http to Gradle, but will not for https.\nAdd proxy settings for https to gradle.propertiesMy installation of Android Studio is completely offline. To resolve these kind of problems I have used the Process Monitor. It showed that a few files are missing within \"Android Studio\\gradle\\m2repository\".\nI have downloaded all files fromand copied these files in \"Android Studio\\gradle\\m2repository\". You have to create the structure below \"m2repository\" as it is below \"maven2\".\nMaybe there are more missing files, but at this time at least Gradle build is finished without errors.build.gradle(project: ...)I had the same problem, but with another problem.My other problem was that the Gradle build was too slow!I resolved my problem by doing thisLIf you do like mdew you need to this any time you're creating your project to do thisSo if you want to set default option to maven Do this: Go to the folder:Then open the  file with notepad++ or notepad\nand replace all  with .EDIT: Why its going down voted? you don't like it?I was having same problem.I couldn't work out why Android Studio was not syncing with gradle. It turned out that it didn't like my VPN, so watch for that!Go to Go to \"File\" -> \"Project Structure\" -> \"App\"\nIn the tab \"properties\". In \"Library Repository\"  put '' then press Ok.\nIt was fixed like that for me. Now the project is compiling.Just connect to Internet and start Android Studio and open your project.\nWhile Gradle Sync it will download the dependencies from Internet(All JAR Files). This solved it for me.\nNo Editing in Gradle file ,all was done by Android Studio Automatically.\nUsing Android Studio 2.2 :)Also don't forget to install Java JDK 1.x(7 or 8 all works fine).I would love to suggest the solution, which perfects suitable for my situation:Simply try to compile and run you project while having active internet connection. it worked for me in Android studio 1.5 Ubuntu 15.04
Java

 has questioned and answered how to declare an empty  but how do I declare an arraylist with values?I've tried the following but it returns a syntax error:You can create a new object using the constructor that accepts a :When you have question like this, you should visit the  and see what constructors available there:Java 8 solution using :You can do like this :Use:If you don't want to add new elements to the list later, you can also use ( returns a fixed-size list):Note: you can also use a static import if you like, then it looks like this:...orThe  contains convenience methods for creating lists and other collections which makes this much prettier than using the standard library classes.Example:(This assumes )Try this!It's a good practice to declare the  with interface  if you don't have to invoke the specific methods.Use this one: 
Java

How does a Java  work when it has an assignment and an equality check -d together??Why is this printing FALSE?The expression is not parsed the way you think. It's notin which case the result would have been , butThe value of  expression is computed first, and it is , because  is set to  going into the computation.The reason it is parsed this way is that the  of the  is lower than that of the  operator, but higher than the precedence of the assignment operator .This is a precedence issue, basically. You're assuming that your code is equivalent to:... but it's not. It's actually equivalent to:... which is equivalent to:(because  is  to start with)... which is equivalent to:which assigns the value  to , with the result of the expression being .See the  for a useful table of operator precedence.Expression  will evaluate in following step.  //precedence of  is highest // Operator  have higher precedence  Since boolean value of expression becomes false.So else statement is being executed. returns false, because both of them are false. this is true because one of them is true
Java

Is it possible in JUnit to assert an object is an instance of a class? For various reasons I have an object in my test that I want to check the type of. Is it a type of Object1 or a type of Object2?Currently I have:This works but I was wondering if there is a more expressive way of doing this.For example something like:I could do this:Is there a specific assert method that allows me to test a type of an object in a more elegant, fluid manner?You can use the  method and the Matchers that comes with JUnit.Take a look at  that describes a little bit about the JUnit Matchers.Example:Test:
Java

Some time ago, I came across a piece of code, that used some piece of standard Java functionality to locate the classes that implemented a given interface. I know the functions were hidden in some non-logical place, but they could be used for other classes as the package name implied. Back then I did not need it, so I forgot about it, but now I do, and I can't seem to find the functions again. Where can these functions be found?Edit: I'm not looking for any IDE functions or anything, but rather something that can be executed within the Java application.Awhile ago, I put together a package for doing what you want, and more. (I needed it for a utility I was writing). It uses the  library. You can use reflection, but ASM turned out to perform better.I put my package in an open source library I have on my web site. The library is here: . You want to start with the with  class.The utility I wrote it for is an RSS reader that I still use every day, so the code does tend to get exercised. I use ClassFinder to support a plug-in API in the RSS reader; on startup, it looks in a couple directory trees for jars and class files containing classes that implement a certain interface. It's a lot faster than you might expect.The library is BSD-licensed, so you can safely bundle it with your code. Source is available.If that's useful to you, help yourself.Update: If you're using Scala, you might find  to be more Scala-friendly.Spring can do this for you...N.B. The TypeFilter is important if you want the correct results!\nYou can also use exclusion filters here instead.The Scanner can be found in the spring-context jar, the registry in spring-beans, the type filter is in spring-core.I really like the  for doing this.It provides a lot of different types of scanners (, , etc), and it is dead simple to write or extend your own.The code you are talking about sounds like  which was introduced in Java 6 to support a feature that has been defined since  or earlier. For performance reasons, this is the recommended approach to find interface implementations at runtime; if you need support for this in an older version of Java, I hope that you'll find  helpful.There are a couple of implementations of this in earlier versions of Java, but in the Sun packages, not in the core API (I think there are some classes internal to ImageIO that do this). As the code is simple, I'd recommend providing your own implementation rather than relying on non-standard Sun code which is subject to change.I know this question has already been answered a long time ago but another solution to this problem is to use Package Level Annotations.While its pretty hard to go find all the classes in the JVM its actually pretty easy to browse the package hierarchy. Then just make your annotation have an argument of an array of Class.\nThen in your package-info.java for a particular package put the MyAno.I'll add more details (code) if people are interested but most probably get the idea.To add to @erickson answer you can also use the service loader approach. Kohsuke has an awesome way of generating the the required META-INF stuff you need for the service loader approach:You could also use the Extensible Component Scanner (extcos: ) and search all classes implementing an interface like so:This works for classes on the file system, within jars and even for those on the JBoss virtual file system. It's further designed to work within standalone applications as well as within any web or application container.In full generality, this functionality is impossible. The Java ClassLoader mechanism guarantees only the ability to ask for a class with a specific name (including pacakge), and the ClassLoader can supply a class, or it can state that it does not know that class.Classes can be (and frequently are) loaded from remote servers, and they can even be constructed on the fly; it is not difficult at all to write a ClassLoader that returns a valid class that implements a given interface for  name you ask from it; a List of the classes that implement that interface would then be infinite in length.In practice, the most common case is an  that looks for classes in a list of filesystem directories and JAR files. So what you need is to get the , then iterate through those directories and archives, and for each class file you find in them, request the corresponding  object and look through the return of its  method.Obviously, Class.isAssignableFrom() tells you whether an  class implements the given interface. So then the problem is getting the list of classes to test.As far as I'm aware, there's no direct way from Java to ask the class loader for \"the list of classes that you could  load\". So you'll have to do this yourself by iterating through the visible jars, calling Class.forName() to load the class, then testing it.However, it's a little easier if you just want to know classes implementing the given interface from those that have  been loaded:If you use the instrumentation technique, then (as explained in the link) what happens is that your \"agent\" class is called essentially when the JVM starts up, and passed an Instrumentation object. At that point, you probably want to \"save it for later\" in a static field, and then have your main application code call it later on to get the list of loaded classes.If you were asking from the perspective of working this out with a running program then you need to look to the java.lang.* package. If you get a Class object, you can use the isAssignableFrom method to check if it is an interface of another Class.There isn't a simple built in way of searching for these, tools like Eclipse build an index of this information.If you don't have a specific list of Class objects to test you can look to the ClassLoader object, use the getPackages() method and build your own package hierarchy iterator.Just a warning though that these methods and classes can be quite slow. 
Java

A GUI with no white space appears 'crowded'.  How can I provide white space without resorting to explicitly setting the position or size of components?\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00ad\u00adUsing various  one can provide spacing between various components. There are a number of ways in a Swing GUI to provide a separation between components, and white space around components:But more generally, look to:Here is an example of using the layout separator  &  values & borders (specifically an ) to provide 'white' (actually shown as 'red' to make it very obvious) space.  Adjust the spinners to see the result.When you use ,  method can help you to make some white space.Another method is . It can help you to make some white space around component.Thanks for Andrew Thompson's remind.I've revised BoxLayout in recent days and I     find that  can add some white space depend on the panel's size and you can not set the explicit pixel value of the length of white space.But  can do that.  Here is a MCTaRE and show the    effect of those two methods. and  can be used too. Besides,  has the ability too create white space too. has multiple ways of creating space. (A space is called a gap in this layout.)\nGaps can be created at the highest level with layout constraints, it is possible to\ncreate gaps between rows and column and gaps can be also set between individual \ncomponents with component constraints. There are also specific gaps around the borders\nof a container called insets which have their own specific keyword to be set.The following example creates all these kinds of gaps:We have four panels in the layout. Each of this panels has a  manager.This line creates container insets and vertical gaps between panels.Here we apply gaps for the whole grid structure and also set container gaps.This line creates gaps between columns.Row gaps are defined with this code.Finally, it is possible to create gaps between individual components.  Author Karsten Lentzsch has a collection of  on UI design.   In particular  speaks to the need for aesthetic whitespace.  Adding meaningful space while also paying attention to clutter separates the wheat from the chaff.
Java

OK, this should really be asked to someone from Google, but I just want other opinions.Even Android supports Native code applications, the main development tool is Java. But why? I mean, isn't it too slow to interpret code on a mobile device? When introducing Froyo, Google said that new JIT compiler can achieve 2-5 times faster applications. This means, that using Java over native code is 2-x times slower.Yes, I know that using managed code applications is safer in terms of system stability, since virtual machine has better control of program, but still, this performance drop is huge, and I don't see any point why to use it.Some points:On the byte-code level, Android doesn't use Java.  The source is Java, but it doesn't use a JVM.The improvement to system stability is  on a device like a cell phone.  is even more important. The Android environment lets users run semi-trusted apps which could exploit the phone in truly unpleasant ways without excellent security. By running all apps in a virtual machine, you guarantee that no app can exploit the OS kernel unless there is a flaw in the VM implementation. The VM implementation, in turn, is presumably small and has a small, well-defined security surface. Perhaps most important, when programs are compiled to code for a virtual machine, they do not have to be recompiled for new hardware. The market for phone chips is diverse and rapidly-changing, so that's a big deal.Also, using Java makes it less likely that the apps people write will be exploitable themselves. No buffer-overruns, mistakes with pointers, etc...Native code is not necessarily any faster than Java code. Where is your profile data showing that native code could run faster?Why Java?Java has a pretty compelling argument for Google using it in Android: it has a huge base of developers. All these developers are (kind of) ready to develop for their mobile platform.Keep in mind that, technically speaking, Android does not use  Java.First of all, according to Google, Android doesn't use Java. That's why Oracle is suing Google. Oracle claims that Android infringes on some Java technology, but Google says it's Dalvik.Secondly, I haven't seen a Java byte code interpreter since 1995.Can you back up your performance conjecture with some actual benchmarks? The scope of your presumptions don't seem justified given the inaccurate background information you provide.As touched on elsewhere, the main issue is that Android is designed as a portable OS, to run on a wide variety of hardware.\nIt's also building on a framework and language familiar to many existing mobile developers.Finally, I would say it is a bet against the future - whatever performance issues exist will become irrelevant as hardware improves - equally by getting developers to code against an abstraction, Google can rip-out and change the underlying OS far more easily, than if developers were coding to the POSIX/Unix APIs.For most applications the overhead of using a VM-based language over native is not significant (the bottleneck for apps consuming web services, like Twitter, is mostly networking). The Palm WebOS also demonstrates this - and that uses JavaScript rather than Java as the main language.  Given that almost all VMs JIT compile down to native code, raw code speed is often comparable with native speed. A lot of delays attributed to higher-level languages are less to do with the VM overhead than other factors (a complex object runtime, 'safety' checking memory access by doing bounds checking, etc).Also remember that regardless of the language used to write an application, a lot of the actual work is done in lower level APIs. The top level language is often just chaining API calls together.There are, of course, many exceptions to this rule - games, audio and graphics apps that push the limits of phone hardware. Even on the iOS, developers often drop down to C/C++ to get speed in these areas.The new JIT is running the applications 2 - 5 times faster than the old dalvikVM (both JAVA). So comparison is not C over JAVA, but JIT over dalvikVM.First of all it's about the same thing will windows mobile or the iPhone, the .net framework needs its own VM as well as cocoa.And even if the performance is not at the best, because it's an interpretation of byte code, android brings the entire java community as potential developers. More applications, more clients, etc.To finish, no performance is not that bad, that's why java is used even on smaller devices (see JavaMe).
Java

I'm attempting to override the default  appearance. Here's the XML that defines the :Now, we have two 30 x 30 icons we want to use for the clicked/non-clicked states. Right now we have code that programmatically changes the background icon depending on the state:Obviously I'm looking for a better way to do this. I've tried to make a selector for the background image, which would automatically switch between the states:But this does not work; reading the  API (), it appears that the only inherited xml attributes areThere does not seem to be the android:state_checked attribute, despite the class having the method  and .So, is there a way to do what I want in XML, or am I stuck with my messy workaround?Your code is fine. However, the toggle button will display the first item in your selector that it matches, so the default should come last. Arrange the items in the following manner to ensure they will all be utilized:
Java

In javadoc for  is the following:What does it mean? What happens if I try to iterate the map with two threads at the same time? What happens if I put or remove a value from the map while iterating it?That means that each iterator you obtain from a  is designed to be used by a single thread and should not be passed around. This includes the syntactic sugar that the for-each loop provides.It will work as expected if each of the threads uses it's own iterator. It is guaranteed that things will not break if you do this (that's part of what the \"concurrent\" in  means). However, there is no guarantee that one thread will see the changes to the map that the other thread performs (without obtaining a new iterator from the map). The iterator is guaranteed to reflect the state of the map at the time of it's creation. Futher changes may be reflected in the iterator, but they do not have to be.In conclusion, a statement likewill be fine (or at least safe) almost every time you see it. You may use this class to test two accessing threads and one mutating the shared instance of :No exception will be thrown.Sharing the same iterator between accessor threads can lead to deadlock:As soon as you start sharing the same  among accessor and mutator threads s will start popping up.It means that you should not share an iterator object among multiple threads. Creating multiple iterators and using them concurrently in separate threads is fine.It means that you should not try to use the same iterator in two threads.  If you have two threads that need to iterate over the keys, values or entries, then they each should create and use their own iterators.It is not entirely clear what would happen if you broke this rule.  You could just get confusing behavior, in the same way that you do if (for example) two threads try to read from standard input without synchronizing.  You could also get non-thread-safe behavior.But if the two threads used different iterators, you should be fine.That's a separate issue, but the javadoc section that you quoted adequately answers it.  Basically, the iterators are thread-safe, but  whether you will see the effects of any concurrent insertions, updates or deletions reflected in the sequence of objects returned by the iterator.  In practice, it probably depends on where in the map the updates occur. might give you a good insight Regarding this:It means, while using iterators produced by ConcurrentHashMap in two threads are safe, it may cause an unexpected result in the application.
Java

At the moment a default entry looks something like this:How do I get it to do this?Clarification I'm using java.util.loggingAs of Java 7,  supports getting its  from a system property, so adding something like this to the JVM command line will cause it to print on one line:Alternatively, you can also add this to your :Java 7 supports a property with the  format string syntax.See .My favorite is:which makes output like:IDEs typically let you set system properties for a project.\nE.g. in NetBeans, instead of adding -D...=... somewhere, add the property in the action dialog, in a form of  - without any quotes. The IDE should figure out.For your convenience, Here is how to put it to Surefire:I have a library with . Amongst them, it's .\n Downloadable jar .Like Obediah Stane said, it's necessary to create your own  method. But I would change a few things:The following class can be  in a , which in turn can be  to the . Note that it ignores all class and method information available in the .Similar to Tervor, But I like to change the property  on runtime. Note that this need to be set before the first SimpleFormatter is created - as was  written in the comments.Per screenshot, in Eclipse select \"run as\" then \"Run Configurations...\" and add the answer from Trevor Robinson with double quotes instead of quotes. If you miss the double quotes you'll get \"could not find or load main class\" errors.I've figured out a way that works. You can subclass SimpleFormatter and override the format methodA bit surprised at this API I would have thought that more functionality/flexibility would have been provided out of the boxThis is what I'm using.You'll get something like...This logging is specific to your application and not a general Java feature. What application(s) are you running?It might be that this is coming from a specific logging library that you are using within your own code. If so, please post the details of which one you are using.If you log in a web application using tomcat add:On VM argumentsif you're using java.util.logging, then there is a configuration file that is doing this to log contents (unless you're using programmatic configuration).  So, your options are \n1) run post -processor that removes the line breaks\n2) change the log configuration AND remove the line breaks from it. Restart your application (server) and you should be good.
Java

Following is resulting in an :Is there a better way to parse  to get  than: ?Use :You can use this (the French locale has  for decimal separator)Or you can use  and set the appropriate symbols:As E-Riz points out, NumberFormat.parse(String) parse \"1,23abc\" as 1.23. To take the entire input we can use:If you don't know the correct Locale and the string can have a thousand separator this could be a last resort:Be aware: this will happily parse strings like \"R 1 52.43,2\" to \"15243.2\".This is the static method I use in my own code:...is very quick as it searches the underlying character array on a char-by-char basis. The string replace versions compile a RegEx to evaluate.Basically replace(char,char) is about 10 times quicker and since you'll be doing these kind of things in low-level code it makes sense to think about this. The Hot Spot optimiser will not figure it out... Certainly doesn't on my system.You of course need to use the correct locale.  question will help.This would do the job:
Java

When running any java application, or just 'java', the jvm fails:Here is a list of  answers:Any ideas?The problem comes from an improper java installation (e.g. an installation done without admin rights or by simply unzipping tools.zip).You can either uninstall, then reinstall Java with an installer and/or more privileges or try the following:Check in your JDK folder for  files in  and \nsuch as  (the default location is  for Microsoft Windows and   for Unix/GNU Linux) Those  files need to be unpacked to  files using this command:and repeat that step with all of the *.pack files and relaunch your program.  For java 8 @ *NIX OS:From directory  (For me it: /usr/java/jdk1.8.0_05/jre/lib)Run:(May You can't use the system's unpack200 cause version problems.)\nThis unpack200 is in java 8 directory (for me: /usr/java/jdk1.8.0_05/bin)BenedekIt seems that for a 64 bit architecture you have to install both the 32-bit version and the 64-bit version of jre (architecture independent files as rt.jar are distributed only in the 32-bit version).Remember then to pay attention to include the correct java executable on the global PATH environment variable. for impatient people ;) On  machines, try this:\nGo to  directory and delete  (or rename it to something like ).Since at least 1.6, there should not be a  in the Windows directory. If there is, it's a leftover from something. I'm really suprised that a question from 2012 doesn't have an approved answer yet and I've actually encountered the same issue in 2015 on my Win 7 32-Bit OS!So what did happen?Basically, everything was working fine, I downloaded H2 database and when I tried to start  I got:I found this question and I was able to confirm the same symptoms:JAVA_HOME is set correctly: fails, while  works fine:\nGo to  directory and delete (I actually renamed)  file!!!!Now, I get:and  works fine as well!Credits go to the last post in this forum:\nYou are most probably missing a file called rt.jar in your installation which has the class file for java.lang.Object. Check your install files etc.In particular, note that a 64-bit intsaller overlays (or installs \"next to\") an existing 32-bit installation. In other words, to get a fully working 64-bit installation, you must first run the 32-bit installation, and follow that up with a 64-bit installation if you have a 64bit capable machine...If instead you do just a 64-bit installation you will be missing certain files in the installation and will get errors such as the one above.I downloaded new JDK today (1.8.0.73) started  and got the infamous:I just wanted to share my working solution on here.When I cd'ied into the  folder, Java would run fine so I knew it was the . I set  to just  at CMD to prove it and it worked.So, one of the folders in the  must have had  that was causing the conflict, I thought. As it turned out, it was  that holds  to the executables.  was pointing to . The file was corrupt, when I started --the exact same error. Bingo. I re-installed JRE and the problem went away. Happy coding...This problem happens when you install the JDK by  it instead of  it. In the first scenario, the runtime libraries, as rt.jar, don't get automatically uncompresessed (thus, you can find the rt.pack files, etc. instead of the .jar ones).You cannot install just the 64bit, you must first install the 32bit and then add the 64bit components.From java.com:I had the same problem recently. In my case my windows 7 machine automatically downloaded java and added  to the beginning of my path environment variable, which messed up my java. Once I got rid of that from the path, it worked.if you do \"chmod u+rx\" on the java binary and run it, it will the unpack the jar files and you can do a java -version without runtime errors If you install a 64-bit version without first installing 32-bit, this error will occur despite fixing all of the other issues.  I have a brand new Dell i7 64-bit Windows 10 Pro machine running Java 8u71.  After having added my %path% and %classpath% to environment variables and trying several other fixes, uninstalling 64-bit, installing 32-bit then reinstalling 64-bit fixed it.Some of the issues, like not having your files unpacked, etc. that have been mentioned as possible causes may still be causing issues, but if you don't do this, as well, the other fixes won't work.In my case, I use a windows 8.1 (installed jdk1.8.0_77), I did three things:and voila got it fixed!I have faced the similar issue and found that the symlink in program data(C:\\ProgramData\\Oracle\\Java\\javapath) was wrong. I have given the correct path and it worked.Another answer could be to use the tar.gz file instead in the Linux case. There seem to be something like that also for the solaris platform. This way all files will already be in the expected format and there won't be any unpacking issues.I have the some problem on x86_64 Linux installations with JDK 1.7.0_40 i586.\nI figured out that the problem is that rpm can't unpack jar files, as mentioned by Rigg802 (though rpm completes marking success):File /lib/ld-linux.so.2 is provided by glibc-2.12-1.107.el6_4.4. which is not among rpm deps of jdk rpm.Oracle JDK rpm also requires 32 bit versions of libgcc-4.4.7-3.el6. to be installedSo, workaround is to install glibc-2.12-1.107.el6_4.4.i686 and libgcc-4.4.7-3.el6.i686 first.Quick fix that worked for me:I found that this error occurred when I extracted the .rpm file.I then removed that folder and downloaded jdk-7u79-linux-x64.tar.gz for Linux 64 and extracted the contents of this file instead.\nAlso:\n    export JAVA_HOME=/opt/java/jdk1.7.0_79\n    export JDK_HOME=/opt/java/jdk1.7.0_79\n    export PATH=${JAVA_HOME}/binJust install the jre . It simply solved my problem. (SonarQube startup batch started to give this error after I installed jdk)Go to control panel, uninstall the java related stuff(close eclipse if opened), then re-install java and open eclipse, clean projects.Just did this on Solaris and ran into this identical problem where even \"java -version\" does not work.  There is a reason that the 64 bit versions of the distro are WAY smaller than the 32-bit.  It is indeed as stated above: In other words, to get a fully working 64-bit installation, you must first run the 32-bit installation, and follow that up with a 64-bit installation if you have a 64bit capable machine...So I ran the installer for the 32-bit:Then I ran the installer for the 64-bit:This gives me several java executables to choose from:The sparcv9 java's are the 64bit versions and they work with \"-version\" when installed alongside the 32bit JDK.-DanOn Windows 10, I was facing the same issue with JRE 1.8 (8u121).\nTyping     the cmd prompt returnsAll the other commands, , , ,  worked fine.Going to environment variables on system administration panel, remove from PATH the link , and be sure to have set in PATH the link to .After that, check if in  exists a  file; if true, delete that file.Typing now  it works fine.I was facing same issue: Error occurred during initialization of VM\njava/lang/NoClassDefFoundError: java/lang/ObjectFollow below steps to resolve issue :Step 1. Goto C:\\Program Files\\ and search for Java folder.Step 2. Delete C:\\Program Files\\Java folder.Step 3. Download new Jdk for your version 32 bit/64 bit from Step 4. Install JDKStep 5: Now Set JAVA_HOME to \"C:\\Program Files\\Java\\jdk1.8.0_91\"Step 6: Open command prompt and enter java -version.It works.I faced same issue, I have installed two java version hence it caused this issue. to confirm this go and click java icon in control panel if doesnt open then issue is same, just go and uninstall one version. piece of cake. thanks.
Java

Is there some one-liner bridge method to dump a given Enumeration to java.util.List or java.util.Set?Something built-in like  or  should exist somewhere, but I'm unable to find that in my IntelliJ debugger's evaluator window (and Google/SO results, too).Thanks in advance,\nAntonYou can use  to convert an  to a  in one line:There's no similar method to get a , however you can still do it one line:How about this: There is a simple example of convert enumeration to list. for this i used    method. Reference :  If you need  rather than , you can use .: JakeRobb is right. My answer is about java.lang.Enum instead of java.util.Enumeration. Sorry for unrelated answer.I needed same thing and this solution work fine, hope it can help someone alsothen you can get the .name() of your enumeration.When using guava (See ) there is . Given an  you can do the following:to get a immutable Set:to get a immutable List:to get a hashSet:
Java

I've always been able to allocate 1400 megabytes for Java SE running on 32-bit Windows XP (Java 1.4, 1.5 and 1.6).Today I tried the same option on a new Windows XP machine using Java 1.5_16 and 1.6.0_07 and got the error:Through trial and error it seems 1200 megabytes is the most I can allocate on this machine.Any ideas why one machine would allow 1400 and another only 1200?Edit: The machine has 4GB of RAM with about 3.5GB that Windows can recognize.Keep in mind that Windows has virtual memory management and the JVM only needs memory that is contiguous . So, other programs running on the system shouldn't necessarily impact your heap size. What will get in your way are DLL's that get loaded in to your address space. Unfortunately optimizations in Windows that minimize the relocation of DLL's during linking make it more likely you'll have a fragmented address space. Things that are likely to cut in to your address space aside from the usual stuff include security software, CBT software, spyware and other forms of malware. Likely causes of the variances are different security patches, C runtime versions, etc. Device drivers and other kernel bits have their own address space (the other 2GB of the 4GB 32-bit space).You  try going through your DLL bindings in your JVM process and look at trying to rebase your DLL's in to a more compact address space. Not fun, but if you are desperate...Alternatively, you can just switch to 64-bit Windows and a 64-bit JVM. Despite what others have suggested, while it will chew up more RAM, you will have  more contiguous virtual address space, and allocating 2GB contiguously would be trivial.This has to do with contiguous memory. for somebody asking that before, supposedly from a \"VM god\":The Java heap size limits for Windows are:This doesn't help you getting a bigger Java heap, but now you know you can't go beyond these values., which can handle a non-contiguous heap, can have a Java heap size of 2.85 GB on Windows 2003/XP with the /3GB switch. It seems that fragmentation can have quite an impact on how large a Java heap can be.The JVM needs contiguous memory and depending on what else is running, what was running before, and how windows has managed memory you may be able to get up to 1.4GB of contiguous memory.  I think 64bit Windows will allow larger heaps.Sun's JVM needs contiguous memory. So the maximal amount of available memory is dictated by memory fragmentation. Especially driver's dlls tend to fragment the memory, when loading into some predefined base address. So your hardware and its drivers determine how much memory you can get. Two sources for this with statements from Sun engineers:  Maybe another JVM? Have you tried ? I think they planned to allow non-continuous memory.I think it has more to do with how Windows is configured as hinted by this response:\nSome more testing: I was able to allocate 1300MB on an old Windows XP machine with only 768MB physical RAM (plus virtual memory). On my 2GB RAM machine I can only get 1220MB. On various other corporate machines (with older Windows XP) I was able to get 1400MB. The machine with a 1220MB limit is pretty new (just purchased from Dell), so maybe it has newer (and more bloated) Windows and DLLs (it's running Window XP Pro Version 2002 SP2).I got this error message when running a java program from a (limited memory) virtuozzo VPS. I had not specified any memory arguments, and found I had to explicitly set a  amount as the default must have been too high. E.g. -Xmx32m (obviously needs to be tuned depending on the program you run).Just putting this here in case anyone else gets the above error message without specifying a large amount of memory like the questioner did.sun's JDK/JRE needs a contiguous amount of memory if you allocate a huge block.The OS and initial apps tend to allocate bits and pieces during loading which fragments the available RAM. If a contiguous block is NOT available, the SUN JDK cannot use it. JRockit from Bea(acquired by Oracle) can allocate memory from pieces.Here is how to increase the Paging sizeEveryone seems to be answering about contiguous memory, but have neglected to acknowledge a more pressing issue.Even with 100% contiguous memory allocation, you can't have a 2 GiB heap size on a 32-bit Windows OS (*by default). This is because 32-bit Windows processes cannot address more than 2 GiB of space.The Java process will contain perm gen (pre Java 8), stack size per thread, JVM / library overhead (which pretty much increases with each build) .Furthermore, JVM flags and their default values change between versions. Just run the following and you'll get some idea:Lots of the options affect memory division in and out of the heap. Leaving you with more or less of that 2 GiB to play with...To reuse portions of  answer of mine (about Tomcat, but applies to any Java process):First, using a page-file when you have 4 GB of RAM is useless. Windows can't access more than 4GB (actually, less because of memory holes) so the page file is not used.Second, the address space is split in 2, half for kernel, half for user mode. If you need more RAM for your applications use the /3GB option in boot.ini (make sure java.exe is marked as \"large address aware\" (google for more info).Third, I think you can't allocate the full 2 GB of address space because java wastes some memory internally (for threads, JIT compiler, VM initialization, etc). Use the /3GB switch for more.
Java

What is the concept of erasure in generics in Java?It's basically the way that generics are implemented in Java via compiler trickery. The compiled generic code  just uses  wherever you talk about  (or some other type parameter) - and there's some metadata to tell the compiler that it really is a generic type.When you compile some code against a generic type or method, the compiler works out what you really mean (i.e. what the type argument for  is) and verifies at  time that you're doing the right thing, but the emitted code again just talks in terms of  - the compiler generates extra casts where necessary. At execution time, a   and a  are exactly the same; the extra type information has been  by the compiler.Compare this with, say, C#, where the information is retained at execution time, allowing code to contain expressions such as  which is the equivalent to  - except that the latter is invalid. (There are further differences between .NET generics and Java generics, mind you.) Type erasure is the source of many of the \"odd\" warning/error messages when dealing with Java generics.Other resources:Just as a side-note, it is an interesting exercise to actually see what the compiler is doing when it performs erasure -- makes the whole concept a little easier to grasp.  There is a special flag you can pass the compiler to output java files that have had the generics erased and casts inserted.  An example:The  is the flag that gets handed off to the compiler that generates the files.  (The  part is what tells  to hand it to the executable jar that actually does the compiling rather than just , but I digress...)  The  is necessary because the compiler needs some place to put the new .java files.This, of course, does more than just erasure; all of the automatic stuff the compiler does gets done here.  For example, default constructors are also inserted, the new foreach-style  loops are expanded to regular  loops, etc.  It is nice to see the little things that are happening automagically.To complete the already very complete Jon Skeet's answer, you have to realize the concept of  derives from a need of .Initially presented at EclipseCon 2007 (no longer available), the compatibility included those points:Original answer:Hence:There are propositions for a greater . Reify being \"Regard an abstract concept as real\", where language constructs should be concepts, not just syntactic sugar.I should also mention the  method of Java\u00a06, which returns a dynamically typesafe view of the specified collection. Any attempt to insert an element of the wrong type will result in an immediate .The generics mechanism in the language .Usually this is not a problem, as the compiler issues warnings on all such unchecked operations.There are, however, times when static type checking alone is not sufficient, like:Update July 2012, almost four years later:It is now (2012) detailed in \"\"Erasure, literally means that the type information which is present in the source code is erased from the compiled bytecode. Let us understand this with some code.If you compile this code and then decompile it with a Java decompiler, you will get something like this. Complementing the already-complemented Jon Skeet answer...It has been mentioned that implementing generics through erasure leads to some annoying limitations (e.g. no ).  It has also been mentioned that the primary reason for doing things this way was backwards compatibility in the bytecode.  This is also (mostly) true.  The bytecode generated -target 1.5 is somewhat different from just de-sugared casting -target 1.4.  Technically, it's even possible (through immense trickery) to gain access to generic type instantiations , proving that there really is something in the bytecode.The more interesting point (which has not been raised) is that implementing generics using erasure offers quite a bit more flexibility in what the high-level type system can accomplish.  A good example of this would be Scala's JVM implementation vs CLR.  On the JVM, it is possible to implement higher-kinds directly due to the fact that the JVM itself imposes no restrictions on generic types (since these \"types\" are effectively absent).  This contrasts with the CLR, which has runtime knowledge of parameter instantiations.  Because of this, the CLR itself must have some concept of how generics should be used, nullifying attempts to extend the system with unanticipated rules.  As a result, Scala's higher-kinds on the CLR are implemented using a weird form of erasure emulated within the compiler itself, making them not-entirely-compatible with plain-old .NET generics.Erasure may be inconvenient when you want to do naughty things at runtime, but it does offer the most flexibility to the compiler writers.  I'm guessing that's part of why it's not going away any time soon.As I understand it (being a  guy) the  has no concept of generics, so the compiler replaces type parameters with Object and performs all the casting for you.This means that Java generics are nothing but syntax sugar and don't offer any performance improvement for value types that require boxing/unboxing when passed by reference.The  is defined as follows: For example:1.The  of , , and  is .2.The  of  is .3.The  of  is .4.The  of  or  is .Now consider a class ,This will  because Now consider  This will show up a  becauseGenerics were introduced to the Java language to provide tighter type checks at compile time and to support generic programming. To implement generics, the Java compiler applies type erasure to:Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded. The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods.\nInsert type casts if necessary to preserve type safety.\nGenerate bridge methods to preserve polymorphism in extended generic types.\nType erasure ensures that no new classes are created for parameterized types; consequently, generics incur no runtime overhead.Erasure of Generic TypesDuring the type erasure process, the Java compiler erases all type parameters and replaces each with its first bound if the type parameter is bounded, or Object if the type parameter is unbounded.Consider the following generic class that represents a node in a singly linked list:public class Node {}\nBecause the type parameter T is unbounded, the Java compiler replaces it with Object:public class Node {}\nIn the following example, the generic Node class uses a bounded type parameter:public class Node> {}\nThe Java compiler replaces the bounded type parameter T with the first bound class, Comparable:public class Node {Java docs for Generics  : Generic programming is introduce in java 1.5 version\n\nGeneric programming is a type safe object,Before generic in collection we can store any type of object. and after generic we must to store the data of specific type of object.  \nThe main advantages of generic is Type casting is not required and also type-sage and Generic will check the compile time. and the general syntax of Generic is ClassOrInterface here type is the signal that this class can have set the class when it instantiated  .\nGenericClassDemo\n\n
Java

can anyone help. I keep getting an error message in eclipse when creating a new project and i don't understand why.I have created a workspace at the levelInside Counter there are no files but there is a directory called counter_src which contains source files for the project CounterSo in eclipse I do, new java project, and then uncheck default location and choose the directory counter_src  (which is one level down from Counter)but it now displaysNow if i create my workspace at which means my counter_src is actually 2 levels down then it allows me, but the problem is that the directory JAVA contains lots of projects so i wanted to create the workspace in Counter (which has no files) which has subdirectory of counter_src where my source files are.Also tested creating directory off of C:\\Users\\Martin\\Java\\ and it appears to work also but I didn't want to create another subdirectory off of \"C:\\Users\\Martin\\Java\\\" just to store my workspace for 1 project.I would really appreciate any help on this, i am a little list.Thnaks in advanceEclipse is erroring because if you try and create a project on a directory that exists, Eclipse doesn't know if it's an actual project or not - so it errors, saving you from losing work!So you have two solutions:So, I was having the same issue, but trying to  via the \"Import...\" menu. When neither of the above two solutions worked on Eclipse Juno:Once the project rebuilds, everything should be back in order.(This was written when Eclipse Indigo was in vogue, and there may be changes as Google updates their tools to cover corner cases.)This has  More your project folder outside your workspace in some other location and then try. Go to Assume D:\\MyDirectory\\MyWorkSpace        - Path of your WorkSpace  in In my case checking the check-box did the trick.simply \"CUT\" project folder and move it out of workspace directory and do the followingand you done !This too took me sometime to figure out.To create a new  under the existing workspace, just have the \"\" ticked ().The name of the project will be determined by you  in step 2 of the creation wizard.It was so confusing because in my case, because when I selected to create a new Maven Project: the default workspace loaction is ticked and directly proceeding it is the grayed out \"Location\" text input had the workspace location + the existing project I was looking at before choose to create a new Maven Project. (ie: Location = '[workspace path]/last looked at project')So I unticked the default workspace location box and entered in '[workspace path]/new project', which didn't work because eclipse expects the [workspace path] to be different compared to the default path. (Otherwise we would of selected the default workspace check box). In my case clicking the checkbox for 'import project into workspace' fixed the error, even though the project was already in the workspace folder and didn't actually get moved their by eclipse.FWIW:Neither of the other suggestions worked for me. I had previously created a project with the same name which I then deleted. I recreated the base source-files (using PhoneGap) - which doesn't create the \"eclipse\"-project. I then tried to create an Android project using existing source files, but it failed with the same error message as the original question implies. The solution for me was to move the source-folder and files out of the workspace, and use the same option, but this time check the option for copying the files into the workspace in the wizard.I know this is older, but wanted to contribute another possibly solution.If you want to keep the project location, as I did, I found that copying the .project file from another project into the project's directory, then editing the .project file to name it properly, then choosing the Import Existing Projects into Workspace option worked for me.In Windows, I used a file monitor to see what Eclipse was doing, and it was simply erroring out for some unknown reason when trying to create the .project file. So, I did that manually and it worked for me.If the project type isn't recognized, preventing one of these import methods from working, then try this.  Once you add the generic project, you can then add support for whatever language you require.
Java

There are discussions around  vs  in Java. The default value of the former is  while in the latter it's . How about  vs ? A variable in my application can have / values. I would like to use / and prefer not to use . Can I use / instead? you can use / instead.First one is Object and second one is primitive type.Now choose your way.  the boolean primitive type. In JDK 5 and upwards, Oracle (or Sun before Oracle bought them) introduced , which essentially allows you to do thisorWhich essentially the compiler does, So, for your answer, it's YES.I am a bit extending provided answers (since so far they concentrate on their \"own\"/artificial terminology focusing on programming a particular language instead of taking care of the bigger picture behind the scene of , in general, i.e. when things like type-safety vs. memory considerations make the difference):Consider with outputJava code on 3rd line  illustrates that  () cannot be implicitly converted (casted) into an . I am bringing this up not to illustrate the details of implementation behind JVM, but to point out that in terms of low level considerations (as memory size) one does have to prefer values over type safety. Especially if that type safety is not truly/fully used as in boolean types where checks are done in form of All just to state that {0,1} < {-2^31, .. , 2^31 -1}. Seems like an overkill, right? Type safety is truly important in user defined types, not in implicit casting of primitives (although last are included in the first).Note that in memory your variable from range of {0,1} will still occupy at least a byte or a word (xbits depending on the size of the register) unless specially taken care of (e.g. packed nicely in memory - 8 \"boolean\" bits into 1 byte - back and forth).By preferring type safety (as in putting/wrapping value into a box of a particular type) over extra value packing (e.g. using bit shifts or arithmetic), one does effectively chooses writing less code over gaining more memory. (On the other hand one can always define a custom user type which will facilitate all the conversion not worth than Boolean).Finally, your question is about comparing  vs. . I believe it is important to explain why or how exactly you will get performance by using/preferring keywords (\"marked\" as ) over types (normal composite user-definable classes using another keyword )\nor in other wordsvs.The first \"thing\" (type) can not be extended (subclassed) and not without a reason. Effectively Java terminology of  and   classes can be simply translated into  value (a LITERAL or a constant that gets directly substituted by compiler whenever it is possible to infer the substitution or  if not - still fallback into wrapping the value). Optimization is achieved due to trivial:That is why when the actual type inference is done it may (still) end up in instantiating of wrapping class with all the type information if necessary (or converting/casting into such).So, the difference between  and  is exactly in  and  (a bit far going but almost as  vs. ). Note the fact that Java can do  is just a \"syntactic sugar\". It does not speed up anything, just allows you to write less code. That's it. Casting and wrapping into type information container is still performed. For performance reasons choose arithmetics which will always skip extra housekeeping of creating class instances with type information to implement type safety. Lack of  is the price you pay to gain performance. For code with boolean-valued expressions type safety (when you write less and hence  code) would be critical e.g. for if-then-else flow controls.You can use the  -  and  instead of  and . You can create your variable as of type  if primitive is what you are after. This way you won't have to create new  objects.  Basically boolean represent a primitive data type where Boolean represent a reference data type. this story is started when Java want to become purely object oriented it's provided wrapper class concept to over come to use of primitive data type. and  are not same.The java.lang.Boolean class wraps a value of the primitive type boolean in an object. An object of type Boolean contains a single field whose type is booleanFollowing is the declaration,\npublic final class Boolean\n   extends Object\n      implements Serializable, Comparable
Java

In the context of security frameworks, a few terms commonly occur ,  and , of which I have not been able to find a clear definition and the difference between them. So, what exactly do these terms mean, and why are these distinctions of  and  needed?These are hierarchical in the way that genus, species and individual are hierarchical.Subject/Object inherits from the same terms as used in grammar.  In a sentence the subject is the actor and the object is the thing acted on.  In this sense the use has been around since before computers were invented.  In a security context, a subject is anything that can make a request.  As noted above, this need not be limited to IT security and so is a very broad classification.  The interesting thing is that subject implies object.  Without an object, there is no subject.Principals are what subjects resolve to.  When you present your credit card you are the subject and the account number is the principal.  In other contexts your user ID or state-issued identification is your principal.  But principals can be associated with many types of subject that are not people.  When applications make requests for system-level functions the principal may the signer of a signed executable code module but even in that case the user driving the request is still the subject.User is more specific than subject or principal in that it usually refers to an interactive operator.  That is why we have a graphical User Interface and not a Graphical Principal Interface.  A user is an instance of  that resolves to a .  A single user may resolve to any number of principals but any principal is expected to resolve to a single user (assuming people observe the requirement not to share IDs).  In the example above, the signer of an executable code module is definitely  the user, but it  a valid principal.  The interactive operator trying to get the module loaded is the user.As noted in the comments, even the authoritative sources do not agree on these terms.  I searched NIST, SANS, IEEE, MITRE and several \"quasi-authoritative\" sources such as security exam guides while preparing this response. No single source that I found which was at least quasi-authoritative covered all three terms and all differed significantly in their usage.  This is my take on how the terms  be used but from a practical standpoint, when you are poring over a manual in the middle of the night, the definitions tend to be whatever the vendor or writer say they are.  Hopefully though responses here will provide enough insight to navigate the waters and parse any security document using these terms.Have a look at my :I think the terminology is taken from . is the entity that requests a service. It can be a user or a process. Probably that is why the name Subject was chosen instead of user. When a subject tries to access a service, the subject has to be authenticated first. Successful authentication ends with loading the  for that Subject. For example, in a Role Based Access Control system, an authenticated (logged-in) user will usually have two principals - userId and roleId. In such systems, the privileges(i.e who can access what) are specified for both roles and for users. During authorization(i.e checking whether the requested service should be permitted), the security system will check for accessibility against both the principals. Therefore, from the perspective of authorization, principals are the actual entities for which access is allowed or disallowed. Subject is just a user/thread/process that holds some principals. As T.Rob explained, Subject is any entity that requests access to an object. Starting from that point I've found a comment on javax.security.auth.Subject code that i've found VERY useful and easy to understand:\"Subjects may potentially have multiple identities. Each identity is represented as a Principal within the Subject. Principals simply bind names to a Subject. For example, a Subject that happens to be a person, Alice, might have two Principals: one which binds \"Alice Bar\", the name on her driver license, to the Subject, and another which binds, \"999-99-9999\", the number on her student identification card, to the Subject. Both Principals refer to the same Subject even though each has a different name.\"Hope it helps.
Java

It's been a while from those school years. Got a job as IT specialist at a hospital.  Trying to move to do some actual programming now.  I'm working on binary trees now, and I was wondering what would be the best way to determine if the tree is height-balanced.  I was thinking of something along this:Is this a good implementation? or am I missing something?Stumbled across this old question while searching for something else. I notice that you never did get a complete answer.The way to solve this problem is to start by writing a specification for the function you are trying to write.Specification: A well-formed binary tree is said to be \"height-balanced\" if (1) it is empty, or (2) its left and right children are height-balanced and the height of the left tree is within 1 of the height of the right tree.Now that you have the specification, the code is trivial to write. Just follow the specification:Translating that into the programming language of your choice should be trivial.Bonus exercise: this naive code sketch traverses the tree far too many times when computing the heights. Can you make it more efficient?Super bonus exercise: suppose the tree is  unbalanced. Like, a million nodes deep on one side and three deep on the other. Is there a scenario in which this algorithm blows the stack? Can you fix the implementation so that it never blows the stack, even when given a massively unbalanced tree?UPDATE: Donal Fellows points out in his answer that there are different definitions of 'balanced' that one could choose. For example, one could take a stricter definition of \"height balanced\", and require that the path length to the  empty child is within one of the path to the  empty child. My definition is less strict than that, and therefore admits more trees. One can also be less strict than my definition; one could say that a balanced tree is one in which the maximum path length to an empty tree on each branch differs by no more than two, or three, or some other constant. Or that the maximum path length is some fraction of the minimum path length, like a half or a quarter.It really doesn't matter usually. The point of any tree-balancing algorithm is to ensure that you do not wind up in the situation where you have a million nodes on one side and three on the other. Donal's definition is fine in theory, but in practice it is a pain coming up with a tree-balancing algorithm that meets that level of strictness. The performance savings usually does not justify the implementation cost. You spend a lot of time doing unnecessary tree rearrangements in order to attain a level of balance that in practice makes little difference. Who cares if sometimes it takes forty branches to get to the farthest leaf in a million-node imperfectly-balanced tree when it could in theory take only twenty in a perfectly balanced tree? The point is that it doesn't ever take a million. Getting from a worst case of a million down to a worst case of forty is usually good enough; you don't have to go all the way to the optimal case. Balance is a truly subtle property; you think you know what it is, but it's so easy to get wrong. In particular, even Eric Lippert's (good) answer is off. That's because the notion of  is not enough. You need to have the concept of minimum and maximum heights of a tree (where the minimum height is the least number of steps from the root to a leaf, and the maximum is... well, you get the picture). Given that, we can define balance to be:(This actually implies that the branches are themselves balanced; you can pick the same branch for both maximum and minimum.)All you need to do to verify this property is a simple tree traversal keeping track of the current depth. The first time you backtrack, that gives you a baseline depth. Each time after that when you backtrack, you compare the new depth against the baselineIn code:I suppose you could do this without using the Observer pattern, but I find it easier to reason this way.[EDIT]: Why you can't just take the height of each side. Consider this tree:OK, a bit messy, but each side of the root is balanced:  is depth 2, , , ,  are depth 3, and , , ,  are depth 4. The height of the left branch is 2 (remember the height decreases as you traverse the branch), the height of the right branch is 3. Yet the overall tree is  balanced as there is a difference in height of 2 between  and . You need a minimax specification (though the actual algorithm can be less complex as there should be only two permitted heights).This only determines if the top level of the tree is balanced. That is, you could have a tree with two long branches off the far left and far right, with nothing in the middle, and this would return true. You need to recursively check the  and  to see if they are internally balanced as well before returning true.Bonus exercise response.  The simple solution.  Obviously in a real implementation one might wrap this or something to avoid requiring the user to include height in their response.Post order solution, traverse the tree only once. Time complexity is O(n), space is O(1), it's better than top-down solution. I give you a java version implementation.The definition of a height-balanced binary tree is:So,\nAn empty binary tree is always height-balanced. \nA non-empty binary tree is height-balanced if:Consider the tree:As seen the left subtree of  is height-balanced (as it is empty) and so is its right subtree. But still the tree is not height-balanced as condition 3 is not met as height of left-subtree is  and height of right sub-tree is .Also the following tree is not height balanced even though the height of left and right sub-tree are equal. Your existing code will return true for it.So the word  in the def is very important.This will work:This is being made way more complicated than it actually is.The algorithm is as follows:What balanced means depends a bit on the structure at hand.  For instance, A B-Tree cannot have nodes more than a certain depth from the root, or less for that matter, all data lives at a fixed depth from the root, but it can be out of balance if the distribution of leaves to leaves-but-one nodes is uneven.  Skip-lists Have no notion at all of balance, relying instead on probability to achieve decent performance.  Fibonacci trees purposefully fall out of balance, postponing the rebalance to achieve superior asymptotic performance in exchange for occasionally longer updates.  AVL and Red-Black trees attach metadata to each node to attain a depth-balance invariant. All of these structures and more are present in the standard libraries of most common programming systems (except python, RAGE!).  Implementing one or two is good programming practice, but its probably not a good use of time to roll your own for production, unless your problem has some peculiar performance need not satisfied by any off-the-shelf collections.Note 1: The height of any sub-tree is computed only once.Note 2: If the left sub-tree is unbalanced then the computation of the right sub-tree, potentially containing million elements, is skipped.Balancing usually depends on the length of the longest path on each direction. The above algorithm is not going to do that for you.What are you trying to implement? There are self-balancing trees around (AVL/Red-black).\nIn fact, Java trees are balanced. If this is for your , I suggest:If binary tree is balanced or not can be checked by Level order traversal:Here is a complete worked out tested solution in C# (sorry I'm no java dev) (just copy paste in console app).\nI know that definition of balanced varies so not everyone may like my test results but please just look at the slightly different approach of checking depth/height in a recursive loop and exiting on the first mismatch without saving node height/level/depth on each node (only maintaining it in a function call).Well, you need a way to determine the heights of left and right, and if left and right are balanced.And I'd just As to writing a  function, read:\nWhat kind of tree are you talking about? There are  trees out there. Check their algorithms where they determine if they need to reorder the tree in order to maintain balance.Here is a version based on a generic depth-first traversal. Should be faster than the other correct answer and handle all the mentioned \"challenges.\" Apologies for the style, I don't really know Java.You can still make it much faster by returning early if max and min are both set and have a difference >1.Here's what i have tried for Eric's bonus exercise.\nI try to unwind of my recursive loops and return as soon as I find a subtree to be not balanced.An empty tree is height-balanced. A non-empty binary tree T is balanced if:1) Left subtree of T is balanced2) Right subtree of T is balanced3) The difference between heights of left subtree and right subtree is not more than 1.Time Complexity: O(n)To have a better performance specially on huge trees you can save the height in each node so it is a trade off space Vs performance:Example of implementing the addition and same for deletion Wouldn't this work?Any unbalanced tree would always fail this.
Java

AssumingI was wondering if doing:is equivalent toor on the other hand it meansFrom the Java Language Specification - .So  is equivalent to .(In some usages, the type-casting makes a difference to the result, but in this one  has to be  and the type-cast does nothing.)In practice, there is little difference between  and .  If  is a variable or a constant, the result is going to be the same for both versions.  There is only a semantic difference when the evaluation of  can have side-effects; i.e. when it is a non-trivial subexpression.On the performance side, the trade-off is between the cost of evaluating , and the cost of a test and branch of the value of , and the potential saving of avoiding an unnecessary assignment to .  The analysis is not straight-forward, but unless the cost of calculating  is non-trivial, the potential performance difference between the two versions is likely to be too small to be worth considering.see .  For boolean operands, the  operator is boolean, not bitwise.  The only difference between  and  for boolean operands is that for  it is short circuited (meaning that the second operand isn't evaluated if the first operand evaluates to false).So in your case, if  is a primitive, , , and  all do the same thing.It's the last one:i came across a similar situation using booleans where I wanted to avoid calling b() if a was already false.This worked for me:
Java

I marked a method with jUnit's @BeforeClass annotation, and got this exception saying it must be static. What's the rationale? This forces all my init to be on static fields, for no good reason as far as I see.In .Net (NUnit), this is not the case. - the fact that a method annotated with @BeforeClass runs only once has nothing to do with it being a static method - one can have a non-static method run only once (as in NUnit).JUnit  creates one instance of the test class for each @Test method.  to make it easier to write tests without side-effects. Good tests do not have any order-of-run dependencies (see ) and creating fresh instances of the test class and its instance variables for each test is crucial in achieving this. Some testing frameworks reuse the same test class instance for all tests, which leads to more possibilities of accidentally creating side-effects between tests.And because each test method has its own instance, it makes no sense for the @BeforeClass/@AfterClass methods to be instance methods. Otherwise, on which of the test class instances should the methods be called? If it would be possible for the @BeforeClass/@AfterClass methods to reference instance variables,  - the rest would have the instance variables at their default values - and the @Test method would be randomly selected, because the order of methods in the .class file is unspecified/compiler-dependent (IIRC, Java's reflection API returns the methods in the same order as they are declared in the .class file, although also that behaviour is unspecified - I have written  for actually sorting them by their line numbers).So enforcing those methods to be static is the only reasonable solution.Here is an example:Which prints:As you can see, each of the tests is executed with its own instance. What JUnit does is basically the same as this:The short answer is this:  In fact, making it static causes all sorts of problems if you use Junit to execute DBUnit based DAO integration tests.  The static requirement interferes with dependency injection, application context access, resource handling, logging, and anything that depends on \"getClass\".JUnit documentation seems scarce, but I'll guess: perhaps JUnit creates a new instance of your test class before running each test case, so the only way for your \"fixture\" state to persist across runs is to have it be static, which can be enforced by making sure your fixtureSetup (@BeforeClass method) is static.there are two types of annotations:so @BeforeClass must be declared static because it is called once. You should also consider that being static is the only way to ensure proper \"state\" propagation between tests (JUnit model imposes one test instance per @Test) and, since in Java only static methods can access static data... @BeforeClass and @AfterClass can be applied only to static methods. This example test should clarify @BeforeClass vs @Before usage:output:I've created a bug tracker entry for this:Seems like nobody had reported this design flaw before ...found a nice workaround called class initializer:it works just like the static{} initializer which runs when the class gets initialized. It seems that JUnit creates a new instance of the test class for each test method. Try this code out The output is \n0\n0\n0This means that if the @BeforeClass method is not static then it will have to be executed before each test method and there would be no way to differentiate between the semantics of @Before and @BeforeClass Though this won't answer the original question. It will answers the obvious follow up. How to create a rule that works before and after a class and before and after a test.To achieve that you can use this pattern:On before(Class) the JPAConnection creates the connection once on after(Class) it closes it. returns an inner class of  that implements jpa's EntityManager and can access the connection inside the . On before (test) it begins a transaction on after (test) it rolls it back again.This isn't thread-safe but can be made to be so.Selected code of To resolve this issue just change the method to and all that are defined in this method to .
Java

I'm surprised at how it is possible to continue execution even after a  has occurred in Java.I know that  is a sublass of the class Error.\nThe class Error is decumented as \"a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch.\"This sounds more like a recommendation than a rule, subtending that catching a Error like a StackOverflowError is in fact permitted and it's up to the programmer's reasonability not to do so. And see, I tested this code and it terminates normally.How can this be? I think by the time the StackOverflowError is thrown, the stack should be so full that there is no room for calling another function. Is the error handling block running in a different stack, or what is going on here?When the stack overflows and  is thrown, the usual exception handling unwinds the stack. Unwinding the stack means:... until the exception is caught. This is normal (in fact, necessary) and independent of which exception is thrown and why. Since you catch the exception outside of the first call to , the thousands of  stack frames that filled the stack have all been unwound and most of the stack is free to be used again.When the StackOverflowError is thrown, the stack is full. However, when it's , all those  calls have been popped from the stack.  can run normally because the stack is no longer overflowing with s. (Note that I don't think the JLS guarantees you can recover from a stack overflow like this.)When the StackOverFlow occurs, the JVM will pop down to the catch, freeing the stack.\nIn you example, it get rids of all the stacked foo.Because the stack doesn't actually overflow.  A better name might be AttemptToOverflowStack.  Basically what it means is that the last attempt to adjust the stack frame errs because there isn't enough free space left on the stack. The stack could actually have lots of space left, just not enough space.  So, whatever operation would have depended upon the call succeeding (typically a method invocation), never gets exectued and all that is left is for the program to deal with that fact.  Which means that it is really no different from any other exception.  In fact, you could catch the exception in the function that is making the call.
Java

Basically I would like to decode a given Html document, and replace all special chars, such as  -> ,  -> .In .NET we can make use of . What's the equivalent function in Java?I have used the Apache Commons  for this:I tried Apache Commons StringEscapeUtils.unescapeHtml3() in my project, but wasn't satisfied with its performance. Turns out, it does a lot of unnecessary operations. For one, it allocates a StringWriter for every call, even if there's nothing to unescape in the string.  I've rewritten that code differently, now it works much faster. Whoever finds this in google is welcome to use it.Following code unescapes all HTML 3 symbols and numeric escapes (equivalent to Apache unescapeHtml3). You can just add more entries to the map if you need HTML 4.The libraries mentioned in other answers would be fine solutions, but if you already happen to be digging through real-world html in your project, the  project has a lot more to offer than just managing  things.And you also get the convenient API for extracting and manipulating data, using the best of DOM, CSS, and jquery-like methods.  It's open source and MIT licence.The following library can also be used for HTML escaping in Java: .HTML can be unescaped this way:A very simple but inefficient solution without any external library is:This should be use only if you have only small count of string to decode.Consider using the  Java class. You may need to add some items (not all entities are in the list). The Apache Commons StringEscapeUtils as suggested by Kevin Hakanson did not work 100% for me; several entities like &#145 (left single quote) were translated into '222' somehow. I also tried org.jsoup, and had the same problem.This did the job for me,Hope this helps :)In my case i use the replace method by testing every entity in every variable, my code looks like this:In my case this worked very well.Incase you want to mimic what php function htmlspecialchars_decode does use php function get_html_translation_table() to dump the table and then use the java code like,
Java

I have a blob column in my database table, for which I have to use  in my Java program as a mapping and to use this data I have to convert it to  or . But I don't know what happens internally when I do so. Can anyone briefly explain me what's happening when I do this conversion?You create and use byte array I/O streams as follows:Assuming that you are using a JDBC driver that implements the standard  (not all do), you can connect a InputStream or OutputStream to a blob using the getBinaryStream and setBinaryStream methods, and you can also get and set the bytes directly.(In general, you should take appropriate steps to handle any exceptions, and close streams.  However, closing  and  in the example above is unnecessary, since they aren't associated with any external resources; e.g. file descriptors, sockets, database connections.)I'm assuming you mean that 'use' means read, but what i'll explain for the read case can be basically reversed for the write case.so you end up with a byte[]. this could represent any kind of data which may need special types of conversions (character, encrypted, etc). let's pretend you want to write this data as is to a file.firstly you could create a  which is basically a mechanism to supply the bytes to something in sequence.then you could create a  for the file you want to create. there are many types of InputStreams and OutputStreams for different data sources and destinations.lastly you would write the InputStream to the OutputStream. in this case, the array of bytes would be sent in sequence to the FileOutputStream for writing. For this i recommend using and in reverseif you use the above code snippets you'll need to handle exceptions and i recommend you do the 'closes' in a finally block.There is no conversion between InputStream/OutputStream and the bytes they are working with. They are made for binary data, and just read (or write) the bytes one by one as is.A conversion needs to happen when you want to go from byte to char. Then you need to convert using a character set. This happens when you make String or Reader from bytes, which are made for character data.we can convert byte[] array into input stream by using ByteArrayInputStreamFor full example please check here I do realize that my answer is way late for this question but I think the community would like . I think this is better since you already have an existing OutputStream in the response object.\nno need to create a new OutputStream.
Java

I doubt if there is a way to make compile-time conditions in Java like #ifdef #ifndef in C++.My problem is that have an algorithm written in Java, and I have different running time improves to that algorithm. So I want to measure how much time I save when each improve is used.Right now I have a set of boolean variables that are used to decide during the running time which improve should be used and which not. But even testing those variables influences the total running time.  So I want to find out a way to decide during the compilation time which parts of the program should be compiled and used.  Does someone knows a way to do it in Java. Or maybe someone knows that there is no such way (it also would be useful).Conditionals like that shown above are evaluated at compile time. If instead you use thisThen any conditions dependent on enableFast will be evaluated by the JIT compiler. The overhead for this is negligible.javac will not output compiled code that is unreachable. Use a final variable set to a constant value for your  and a normal  statement for the .You can use javap to prove that the unreachable code isn't included in the output class file. For example, consider the following code: gives the following output, indicating that only one of the two paths was compiled in (and the if statement wasn't):I think that I've found the solution, It's much simpler.\nIf I define the boolean variables with \"final\" modifier Java compiler itself solves the problem. Because it knows in advance what would be the result of testing this condition.\nFor example this code:runs about 3 seconds on my computer.\nAnd this oneruns about 1 second. The same time this code takesNever used it, but this existsIf you really need conditional compilation and you use , you might be able to filter your code and do a search-and-replace in it.For example: In the same manner you can, for example, write a filter to replace  with . This would still execute faster than  stuff, not to mention being more concise at the same time.If you use , there is a similar feature described .Use the Factory Pattern to switch between implementations of a class?  The object creation time can't be a concern now could it? When averaged over a long running time period, the biggest component of time spent should be in the main algorithm now wouldn't it?Strictly speaking, you don't really need a preprocessor to do what you seek to achieve.  There are most probably other ways of meeting your requirement than the one I have proposed of course.
Java

I am doing a https post and I'm getting an exception of ssl exception Not trusted server certificate. If i do normal http it is working perfectly fine. Do I have to accept the server certificate somehow?I'm making a guess, but if you want an actual handshake to occur, you have to let android know of your certificate.  If you want to just accept no matter what, then use this pseudo-code to get what you need with the Apache HTTP Client:CustomSSLSocketFactory:FullX509TrustManager is a class that implements javax.net.ssl.X509TrustManager, yet none of the methods actually perform any work, get a sample .Good Luck!This is what I am doing. It simply doesn't check the certificate anymore.andWhile trying to answer this question I found a better tutorial.  With it you don't have to compromise the certificate check.*I did not write this but thanks to Bob Lee for the workYou can also look at my blog article, very similar to crazybobs.This solution also doesn't compromise certificate checking and explains how to add the trusted certs in your own keystore.Courtesy Maduranga When developing an application that uses https, your test server doesn't have a valid SSL certificate. Or sometimes the web site is using a self-signed certificate or the web site is using free SSL certificate. So if you try to connect to the server using Apache , you will get a exception telling that the \"peer not authenticated\". Though it is not a good practice to trust all the certificates in a production software, you may have to do so according to the situation.\nThis solution resolves the exception caused by \"peer not authenticated\".But before we go to the solution, I must warn you that this is not a good idea for a production application. This will violate the purpose of using a security certificate. So unless you have a good reason or if you are sure that this will not cause any problem, don't use this solution.Normally you create a  like this.But you have to change the way you create the HttpClient.First you have to create a class extending .Then create a method like this.Then you can create the .If you are trying to send a post request to a login page the rest of the code would be like this.You get the html page to the InputStream. Then you can do whatever you want with the returned html page.But here you will face a problem. If you want to manage a session using cookies, you will not be able to do it with this method. If you want to get the cookies, you will have to do it via a browser. Then only you will receive cookies.If you are using a StartSSL or Thawte certificate, it will fail for Froyo and older versions. You can use a  instead of trusting every certificate.None of these worked for me (aggravated by the  as well). Eventually I got it fixed with  and Any of this answers didn't work for me so here is code which trust any certificates.I don't know about the Android specifics for ssl certificates, but it would make sense that Android won't accept a self signed ssl certificate off the bat. I found this post from android forums which seems to be addressing the same issue:\nThis is a known problem with Android 2.x. I was struggling with this problem for a week until I came across the following question, which not only gives a good background of the problem but also provides a working and effective solution devoid of any security holes.For some reason the solution mentioned for httpClient above didn't worked for me. At the end I was able to make it work by correctly overriding the method when implementing the custom SSLSocketFactory class.This is how it worked perfectly for me. You can see the full custom class and implementing on the following thread:\nI make this class and foundin you code white thisSources that helped me get to work with my self signed certificate on my AWS Apache server and connect with HttpsURLConnection from android device:\n - amazon tutorial on ssl\n - creating your own trust manager on client for accepting your certificate\n - easy script for creating your certificatesThen I did the following:Just use this method as your HTTPClient:
Java

I want to use leiningen to build and develop my clojure project. Is there a way to modify project.clj to tell it to pick some jars from local directories?I have some proprietary jars that cannot be uploaded to public repos.Also, can leiningen be used to maintain a \"lib\" directory for clojure projects? If a bunch of my clojure projects share the same jars, I don't want to maintain a separate copy for each of them.ThanksYou could put your private jars in  and they'd be on the classpath for the purposes of  and the like; this does seem to defeat the point of using a dependency management tool, though if you don't actually  those dependencies managed, you could treat Leiningen as an \"open source dependencies management tool\" and maybe be careful with .As the situation becomes more complex -- there's a larger number of private jars involved, they evolve and you need to take some versioning info on them into account -- Arthur's idea of creating a private Maven repo may be more appropriate.Also, as of yet, there is no universal agreement on the question of which is the best build tool for Clojure, and Leiningen, while gaining in mindshare, is also constantly gaining in the areas features and polish -- meaning, in particular, that it's not yet complete. Here's a quote from Stuart Halloway, the author of Pragmatic Bookshelf's \"Programming Clojure\": \"My 2c: Leiningen is an important step, but there is still plenty to do.\" For the full posting and a very interesting discussion re: build tools and the like in Clojure space, see the  thread on the Clojure Google group. Many participants specifically mention the need to have local dependencies not contained in any repositories, local or otherwise, and elaborate on the solutions they've come up with for such scenarios. Perhaps you could see if there's anything over there which can solve your problem now / might solve it in the future, when feature sets mature?Anyway, it is possible that Leiningen may not in fact have a good story ready yet for some complex scenarios. If you feel this may be true of your case (and I mean after you consider the private repo idea), here's some links to maven-based alternatives taken from the above mentioned thread: , ;  aims to be useful to people trying to use maven with Clojure. As I recall, Meikel Brandmeyer (also on SO under his online handle of kotarak) uses Gradle (a Groovy build system) with a plugin to accomodate Clojure called Clojuresque; I never tried it myself, as don't know the first thing about Groovy, but he claims to run a very nice building act with it and I believe it's got nothing to do with maven -- something which is a plus in and of itself for some of us. :-)Just use  in your project.clj file. I use it, e.g. to connect to Siebel servers. Just created a  directory in my project directory and copied the jar files in there. But of course you could use a more generic directory:Then from the  I can create Siebel Data Bean instances, e.g.If you have a newer Java version you can of course use wildcards in your path specification like this for a more general directory: The warning can be ignored, since the jar will be checked into the project and not downloaded from the internet.Original source:  (changed since copying)I find  works well when developing libraries. Do this in the library being developed and your application requiring it will use it without any  foo required.Alternatively,  is slightly more concise.This allows calling the library like any other I believe the \"correct\" approach is to  so that you can store the jars in a single location and all your branches etc will pick up the changes. This may be overkill for what your doing. I'm curious if these is an easier way.You may like to use the plugin : A recent development is Phil's  plugin for Leiningen: This should allow you to publish artifacts to a private remote repo.Maybe have a look at this , I provide step by step instructions to setup a repository local to the project (accessed through ) in which you could install your jars.Try my solution how to build jar file with dependencies \nNone of these solutions worked me. Instead I have installed a local repository, and used maven to install the jar file in the local repo, and added the local repo to my project.cljIn command line:And I write my project.clj like this:Hope it helps.[REFERENCE:  ]
Java

Is there a way to extract the source code from an executable .jar file (Java ME)? Use . Open the application, drag and drop your JAR file into it.You can extract a jar file with the command :References : I believe this can be done very easily. You can always extract the source files (Java files) of a jar file into a zip.Hope this helps.The link is dead due to some reason so adding the link from where you can download the Your JAR may contain source and javadoc, in which case you can simply use  to extract them.Otherwise you can use a decompiler as mentioned in adarshr's answer:I know it's an old question Still thought it would help someone1) Go to your jar file's folder.2) change it's extension to .zip.3) You are good to go and can easily extract it by just double clicking it.  I tested this in MAC, it works. Hopefully it will work on windows too.AndroChef Java Decompiler produces very good code that you can use directly in your projects...-Covert .jar file to .zip (In windows just change the extension)\n-Unzip the .zip folder \n-You will get complete .java files is a Java decompiler website.Just upload your  and Bingo!!! Get your source code.P.S : This saved my entire week's efforts..suppose your JAR file is in C:\\Documents and Settings\\mmeher\\Desktop\\jar and the JAR file name is xx.jar, then write the below two commands in command prompt:1> cd C:\\Documents and Settings\\mmeher\\Desktop\\jar 2> jar xf xx.jarAbove tools extract the jar. Also there are certain other tools and commands to extract the jar.\nBut AFAIK you cant get the java code in case code has been obfuscated.
Java

Is it possible to iterate through  object using Iterator?Not with an iterator.For , you can do:For , you can do:You can use the  method and use a classical  loop.
Java

Currently whenever I need to create stream from an array, I doIs there some direct way to create stream from an array?You can use Arrays.stream E.g.You can also use  as mentioned by @fge , which looks likeBut note  will return  whereas  will return  providing you pass an array of type . So in a nutshell for primitives type you can observe the difference between 2 methods E.g.When you pass primitive array to , the following code is invokedand when you pass primitive array to  the following code is invokedHence you get different results.: As mentioned by  comment\nThe subrange overload of  is preferable to using  because the former results in a SIZED stream whereas the latter does not. The reason is that  doesn't know whether the size is m or less than m, whereas  does range checks and knows the exact size of the stream\nYou can read the source code for stream implementation returned by   , whereas for stream implementation returned by  is within .Alternative to @sol4me's solution:Of the difference between this and : it  make a difference if your array is of a primitive type. For instance, if you do:where  is a , it will return a . , on the other hand, will return a  with a single element.Or, if you are already have an array, you can also do For primitive types use  or  etc.You can make it also by low level method which has parallel option:
Java

I have some big (more than 3 fields) Objects which can and should be immutable. Every time I run into that case i tend to create constructor abominations with long parameter lists. It doesn't feel right, is hard to use and readability suffers.It is even worse if the fields are some sort of collection type like lists. A simple  would ease the object creation so much but renders the object mutable.What do you guys use in such cases? I'm on Scala and Java, but i think the problem is language agnostic as long as the language is object oriented.Solutions I can think of:Thanks for your input!Well, you want both an easier to read and immutable object once created?I think a fluent interface  would help you.It would look like this (purely made up example):I wrote  in bold because most Java programmers get fluent interfaces wrong and pollute their object with the method necessary to build the object, which is of course completely wrong.The trick is that  (hence you Foo can be immutable).,  and  all create \"something else\".That something else may be a FooFactory, here's one way to do it....You FooFactory would look like this:In Scala 2.8, you could use named and default parameters as well as the  method on a case class. Here's some example code:Well, consider this on Scala 2.8:This does have its share of problems, of course. For instance, try making  and , and then getting two persons married to each other. I can't think of a way to solve that without resorting to either a  and/or a  constructor plus a factory.Here are a couple of more options:Make the implementation itself mutable, but separate the interfaces that it exposes to mutable and immutable. This is taken from the Swing library design.If your application contains a large but pre-defined set of immutable objects (e.g., configuration objects), you might consider using the  framework.You could also make the immutable objects expose methods that look like mutators (like addSibling) but let them return a new instance. That's what the immutable Scala collections do.The downside is that you might create more instances than necessary. It's also only applicable when there exist intermediate valid configurations (like some node without siblings which is ok in most cases) unless you don't want to deal with partially built objects.For example a graph edge which has no destination yet isn't a valid graph edge.Consider four possibilities:To me, each of 2, 3, and 4 is adapted to a difference situation. The first one is hard to love, for the reasons cited by the OP, and is generally a symptom of a design that has suffered some creep and needs some refactoring.What I'm listing as (2) is good when there is no state behind the 'factory', whereas (3) is the design of choice when there is state. I find myself using (2) rather than (3) when I don't want to worry about threads and synchronization, and I don't need to worry about amortizing some expensive setup over the production of many objects. (3), on the other hand, is called forth when real work goes into the construction of the factory (setting up from an SPI, reading configuration files, etc).Finally, someone else's answer mentioned option (4), where you have lots of little immutable objects and the preferable pattern is to get news ones from old ones.Note that I'm not a member of the 'pattern fan club' -- sure, some things are worth emulating, but it seems to me that they take on an unhelpful life of their own once people give them names and funny hats.Another potential option is to refactor to have fewer configurable fields.  If groups of fields only work (mostly) with each other, gather them up into their own small immutable object.  That \"small\" object's constructors/builders should be more manageable, as will the constructor/builder for this \"big\" object.It helps to remember there are . For your case, I think \"popsicle\" immutability will work really well:So you initialize your object, then set a \"freeze\" flag of some sort indicating that its no longer writable. Preferably, you'd hide the mutation behind a function so the function is still pure to clients consuming your API.I use C#, and these are my approaches. Consider: Constructor with optional parametersUsed as e.g. . Not for Java or C# versions before 4.0. but still worth showing, as it's an example how not all solutions are language agnostic. Constructor taking a single parameter objectUsage example: C# from 3.0 on makes this more elegant with object initializer syntax (semantically equivalent to the previous example):\nRedesign your class not to need such a huge number of parameters. You could split its repsonsibilities into multiple classes. Or pass parameters not to the constructor but only to specific methods, on demand. Not always viable, but when it is, it's worth doing.
Java

I have a standalone enum type defined, something like this:Now, I want to inject a value of that type into a bean property:...and that didn't work :(How should I Inject an Enum into a spring bean? Have you tried just \"TYPE1\" ? I suppose spring uses reflection to determine the type of \"type\" anyway, so the fully qualified name seems redundant. I must admit I'm guessing, but spring generally doesn't subscribe to redundancy ;)Use the value child element instead of the value attribute and specify the Enum class name:The advantage of this approach over just writing  is that it also works if Spring can't infer the actual type of the enum from the property (e.g. the property's declared type is an interface).I know this is a really old question, but in case someone is looking for the newer way to do this, use the spring util namespace:As described in the .You can just do \"TYPE1\".This is what did it for me MessageDeliveryMode is the enum the bean will have the value PERSISTENT:Using SPEL and P-NAMESPACE:You can write Bean Editors (details are in the Spring Docs) if you want to add further value and write to custom types.Spring-integration example, routing based on a an Enum field:config:To be specific, set the value to be the name of a constant of the enum type, e.g., \"TYPE1\" or \"TYPE2\" in your case, as shown below. And it will work:
Java

I've got a large-ish class (40 or so methods) that is part of a package I will be submitting as course-work. Currently, the methods are pretty jumbled up in terms of utility public/private etc. and I want to order them in a sensible way. Is there a standard way of doing this? E.g. normally fields are listed before methods, the constructor(s) are listed before other methods, and getters/setters last; what about the remaining methods?Some conventions list all the public methods first, and then all the private ones - that means it's easy to separate the API from the implementation, even when there's no interface involved, if you see what I mean.Another idea is to group related methods together - this makes it easier to spot seams where you could split your existing large class into several smaller, more targeted ones.Source: The more precise link to \u00abCode Conventions\u00bb: Not sure if there is universally accepted standard but my own preferences are;40 methods in a single class is a bit much.Would it make sense to move some of the functionality into other - suitably named - classes.  Then it is much easier to make sense of.When you have fewer, it is much easier to list them in a natural reading order.  A frequent paradigm is to list things either  or  you need them , in the order you need them.This usually means that main() goes on top or on bottom.My \"convention\": static before instance, public before private, constructor before methods, but main method at the bottom (if present). Also, eclipse offers the possibility to sort class members for you, if you for some reason mixed them up:Open your class file, the go to \"Source\" in the main menu and select \"Sort Members\".taken from here: Are you using Eclipse? If so I would stick with the default member sort order, because that is likely to be most familiar to whoever reads your code (although it is not my favourite sort order.)
Java

I am doing Android programming and was learning about Intents, when I saw a constructor that, to my C# trained mind, seemed funky.  The call was: Both of the parameters are new to me.  How is there a static \".this\" off of a Class Name?  Is this a Java thing or an Android thing?  I am assuming that it is the same as just saying \"this\", since I am in the context of , but I don't get how the \"this\" can be called off of the Class name itself.  Also.  The \".class\" looks like it is used for reflection, which I am familiar with in C#, but any insight into this would be welcomed as well.Thanks.Usually, you can use only . But, sometimes  makes reference to an inner class... so, for example:One at a time:The first construct is called a . The purpose of the syntax is in the case where you are in an inner class (typically an anonymous inner class) and you want to reference the  of the outer class rather than the  of the (anonymous) inner class. The \"qualified this\" can only be used in a context where  would be ambiguous. The quote the JLS \"It is a compile-time error if the expression occurs in a class or interface which is not an inner class of class T or T itself\".The second construct is called a  is the way to reference the Class object that represents that type. It can be used in any context.The syntax \"Classname.this\" is for inner classes. If you want to refer to the enclosing instance of type \"Outerclass\" then you do it as \"Outerclass.this\".NextActivity.class is simply the Class object that describes class \"NextActivity\". is used to reference the current instance of an outerclass from an inner class. in java means  in C#is used in nested classes to refer to the current instance of the enclosing class, since the `this' keyword refers to the nest class instance.
Java

I'm working on a fairly big Maven project.  We have probably around 70 or so individual artifacts, which are roughly split into two libraries of shared code and maybe ten applications which use them.  All of these items live in the namespace .Most of the time we're running against snapshot builds.  So to do a full build of an application, I might first build the library projects so that they are installed to my local repository (as, say, ).The problem is that when I then go build the applications.  For some reason, Maven wants to check the main two public repositories (maven-net-repo and java-net-repo) for updates for all of the  artifacts.  Of course, they aren't found there, and everything eventually resolves back to the versions I just built to my local repository, but I'd like Maven to stop doing this because (a) it makes me feel like a bad net.citizen for constantly checking these repositories for things that will never be there, and (b) it adds some unnecessary and annoying network latency into my build process.I've taken to running maven in offline mode most of the time to work around this, but that's not ideal since occasionally a dependency on a public library will be updated.  So what I'm looking for is a solution which will cause Maven not to check for updates from given repositories for artifacts which meet certain criteria - in this case, I'd be happy if Maven would ignore either SNAPSHOT versions or artifacts which were in the  namespace.The updatePolicy tag didn't work for me. However Rich Seller mentioned that snapshots should be disabled anyways so I looked further and noticed that the extra repository that I added to my settings.xml was causing the problem actually. Adding the snapshots section to this repository in my settings.xml did the trick!Also, you can use  or  in the mvn command line which will put maven in \"offline mode\" so it won't check for updates. You'll get some warning about not being able to get dependencies not already in your local repo, but no big deal.Something that is now available in maven as well isor in shortUpdate: I should have probably started with this as your projects are SNAPSHOTs. It is part of the SNAPSHOT semantics that Maven will check for updates on each build. Being a SNAPSHOT means that it is volatile and subject to change so updates should be checked for. However it's worth pointing out that the   configures central to have snapshots disabled, so Maven shouldn't ever check for updates for SNAPSHOTs on central unless you've overridden that in your own pom/settings.You can configure Maven to use a  for the central repository, this will redirect all requests that would normally go to central to your internal repository.In your settings.xml you would add something like this to set your internal repository as as mirror for central:If you are using a repository manager like  for your internal repository. You can set up a  for proxy central, so any requests that would normally go to Central are instead sent to your proxy repository (or a  containing the proxy), and subsequent requests are cached in the internal repository manager. You can even set the proxy cache timeout to -1, so it will never request for contents from central that are already on the proxy repository.A more basic solution if you are only working with local repositories is to set the  for the central repository to \"never\", this means Maven will only ever check for artifacts that aren't already in the local repository. This can then be overridden at the command line when needed by using the -U switch to force Maven to check for updates.You would configure the repository (in your pom or a profile in the settings.xml) as follows:Very simple :In your Super POM parent or setting.xml, useIt's my tipsI had some trouble similar to this,Setting the updatePolicy to \"never\" did not work. Removing these repo was the way I solved it.\nps: I was following this  about web services (btw, probably the best tutorial for ws for java)
Java

How does my java program know where my keystore containing the certificate is? Or alternatively how do I tell my java program where to look for the keystore?After specifying the keystore in some way, how to specify the certificate to use for authenticating the server to client? SSL properties are set at the JVM level via system properties. Meaning you can either set them when you run the program (java -D....) Or you can set them in code by doing System.setProperty. The specific keys you have to set are below: First of all, there're two kinds of keystores. and The application will use the one indicated in the startup or the default of the system.It will be a different folder if JRE or JDK is running, or if you check the personal or the \"global\" one.In short, the path will be like:$JAVA_HOME/lib/security/cacerts for the \"general one\", who has all the CA for the Authorities and is quite important.
Java

This came up as a question I asked in an interview recently as something the candidate wished to see added to the Java language. It's commonly-identified as a pain that Java doesn't have  but, when pushed, the candidate couldn't actually tell me the sort of things that he could have achieved were they there.Obviously because raw types are allowable in Java (and unsafe checks), it is possible to subvert generics and end up with a  that (for example) actually contains s. This clearly could be rendered impossible were type information reified; !Could people post examples of things that , were reified generics available? I mean, obviously you could get the type of a  at runtime - but what would you do with it?: A quick update to this as the answers seem mainly to be concerned about the need to pass in a  as a parameter (for example ). I was looking more for something along the lines of . For example:From the few times that I came across this \"need\", it ultimately boils down to this construct:This does work in C# assuming that  has a  constructor. You can even get the runtime type by  and get the constructors by .The common Java solution would be to pass the  as argument.For all other generic type constructs, the actual type can easily be resolved with a bit help of reflection. The below Q&A illustrate the use cases and possibilities:The thing that most commonly bites me is the inability to take advantage of multiple dispatch across multiple generic types. The following isn't possible and there are many cases where it would be the best solution: comes to mind. Downcasting to a parametrized type will always be unsafe without reified generics:Also,  - at least the ones which may be interested in runtime information about their type parameters. Today, if you need any kind of runtime information about the type of one of the generic parameters you have to pass its  along as well. That way, your external interface depends on your implementation (whether you use RTTI about your parameters or not).You'd be able to create generic arrays in your code.This is an old question, there are a ton of answers, but I think that the existing answers are off the mark.\"reified\" just means real and usually just means the opposite of type erasure.The big problem related to Java Generics:My exposure to Java Geneircs is quite limited, and apart from the points other answers have already mentioned there is a scenario explained in the book , by Maurice Naftalin and Philip Walder, where the reified generics are useful.Since the types are not reifiable, it is not possible to have Parameterized exceptions. For example the declaration of below form is not valid.This is because the  clause checks whether the thrown exception matches a given type. This check is same as the check performed by instance test and since the type is not reifiable the above form of statement is invalid.If the above code was valid then exception handling in the below manner would have been possible:The book also mentions that if Java generics are defined similar to the way C++ templates are \ndefined (expansion) it may lead to more efficient implementation as this offers more \nopportunities for optimization. But doesn't offer any explanation more than this, so any explanation (pointers) from the knowledgeable folks would be helpful.Serialization would be more straightforward with reification.  What we would want isWhat we have to do islooks ugly and works funkily.There are also cases where it would be really helpful to say something likeThese things don't bite often, but they do bite when they happen.Arrays would probably play much nicer with generics if they were reified.I have a wrapper that presents a jdbc resultset as an iterator, (it means I can unit test database-originated operations a lot easier through dependency injection).  The API looks like  where T is some type that can be constructed using only strings in the constructor.  The Iterator then looks at the strings being returned from the sql query and then tries to match it to a constructor of type T.In the current way that generics are implemented, I have to also pass in the class of the objects that I will be creating from my resultset.  If I understand correctly, if generics were reified, I could just call T.getClass() get its constructors, and then not have to cast the result of Class.newInstance(), which would be far neater.Basically, I think it makes writing APIs (as opposed to just writing an application) easier, because you can infer a lot more from objects, and thereby less configuration will be necessary...I didn't appreciate the implications of annotations until I saw them being used in things like spring or xstream instead of reams of config.One nice thing would be avoiding boxing for primitive (value) types.  This is somewhat related to the array complaint that others have raised, and in cases where memory use is constrained it could actually make a significant difference.There are also several types of problems when writing a framework where being able to reflect over the parameterized type is important.  Of course this can be worked around by passing a class object around at runtime, but this obscures the API and places an additional burden on the user of the framework.It's not that you will achieve anything extraordinary. It will just be simpler to understand. Type erasure seems like a hard time for beginners, and it ultimately requires one's understanding on the way the compiler works.My opinion is, that generics are simply  that saves a lot of redundant casting.Here's one that's caught me today: without reification, if you write a method that accepts a varargs list of generic items ... callers can THINK they're typesafe, but accidentally pass in any-old crud, and blow up your method.Seems unlikely that would happen? ... Sure, until ... you use Class as your datatype. At this point, your caller will happily send you lots of Class objects, but a simple typo will send you Class objects that don't adhere to T, and disaster strikes.(NB: I may have made a mistake here, but googling around \"generics varargs\", the above appears to be just what you'd expect. The thing that makes this a practical problem is the use of Class, I think - callers seem to be less careful :( )For instance, I'm using a paradigm that uses Class objects as a key in maps (it's more complex than a simple map - but conceptually that's what's going on).e.g. this works great in Java Generics (trivial example) :e.g. without reification in Java Generics, this one accepts ANY \"Class\" object. And it's only a tiny extension of the previous code :The above methods have to be written out thousands of times in an individual project - so the possibility for human error becomes high. Debugging mistakes is proving \"not fun\". I'm currently trying to find an alternative, but don't hold much hope.
Java

I tried to migrate a project from Eclipse to Android studio. Finally I am able to run it, but at a certain point I got this exception, and I found nothing in google about this:Please advice me if you can.alternative to @sbaar's answer,keep  to  and add as well and set it to .ieRemove from your theme, then make sure you are inheriting from a .NoActionBar Theme, then set your toolbar like normal.Make sure that your theme is child from , then in :Btw, it's a new issue for Support Library 22.1.Check if you call setContentView() after super.onCreate(), and not before. This helped in my case.Use this parent in Style.xml\nparent=\"Theme.AppCompat.Light.NoActionBar\"in my case i didnt change to .NoActionBar Theme. i just remove android prefix from this item.and the error goes away.Make sure thatare at the top of everything this works for me....good luckadd dependency to gradle like thisI solved the issue by my main Activity extending AppCompatActivity :)I had the same problem when I upgraded the library version from 22.0.0 to 22.1.1 and fixed it by dropping back to the previous version: com.android.support:appcompat-v7:22.0.0 and go back to using ActionBarActivity, not AppCompatActivity in my Activity classes as required by the newer version of the compatibility library. I'll try again later.just Use this in your style.xml no other editing is neededdon't add anything in to activity file please leave itIn Java class change  to . It worked for me.In my case, I look for @rewrihitesh answer, and I notice that I . Changing from to Fix my problem.Hope it helps !!if you have added ,\nthen ,you need to addto solve the problem.
Java

If I do this...it printsThe problem is, I am behind a proxy. Where does the JVM get its proxy information from on Windows? How do I set this up? All my other apps seem perfectly happy with my proxy.Since java 1.5 you can also pass a  instance to the  method:If your proxy requires authentication it will give you response 407.In this case you'll need the following code:This is fairly easy to answer from the internet. Set system properties  and . You can do this with , or from the command line with the  syntax.Proxies are supported through two system properties: http.proxyHost and http.proxyPort. They must be set to the proxy server and port respectively. The following basic example illustrates it:Set following before you openConnection,If proxy requires authentication,You can also setOn Windows and Linux this will use the system settings so you don't need to repeat yourself (DRY)The approved answer will work ... if you know your proxy host and port =) . But in case you are looking for the proxy host and port the steps below should helpkudos to bekur from Once you have the host and port just pop in into this and your good to goFor Java 1.8 and higher you must set  to make proxies with Basic Authorization working with https.
Java

For Example I have the date: \"23/2/2010\" (23th Feb 2010). I want to pass it to a function which would return the . How can I do this?In this example, the function should return  \"Tue\".Additionally, if just the day ordinal is desired, how can that be retrieved?Yes.  Depending on your exact case:Use this code for find the Day name from a input date.Simple and well tested.Simply use SimpleDateFormat stufs :)The result is:  . If you want diferent positions just replace it at applyPattern method.But if you want only the day of the week leave it like that:UPDATE: The Joda-Time project is now in maintenance mode. The team advises migrating to the java.time classes. The java.time framework is built into Java 8 (as well as  and ). See the .Here is example code using the  library version 2.4, as mentioned in the . Joda-Time is far superior to the java.util.Date/.Calendar classes bundled with Java.Joda-Time offers the  class to represent a date-only without any time-of-day or time zone. Just what this Question calls for. The old java.util.Date/.Calendar classes bundled with Java lack this concept.Parse the string into a date value.Extract from the date value the day of week number and name. Dump to console.When run.Using  framework built into Java 8 and later.The   can generate a String of the day\u2019s name automatically localized to the human language and cultural norms of a . Specify a  to indicate you want long form or abbreviated name.Another \"fun\" way is to use . It's a way longer method but it's also faster if you don't need to create a Calendar object with a given date.Get the day value by providing the current time stamp.You can try the following code:
Java

How do I add n hours to a Date object?  I found another example using days on StackOverflow, but still don't understand how to do it with hours.Check Calendar class. It has  method (and some others) to allow time manipulation. Something like this should work.Check  for more.If you use , you can do it in one step using :(The original object is unchanged)With To simplify @Christopher's example.Say you have a constantYou can write.If you use  to store date/time instead of the Date object you can doSince Java 8:See .Something like:The java.time framework built into Java 8 and later supplants the old Java.util.Date/.Calendar classes. Those old classes are notoriously troublesome. Avoid them.Use the  method newly added to java.util.Date to convert from the old type to the new java.time type. An  is a moment on the time line in  with a resolution of .You can add hours to that  by passing a  such as . To read that date-time, generate a String in standard ISO 8601 format by calling .You may want to see that moment through the lens of some region\u2019s . Adjust the  into your desired/expected time zone by creating a .Alternatively, you can call  to add your count of hours. Being zoned means Daylight Saving Time (DST) and other anomalies will be handled on your behalf.You should avoid using the old date-time classes including  and . But if you truly need a  for interoperability with classes not yet updated for java.time types, convert from  via . New methods added to the old classes facilitate conversion to/from java.time types.For more discussion on converting, see  to the Question, .The  framework is built into Java 8 and later. These classes supplant the troublesome old  date-time classes such as , , & .The  project, now in , advises migration to java.time.To learn more, see the . And search Stack Overflow for many examples and explanations. Specification is .Where to obtain the java.time classes? The  project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as , , , and .Using the newish  class you can do it like thisThis is another piece of code when your  object is in Datetime format. The beauty of this code is, If you give more number of hours the date will also update accordingly.Here is the Output:You can do it with Joda DateTime APIIf you're willing to use , here's a method to add ISO 8601 formatted durations:You can use this method, It is easy to understand and implement :
Java

Why can't you switch on an enum in Java? It seems simple enough to do and would make for some convenient code. Also this question could apply to 's. You can switch on a , but not a  ...?You definitely can switch on enums. An example posted from the java .You actually can  on s, but you can't  on s until Java 7. You might consider using polymorphic method dispatch with Java s rather than an explicit . Note that s are objects in Java, not just symbols for s like they are in C/C++. You can have a method on an  type, then instead of writing a , just call the method - one line of code: done!First, you can switch on an  in Java. I'm guessing you intended to say you can\u2019t, but you can. s have a set range of values, so it's easy to compare. Strings can be anything.A  statement is usually implemented as a  in the underlying compilation, which is only possible with a finite set of values. C#  switch on strings, but it causes a performance decrease because a jump table cannot be used.Java 7 and later supports  with the same characteristics.You might be using the enums incorrectly in the switch cases. In comparison with the above example by CoolBeans.. you might be doing the following:Make sure that you use the actual enum values instead of EnumType.EnumValueEclipse points out this mistake though..Actually you can use a switch statement with Strings in java...unfortunetly this is a new feature of Java 7 and most people are not using Java 7 yet because it's so new.
Java

According to  the String '\u0967\u0968\u0969' is numeric. Since I believed this might be a mistake in the documentation, I ran tests to verify the statement. I found that according to Apache Commons it is numeric.Why is this String numeric? What are those characters representing?Because that \"CharSequence contains only Unicode digits\" (quoting your ).All of the characters return true for : are Devanagari digits:The symbol  is the same as 123 for the Nepali language or any other language using the  like Hindi, Gujarati...\ntherefore is a number for Apache Commons. :)You can use  to check the character's general category:This will print , which is an \"evidence\" that '\u0967' is a .Now let's examine the unicode value of the '\u0967' character:This number is on the range of  - which is:  through .Also try: is:\"\u0967\u0968\u0969\" is a \"123\" (Basic Latin unicode).Reading:If you ever want to know what properties a particular \"character\" has (and there are quite a few), go directly to the source: . They have research tools that can show you most anything you would care to know. The Unicode Consortium produces a specification, not software. This means that it is up to each software vendor to implement the specification . So just like HTML, JavaScript, CSS, SQL, etc, there is variation between different platforms, languages, and so on. For example, I found a bug in Microsoft's .NET Framework whereby circled Latin letters  and   -- Code Points 0x24B6 through 0x24E9 -- do not properly register as being  (). And that leads to unexpected behavior in related functionality, such as when calling the  method ().Symbols '\u0967\u0968\u0969' are actually derived from Hindi language(Basically from Sanskrit language i.e Devanagiri) which represent numeric values just like:\u0967 represent 1\u0968 represent 2and like wise If you want to know whether a character is a digit or not simply call the utility method  and if you want to know its corresponding name use .So in your case, you could write this simple code to get more information about those specific characters that you don't know:
Java

Apart from the fact that  does not allow duplicate values, what is the difference between  and ?I mean implementation wise? It's a little bit vague because both use  to store values.They are entirely different constructs.  A  is an implementation of .  A  maps keys to values.  The key look up occurs using the hash.On the other hand, a  is an implementation of .  A  is designed to match the mathematical model of a set.  A  does use a  to back its implementation, as you noted.  However, it implements an entirely different interface.When you are looking for what will be the best  for your purposes, this  is a good starting place.  If you truly want to know what's going on, , too.HashSet is a , e.g. HashMap is a  (key to value) map, e.g. Notice in my example above that in the HashMap there must not be duplicate keys, but it may have duplicate values.In the HashSet, there must be no duplicate elements.It's really a shame that both their names start with .  That's the least important part of them.  The important parts come after the  - the  and , as others have pointed out.  What they are, respectively, are a  - an unordered collection - and a  - a collection with keyed access.  They happen to be implemented with hashes - that's where the names come from - but their essence is hidden behind that part of their names.Don't be confused by their names; they are deeply different things.Please refer  to find more information.HashSet allows us to store objects in the set where as HashMap allows us to store objects on the basis of key and value. Every object or stored object will be having key.As the names imply, a   is an associative  (mapping from a key to a value), a  is just a .A  is to add, get, remove, ... objects indexed by a custom key of any type.\nA  is to add elements, remove elements and check if elements are present by comparing their hashes.So a HashMap contains the elements and a HashSet remembers their hashes.Differences:\nwith respect to heirarchy: \nHashSet implements Set.\nHashMap implements Map and stores a mapping of keys and values.A use of HashSet and HashMap with respect to database would help you understand the significance of each.\n\n is generally used for storing unique collection objects.\nE.g: It might be used as implementation class for storing many-to-one relation ship between \n\n is used to map a key to value.the value may be null or any Object /list of Object (which is object in itself).HashSet internally uses HashMap to store objects.when add(String) method called it calls HahsMap put(key,value) method where key=String object & value=new Object(Dummy).so it maintain no duplicates because keys are nothing but Value Object.the Objects which are stored as key in Hashset/HashMap should override hashcode & equals contract. Keys which are used to access/store value objects in HashMap should declared as Final because when it is modified Value object can't be located & returns null.A  is implemented in terms of a .  It's a mapping between the key and a PRESENT object.you pretty much answered your own question - hashset doesn't allow duplicate values. it would be trivial to build a hashset using a backing hashmap (and just a check to see if the value already exists). i guess the various java implementations either do that, or implement some custom code to do it more efficiently.A HashSet uses a HashMap internally to store its entries.  Each entry in the internal HashMap is keyed by a single Object, so all entries hash into the same bucket.  I don't recall what the internal HashMap uses to store its values, but it doesn't really matter since that internal container will never contain duplicate values.:  To address Matthew's comment, he's right; I had it backwards.  The internal HashMap is keyed .  The values of the HashMap are an Object that's just simply stored in the HashMap buckets.   First and most significant difference between HashMap and HashSet is that HashMap is an implementation of Map interface while HashSet is an implementation of Set interface, which means HashMap is a key value based data-structure and HashSet guarantees uniqueness by not allowing duplicates.In reality HashSet is a wrapper around HashMap in Java, if you look at the code of add(E e) method of HashSet.java you will see following code :where its putting  Object into map as key and value is an final object PRESENT which is dummy. Second difference between HashMap and HashSet is that , we use add() method to put elements into Set but we use put() method to insert key and value into HashMap in Java. HashSet allows only one null key, but HashMap can allow one null key + multiple null values.That's all on difference between HashSet and HashMap in Java. In summary HashSet and HashMap are two different type of Collection one being Set and other being Map. HashSet  is implementation of Set Interface which does not allow duplicate value all the methods which are in Collection Framework are also in Set Interface by default but when we are talking about Hash set the main thing is objects which are going to be stored in HashSet must override equals() and hashCode() method so that we can check for equality and no duplicate value are stored in our set.if we have created our own objects we need to implement hashCode() and equal() in such a manner that will be able to compare objects correctly when storing in a set so that duplicate objects are not stored,if we have not override this method objects will take default implementation of this method.\npublic boolean add(Object o)  Method is used to add element in a set which returns false if it\u2019s a duplicate value in case of  HashSet otherwise returns true if added successfully.HashMap is a implementation of Map Interface, which maps a key to value.Duplicate keys are not allowed in a map.Basically map Interface has two implementation classes HashMap and TreeMap the main difference is TreeMap maintains order of the objects but HashMap will not.HashMap allows null values and null keys.HashMap is not synchronized,but collection framework provide methods so that we can make them synchronized if multiple threads are going to access our hashmap and one thread is structurally change our map.\npublic Object put(Object Key,Object value) method is used to add element in map. is a  implementation, allowing  but . For adding an object a Key/Value pair is required. Null Keys and Null values are allowed. eg: is a  implementation,which does .If you tried to add a duplicate object, a call to  method, then the set remains unchanged and returns . eg:1) First and most significant difference between HashMap and HashSet is that HashMap is an implementation of Map interface while HashSet is an implementation of Set interface, which means HashMap is a key value based data-structure and HashSet guarantees uniqueness by not allowing duplicates.In reality HashSet is a wrapper around HashMap in Java, if you look at the code of add(E e) method of HashSet.java you will see following code :where its putting  Object into map as key and value is an final object PRESENT which is dummy.2) Second difference between HashMap and HashSet is that , we use add() method to put elements into Set but we use put() method to insert key and value into HashMap in Java.3) HashSet allows only one null key, but HashMap can allow one null key + multiple null values.That's all on difference between HashSet and HashMap in Java. In summary HashSet and HashMap are two different type of Collection one being Set and other being Map.Basically in HashMap, user has to provide both Key and Value, whereas in HashSet you provide only Value, the Key is derived automatically from Value by using hash function. So after having both Key and Value, HashSet can be stored as HashMap internally. HashSet and HashMap both store  pairs , the difference lies that in HashMap you can specify a key while in HashSet the key comes from object's hash code allow one null key and null values. They are not synchronized, which increases efficiency. If it is required, you can make them synchronized using  don't allow null keys and are synchronized.HashMap  is a implementation of Map interface\nHashSet is an implementation of Set InterfaceHashMap Stores data in form of  key value pair\nHashSet Store only objectsPut method is used to add element in map\nAdd method is used to add element is SetIn hash map hashcode value is calculated using key object\nHere member object is used for calculating hashcode value which can be same for two objects so equal () method is used to check for equality if it returns false that means two objects are different.HashMap is faster than hashset because unique key is used to access object\nHashSet is slower than HashmapThe Hashset Internally implements HashMap. If you see the internal implementation\n on  the values inserted in HashSet are stored as keys in the HashMap and the value is a Dummy object of Object class.\nDifference between HashMap vs HashSet is:-\n1. HashMap contains key value pairs and each value can be accessed by key where as HashSet needs to be iterated everytime as there is no get method.\n2. HashSet implements Map interface and allows one null value as a key and multiple null values as values.Where as HashSet implements Set interface, allows only one null value and no duplicated values.(Remeber one null key is allowed in HashMap key hence one null value in HashSet as HashSet implemements HashMap internally).\n3.HashSet and HashMap does not maintain the order of insertion while iterating.
Java

I have read a lot of stackoverflow questions but none seems to be working for me. i am using  to round off.\nthis is the code:the output i get is:  but i want it to be . i read that adding  will help but as you can see i didn't manage to get it to work.it is absolutely essential for both input and output to be a double.it would be great great help if you change the line 4 of the code above and post it.Output isOr as @Rufein said this will do it for you as well.Go back to your code, and replace  by  and let me know if it works.\nHowever, if you want to be formal, try this:should be Adding 'D' to 100 makes it Double literal, thus result produced will have precisionTry :seems like you are hit by integer arithmetic: in some languages (int)/(int) will always be evaluated as integer arithmetic.\nin order to force floating-point arithmetic, make sure that at least one of the operands is non-integer:Just pass your number to this function as a double, it will return you rounding the decimal value up to the nearest value of 5;if 4.25, Output 4.25if 4.20, Output 4.20if 4.24, Output 4.20if 4.26, Output 4.30if you want to round upto 2 decimal places,then useif up to 3 places, new DecimalFormat(\"#.###\") if up to n places, new DecimalFormat(\"#.\")I know this is 2 year old question but as every body faces a problem to round off the values at some point of time.I would like to share a different way which can give us rounded values to any scale by using  class .Here we can avoid extra steps which are required to get the final value if we use     or using  .This program would give us below outputI just modified your code. It works fine in my system. See if this helpsShould be ok for most cases. You can still changes types if you want to be compliant with doubles for instance.
Java

I'm trying to make sure my Java application takes reasonable steps to be robust, and part of that involves shutting down gracefully. I am reading about  and I don't actually get how to make use of them in practice.Is there a practical example out there?Let's say I had a really simple application like this one below, which writes numbers to a file, 10 to a line, in batches of 100, and I want to make sure a given batch finishes if the program is interrupted. I get how to register a shutdown hook but I have no idea how to integrate that into my application. Any suggestions?You could do the following:Some sketchy code:That's roughly how I do a graceful \"reject all clients upon hitting Control-C\" in terminal.From :That is, a shutdown hook keeps the JVM running until the hook has terminated (returned from the -method.Shutdown Hooks are unstarted threads that are registered with Runtime.addShutdownHook().JVM does not give any guarantee on the order in which shutdown hooks are started.For more info refer 
Java

My question is a variation of .Since my Java Web-app project requires a lot of read filters/queries and interfaces with tools like GridFS, I'm struggling to think of a sensible way to employ MongoDB in the way the above solution suggests.Therefore, I'm considering running an embedded instance of MongoDB alongside my integration tests. I'd like it to  (either for each test or the whole suite),  for every test, and  at the end. These tests might be run on development machines as well as the CI server, so my solution will also need to be .Can anyone with more knowledge on MongoDB help me get idea of the feasibility of this approach, and/or perhaps suggest any reading material that might help me get started?I'm also open to other suggestions people might have on how I could approach this problem...I have found  library which looks quite promising and does what you have asked for. Currently supports MongoDB versions:  to , provided the binaries are still available from the configured mirror.Here is short example of use, which I have just tried and it works perfectly:There is Foursquare product .\nFongo is an in-memory java implementation of mongo. It intercepts calls to the standard mongo-java-driver for finds, updates, inserts, removes and other methods. The primary use is for lightweight unit testing where you don't want to spin up a mongo process.If you are using sbt and specs2, I wrote the same kind of wrapper for embedmongoIf you're using Maven you may be interested in a plugin I've created that wraps the :It provides a  goal that you can use to start any version of MongoDB you want (e.g. during ), and a  goal that will stop MongoDB (e.g. during ).The real benefit of using this plugin over others is that there is no requirement for MongoDB to be installed beforehand. MongoDB binaries are downloaded and stored in  for future builds.with spring-boot 1.3 you can use If you are using maven, you can use ours You can also check this project which simulate a MongoDB inside JVM memory.\n\nBut it is still in development.You can run MongoDB in memory as of version 3.2.6. From the :Not [just for] for unit testings, but read this blog post if you like to run MongoDB (even a cluster) as in-memory deployment if you're using Linux.  Would be great to have it out of the box like RavenDB though.Similar to the embedmongo-maven-plugin mentioned here, there is also a  available. Like the Maven plugin it also wraps the  and allows you to run a managed instance of Mongo from your Gradle builds.In production, you will be using a real database.If you want your tests to reflect how your product behaves in production, use a real instance of Mongo.A fake implementation may not behave exactly the same as a real one. When testing, you should strive for correctness. Speed of execution comes second.Check this code example here: . No installation, no dependency. It's simply a platform independent ant script that do download and setup for you. It also cleans up everything after your tests.
Java

I'm looking for a Java in-memory object caching API. Any recommendations? What solutions have you used in the past?Right now, I'm just using a Map:I need to extend the cache to include basic features like:However, I don't need more sophisticated features like:In-Memory caching:Enterprise caching: is very nice.  You can create an in memory cache. Check out their  for an example of creating an in memory cache.  You can specify a max size, and a time to live.EHCache does offer some advanced features, but if your not interested in using them - don't.  But it's nice to know they are there if your requirements ever change.Here is an in memory cache.  Created in code, with no configuration files.Creates a cache that will hold 200 elements, and has a ttl of 24 hours.I really like the  that comes with  ()The JavaDoc has a pretty neat example that demonstrates both its ease of use and its power:Furthermore,  introduced the much more extensive .You can also check out my little cache library called KittyCache at: There are some performance benchmarks vs ehcache.It's used in the  project as a second level cache.Guava's  has been replaced by their  class.You can check out LinkedHashMap to implement a simple cache without third party jars:then you can get from the cache likerest left as exercise for reader :) is tried and true.  Even though it is light as far as caching mechanisms go, you might dig into the actual code and mimic what they do with HashMap under the covers to exactly what you need and no more.  You seem to have a pretty good idea of what you are looking for.  memcached has client for Java.  Requires separate process to be a caching server, but powerful thing.
Java

I saw this quote on the question: Is this true?  If so, what is it about the JVM that creates this fundamental limitation?This post:  might help.In short, tail call optimization is hard to do in the JVM because of the security model and the need to always have a stack trace available. These requirements could in theory be supported, but it would probably require a new bytecode (see ).There is also more discussion in , where the evaluation (from 2002) ends:Currently, there is some work going on in the  project. The tail call subproject's status is listed as \"proto 80%\"; it is unlikely to make it into Java 7, but I think it has a very good chance at Java 8.The fundamental limitation is simply that the JVM does not provide tail calls in its byte code and, consequently, there is no direct way for a language built upon the JVM to provide tail calls itself. There are workarounds that can achieve a similar effect (e.g. trampolining) but they come at the grave cost of awful performance and obfuscating the generated intermediate code which makes a debugger useless.So the JVM cannot support any production-quality functional programming languages until Sun implement tail calls in the JVM itself. They have been discussing it for years but I doubt they will ever implement tail calls: it will be very difficult because they have prematurely optimized their VM before implementing such basic functionality, and Sun's effort is strongly focused on dynamic languages rather than functional languages.Hence there is a very strong argument that Scala is not a real functional programming language: these languages have regarded tail calls as an essential feature since Scheme was first introduced over 30 years ago.Scala 2.7.x supports tail-call optimization for self-recursion (a function calling itself) of final methods and local functions.Scala 2.8 might come with library support for trampoline too, which is a technique to optimize mutually recursive functions.A good deal of information about the state of Scala recursion can be found in .In addition to the paper linked in Lambda The Ultimate (from the link mmyers posted above), John Rose from Sun has some more to say about tail call optimization.I have heard that it might be implemented on the JVM someday. Tail call support amongst other things are being looked at on the Da Vinci Machine.All sources point to the JVM being unable to optimize in the case of tail recursion, but upon reading  (2003, O'reilly) I found the author claiming he can achieve greater recursion performance by implementing tail recursion.You can find his claim on page 212 (search for 'tail recursion' it should be the second result). What gives?
Java

Will Java code built and compiled against a 32-bit JDK into 32-bit byte code work in a 64-bit JVM?  Or does a 64-bit JVM require 64-bit byte code?To give a little more detail, I have code that was working in a Solaris environment running a 32-bit JVM, but now I'm getting issues after upgrading the JDK and Weblogic Server to 64-bit.Yes, Java bytecode (and source code) is platform independent, assuming you use platform independent libraries. 32 vs. 64 bit shouldn't matter.I accidentally ran our (largeish) application on a 64bit VM rather than a 32bit VM and didn't notice until some external libraries (called by JNI) started failing.Data serialized on a 32bit platform was read in on the 64bit platform with no issues at all.What sort of issues are you getting? Do some things work and not others? Have you tried attaching JConsole etc and have a peak around?If you have a very big VM you may find that GC issues in 64 bit can affect you. Yes to the first question and no to the second question; it's a virtual machine. Your problems are probably related to unspecified changes in library implementation between versions. Although it could be, say, a race condition.There are some hoops the VM has to go through. Notably references are treated in class files as if they took the same space as s on the stack.  and  take up two reference slots. For instance fields, there's some rearrangement the VM usually goes through anyway. This is all done (relatively) transparently.Also some 64-bit JVMs use \"compressed oops\". Because data is aligned to around every 8 or 16 bytes, three or four bits of the address are useless (although a \"mark\" bit may be stolen for some algorithms). This allows 32-bit address data (therefore using half as much bandwidth, and therefore faster) to use heap sizes of 35- or 36-bits on a 64-bit platform.All byte code is 8-bit based. (That's why its called BYTE code) All the instructions are a multiple of 8-bits in size. \nWe develop on 32-bit machines and run our servers with 64-bit JVM.Could you give some detail of the problem you are facing?  Then we might have a chance of helping you. Otherwise we would just be guessing what the problem is you are having.Unless you have native code (machine code compiled for a specific arcitechture) your code will run equally well in a 32-bit and 64-bit JVM.Note, however, that due to the larger adresses (32-bit is 4 bytes, 64-bit is 8 bytes) a 64-bit JVM will require more memory than a 32-bit JVM for the same task.The 32-bit vs 64-bit difference does become more important when you are interfacing with native libraries. 64-bit Java will not be able to interface with a 32-bit non-Java dll (via JNI)Add a paramter as below in you in configuration while creating the exeI hope it helps.thanks.../javThe Java JNI requires OS libraries of the same \"bittiness\" as the JVM. If you attempt to build something that depends, for example, on IESHIMS.DLL (lives in %ProgramFiles%\\Internet Explorer) you need to take the 32bit version when your JVM is 32bit, the 64bit version when your JVM is 64bit. Likewise for other platforms.Apart from that, you should be all set. The generated Java bytecode s/b the same.Note that you should use 64bit Java compiler for larger projects because it can address more memory. yo where wrong! To this theme i wrote an question to oracle. The answer was. \"If you compile your code on an 32 Bit Machine, your code should only run on an 32 Bit Processor. If you want to run your code on an 64 Bit JVM you have to compile your class Files on an 64 Bit Machine using an 64-Bit JDK.\"
Java

I'm acquainted with the fact that , and in particular you need a \"lexer hack\" in C. On the other hand, I'm under the impression that you can parse Java with only 2 tokens of look-ahead, despite considerable similarity between the two languages.I ask because all of the examples I've seen of C's context-sensitivity are technically allowable but awfully weird. For example,could be calling the void function  with argument . Or, it could be declaring  to be an object of type , but you could just as easily get rid of the parantheses. In part, this weirdness occurs because the \"direct declarator\" production rule for the  fulfills the dual purpose of declaring both functions and variables.On the other hand, the  has separate production rules for variable declaration and function declaration. If you writethen you know it's a variable declaration and  can unambiguously be parsed as a typename. This might not be valid code if the class  hasn't been defined somewhere in the current scope, but that's a job for semantic analysis that can be performed in a later compiler pass.I've seen it said that C is hard to parse because of typedef, but you can declare your own types in Java too. Which C grammar rules, besides , are at fault?See this .  The short summary is that C and C++  are inherently ambiguous; they will give you multiple parses and you  use context to resolve the ambiguities. People then make the mistake of assuming you have to resolve ambiguities as you  parse; not so, see below.  If you insist on resolving ambiguities as you parse, your parser gets more complicated and that much harder to build; but that complexity is a self-inflicted wound.IIRC,  Java 1.4's \"obvious\" LALR(1) grammar was not ambiguous, so it was \"easy\" to parse.  I'm not so sure that modern Java hasn't got at least long distance local ambiguities; there's always the problem of deciding whether \"...>>\" closes off two templates or is a \"right shift operator\".  I suspect . But one can get past the parsing problem by using strong parsers (or weak parsers and context collection hacks as C and C++ front ends mostly do now), for both languages.\nC and C++ have the additional complication of having a preprocessor; these are more complicated in practice than they look.  One claim is that the C and C++ parsers are so hard they have to be be written by hand.    Once you parse, you will want to do something with the AST/parse tree.  In practice, you need to know, for every identifier, what its definition is and where it is used  (\"name and type resolution\", sloppily, building symbol tables).   This turns out to be a LOT more work than getting the parser right, compounded  by inheritance, interfaces, overloading and templates, and the confounded by the fact that the semantics for all this is written in informal natural language spread across tens to hundreds of pages of the language standard.  C++ is really bad here.  Java 7 and 8 are getting to be pretty awful from this point of view. (And symbol tables aren't all you need; see my bio for a longer essay on \"Life After Parsing\").Most folks struggle with the pure parsing part (often never finishing; check SO itself for the many, many questions about to how to build working parsers for real langauges), so they don't ever see life after parsing.  And then we get folk theorems about what is hard to parse and no signal about what happens after that stage.Regarding changing the C++ syntax: you'll find you need to patch a lot of places to take care of the variety of local and real ambiguities in any C++ grammar.  If you insist, the .   I contend there is no point in doing this if you are not the C++ standards committee; if you did so, and built a compiler using that, nobody sane would use it.   There's too much invested in existing C++ applications to switch for convenience of the guys building parsers; besides, their pain is over and existing parsers work fine.You may want to write your own parser.  OK, that's fine; just don't expect the rest of the community to let you change the language they must use to make it easier for you.  They all want it easier for them, and that's to use the language as documented and implemented.
Java

Is it possible to see the return value of a method after the line has been run and before the instruction pointer returns to the calling function?I am debugging code I can't modify , and sometimes it jumps to code I don't have source to or the return expression has side effects that stop me being able to just run the expression in the  tab.Often the return value is used in a compound statement, and so the  view will never show me the value (hence wanting to see the result before control returns to the calling function). I can't use the expression viewer as there are side-effects in the statement.This feature was added to Eclipse version 4.7 M2 under .Found a really good shortcut for this.\nSelect the expression which returns the value and press This will display the value of the return statement. This is really helpful in cases where you can't or don't want to change just for debugging purpose.Hope this helps.Note: Have not tested this with third party libraries, but it is working fine for my code.\nTested this on That's why I always stick with the following pattern for methods:My rules:Naturally, the most trivial getters are exempt.This is actually a long standing bug in Eclipse, dating back from the very first days of the IDE: I am curious about to learn the answer to this question also. In the past, when dealing with 3rd party library like that, what I did is to create a wrapper class or child class that delegate to the parent class and do my debugging in the wrapper/child class. It takes extra work though.Depending on the return statement, you can highlight the expression that is being returned and from the right-click menu, there should be something like \"evaluate expression\" (I don't have eclipse in front of me now, but it's something like that).  It will show you what is going to be returned. Tough one.  My experience, outside of Eclipse, is that if you might need to see the return value, it is best to assign it to a local variable in the function so that the return statement is a simple  and not .  However, that's not dreadfully helpful to you since you say you can't (or don't want to) modify or even recompile the code.  So, I don't have a good answer for you - perhaps you need to reconsider your requirement.This is a bit far-fetched, but as there doesn't seem to be a simple way:You could use AspectJ to instrument the JAR with aspects that get hold of the return value of the methods you're interested in. According to Eclipse's documentation, AspectJ programs can be  like other programs.There are two options to weave your classes without recompiling the library :See the eclipse documentation (link above) and also the .
Java

I'm following a tutorial. I've created a new activity using a wizard. I get  when attempting to call a method on s obtained with  in my activity .Activity :Layout XML ():The tutorial is probably outdated, attempting to create an activity-based UI instead of the fragment-based UI preferred by wizard-generated code.The view is in the fragment layout ()  and not in the activity layout ().  is too early in the lifecycle to find it in the activity view hierarchy, and a  is returned. Invoking a method on  causes the NPE.The preferred solution is to move the code to the fragment , calling  on the inflated fragment layout :As a side note, the fragment layout will eventually be a part of the activity view hierarchy and discoverable with activity  but only after the fragment transaction has been run. Pending fragment transactions get executed in  after .Try  method and just use or Declare any View using  method in  Declare click listener on view by Agreed, this is a typical error because people often don't really understand how Fragments work when they begin working on Android development. To alleviate confusion, I created a simple example code that I originally posted on  , but I posted it here as well.An example is the following:activity_container.xml:ExampleFragment:fragment_example.xml:And that should be a valid example, it shows how you can use an Activity to display a Fragment, and handle events in that Fragment. And also how to communicate with the containing Activity.You are trying to access UI elements in the onCreate() but , it is too early to access them , since in fragment views can be created in onCreateView() method. \nAnd onActivityCreated() method is reliable to handle any actions on them, since activity is fully loaded in this state.Try to shift your accessing views to the onViewCreated method of fragment because sometimes when you try to access the views in onCreate method they are not rendered at the time resulting null pointer exception.The view \"something\" is in fragment and not in activity, so instead of accessing it in activity you must access it in the fragment class like Since you have declared your View in the ,move that piece of code where you get the NPE in the  method of the fragment.\nThis should solve the issue.Add the following in your in the posted code above in the question there is a problem :\nyou are using R.layout.activity_main in oncreate method, but the xml files name is \"fragment_main.xml\" , means you are trying to get the view of fragment_main.xml file which is not being shown so it gives null pointer exception. change the code like :I've got the same NullPointerException initializing a listener after calling findViewById onCreate and onCreateView methods.But when I've used the (Bundle savedInstanceState) {...} it works. So, I could access the GroupView and set my listener.I hope it be helpful.
Java

Two years after , there seems to be a   and  has listed the feature as \"proto 80%\" for some time now.Is there no active interest from Sun's/Oracle's side in supporting tail calls or is it just that tail calls are \"[...]  [...]\" as mentioned at the ?I would be really interested if someone has tested a MLVM build and could share some impressions of how well it works (if at all).  () explains why the JVM does not support tail-call optimization.It then gives an example of Java code that won't transform.Then it gives a test you can use to figure out if your JIT does this.Naturally, since this is an IBM paper, it includes a plug:One reason I've seen in the past for not implementing TCO (and it being seen as difficult) in Java is that the permission model in the JVM is stack-sensitive and thus tail-calls must handle the security aspects.  I believe this was shown to not be an obstacle by Clements and Felleisen [1] [2] and I'm pretty sure the MLVM patch mentioned in the question deals with it as well.I realize this does not answer your question; just adding interesting information.Perhaps you know this already, but the feature is not as trivial as it may sound since the Java language actually exposes the stack trace to the programmer.Consider the following program:Even though this has a \"tail-call\" it may not be optimized. (If it  optimized, it still requires book-keeping of the entire call-stack since the semantics of the program relies on it.)Basically, this means that it's hard to support this while still being backward compatible.Java is the least functional language you could possibly imagine (well, OK, !) but this would be a great advantage for JVM languages, like , which are. My observations are that making the JVM a platform for other languages has never seemed to be at the top of the priority list for Sun and I guess, now for Oracle.
Java

And what kind of alternative strategies do you use for avoiding LazyLoadExceptions?I do understand that open session in view has issues with:But, if you know that your application is running on a single vm, why not ease your pain by using an open session in view strategy?Because sending possibly uninitialised Proxies, especially collections, in the view layer and triggering hibernate loading from there can be troubling from both a performance and understanding point of view.:Using OSIV 'pollutes' the view layer with concerns related to the data access layer.The view layer is not prepare to handle a  which may happen when lazy loading, but presumably the data access layer is.:OSIV tends to tug proper entity loading under the carpet - you tend not to notice that your collections or entities are lazily initialised ( perhaps N+1 ). More convenience, less control. see  for a larger discussion regarding this subject. The author lists three important points:For a longer description, you can read my  article. Otherwise, here's a summary for why you shouldn't use Open Session In View.Open Session In View takes a bad approach to fetching data. Instead of letting the business layer decide how it\u2019s best to fetch all the associations that are needed by the View layer, it forces the Persistence Context to stay open so that the View layer can trigger the Proxy initialization.At a first glance, this might not look like a terrible thing to do, but, once you view it from a database perspective, a series of flaws start to become more obvious.The service layer opens and closes a database transaction, but afterward, there is no explicit transaction going on. For this reason, every additional statement issued from the UI rendering phase is executed in auto-commit mode. Auto-commit puts pressure on the database server because each statement must flush the transaction log to disk, therefore causing a lot of I/O traffic on the database side. One optimization would be to mark the  as read-only which would allow the database server to avoid writing to the transaction log.There is no separation of concerns anymore because statements are generated both by the service layer and by the UI rendering process. Writing integration tests that  requires going through all layers (web, service, DAO), while having the application deployed on a web container. Even when using an in-memory database (e.g. HSQLDB) and a lightweight web server (e.g. Jetty), these integration tests are going to be slower to execute than if layers were separated and the back-end integration tests used the database, while the front-end integration tests were mocking the service layer altogether.The UI layer is limited to navigating associations which can, in turn, trigger N+1 query problems. Although Hibernate offers  for fetching associations in batches, and  to cope with this scenario, the annotations are affecting the default fetch plan, so they get applied to every business use case. For this reason, a data access layer query is much more suitable because it can be tailored for the current use case data fetch requirements.Last but not least, the database connection could be held throughout the UI rendering phase(depending on your connection release mode) which increases connection lease time and limits the overall transaction throughput due to congestion on the database connection pool. The more the connection is held, the more other concurrent requests are going to wait to get a connection from the pool.So, either you get the connection held for too long, either you acquire/release multiple connections for a single HTTP request, therefore putting pressure on the underlying connection pool and limiting scalability.I wouldn't say that Open Session In View is considered a bad practice; what gives you that impression?Open-Session-In-View is a simple approach to handling sessions with Hibernate.  Because it's simple, it's sometimes simplistic.  If you need fine-grained control over your transactions, such as having multiple transactions in a request, Open-Session-In-View is not always a good approach.As others have pointed out, there are some trade-offs to OSIV -- you're much more prone to the N+1 problem because you're less likely to realize what transactions you're kicking off.  At the same time, it means you don't need to change your service layer to adapt to minor changes in your view.If you're using an Inversion of Control (IoC) container such as Spring, you may want to read up on . Essentially, I'm telling Spring to give me a Hibernate  object whose life cycle spans the entire request (i.e., it gets created and destroyed at the start and end of the HTTP request). I don't have to worry about s nor closing the session since the IoC container manages that for me.As mentioned, you will have to think about N+1 SELECT performance issues. You can always configure your Hibernate entity afterwards to do eager join loading in places where performance is an issue.The bean scoping solution is not a Spring-specific. I know PicoContainer offers the same capability and I'm sure other mature IoC containers offer something similar.I just did a post on some guidelines as to when to use open session in view in my blog. Check it out if your interested.In my own experience, OSIV is not so bad.\nThe only arrangement I made is using two different transactions:\n- the first, opened in \"service layer\", where I have the \"business logic\"\n- the second opened just before the view renderingI am v. rusty on Hibernate.. but I think its possible to have multiple transactions in one Hibernate session. So your transaction boundaries do not have to be the same as session start/stop events.OSIV, imo, primarily is useful because we can avoid writing code for starting a 'persistence context' (a.k.a. session) every time the request needs to make a DB access.In your service layer, you will probably need to make calls to methods which have different transaction needs, such as 'Required, New Required, etc.' The only thing these methods need is that somebody (i.e the OSIV filter) has started up the persistence context, so that only thing they have to worry about is - \"hey give me the hibernate session for this thread.. I need to do some DB stuff\".This won't help too much but you can check my topic here:\n* I have some OutOfMemory issues because of OpenSessionInView and a lot of entities loaded, because they stay in Hibernate cache level1 and are not garbage collected (i load a lot of entities with 500 items per page, but all entities stay in cache)
Java

I came across this question in a quiz,The output of this program is \"String Version\". But I was not able to understand why passing a null to an overloaded method chose the string version. Is null a String variable pointing to nothing ?However when the code is changed to,it gives a compile error saying \"The method method(StringBuffer) is ambiguous for the type MoneyCalc\"A null reference can be converted to an expression of any class type. So in the case of , this is fine:The  overload here is chosen because the Java compiler picks the  overload, as per . In particular:In your second case, both methods are still applicable, but neither  nor  is more specific than the other, therefore neither method is more specific than the other, hence the compiler error.Additionally, the  also declares that \"null\" is a literal value of the \"null type\". Therefore there exists a type called \"null\".Later, the  states that there exists a null type of which is impossible to declare variables, but you can use it through the null literal only. Later it says:Why the compiler chooses to widen it to String might well be explained in .You can assign a  to a  value so it is valid and the order for java and most programming languages is fit to the closest type and then to object. To answer the question in the title:  is neither a  nor an , but a reference to either can be assigned to .I'm actually surprised this code even compiles.  I tried something similar previously and I got a compiler error saying that the call was ambiguous.However, in this case, it seems like the compiler is choosing the method which is lowest on the food chain.  It's assuming that you want the least generic version of the method in order to help you out.I'll have to see if I can dig up the example where I got a compiler error in this (seemingly) exact same scenario, though...]  I see.  In the version I made, I had two overloaded methods accepting a  and an .  In this scenario, there is no \"most specific\" parameter (as in  and ), so it can't choose between them, unlike in your code.Very cool question!As String type is more specific than Object type. Let's say you add one more method that takes an Integer type.Then you will get a compiler error saying that the call is ambiguous. As now we two equally specific methods with same precedence.Java compiler gives most derived class type to assign null.Here is the example to understand it : B Class.on the other hand: The method fun(C) is ambiguous for the type MyTestHope it will help to understand this case better.I would say neither.  NULL is a state not a value.  Check out this  for more info on this (the article applies to SQL, but I think it helps with your question as well).
Java

 when we split on empty string like split mechanism would split in places marked with because empty space  exists before and after each character. So as result it would generate at first this arrayand later will  (because we didn't explicitly provide negative value to  argument) so it will finally return  split mechanism seems to have changed. Now when we use we will get  array instead of  so it looks like empty strings at start are also removed. But this theory fails because for instanceis returning array with empty string at start . Can someone explain what is going on here and how rules of split for this cases have changed in Java\u00a08?The behavior of  (which calls ) changes between Java 7 and Java 8.Comparing between the documentation of  in  and , we observe the following clause being added:The same clause is also added to  in , compared to .Let us compare the code of  of the reference implemetation in Java 7 and Java 8. The code is retrieved from grepcode, for version 7u40-b43 and 8-b132.The addition of the following code in Java 8 excludes the zero-length match at the beginning of the input string, which explains the behavior above.To make  behaves consistently across versions and compatible with the behavior in Java 8: checks that the string does not end at the beginning of the string, which implies that the match is an empty match at the beginning of the string.There is no general solution to make  backward-compatible with Java 7 and prior, short of replacing all instance of  to point to your own custom implementation.This has been specified in the documentation of .In  you  got a zero-width match at the beginning so the leading empty substring is not included in the resulting array. However in your second snippet when you split on  you got a positive width match (1 in this case), so the empty leading substring is included as expected.(Removed irrelevant source code)There was a slight change in the docs for  from Java 7 to Java 8. Specifically, the following statement was added:The empty string split generates a zero-width match at the beginning, so an empty string is not included at the start of the resulting array in accordance with what is specified above. By contrast, your second example which splits on  generates a -width match at the start of the string, so an empty string is in fact included at the start of the resulting array.
Java

Swing components have multiple methods related to updates of screen layout, in particular:The Java documentation defines these somewhat from a technical perspective, but it's not particularly clear how they are meant to be used.What is the difference between these, and in what circumstances should you use one rather than the others?Just IMHO. Not sure it's 100% correct. marks the container as invalid. Means the content is somehow wrong and must be relayed out. But it's just a kind of mark/flag. It's possible that multiple invalid containers must be refreshed later. performs relayout. It means invalid content is asked for all the sizes and all the subcomponents' sizes are set to proper values by . is just sum of both. It marks the container as invalid and performs layout of the container. : In Swing when you create a Component, it is not  i.e. its valid property is . A component is said to be valid, when its width, height, location and stuff has been determined. This is usually done by calling their  method, directly or indirectly. When we call  on containers, it will validate the container (if it is invalid) by calling its  method, which typically will invoke the . Now each child placed on this container will be validated recursively, so that the entire tree will be laid out and will become valid. :  is to be called when you change an attribute that would affect their width/height and call repaint() when you change an attribute that would affect their appearance.\nFor example, if your  contains a , now at a certain point of time you removed that  and inserted a new one in its place, depending on the contents of the newly placed , the size of the components inside the  as well as  itself (by virtue of the layout manager used by it), changes. Which pushes it to the invalid state. So in order to validate this change, you have to explicitly call . : This thing is something, I have never used, so might not be much of info I can give. But seems like the scenario presented above, can give a bit of a hint, as to what happens in . 
Java

I have the following Java code with several big arrays which never change their size. It runs in 1100 ms on my computer.I implemented the same code in C++ and used .The time of the C++ implementation which runs the exact same code is 8800 ms on my computer. What did I do wrong, so that it runs this slowly?Basically the code does the following:It iterates through different arrays with a size of around 20000.You can find both implementations under the following links:(On ideone I could only run the loop 400 times instead of 2000 times because of the time limitation. But even here there is a difference of three times)Here is the C++ version with the per-node data gathered into a structure, and a single vector of that structure used:The time is now 2x the speed of the Java version.  (846 vs 1631).Odds are the JIT noticed the cache burning of accessing data all over the place, and transformed your code into a logically similar but more efficient order.I also turned off stdio synchronization, as that is only needed if you mix / with C++  and .  As it happens, you only print out a few values, but C++'s default behavior for printing is overly paranoid and inefficient.If  is not an actual constant value, then the 3 \"array\" values will have to be stripped out of the .  That shouldn't cause a huge performance hit.You might be able to get another performance boost by sorting the values in that  by decreasing size, thus reducing memory footprint (and sorting access as well when it doesn't matter).  But I am unsure.A rule of thumb is that a single cache miss is 100x more expensive than an instruction.  Arranging your data to have cache coherency has lots of value.If rearranging the data into a  is infeasible, you can change your iteration to be over each container in turn.As an aside, note that the Java and C++ versions had some subtle differences in them.  The one I spotted was that the Java version has 3 variables in the \"for each edge\" loop, while the C++ one only had 2.  I made mine match the Java.  I don't know if there are others.Yep, the cache in the c++ version takes a hammering. It seems the JIT is better equipped to handle this. If you change the outer  in isUpdateNeeded() to shorter snippets. The difference goes away. The sample below produces a 4x speedup. This shows to a reasonable degree that cache misses are the reason for the slowdown. It is also important to note that the variables are not dependent so a threaded solution is easily created. As per stefans comment I tried grouping them in a struct using the original sizes. This removes the immediate cache pressure in a similar fashion. The result is that the c++ (CCFLAG -O3) version is about 15% faster than the java version. My result differs slightly from Jerry Coffins for the original sizes. For me the differences remains.  It might well be my java version, 1.7.0_75. As @Stefan guessed in a comment on @CaptainGiraffe's answer, you gain quite a bit by using a vector of structs instead of a struct of vectors. Corrected code looks like this:Compiled with the compiler from VC++ 2015 CTP, using , I get results like:Compiling with g++ produces a result that's slightly slower:On the same hardware, using the compiler/JVM from Java 8u45, I get results like:This is around 35% slower than the version from VC++, and about 16% slower than the version from g++.If we increase the number of iterations to the desired 2000, the difference drops to only 3%, suggesting that part of the advantage of C++ in this case is simply faster loading (a perennial problem with Java), not really in execution itself. This doesn't strike me as surprising in this case--the computation being measured (in the posted code) is so trivial that I doubt most compilers can do a whole lot to optimize it.I suspect this is about allocation of memory.I am thinking that  grabs a large contiguous block at program startup whereas  asks the OS for bits and pieces as it goes along.To put that theory to the test I made one modification to the  version and it suddenly started running slightly faster than the  version:Runtime  the preallocating vector:Runtime  the preallocating vector:Runtime for  version:
Java

I'm using JUnit 4.4 and Maven and I have a large number of long-running integration tests.When it comes to parallelizing test suites there are a few solutions that allow me to run each test method in a single test-class in parallel. But all of these require that I change the tests in one way or another.I really think it would be a much cleaner solution to run X different test classes in X threads in parallel. I have hundreds of tests so I don't really care about threading individual test-classes.Is there any way to do this?Use maven plugin:From junit 4.7 it's now possible to run tests in parallel without using TestNG. Actually it has been possible since 4.6, but there are a number of fixes being made in 4.7 that will make it a viable option. You may also run parallel tests with spring, which you can read about Inspired by JUnit's experimental  runner I've built my own  and  runners. Using these runners one can easily parallelize test suites and parameterized tests.Usage is simple. Just change  annotations value to one of these  classes. offers something similar, check the docs for details. It relies on JUnit 4.7 and you just mark your test to .Cheers (this was my first reflex - then I saw you're already having a lot of testcases). For JUnit, look at . You can check out the open source library - . It does exactly what you ask for - run different test classes in parallel. This integrates at the ant-junit level so that you do not have to change your tests in anyway. I am one of the authors of the library.Also, think about not running them in threads as you may need a process level sandbox. For example, if you are hitting a DB in your integration tests, you do not want one test to fail because another test added some data in a different thread. Most of the times, tests are not written with this in mind.Finally, how have solved this problem till now?You can run the tests in parallel using ParallelComputer provided by Junit itself. Here's a small snippet to get you started.This will help when you need to run tests from code as it has no dependencies on Maven or any other build management tools.Please note that, this will run all test cases in parallel, if you have any dependencies between different test cases it might result in false positives. You SHOULD NOT have interdependent tests anyway.You can change your test to be TestNg test in a minute (you just need to change imports), TestNG is the best in parallel testing.You could try  that lets you run distribute your tests across a compute grid. 
Java

Having a chain of \"instanceof\" operations is considered a \"code smell\".  The standard answer is \"use polymorphism\".  How would I do it in this case?There are a number of subclasses of a base class; none of them are under my control.  An analogous situation would be with the Java classes Integer, Double, BigDecimal etc.I do have control over NumberStuff and so on.I don't want to use many lines of code where a few lines would do.  (Sometimes I make a HashMap mapping Integer.class to an instance of IntegerStuff, BigDecimal.class to an instance of BigDecimalStuff etc.  But today I want something simpler.)I'd like something as simple as this:But Java just doesn't work that way.I'd like to use static methods when formatting.  The things I'm formatting are composite, where a Thing1 can contain an array Thing2s and a Thing2 can contain an array of Thing1s.  I had a problem when I implemented my formatters like this:Yes, I know the HashMap and a bit more code can fix that too.  But the \"instanceof\" seems so readable and maintainable by comparison.  Is there anything simple but not smelly?Note added 5/10/2010:It turns out that new subclasses will probably be added in the future, and my existing code will have to handle them gracefully.  The HashMap on Class won't work in that case because the Class won't be found.  A chain of if statements, starting with the most specific and ending with the most general, is probably the best after all:You might be interested in this entry from Steve Yegge's Amazon blog: . Essentially he's addressing cases like this, when polymorphism causes more trouble than it solves. The issue is that to use polymorphism you have to make the logic of \"handle\" part of each 'switching' class - i.e. Integer etc. in this case. Clearly this is not practical. Sometimes it isn't even logically the right place to put the code. He recommends the 'instanceof' approach as being the lesser of several evils.As with all cases where you are forced to write smelly code, keep it buttoned up in one method (or at most one class) so that the smell doesn't leak out.As highlighted in the comments, the visitor pattern would be a good choice. But without direct control over the target/acceptor/visitee you can't implement that pattern.  Here's one way the visitor pattern could possibly still be used here even though you have no direct control over the subclasses by using wrappers (taking Integer as an example):Of course, wrapping a final class might be considered a smell of its own but maybe it's a good fit with your subclasses.  Personally, I don't think  is that bad a smell here, especially if it is confined to one method and I would happily use it (probably over my own suggestion above).  As you say, its quite readable, typesafe and maintainable. As always, keep it simple.Instead of a huge , you can put the instances you handle in a map (key: class, value: handler).If the lookup by key returns , call a special handler method which tries to find a matching handler (for example by calling  on every key in the map). When a handler is found, register it under the new key.This makes the general case fast and simple and allows you to handle inheritance.You can use reflection:You can expand on the idea to generically handle subclasses and classes that implement certain interfaces.I think that the best solution is HashMap with Class as key and Handler as value. Note that HashMap based solution runs in constant algorithmic complexity \u03b8(1), while the smelling chain of if-instanceof-else runs in linear algorithmic complexity O(N), where N is the number of links in the if-instanceof-else chain (i.e. the number of different classes to be handled). So the performance of HashMap based solution is asymptotically higher N times than the performance of if-instanceof-else chain solution.\nConsider that you need to handle different descendants of Message class differently: Message1, Message2, etc. . Below is the code snippet for HashMap based handling.More info on usage of variables of type Class in Java: You could consider . For your first example, something like:and then similarly for your other handlers. Then it's a case of stringing together the StuffHandlers in order (most specific to least specific, with a final 'fallback' handler), and your despatcher code is just .(An alternative is to, rather than using a chain, just have a  in your dispatcher class, and have it loop through the list until  returns true).Just go with the instanceof.  All the workarounds seem more complicated.  Here is a blog post that talks about it:  I have solved this problem using  (around 15 years back in pre Generics era).I have defined one Generic Class ( abstract Base class). I have defined many concrete implementations of base class. Each concrete class will be loaded with className  as parameter. This class name is defined as part of configuration. Base class defines common state across all concrete classes and concrete classes will modify the state by overriding abstract rules defined in base class. At that time, I don't know the name of this mechanism, which has been known as  . Few more alternatives are listed in this  :  and  apart from reflection. 
Java

Is there an elegant way to handle exceptions that are thrown in  block? For example:How do you avoid the / in the  block?I usually do it like this:Elsewhere:I typically use one of the  methods in :If you're using Java 7, and  implements , you can do this (using InputStream as an example):Arguably a bit over the top, but maybe useful if you're letting exceptions bubble up and you can't log anything from within your method (e.g. because it's a library and you'd rather let the calling code handle exceptions and logging):UPDATE: I looked into this a bit more and found a great blog post from someone who has clearly thought about this more than me:   He goes one step further and combines the two exceptions into one, which I could see being useful in some cases.As of Java 7 you no longer need to explicitly close resources in a  block instead you can use -with-resources syntax. The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.Assume the following code:If any exception happens the  method will be called on each of these three resources in opposite order in which they were created. It means the close method would be called first for ResultSetm then the Statement and at the end for the Connection object.It's also important to know that any exceptions that occur when the close methods is automatically called are suppressed. These suppressed exceptions can be retrieved by  method defined in the  class.Source: One solution, if the two Exceptions are two different classesBut sometimes you cannot avoid this second try-catch. e.g. for closing a streamIgnoring exceptions which occur in a 'finally' block is generally a  unless one knows what those exceptions will be and what conditions they will represent.  In the normal  usage pattern, the  block places things into a state the outside code won't be expecting, and the  block restores those things' state to what the outside code expects.  Outside code which catches an exception will generally expect that, despite the exception, everything has been restored to a  state.  For example, suppose some code starts a transaction and then tries to add two records; the \"finally\" block performs a \"rollback if not committed\" operation.  A caller might be prepared for an exception to occur during the execution of the second \"add\" operation, and may expect that if it catches such an exception, the database will be in the state it was before either operation was attempted.  If, however, a second exception occurs during the rollback, bad things could happen if the caller makes any assumptions about the database state.  The rollback failure represents a  crisis--one which should not be caught by code expecting a mere \"Failed to add record\" exception.My personal inclination would be to have a finally method catch exceptions that occur and wrap them in a \"CleanupFailedException\", recognizing that such failure represents a major problem and such an exception should not be caught lightly.Why do you want to avoid the additional block? Since the finally block contains \"normal\" operations which may throw an exception AND you want the finally block to run completely you HAVE to catch exceptions.If you don't expect the finally block to throw an exception and you don't know how to handle the exception anyway (you would just dump stack trace) let the exception bubble up the call stack (remove the try-catch from the finally block).If you want to reduce typing you could implement a \"global\" outer try-catch block, which will catch all exceptions thrown in finally blocks:After lots of consideration, I find the following code best:That code guarantees following:If you can you should test to avoid the error condition to begin with.Also you should probably only be catching exceptions that you can recover from, if you can't recover then let it propagate to the top level of your program.  If you can't test for an error condition that you will have to surround your code with a try catch block like you already have done (although I would recommend still catching specific, expected errors).You could refactor this into another method ... I usually do this:Rationale: If I'm done with the resource and the only problem I have is closing it, there  is not much I can do about it. It doesn't make sense either to kill the whole thread if I'm done with the resource anyway.This is one of the cases when at least for me, it is safe to ignore that checked exception.To this day I haven't had any problem using this idiom. Job done. No null tests. Single catch, include acquire and release exceptions. Of course you can use the Execute Around idiom and only have to write it once for each resource type.
Java

We recently had an issue with an Eclipse project for one of our team members. Tomcat was not deploying JARs of the application. We eventually noticed the  Eclipse file was not the same as for the team members where the project was OK. We replaced the  file with one from a project that was OK and the Tomcat deploy was complete.Just out of curiosity and to know at what to look in the future if something is wrong, Eclipse is a runtime environment for plugins. Virtually everything you see in Eclipse is the result of plugins installed on Eclipse, rather than Eclipse itself.The  file is maintained by the core Eclipse platform, and its goal is to describe the project from a generic, plugin-independent Eclipse view. What's the project's name? what other projects in the workspace does it refer to? What are the builders that are used in order to build the project? (remember, the concept of \"build\" doesn't pertain specifically to Java projects, but also to other types of projects)The  file is maintained by Eclipse's JDT feature ( = set of plugins). JDT holds multiple such \"meta\" files in the project (see the  directory inside the project); the  file is just one of them. Specifically, the  file contains information that the JDT feature needs in order to properly compile the project: the project's source folders (that is,  to compile); the output folders (where to compile ); and classpath entries (such as other projects in the workspace, arbitrary JAR files on the file system, and so forth).Blindly copying such files from one machine to another may be risky. For example, if arbitrary JAR files are placed on the classpath (that is, JAR files that are located outside the workspace and are referred-to by absolute path naming), the  file is rendered non-portable and must be modified in order to be portable. There are certain best practices that can be followed to guarantee  file portability.When a project is created in the workspace, a project description file is automatically generated that describes the project. The sole purpose of this file is to make the project self-describing, so that a project that is zipped up or released to a server can be correctly recreated in another workspace.Classpath specifies which Java source files and resource files in a project are considered by the Java builder and specifies how to find types outside of the project. The Java builder compiles the Java source files into the output folder and also copies the resources into it.Complete reference is not available for the mentioned files, as they are extensible by various plug-ins.Basically, .project files store project-settings, such as builder and project nature settings, while .classpath files define the classpath to use during running. The classpath files contains src and target entries that correspond with folders in the project; the con entries are used to describe some kind of \"virtual\" entries, such as the JVM libs or in case of eclipse plug-ins dependencies (normal Java project dependencies are displayed differently, using a special src entry).
Java

What is the best data type to use for money in java application?Java has  class that represents the ISO 4217 currency codes.\n is the best type for representing currency decimal values.  has provided a library to represent money.You can use . This API is expected to be part of Java 9. You can use this API in Java 7 and Java 8, provided you add appropriate dependencies to your project.For Java 8, add the following reference implementation as a dependency to your :This dependency will transitively add  as a dependency.You can then use the API:An integral type representing the smallest value possible. In other words your program should think in cents not in dollars/euros.This should not stop you from having the gui translate it back to dollars/euros. can be used, good explanation of why to not use Float or Double can be seen here: I would use It's still at version 0.6 but looks very promisingJSR 354 provides an API for representing, transporting, and performing comprehensive calculations with Money and Currency. You can download it from this link: An example of creating a MonetaryAmount and printing it to the console looks like this::When using the reference implementation API, the necessary code is much simpler:The API also supports calculations with MonetaryAmounts:CurrencyUnit and MonetaryAmountMonetaryAmount has various methods that allow accessing the assigned currency, the numeric amount, its precision and more:MonetaryAmounts can be rounded using a rounding operator:When working with collections of MonetaryAmounts, some nice utility methods for filtering, sorting and grouping are available.Custom MonetaryAmount operationsResources: See Also: You should use   to represent monetary values .It allows you to use a variety of , and in\nfinancial applications, the rounding mode is often a hard requirement\nthat may even be mandated by law.BigDecimal is the best data type to use for currency.There are a whole lot of containers for currency, but they all use BigDecimal as the underlying data type. You won't go wrong with BigDecimal, probably using BigDecimal.ROUND_HALF_EVEN rounding.I like using  which would wrap either a double, BigDecimal, or int as previous answers have suggested.  (I would use a double unless precision problems crop up).A Tiny Type gives you type safety so you don't confused a double money with other doubles.I have done a microbenchmark (JMH) to compare Moneta (java currency JSR 354  implementation) against BigDecimal in terms of performance.Surprisingly, BigDecimal performance seems to be better than moneta's. \nI have used following moneta config: org.javamoney.moneta.Money.defaults.precision=19\norg.javamoney.moneta.Money.defaults.roundingMode=HALF_UPResulting in Please feel free to correct me if i'm missing somethingFor simple case (one currency) it'is enough /. \nKeep money in cents (...) or hundredth / thousandth of cents (any precision you need with fixed divider)
Java

An existing web application is running on Tomcat 4.1.  There is an XSS issue with a page, but I can't modify the source.  I've decided to write a servlet filter to sanitize the parameter before it is seen by the page.I would like to write a Filter class like this:But  doesn't exist.How can I change the value of the request parameter before passing the request down the chain?As you've noted  does not have a setParameter method. This is deliberate, since the class represents the request as it came from the client, and modifying the parameter would not represent that.One solution is to use the  class, which allows you to wrap one request with another. You can subclass that, and override the  method to return your sanitized value. You can then pass that wrapped request to  instead of the original request.It's a bit ugly, but that's what the servlet API says you should do.  If you try to pass anything else to , some servlet containers will complain that you have violated the spec, and will refuse to handle it.A more elegant solution is more work - modify the original servlet/JSP that processes the parameter, so that it expects a request  instead of a parameter. The filter examines the parameter, sanitizes it, and sets the attribute (using ) with the sanitized value. No subclassing, no spoofing, but does require you to modify other parts of your application.For the record, here is the class I ended up writing:Write a simple class that subcalsses  with a getParameter() method that returns the sanitized version of the input. Then pass an instance of your  to  instead of the request object directly.Try . It worked fine for me.Please find this code sample:You can use  for Sanitization. Inside filter before calling  method, call this code.\nHere is Sample Code:
Java

I want to copy text from a 's cell to the clipboard, making it available to be pasted into other programs such as Microsoft Word. I have the text from the , but I am unsure how to copy it to the clipboard.This works for me and is quite simple:Import these:And then put this snippet of code wherever you'd like to alter the clipboard:I've just tried it and it works. Not sure if there are some 'good practice' flaws in though, but it will solve your problem!LHThe following class allows you to copy/paste a String to/from the clipboard.
Java

Is there an easy way to get the ID (ObjectID) of the last inserted document of a mongoDB instance using the Java driver?Hate to answer my own question, but I just realized you can do this:It's safe to do if you look at driver code I do not know about the Java driver but for posterity, the getLastError command can be run to get the _id of a write, even an upsert (as of 1.5.4)To avoid casting from  to , given a  and a , you can do the following:After a document is inserted into the MongoDB collection, the successful insertion should update required fields (viz. _id). You may query the inserted object for the _id.In MongoTemplate.class has a methodand the method will set id for uswe can see if the entity is a sub-class of BasicDBObject,it will set a id for us.This is insert operation:After insert u get last inserted id:after getting value convert to inter type.
Java

I have data that is organized in kind of a \"key-key\" format, rather than \"key-value\".  It's like a HashMap, but I will need O(1) lookup in both directions.  Is there a name for this type of data structure, and is anything like this included in Java's standard libraries? (or maybe Apache Commons?)I could write my own class that basically uses two mirrored Maps, but I'd rather not reinvent the wheel (if this already exists but I'm just not searching for the right term).There is no such class in the Java API. The Apache Commons class you want is going to be one of the implementations of .As a mathematician, I would call this kind of structure a bijection.In addition to Apache Commons,  also has a .Here is a simple class I used to get this done (I did not want to have yet another third party dependency). It does not offer all features available in Maps but it is a good start.  If no collisions occur, you can always add both directions to the same HashMap :-)Here my 2 cents.Or you can use a simple method with generics. Piece of cake.Of course you must have a map with unique values. Otherwise, one of them will be replaced.Quite an old question here, but if someone else has brain block like I just did and stumbles on this, hopefully this will help.I too was looking for a bi-directional HashMap, sometimes it is the simplest of answers that are the most useful.If you do not wish to re-invent the wheel and prefer not to add other libraries or projects to your project, how about a simple implementation of parallel arrays (or ArrayLists if your design demands it).As soon as you know the index of 1 of the two keys you can easily request the other. So your lookup methods could looks something like:This is assuming you are using proper object oriented structures, where only methods are modifying these arrays/ArrayLists, it would be very simple to keep them parallel. Even easier for an ArrayList since you would not have to rebuild if the size of the arrays change, so long as you add/remove in tandem.Inspired by  I decided to write something similar by myself with some improvements:Usage is just like a normal map, to get a reverse view on the mapping call . The content is not copied, only a view is returned.I'm not sure this is totally fool-proof (actually, it's probably not), so feel free to comment if you notice any flaws and I'll update the answer.
Java

How would I  something is ?for example But I get an error saying that I cannot have  in .You can use  method:why not use  /  ?If you want to , you can do In  you can do Use the following (from Hamcrest):
Java

I'm currently working on a Java project that is emitting the following warning when I compile:I'm not sure how SO will render the character before the date, but it should be a copyright symbol, and is displayed in the warning as a question mark in a diamond.It's worth noting that the character appears in the output artifact correctly, but the warnings are a nuisance and the file containing this class may one day be touched by a text editor that saves the encoding incorrectly...How can I inject this character into the \"copyright\" string so that the compiler is happy, and the symbol is preserved in the file without potential re-encoding issues?Use the \"\\uxxxx\" escape format.According to , the copyright symbol is unicode U+00A9 so your line should read:Try with:\njavac -encoding ISO-8859-1 file_name.java If you're using Maven, set the  explicitly in the compiler plugin's configuration, e.g.This helped for me: Source: put this line in yor file .gradle  above the Java conf.Most of the time this compile error comes when unicode(UTF-8 encoded) file compiling and also You can add this compile option to your IDE \nex:  Intellij idea\n(File>settings>Java Compiler) add as additional command line parameterI had the same problem, where the character index reported in the java error message was incorrect. I narrowed it down to the double quote characters just prior to the reported position being hex 094 (cancel instead of quote, but represented as a quote) instead of hex 022.  As soon as I swapped for the hex 022 variant all was fine.If one is using Maven Build from the command prompt one can use the following command as well:This worked for me - If you use eclipse (Eclipse can put utf8 code for you even you write utf8 character. You will see normal utf8 character when you programming but background will be utf8 code) ; this will ok if you static value in code. For Example String test = \"\u0130\u0130\u0130\u0130\u0130\u0131\u0131\u0131\u0131\u0131\u0131\u00e7\u00e7\u00e7\u00e7\u00e7\";
Java

In this question  is a handy flow chart to use when choosing C++ collections.I thought that this was a useful resource for people who are not sure which collection they should be using so I tried to find a similar flow chart for Java and was not able to do so.What resources and \"cheat sheets\" are available to help people choose the right Collection to use when programming in Java? How do people know what List, Set and Map implementations they should use?Since I couldn't find a similar flowchart I decided to make one myself.This flow chart does not try and cover things like synchronized access, thread safety etc or the legacy collections, but it does cover the 3 standard s, 3 standard s and 2 standard s.Probably the most useful other reference is the following page from the oracle documentation which describes each .There is a detailed discussion of when to use  or  here:\nDetailed discussion: : An interface representing an unordered \"bag\" of items, called \"elements\". The \"next\" element is undefined (random).Basic collection diagrams:Comparing the insertion of an element with an  and :Even simpler picture is here. Intentionally simplified!It is simple: if you need to store values with keys mapped to them go for the Map interface, otherwise use List for values which may be duplicated and finally use the Set interface if you don\u2019t want duplicated values in your collection. Here is the complete explanation  , including flowchart etc
Java

I have configured java to dump garbage collection information into the logs (). I am unsure of what the garbage collection entries in the logs mean. A sample of these entries are posted below. I've searched around on  and have not found solid explanations. I have some reasonable guesses, but I'm looking for answers which provide strict definitions of what the numbers in the entries mean, backed up by credible sources. An automatic +1 to all answers which cite sun documentation. My questions are:Most of it is explained in the  (which you would do well to read anyway).I'm not certain why there's a PSYoungGen in yours; did you change the garbage collector?An example of an associated full GC also shows the collectors used for the old and permanent generations:Finally, breaking down one line of your example log output:I just wanted to mention that one can get the detailed GC log with the parameter. Then you see the PSYoungGen or PSPermGen output like in the answer.Also  seems to generate the same output like  but you can specify an output file in the first.Example usage:To visualize the data better you can try  (a more recent version can be found on ).Take care to write the parameters correctly, I forgot the \"+\" and my JBoss would not start up, without any error message!
Java

When should I create a checked exception, and when should I make a runtime exception?For example, suppose I created the following class:How should I create my ? Should it extend  or ? Or should I just use  instead?There's a LOT of disagreement on this topic.  At my last job, we ran into some real issues with Runtime exceptions being forgotten until they showed up in production (on agedwards.com), so we resolved to use checked exceptions exclusively.At my current job, I find that there are many who are for Runtime exceptions in many or all cases.Here's what I think:  Using CheckedExceptions, I am forced at compile time to at least acknowledge the exception in the caller.  With Runtime exceptions, I am not forced to by the compiler, but can write a unit test that makes me deal with it.  Since I still believe that the earlier a bug is caught the cheaper it is to fix it, I prefer CheckedExceptions for this reason.From a philosophical point of view, a method call is a contract to some degree between the caller and the called.  Since the compiler enforces the types of parameters that are passed in, it seems symmetrical to let it enforce the types on the way out.  That is, return values or exceptions.My experience tells me that I get higher quality, that is, code that JUST WORKS, when I'm using checked exceptions.  Checked exceptions may clutter code, but there are techniques to deal with this.  I like to translate exceptions when passing a layer boundary.  For example, if I'm passing up from my persistence layer, I would like to convert an SQL exception to a persistence exception, since the next layer up shouldn't care that I'm persisting to a SQL database, but will want to know if something could not be persisted.  Another technique I use is to create a simple hierarchy of exceptions.  This lets me write cleaner code one layer up, since I can catch the superclass, and only deal with the individual subclasses when it really matters.In general, I think the advice by Joshua Bloch in  best summarises the answer to your question:  (Item 58 in 2nd edition). So in this case, if you really want to use exceptions, it should be a checked one. (Unless the documentation of  made it very clear that the method  be called without checking for sufficient balance first by using some other  method - but this would seem a bit awkward.)But also note Items 59:  and 57: . As others have pointed out, this case may not warrant an exception at all. Consider returning  (or perhaps a status object with details about what happened) if there is not enough credit.When to use checked exceptions?  Honestly?  In my humble opinion... never.  I think it's been about 6 years since I last created a checked exception.You can't force someone to deal with an error.  Arguably it makes code worse not better.  I can't tell you the number of times I've come across code like this:Whereas I have countless times written code like this:Why?  Because a condition (not necessarily IOException; that's just an example) wasn't recoverable but was forced down my throat anyway and I am often forced to make the choice between doing the above and polluting my API just to propagate a checked exception all the way to the top where it's (rightlfully) fatal and will be logged.There's a reason Spring's DAO helper classes translate the checked SQLException into the unchecked DataAccessException.If you have things like lack of write permissions to a disk, lack of disk space or other fatal conditions you want to be making as much noise as possible and the way to do this is with... unchecked exceptions (or even Errors).Additionally, .This idea that checked exceptions should be used for \"recoverable\" errors is really pie-in-the-sky wishful thinking.Checked exceptions in Java were an experiment... a failed experiment.  We should just cut our losses, admit we made a mistake and move on.  IMHO .Net got it right by only having unchecked exceptions.  Then again it had the second-adopter advantage of learning from Java's mistakes.IMHO, it shouldn't be an exception at all. An exception, in my mind, should be used when exceptional things happen, and not as flow controls.In your case, it isn't at all an exceptional status that someone tries to transfer more money than the balance allows. I figure these things happen very often in the real world. So you should program against these situations. An exception might be that your if-statement evaluates the balance good, but when the money is actually being subtracted from the account, the balance isn't good anymore, for some strange reason.An exception might be that, just before calling , you checked that the line was open to the bank. But inside the , the code notices that the line isn't open any more, although, by all logic, it should be.  is an exception. If the line can't be opened, that's not an exception, that's a plausible situation.IMHO recap: Exceptions == weird black magic.So, not to be all too contradictive, the method itself might very well throw an exception. But the use of the method should be controlled: You first check the balance (outside of the  method), and if the balance is good, only then call . If  notices that the balance, for some odd reason, isn't good anymore, you throw the exception, which you diligently catch. In that case, you have all your ducks in a row, and know that there's nothing more you can do (because what was  became , as if by itself), other than log the exception, send a notification to someone, and tell the customer politely that someone didn't sacrifice their virgins properly during the last full moon, and the problem will be fixed at the first possible moment.If you are doing this for your own pleasure (and the case seems to be this, see comments), I'd suggest returning a boolean instead. The usage would be something like this:I recently had a problem with exceptions, code threw NullPointerException and I had no idea why, after some investigation it turned out that real exception was swallowed(it was in new code, so its still being done) and method just returned null. If you do checked exceptions you must understand that bad programmers will just try catch it and ignore exception.My feeling is that the checked exception is a useful contract that should be used sparingly.  The classic example of where I think a checked exception is a good idea is an .  My feeling is that I do want to be able to stop a thread / process when I want it to stop, regardless of how long someone has specified to Thread.sleep().So, trying to answer your specific question, is this something that you absolutely want to make sure that everyone deals with?  To my mind, a situation where an  doesn't have enough money is a serious enough problem that you have to deal with it. In response to 's comment: here's an example using InterruptedException as concrete case of an exception that should be handled and you need to have a useful default handler.  Here is what I strongly recommend, certainly at my real job.  You should at least do this:That handler will ensure that the code catches the checked exception and does exactly what you want: get this thread to stop.  Admittedly, if there's another exception handler / eater upstream, it's not impossible that it will handle the exception less well.  Even so,  can help you find those.Now, reality sets in: you can't necessarily force everyone who writes an exception handler for your checked exception to handle it well.  That said, at least you'll be able to \"Find Usages\" and know where it is used and give some advice.Short form: you're inflicting a load the users of your method if you use a checked exception.  Make sure that there's a good reason for it, recommend a correct handling method and document all this extensively.My rule isThere is much documentation on the subject. You can find a lot by browsing the Hibernate\nweb pages since they changed all exceptions of Hibernate 2.x from checked to unchecked in version 3.xFrom :Note that an unchecked exception is one derived from  and a checked exception is one derived from .Why throw a  if a client cannot do anything to recover from the exception?  The article explains:A checked exception means that clients of your class are forced to deal with it by the compiler.  Their code cannot compile unless they add a try/catch block.The designers of C# have decided that unchecked exceptions are preferred.Or you can follow the C-style and check return values and not throw exceptions.Exceptions do have a cost, so they shouldn't be used for control flow, as noted earlier.  But the one thing they have going for them is that they can't be ignored.  If you decide that in this case to eschew exceptions, you run the risk that a client of your class will ignore the return value or fail to check the balance before trying to transfer.  I'd recommend an unchecked exception, and I'd give it a descriptive name like InsufficientFundsException to make it quite clear what was going on.Line isn't always clear, but for me usually runtime exceptions = programming errors, checked exceptions = external errors. This is very rough categorization though. Like others say, checked exceptions force you to handle, or at least think for a very tiny fraction of time, about it.Simply put, use checked exception only as part of external contract for a library, and only if the client wants/needs to catch it. Remember, when using checked exception you are forcing yourself on the caller. With runtime exception, if they are well-documented, you are giving the caller a choice.It is a known problem that checked exceptions are over-used in Java, but it doesn't mean that they are all bad. That's why it is such in integral part of the Spring philosophy, for example ()The advantage of checked exceptions is that the compiler forces the developer to deal with them earlier.  The disadvantage, in my mind anyway, is that developers tend to be lazy and impatient, and stub out the exception-handling code with the intention of coming back and fixing it later.  Which, of course, rarely happens.Bruce Eckel, author of , has a nice  on this topic.I don't think the scenario (insufficient funds) warrants throwing an  --- it's simply  exceptional enough, and should be handled by the normal control flow of the program. However, if I really had to throw an exception, I would choose a , by extending , not  which is unchecked. This forces me to handle the exception explicitly (I need to declare it to be thrown, or catch it somewhere). is a subclass of , which makes it an unchecked exception. I would only consider throwing this if the caller has some convenient way of determining whether or not the method arguments are legal. In your particular code, it's not clear if the caller has access to , or whether the whole \"check balance and transfer funds\" is an atomic operation (if it isn't then the caller really has no convenient way of validating the arguments).EDIT: Clarified my position on throwing .Myself, I prefer using checked exceptions as I can.If you are an API Developer (back-end developer), use checked exceptions, otherwise, use Runtime exceptions.Also note that, using Runtime exceptions in some situations is to be considered a big mistake, for example if you are to throw runtime exceptions from your session beans (see :  for more info about the problem from using Runtime excpetions in session beans).
Java

In this code, what does the two joins and break mean?  causes  to stop until  terminates?To quote from the :There is a thread that is running your example code which is probably the .It is important to understand that the  and  threads have been running  but the main thread that started them needs to wait for them to finish before it can continue.  That's a common pattern.  Also,  and/or  could have finished  the main thread calls  on them.  If so then  will not wait but will return immediately.No.  The  thread that is calling  will stop running and wait for the  thread to finish.  The  thread is running in parallel and is not affected by  or the  call at all.In terms of the try/catch, the  throws  meaning that the main thread that is calling  may itself be interrupted by another thread.This is a  question. means, t1 says something like \"\". Same is the case with . No matter who started  or  thread (in this case the  method), main will wait until  and  finish their task.However, an important point to note down,  and  themselves   on  and . It is the  thread that has to . means waiting for a thread to complete. This is a blocker method. Your main thread (the one that does the ) will wait on the  line until  finishes its work, and then will do the same for .When thread tA call tB.join() its causes not only waits for tB to die or tA be interrupted itself but create happens-before relation between last statement in tB and next statement after tB.join() in tA thread.It means programAlways printBut programCan print not only But Always only '0'. Because Java Memory Model don't require 'transfering' new value of 'sharedVar' from threadB to main thread without heppens-before relation (thread start, thread join, usage of 'synchonized' keyword, usage of AtomicXXX variables, etc).From oracle documentation If t1 is a  object whose thread is currently executing,If t2 is a  object whose thread is currently executing, API is low level API, which has been introduced in earlier versions of java. Lot of things have been changed over a period of time (especially with jdk 1.5 release) on concurrency front. You can achieve the same with java.util.concurrent API. Some of the examples are Refer to related SE questions:
Java

Ok so I have a been making an addressbook application and have pretty much finished all the key features but I am looking to implement a sort feature in the program.I want to sort an Arraylist which is of a type called Contact (contactArray) which is a separate class which contains four fields; name, home number, mobile number and address.\nSo I was looking into using the collection sort yet am not sure how i'd implement this.Is this the right sort I should be using / is it possible to use or should I look into making a custom sort?Here's a tutorial about ordering objects:Although I will give some examples, I would recommend to read it anyway.There are various way to sort an . If you want to define a  (default) , then you need to let  implement . Assuming that you want to sort by default on , then do (nullchecks omitted for simplicity):so that you can just doIf you want to define an  (which overrides the natural ordering), then you need to create a :You can even define the s in the  itself so that you can reuse them instead of recreating them everytime:which can be used as follows:And to cream the top off, you could consider to use a :which you can use as follows:In addition to what was already posted you should know that since Java 8 we can shorten our code and write it like:or since List now have  method Since Java 8, functional interfaces (interfaces with only one abstract method - they can have more default or static methods) can be easily implemented using:Since  has only one abstract method  it is functional interface.So instead of (example from  )we can reduce this code to:We can simplify this (or any) lambda by skipping So instead of  we can writeAlso now  has static methods like  or  which we could use to easily create Comparators which should compare some specific values from objects. In other words we can rewrite above code as tells you all you need to know about sorting collections, such as ArrayList.Basically you need toThere's another way as well, involving creating a Comparator class, and you can read about that from the linked page as well.Example:BalusC and bguiz have already given very complete answers on how to use Java's built-in Comparators.I just want to add that google-collections has an  class which is more \"powerful\" than the standard Comparators.\nIt might be worth checking out. You can do cool things such as compounding Orderings, reversing them, ordering depending on a function's result for your objects... is a blog post that mentions some of its benefits.You need make your Contact classes implement , and then implement the  method.  That way, the Collections.sort will be able to sort them for you.  Per the page I linked to, compareTo 'returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.'For example, if you wanted to sort by name (A to Z), your class would look like this:By using  you can sort a collection of your contacts (for example by their name) as it followsor by their address:and so on. More in general, it offers a DSL to access and manipulate your collections in many ways, like filtering or grouping your contacts based on some conditions, aggregate some of their property values, etc.The Collections.sort is a good sort implementation. If you don't have The comparable implemented for Contact, you will need to pass in a Of note:The merge sort is probably better than most search algorithm you can do.I did it by the following way.\nnumber and name are two arraylist. I have to sort name .If any change happen to name arralist order then the number arraylist also change its order.You shoud use the Arrays.sort function. The containing classes should implement Comparable.
Java

In my application, I have 2 's right above each other. Via a menu option, I want to be able to make the bottom one disappear, and have the top one drop down over the disappeared .The problem is, I have no idea on how to do this in Java.It doesn't have to be animated, I want to hide the  on return of another activity (the menu), in . The menu  sets a  on which I check in , and according to it's value I determine if I need to hide or show the bottom :Can anybody give me a hint or a link on how I should do this?You can call  if you want to remove it from the layout.Or  if you just want to hide it.From :Try this: 
Java

I want to write an comparator that will let me sort TreeMap by value instead of the default natural sorting. i tried something like this, but can't find out what went wrong:I guess what am i asking is what controls what gets passed to comparator function, can i get an Map.Entry passed to comparator?You can't have the  itself sort on the values, since that defies the  specification:However, using an external collection, you can always sort  however you wish, either by keys, values, or even a combination(!!) of the two.Here's a generic method that returns a  of , given a  whose values are :Now you can do the following:Note that funky stuff will happen if you try to modify either the  itself, or the  within, because this is no longer a \"view\" of the original map like  is.Generally speaking, the need to sort a map's entries by its values is atypical.Your original comparator compares  using . This is almost always wrong, since  with  operands is a reference equality, not value equality.polygenelubricants answer is  perfect. It has one important bug though. It will not handle map entries where the values are the same.This code:...Would output:Note how our cow dissapeared  as it shared the value \"1\" with our ape :O!This modification of the code solves that issue:In Java 8:A  is  sorted by the keys, anything else is impossible. A  merely allows you to control   the keys are sorted.If you want the sorted values, you have to extract them into a  and sort that.This can't be done by using a , as it will always get the  of the map to compare.  can only sort by the key.Olof's answer is good, but it needs  more thing before it's perfect. In the comments below his answer, dacwe (correctly) points out that his implementation violates the Compare/Equals contract for Sets. If you try to call contains or remove on an entry that's clearly in the set, the set won't recognize it because of the code that allows entries with equal values to be placed in the set. So, in order to fix this, we need to test for equality between the keys:\"Note that the ordering maintained by a sorted set (whether or not an explicit comparator is provided) must be consistent with equals if the sorted set is to correctly implement the Set interface... the Set interface is defined in terms of the equals operation, but .\"\n()Since we originally overlooked equality in order to force the set to add equal valued entries, now we have to test for equality in the keys in order for the set to actually return the entry you're looking for. This is kinda messy and definitely not how sets were intended to be used - but it works.A lot of people hear adviced to use List and i prefer to use it as wellhere are two methods you need to sort the entries of the Map according to their values.I know this post specifically asks for sorting a TreeMap by values, but for those of us that don't really care about implementation but do want a solution that keeps the collection sorted as elements are added, I would appreciate feedback on this TreeSet-based solution. For one, elements are not easily retrieved by key, but for the use case I had at hand (finding the n keys with the lowest values), this was not a requirement.
Java

I need to find my MySQL username. When I open the MySQL command line client, it only asks me for my password. I don't remember my username. And for connectivity with JDBC, I need the URL, host and port number. Where do I find all of these?If you're already logged into the command line client try this:It will output something similar to this:In my example above, I was logged in as  from .To find port number and other interesting settings use this command:If you want to know the  is running you can use this query on MySQL Command line client --It will give you the port number on which MySQL is running.If you want to know the  you can use this query on MySQL Command line client --It will give you the hostname for mysql.If you want to know the  you can use this query on MySQL Command line client --It will give you the username for mysql.For example, you can try:If you don't know the exact variable name use , as the result may contain more than 500 rows:For Example in my case :  is the host name of the box where my mysql is running. And it my local PC host name.  If it is romote box than you can ping that host directly if, If you are in network with that box you should be able to ping that host.If it  in terminal to check the host name.\nif it is windows you can see same value in   you can see ( i.e System Properties) Hope it will answer your Q. If you use phpMyAdmin, click on , then  on the top menu. Look for the  setting on the page. The value it is set to is the port your MySQL server is running on.Here are the default settings
Java

My POST method looks like this:When I create a Jersey Client in Netbeans the method who calls the post method looks like this:When running this test:It gives the following output in the server:What do I need to change so that the parameters are giving the correct value?Your  method should be accepting a JSON object instead of a string.  Jersey uses JAXB to support marshaling and unmarshaling JSON objects (see ).  Create a class like:Then your  method would look like the following:This method expects to receive JSON object as the body of the HTTP POST.  JAX-RS passes the content body of the HTTP message as an unannotated parameter --  in this case.  The actual message would look something like:Using JSON in this way is quite common for obvious reasons.  However, if you are generating or consuming it in something other than JavaScript, then you do have to be careful to properly escape the data.  In JAX-RS, you would use a  and  to implement this.  I believe that Jersey already has implementations for the required types (e.g., Java primitives and JAXB wrapped classes) as well as for JSON.  JAX-RS supports a number of other methods for passing data.  These don't require the creation of a new class since the data is passed using simple argument passing.The parameters would be annotated using :The browser will encode the form using .  The JAX-RS runtime will take care of decoding the body and passing it to the method.  Here's what you should see on the wire:The content is  in this case.If you do not know the names of the FormParam's you can do the following:You can using the  annotation if you want to pass parameters via HTTP headers:Here's what the HTTP message would look like.  Note that this POST does not have a body.I wouldn't use this method for generalized parameter passing.  It is really handy if you need to access the value of a particular HTTP header though.This method is primarily used with HTTP GETs but it is equally applicable to POSTs.  It uses the  annotation.Like the previous technique, passing parameters via the query string does not require a message body.  Here's the HTTP message:You do have to be particularly careful to properly  on the client side.  Using query parameters can be problematic due to URL length restrictions enforced by some proxies as well as problems associated with encoding them.Path parameters are similar to query parameters except that they are embedded in the HTTP resource path.  This method seems to be in favor today.  There are impacts with respect to HTTP caching since the path is what really defines the HTTP resource.  The code looks a little different than the others since the  annotation is modified and it uses :The message is similar to the query parameter version except that the names of the parameters are not included anywhere in the message.This method shares the same encoding woes that the query parameter version.   so you do have to be careful there as well.As you can see, there are pros and cons to each method.  The choice is usually decided by your clients.  If you are serving -based HTML pages, then use .  If your clients are JavaScript+HTML5-based, then you will probably want to use JAXB-based serialization and JSON objects.  The  implementations should take care of the necessary escaping for you so that is one fewer thing that can go wrong.  If your client is Java based but does not have a good XML processor (e.g., Android), then I would probably use  encoding since a content body is easier to generate and encode properly than URLs are.  Hopefully this mini-wiki entry sheds some light on the various methods that JAX-RS supports. in the interest of full disclosure, I haven't actually used this feature of Jersey yet.  We were tinkering with it since we have a number of JAXB+JAX-RS applications deployed and are moving into the mobile client space.  JSON is a much better fit that XML on HTML5 or jQuery-based solutions.
Java

Is it good/bad/acceptable practice to pass the current object in a method call.  As in:Specifically, is the line  acceptable?There's no reason not to use it,  is the current instance and it's perfectly legitimate to use. In fact there's often no clean way to omit it.So use it.As it's hard to convince it's acceptable without example (a negative answer to such a question is always easier to argument), I just opened one of the most common java.lang classes, the  one, and of course I found instances of this use, for exampleLook for  in big \"accepted\" projects, you won't fail to find it.There's nothing wrong with that. What is  is to do the same inside constructors, because you would give a reference to a not-yet-completely-initialized object.There is a sort of similar post here: \n where they give an explanation of why the latter is a bad practice., but you should be careful about two things  It's perfectly normal and perfectly acceptable.this stands for the current object. What you are doing is sytatically correct but i don't see a need of this if you are calling the method in the same class.  you can use it.Its just common in programming to pass .But there are pros and cons about using that.Still it is not hazardous  to do so. to pass the current object in a method call if there less complex alternatives to achieve the same behaviour.By definition, a bidirectional association is created as soon as  is passed from one object to another.To quote Refactoring, by Martin Fowler:So, theoretically, we should be hearing alarm bells when we find we need to pass  and try really hard to think of other ways to solve the problem at hand. There are, of course, times when, at last resort, it makes sense to do it. Also it is often necessary to corrupt your design temporarily, doing 'bad practice things', during a longer term refactoring of your code for an overall improvement. (One step back, two steps forward).In practice I have found my code has improved  by avoiding bidirectional links like the plague.Just to add one more example where passing  is correct and follows good design: . In Visitor design pattern, method  is typically implemented in a way it just calls .AcceptableSnippet from Oracle JAVA docs:Everything in java is passed by value. But objects are NEVER passed to the method!\nWhen java passes an object to a method, it first makes a copy of a reference to the object, not a copy of the object itself. Hence this is pefectly used method in java. And most commonly followed usage. 
Java

Is it possible to use a DB sequence for some column that ? I'm using hibernate as jpa provider, and I have a table that has some columns that are generated values (using a sequence), although they are not part of the identifier.What I want is to use a sequence to create a new value for an entity, where the column for the sequence is  (part of) the primary key:Then when I do this:the id will be generated, but the  property will be also generated by my JPA provider.Just to make things clear: I want  to generate the value for the  property. I know Hibernate can handle database-generated values, but I don't want to use a trigger or any other thing other than Hibernate itself to generate the value for my property. If Hibernate can generate values for primary keys, why can't it generate for a simple property?Looking for answers to this problem, I stumbled upon It seems that Hibernate/JPA isn't able to automatically create a value for your non-id-properties. The  annotation is only used in conjunction with  to create auto-numbers.The  annotation just tells Hibernate that the database is generating this value itself.The solution (or work-around) suggested in that forum is to create a separate entity with a generated Id, something like this:I found that  works perfect but only for PostgreSQL. For me this was perfect solution, because second entity is \"ugly\" option.Hibernate definitely supports this. From the docs:\"Generated properties are properties which have their values generated by the database. Typically, Hibernate applications needed to refresh  objects which contain any properties for which the database was generating values. Marking properties as generated, however, lets the application delegate this responsibility to Hibernate. Essentially, whenever Hibernate issues an SQL INSERT or UPDATE for an entity which has defined generated properties, it immediately issues a select afterwards to retrieve the generated values.\"For properties generated on insert only, your property mapping (.hbm.xml) would look like:For properties generated on insert and update your property mapping (.hbm.xml) would look like:Unfortunately, I don't know JPA, so I don't know if this feature is exposed via JPA (I suspect possibly not)Alternatively, you should be able to exclude the property from inserts and updates, and then \"manually\" call session.refresh( obj ); after you have inserted/updated it to load the generated value from the database.This is how you would exclude the property from being used in insert and update statements:Again, I don't know if JPA exposes these Hibernate features, but Hibernate does support them.I know this is a very old question, but it's showed firstly upon the results and jpa has changed a lot since the question.The right way to do it now is with the  annotation. You can define the sequence, set the default in the column to that sequence and then map the column as:As a followup here's how I got it to work:Although this is an old thread I want to share my solution and hopefully get some feedback on this. Be warned that I only tested this solution with my local database in some JUnit testcase. So this is not a productive feature so far.I solved that issue for my by introducing a custom annotation called Sequence with no property. It's just a marker for fields that should be assigned a value from an incremented sequence.Using this annotation i marked my entities.To keep things database independent I introduced an entity called SequenceNumber which holds the sequence current value and the increment size. I chose the className as unique key so each entity class wil get its own sequence.The last step and the most difficult is a PreInsertListener that handles the sequence number assignment. Note that I used spring as bean container.As you can see from the above code the listener used one SequenceNumber instance per entity class and reserves a couple of sequence numbers defined by the incrementValue of the SequenceNumber entity. If it runs out of sequence numbers it loads the SequenceNumber entity for the target class and reserves incrementValue values for the next calls. This way I do not need to query the database each time a sequence value is needed.\nNote the StatelessSession that is being opened for reserving the next set of sequence numbers. You cannot use the same session the target entity is currently persisted since this would lead to a ConcurrentModificationException in the EntityPersister.Hope this helps someone.I run in the same situation like you and I also didn't find any serious answers if it is basically possible to generate non-id propertys with JPA or not.My solution is to call the sequence with a native JPA query to set the property by hand before persisiting it.This is not satisfying but it works as a workaround for the moment.MarioI've found this specific note in session 9.1.9 GeneratedValue Annotation from JPA specification:\n\"[43] Portable applications should not use the GeneratedValue annotation on other persistent fields or properties.\"\nSo, I presume that it is not possible to auto generate value for non primary key values at least using simply JPA.I've been in a situation like you (JPA/Hibernate sequence for non @Id field) and I ended up creating a trigger in my db schema that add a unique sequence number on insert. I just never got it to work with JPA/Hibernate\"I don't want to use a trigger or any other thing other than Hibernate itself to generate the value for my property\"In that case, how about creating an implementation of UserType which generates the required value, and configuring the metadata to use that UserType for persistence of the mySequenceVal property?This is not the same as using a sequence.  When using a sequence, you are not inserting or updating anything.  You are simply retrieving the next sequence value.  It looks like hibernate does not support it.I fixed the generation of UUID (or sequences) with Hibernate using  annotation:
Java

From :The second criteria confuses me a bit. Given the first collection is unmodifiable, and assuming that the original collection reference has been disposed away, what are the changes that are referred to in the second line? Is it referring to the changes in the elements held in the collection ie the state of the elements? Second question:\nFor a collection to be immutable, how does one go about providing the additional guarentees specified? If the state of an element in the collection is updated by a thread, is it sufficient for immutability that those updates in the state are not visible on the thread holding the immutable collection?Edit : (highlighting the focus of second question) :Unmodifiable collections are usually read-only views (wrappers) of other collections. You can't add, remove or clear them, but the underlying collection can change.Immutable collections can't be changed at all - they don't wrap another collection - they have their own elements.Here's a quote from guava's So, basically, in order to get an immutable collection out of a mutable one, you have to copy its elements to the new collection, and disallow all operations.The difference is that you can't have a reference to an immutable collection which allows changes. Unmodifiable collections are unmodifiable , but some other object may point to the same data through which it can be changed.e.g. is  (i.e. neither  nor ).\n is : it can't be changed itself, but if later on I change  then  change will be visible in .This is because  is simply a wrapper around  and not really an independent copy. Guava provides the  and some implementations. Those work by actually creating a copy of the input (unless the input is an immutable collection on its own).Regarding your second question:The mutability/immutability of a collection does  depend on the mutability/immutability of the objects contained therein. Modifying an object contained in a collection does  count as a \"modification of the collection\" for this description. Of course if you need a immutable collection, you  also want it to contain immutable objects.I believe the point here is that even if a collection is Unmodifiable, that does not ensure that it cannot change. Take for example a collection that evicts elements if they are too old. Unmodifiable just means that the object holding the reference cannot change it, not that it cannot change. A true example of this is  method. It returns an unmodifiable view of a List. The the List reference that was passed into this method is still modifiable and so the list can be modified by any holder of the reference that was passed. This can result in ConcurrentModificationExceptions and other bad things.Immutable, mean that in no way can the collection be changed.Second question: An Immutable collection does not mean that the objects contained in the collection will not change, just that collection will not change in the number and composition of objects that it holds. In other words, the collection's list of references will not change. That does not mean that the internals of the object being referenced cannot change. supports what you are after, in two ways.First, it provides an  annotation, so that you can annotate a class to say that it is immutable.  There is a maven plugin to allow you to check that your code  immutable (use of  etc.).  Second, it provides the persistent collections from Clojure, (with added generics) and ensures that elements added to the collections are immutable.  Performance of these is apparently pretty good.  Collections are all immutable, but implement java collections interfaces (and generics) for inspection.  Mutation returns new collections.Now  has factory Methods for Immutable List, Set, Map and Map.Entry .In Java SE 8 and earlier versions, We can use Collections class utility methods like unmodifiableXXX to create Immutable Collection objects. However these Collections.unmodifiableXXX methods are very tedious and verbose approach. To overcome those shortcomings, Oracle corp has added couple of utility methods to List, Set and Map interfaces. \nList and Set interfaces have \u201cof()\u201d methods to create an empty or no-empty Immutable List or Set objects as shown below:I have written the documentation for  collections that are introduced in Java 9 which can be found .
Java

Guava offers a nice shortcut for initializing a map.  However I get the following compiler error (Eclipse Indigo) when my map initializes to nine entries. The method  in the type  is not applicable for the arguments \nThe message appears to say that Obviously, this cannot be the case but I can't figure out what to do to increase the size of my initializer.Can someone tell me what is missing?Notice that your error message only contains five  pairs, 10 arguments total. This is by design; the ImmutableMap class provides six different  methods, accepting between zero and six key-value pairings. There is not an  overload accepting a varags parameter because  and  can be different types.You want an :if the map is short you can do:If it is longer then:
Java

I'm currently using jackson 2.1.4 and I'm having some trouble ignoring fields when I'm converting an object to a JSON string.Here's my class which acts as the object to be converted:And here's how I convert it:Here's the output:How can I avoid those null values? I only want to take required information for the \"subscription\" purpose!Here's exactly the output that I'm looking for:I also tried @JsonInclude(Include.NON_NULL) and put all my variables to null, but it didn't work either! Thanks for your help guys!You have the annotation in the wrong place - it needs to be on the class, not the field. i.e: As noted in comments, in version 2.x+ the syntax for this annotation is: The other option is to configure the  directly, simply by calling \n(for the record, I think the popularity of this answer is an indication that this annotation  be applicable on a field-by-field basis *ahem @fasterxml*)You can also set the global option:Also you can try to use if you are dealing with jackson with version below 2+ (1.9.5) i tested it, you can easily use this annotation above the class. Not for specified for the attributes, just for class decleration.Or you can use GSON [], where these null fields will be automatically removed.OUTPUT:I used For jackson 2.x@JsonInclude(JsonInclude.Include.NON_NULL) just before the field.You need to add import com.fasterxml.jackson.annotation.JsonInclude;Add  on top of POJO If you have nested POJO then need to add on every values.NOTE:\nJAXRS (Jersey ) automatically handle this scenario 2.6 and above.I was having similar problem recently with version 2.6.6. Using above annotation either on filed or class level was not working as expected. The POJO was mutable where I was applying the annotation. When I changed the behaviour of the POJO to be immutable the annotation worked its magic. I am not sure if its down to new version or previous versions of this lib had similar behaviour but for 2.6.6 certainly you need to have Immutable POJO for the annotation to work. Above option mentioned in various answers of setting serialisation inclusion in ObjectMapper directly at global level works as well but, I prefer controlling it at class or filed level. So if you wanted all the null fields to be ignored while JSON serialisation then use the annotation at class level but if you want only few fields to ignored in a class then use it over those specific fields. This way its more readable & easy for maintenance if you wanted to change behaviour for specific response.
Java

The Eclipse IDE is showing red underline and when I focus it the tag is : can not find the library descriptor for I also use this but I don't get any error.Did you include the  in your library? If not maybe this causing the problem. And also the 'tld' folder do you have it? And how about your  did you map it?Have a look on the info about  for other information.I know this thread is a year old now but having experienced the same problem I managed to solve the problem by setting a target server for my project.i.e. right-click on your project and select 'Properties' -> 'Targeted Runtimes' and select the server you going to run your web app on (Tomcat 6 or 7).As @ace mentioned you will need the jstl.jar in your project, so if you are using maven, you could add this dependency:Source: Hope it helps. Most of servers already have this dependency, if you add it using maven it may cause version conflicts (like Method/ClassNotFoundException) if you don't configure the server well, so it's better set a target server for your project, as @willix mentioned.Try to add like this:instead of having After a couple of hit and trial I use this. This works for me.WARNING: As BalusC correctly mentioned, this works for JSTL 1.0.Add both javax.servlet.jsp.jstl-api-1.2.1.jar and standard-1.1.2.jarYou are probably targeting a server without built-in JSTL support (e.g. some version of Tomcat.) You will need to provision your own JSTL tag library.I tried \"validating\" de *.jsp and *.xml files in eclipse with the validate tool.\"right click on directory/file ->- validate\" and it worked!Using eclipse juno.Hope it helps!Resolves the problem.paste below two jar in your /WEB-INF/lib folder and then go to project properties and go to add jar and select these two jars  then click Ok, Okstandard.jar, \njstl-1.0.2.jarIt has nothing to do about .Just go to project and right click then  project menu -> Clean the project error will definitely remove and update maven .It will work perfectly when you will place the two required jar files under /WEB-INF/lib folder i.e. \njstl-1.2.jar\nand javax.servlet.jsp under /WEB-INF/lib folder.Hope it helps. :) This should work     and moreover please let us know why are you importing all these classWe don't need to include java.lang as it is the default package.I will throw one more solution into the mix. I downloaded a sample app and it was crimping only on this taglib. Turns out it didn't care for the single quotes around the attributes.Once I changed those and made sure jstl.jar was in the web app, i was good to go.I added jstl jar in a library and added it to build path and deployment assembly but it dint worked.\nthen i simply copied my jstl jar into lib folder inside webcontent, it worked.\nin eclipse lib folder in included to deployment assembly by defaultYou have to write asMake sure you have  jstl-1.0 & standard.jar  files are placed in a classpathI solved this issue.\nuse below taglib and add jstl-1.2.jar
Java

I want to use the count from the JSTL forEach loop, but my code doesnt seem to work.produces The variable set by varStatus is a  object, not an int. Use:To clarify:You can try this. similar resultIts really helped me to dynamically generate ids of  for the below code.if you execute this line  prints the below:you'd use any of these:JSTL c:forEach varStatus propertiesProperty    Getter  Description 
Java

I am seeking to run a common Java program in both Windows and Linux.The program needs to do some things differently on each platform.So how can / should my Java program detect it is running under Linux vs. Windows? has a class \nyou can use :Try:Useful simple class are forked by me on: \nI think It's a best approach to use Apache lang dependency to decide which OS you're running programmatically through JavaYou can use \"system.properties.os\", for example:Here are more details:
Java

I've a Java object 'ChildObj' which is extended from 'ParentObj'. Now, if it is possible to retrieve all the attribute names and values of ChildObj, including the inherited attributes too, using Java reflection mechanism? gives me the array of public attributes, and  gives me the array of all fields, but none of them includes the inherited fields list.Is there any way to retrieve the inherited attributes also?no, you need to write it yourself. It is a simple recursive method called on :If instead you wanted to rely upon a library to accomplish this,  version 3.2+ provides :You need to call:Recursing up the inheritance hierarchy as necessary.Use Reflections library:Working version of \"DidYouMeanThatTomHa...\" solution aboveThe recursive solutions are OK, the only small issue is that they return a superset of declared and inherited members. Note that getDeclaredFields() method returns also private methods. So given that you navigate the whole superclass hierarchy you will include all private fields declared in the superclasses, and those don't get inherited.A simple filter with a Modifier.isPublic || Modifier.isProtected predicate would do:You can try:Shorter and with less object instantiated ? ^^
Java

I'm starting a new project now. I have to choose technologies. I need something light, so no EJB or Seam. On the other hand I need JPA (Hibernate or alternative) and JSF with IceFaces.Do you think that such a stack on Spring 3 deployed on Tomcat is a good choice? Or a Java EE 6 web application could be better? I'm afraid that Java EE 6 is a new technology, not well documented yet. Tomcat seems to be easier to maintain than Glassfish 3. What's your opinion? Do you have any experiences?Would you care to explain what makes EJBs heavy since EJB3? Do you realize that we are not in 2004 anymore? I'd really like to read  definition of light and your arguments (and I will update my answer with pleasure because I'm pretty sure I would have a few solid things to say).Java EE 6 Web Profile which includes JSF 2.0, JPA 2.0, Bean Validation, EJB 3.1 Lite, CDI,... would be perfect for this and you can use  to run an application built with the Java EE 6 Web Profile.Well,  like the idea to run my code on a  (Java EE) rather than on a  (Spring). And I think that Java EE 6 is good enough (and this is an euphemism, EJB 3.1 (Lite), JPA 2.0, JSF 2.0, CDI kick ass). Note that I was a JSF skeptic but I took a second look and JSF 2.0 with CDI is so different that I can't even compare. And if you didn't look at CDI, let me tell you that it rocks. Java EE looks pretty well documented to me. This sounds like free claim. And, believe me or not,  start to find Spring getting complicated while Java EE getting easier.Did you try something? Did you face any particular problem? Again, this sounds like free claim.I have not used JavaEE6.However, I have been beaten up badly enough by all the previous versions of JavaEE and EJB's that I won't trust it until it establishes itself as the de facto standard, not just the de jure standard.  Right now, Spring is still the de facto standard.Fool me once, shame on you.  Fool me twice, shame on me.   Fool me three times, EJB.Some will claim that Spring is proprietary.  I would argue that the vendor implementations of the JavaEE specs have been just as proprietary, if not more so.I went through a major conversion recently of moving a bunch of Java Applications from JBoss to Weblogic.  All of the Spring/Hibernate apps ported with zero modifications, because they had all the libraries they needed built in.  All the apps that used JPA and EJB and JSF were a disaster to port.  Subtle differences in interpretations of JPA, EJB, and JSF between appservers caused all kinds of nasty bugs that took forever to fix.  Even something as simple as JNDI naming was completely different between AppServers.Spring is an implementation.  JavaEE is a spec.  That is a HUGE difference.  I would prefer to use a spec IF the spec was 100% air-tight and gave absolutely no wiggle room in the way vendors implement that spec.  But the JavaEE spec has never been that.  Maybe JavaEE6 is more air-tight?  I don't know.  The more you can package in your WAR, and the less you depend on AppServer libraries, the more portable your application will be, and that, after all, is the reason I use Java and not Dot-NET.Even IF the spec was air-tight, it would be nice to be able to upgrade the appserver without having to upgrade all my technology stacks in all my applications along with it.  If I want to upgrade from JBoss 4.2 to JBoss 7.0, I have to consider the impact of the newer version of JSF on all of my applications.  I don't have to consider the impact on my Spring-MVC (or Struts) applications.   It doesn't matter. Java EE 6 is good enough and because of the profiles there, it is not \"heavy\" - you'll just be using the web profile.Personally, I prefer Spring. But I'm running out of rational arguments against Java EE 6 :)(As I was reminded by a comment - you might want to try , as well as  and/or  - depending on what components you need).Recently, one of my client assignments involved evaluating Spring Stack Vs Custom framework stack Vs a Java EE Standards. After a month of evaluation and prototyping, I was not just happy but blown away by the Java EE 6 feature set. For any new \"enterprise\" project architecture in 2011 and going forward, I would go with Java EE 6 and potential extensions like Seam 3 or the upcoming Apache JSR299 extensions project. Java EE 6 Architecture is streamlined and incorporates best of many open source ideas that have evolved in the last several years. Consider the following features out of the box: Event Management, Contexts and DI, Interceptors, Decorators, RESTful webservices, integrated testing with embeddable container, Security, and many more.Most of my results are  explaining the key concepts of Java EE 6 that you might find useful.Of course, there is no hard and fast rule for choosing a framework. Java EE 6 could be well bloated for simpler \"web sites\" that don't require a rich conversational session state. You might as well pick Grails or Play! Framework. But for conversational web applications, I can't see a better argument why Java EE 6 is not a good fit.Now, after some time, I have experience with stacks : My colclusions are:Read Adam Bien's , including comments to get both sides of coin. I will choose Spring for several reasons and following is one of them (reproducing one of the comments from post)'I am not sure which Java EE 6 server you are talking about. There is Glassfish certified and TMAX JEUS. It will take quite a while (read: years) until Java EE 6 compliant versions of WebSphere, WebLogic, JBoss etc are in production and can be used for real application. Spring 3 just needs Java 1.5 and J2EE 1.4 so can readily be used in almost all environments' My opinion is based on something not mentioned by others, namely that code at my work tend to live for decades (literaly), and hence that maintenance is very important to us.  Maintenance of our own code, and the libraries we use.  Our own code we control, but it is in our interest that the libraries we use, are maintained by  in the above mentioned decades or more.To make a long story short, I have concluded that the best way to achieve this is by using open source implementations of Sun specifications all the way down to the raw JVM.Of the open source implementations Apache Jakarta has proven to maintain their libraries, and recently Sun has done a lot of work in producing high quality implementations for Glassfish v3.  In any case, we also have the source for all modules, so if all else fails, we can maintain them ourselves.Sun specifications are usually very strict meaning that implementations conforming to the spec can be interchanged easily.  Just have a look at servlet containers.In this particular case, I would suggest having a look at JavaServer Faces simply because it is part of Java EE 6 meaning it will be available and maintained for a very, very long time.  Then we have chosen to augment with MyFaces Tomahawk as it gives some useful additions, and it is a jakarta project.There is nothing wrong with JBoss Seam or others.  It is just that their focus is less towards the maintenance issue that is so important to us.I can see using Spring if you already have it, but for the new project, what's the point? I would go directly with Java EE 6 (ejb3, jsf2.0, etc.)If the client is fine with Flex, go for it. Use BlazeDS or similar - no mvc. You might spend more time on that part (exchanging data between server and client) but you have full control on both sides.Don't use Vaadin, unless you want to kill your browser. Plus, you spend more time on getting around the code once your pages become more complex. Also, your mindset will need to be completely changed and anything you know about standard front end development will be waste. The argument that you don't have to use HTML or JS doesn't make much sense. You still have to know it even if you don't use it. It renders to HTML and JS eventually. Then try to debug it - make sure you got few days for simple stuff. Plus, I cannot imagine web developer who doesn't know html/js.I just don't understand why people are trying all those abstractions instead of using Java EE directly.Why is there still rumblings about EJB being heavyweight in 2010? It seems people are not being updated in Java EE technologies. Just try it out , you will be pleasantly surprised how things are simplified in Java EE 6. The answer to your questions depends on your project requirements. If you don't require the Java EE features like message queues, container managed global transactions etc then go with tomcat+spring.Also from experience I have found that projects that require a lot of web service integration, scheduling, message queues are best best done using some of the Java EE stack.\nThe good thing is using spring you can still integrate with Java EE modules running in an application server. Java EE 6 is very different from the previous releases, and it really makes everything lot easier. Java EE 6 combines the best ideas from the diverse Java community - for instance Rod Johnson from Spring framework was actively involved in the making of the Dependency Injection JSR in Java EE 6. A benefit of using Java EE 6 is that you are coding according to a standard, which could be important in some organizations for vendor support etc. GlassFish v3 supports Java EE 6 and it is quite light-weight and starts up really fast. I have been using glassfish v3 for my developments, and it is really easy to configure. It comes with a very user-friendly admin console that lets you graphically administer your server.If you are using GlassfishV3 and JSF 2, then you can take advantage of the CDI features of Java EE 6, that lets you easily create conversations (e.g. wizard like pages) in JSF.Having said that, using Java EE 6 also requires you to learn a new API. Depending on the timeframe available it might not be the best choice for you. Tomcat has been around for ages, and the tomcat+spring combination has been adopted by many web projects, which means lots of documentation/forums are around.I have worked in both Spring and Java EE 6. What I can say from my experience is that If you are going for the age old JSP or proprietary Flex then you are safe if you stay with Spring.But if you are to move ahead with JSF then it's time to shift to Java EE 6. With Java EE 6 you are moving to Facelets and standardized script libraries and component libraries. No more script incompatibilities and component library matrices.Regarding Spring MVC, it's good as long as your project doesn't grow too big. If it's a huge enterprise application stick on to Java EE 6. Because that's the only way you could maintain your own component libraries and resource bundles in an orderly manner.If you need the Java EE full stack I recommend you GlassFish 3.1. It starts very quickly compared to other Java EE containers which implements some part or all Java EE 6 (JBoss 6, WebLogic 10.3.4), redeployment take seconds and almost all can be done by convention over configuration, it is very friendly.I you want something \"Light\" you can customize an Apache Tomcat 7.x with the desired features. I used a lot with the following libraries:\nWeld 1.1.0 (CDI)\nJPA 2.0 (Hibernate 3.6.x) - only resource local transactions\nJSF 2.x (Mojarra)\nRichFaces 4.0\nBIRT runtimeBeen a Java EE developer for the past 10 years (I suffer early EJB, JSF and web technologies), Java EE 6 is very easy, well coupled and current hardware runs smooth so original reasons that motivated Spring are no longer valid.I'd still prefer Spring.And I'd pass on JSF.  I think it's a dead technology.  Spring MVC would be a better alternative.  So would Flex.  Think in terms of contract first XML services and you can decouple the back end from the UI completely.  I'd recommend Spring + Tomcat unless you can wait the time for glassfish v3 and Weld to become more mature.  There are currently a few issues with memory consumption/cpu load when running glassfish with CDI enabled applications.Didn't read everything but just to tell that you can now use EJB3 inside a war on Java EE 6 so you can use EJB3 on Tomcat (I think).I recommended to you Tomcat with Spring because:It is good choice to choose Tomcat because you don't need any heavyweight processing
Java

I have enums like:When formatting the file, the output becomes:The answer by @wjans worked fine for normal enums, but not for enums with arguments. To expand on his answer a bit, here's the settings that provided the most sensible formatting for me in Eclipse Juno:This sets the 3 subnodes for the enum treenode to the same wrapping policy, and the same force split policy except for the  treenode, so your enums with arguments will be formatted each on their own line. The arguments will only wrap if they exceed maximum line width.You can specify this in your formatter preferences:It's slightly ugly too, but if your company policy prevents you from changing the formatter, you can just put comments at the end of lines you don't want to be wrapped.It's not nice but you can turn the Eclipse formatter off for some sections of code...the option is in the Windows->Preferences->Java->Code Style->Formatter->Edit->Off/On Tags panelYou need to set the line wrapping policy under enum declaration for \"Constants.\"Set the wrapping policy to
Java

I have several output listeners that are implementing .\nThey can be either a  writing to stdout or to a , or they can be writing to memory or any other output destination; therefore, I specified  as an argument in the method.Now, I have received the String. What is the best way to write to streams here?Should I just use ? I can give it bytes, but if the destination stream is a character stream then will it convert automatically?Do I need to use some bridge streams here instead?Thank you.Streams ( and ) transfer  data. If you want to write a string to a stream, you must first convert it to bytes, or in other words  it. You can do that manually (as you suggest) using the  method, but you should avoid the  method, because that uses the default encoding of the JVM, which can't be reliably predicted in a portable way.The usual way to write character data to a stream, though, is to wrap the stream in a , (often a ), that does the conversion for you when you call its  (or ) method. The corresponding wrapper for InputStreams is a . is a special  implementation in the sense that it also contain methods that automatically encode strings (it uses a writer internally). But it is still a stream. You can safely wrap your stream with a writer no matter if it is a  or some other stream implementation. There is no danger of double encoding.OutputStream writes bytes, String provides chars. You need to define Charset to encode string to byte[]:Change  to a charset of your choice.You can create a PrintStream wrapping around your OutputStream and then just call it's print(String):Wrap your OutputStream with a  and use the print methods on that class.  They take in a String and do the work for you. it is to be done this way:You may use :
Java

I'm trying to write an app that helps you manage your finances.  I'm using an  Field where the user can specify an amount of money.I set the  to  which works fine, except that this allows people to enter numbers such as  which is not perfect for money.Is there a way to limit the number of characters after the decimal point to two?More elegant way would be using a regular expression ( regex ) as follows:To use it do: Simpler solution without using regex:To use: This implementation of  solves the problem.Here is a sample  which only allows max 4 digits before the decimal point and max 1 digit after that.Values that edittext allows: , , Values that edittext blocks: , , I achieved this with the help of  by the following wayThis solution will not allow the user to enter more than two digit after decimal point. Also you can enter any number of digits before decimal point. See this blog  to set filter for multiple EditText. I hope this will help. Thank you.I made some fixes for @Pinhassi solution. It handles some cases:1.you can move cursor anywhere2.minus sign handling3.digitsbefore = 2  and digitsafter = 4 and you enter 12.4545. Then if you want to remove \".\", it will not allow.My solution is simple and works perfect!Usage:I don't like the other solution and I created my own.\nWith this solution you can't enter more than MAX_BEFORE_POINT digit before the point and the decimals can't be more than MAX_DECIMAL.You just can't type the digit in excess, no other effects!\nIn additional if you write \".\" it types \"0.\"And it's done!Try using  to format your string before you put it into a TextView.Something like: - There is no inputType for currency that I could find in the docs. I imagine this is because there are some currencies that don't follow the same rule for decimal places, such as the Japanese Yen.As LeffelMania mentioned, you can correct user input by using the above code with a  that is set on your .Slightly improved @Pinhassi solution.Works very well. It validates concatenated strings.The requirement is  There should be  for digits before decimal point. So, solution should be,And use it as,Thanks to @Pinhassi for the inspiration.All answers here are pretty complex I tried to make it much simpler.Look at my code and decide for yourself - What this does is when you exit editing phase it formats the field to the right format. At them moment it has only 2 decimal charachters. I think this is pretty easy way to do this.I have modified the above solutions and created following one. You can set number of digits before and after decimal point.}Simple Helper class is here to prevent the user entering more than 2 digits after decimal :The InputFilter I came up with allows you to configure the number of digits before and after the decimal place.  Additionally, it disallows leading zeroes.Here is my solution:If the user enters a number with more than two numbers after the decimal point, it will be automatically corrected.I hope I have helped!I've also came across this problem. I wanted to be able to reuse the code in many EditTexts. This is my solution:Usage :Class:I really liked Pinhassi's answer, but noticed that after the user had entered the specified number digits after the decimal point you could no longer enter text to the left side of the decimal point.  The problem was that the solution only tested the previous text that had been entered, not the current text being entered.  So here is my solution that inserts the new character into the original text for validation.And the call to set the editText filterI improved on the solution that uses a regex by Pinhassi so it also handles the edge cases correctly. Before checking if the input is correct, first the final string is constructed as described by the android docs.Usage:@Meh for u..A very late response:\nWe can do it simply like this:Like others said, I added this class in my project and set the filter to the  I want. The filter is copied from @Pixel's answer. I'm just putting it all together. Now set the filter in your  like this.Here one important thing is it does solves my problem of not allowing showing more than two digits after the decimal point in that  but the problem is when I  from that , it returns the whole input I typed. For example, after applying the filter over the , I tried to set input 1.5699856987. So in the screen it shows 1.56 which is perfect.Then I wanted to use this input for some other calculations so I wanted to get the text from that input field (). When I called  it returns 1.5699856987 which was not acceptable in my case.So I had to parse the value again after getting it from the .  does the trick here after getting the full text from the . et = (EditText) vw.findViewById(R.id.tx_edittext);This works fine for me. It allows value to be entered even after focus changed and retrieved back. For example: ,  , , etc..1.\nSpecifies the length of the input  accessed from  file.It is quiet easy to change values.\n2., this is for decimal places max limit.Array of  values that allows to perform action.I just used array of values that contain multiple edittext\nNext  file.Here is the  that allow only  number of digits after decimal point.ThanksThis is to build on pinhassi's answer - the issue that I came across was that you couldn't add values before the decimal once the decimal limit has been reached.  To fix the issue, we need to construct the final string before doing the pattern match.The simplest way to achieve that is:I have changed answer \u21166 (by Favas Kv)  because there You can put just point in the first position.  This is the simplest solution to limit the number of digits after decimal point to two.Hope this helps!
Java

Two questions about using a question mark \"?\" and colon \":\" operator within the parentheses of a print function:  What do they do? Also, does anyone know the standard term for them or where I can find more information on their use?  I've read that they are similar to an 'if' 'else' statement.This is the , which can be used anywhere, not just the print statement. It's sometimes just called \"the ternary operator\", but , just the most common one.Here's a good example from Wikipedia demonstrating how it works:Basically it takes the form:So if the boolean statement is true, you get the first part, and if it's false you get the second one.Try these if that still doesn't make sense:Thats an if/else statement equilavent toMaybe It can be perfect example for Android,\n since the condition is false it takes y value.A question mark (?)\n. The value to use if the condition is trueA colon (:)\n. The value to use if the condition is falseit is a ternary operator and in simple english it states Also just though I'd post the answer to another related question I had,Is equivalent to:If x is false or null then the value of y is taken.They are called  since they are the only one in Java. The difference to the if...else construct is, that they return something, and this something can be anything: 
Java

I was testing out some new features of Java 8 and copied the example into my IDE (Eclipse originally, then IntelliJ) as shown here:\nEclipse offered no support whatsoever for lambda expressions, and IntelliJ kept reporting an error \"Lambda expressions not supported at this language level\".  I would like to know if this is a problem with my install, the code, or support.In IntelliJ IDEA:In  \u2192  \u2192 , change  to You should change source code Language Level also on the Source tab (Modules part). For intellij 13, \nSimply change the  itself to  with following navigation. I also had to update  when there was no maven plugin for .But this  would automatically be fixed if there's already a  for it, Just add  in build.gradle yours app:Actually, Eclipse support for Java 8 is available: see  and .To compile with Java 8 (lambdas etc) in IntelliJ IDEA 15;As Stephen C pointed out, Eclipse Kepler (4.3) has Java 8 support when the patch is installed (installation instructions )Once installed, you\u2019ll need to tell your projects to use java 8. First add the JDK to eclipse:Then tell the project to use JDK 1.8:In intellij 14, following settings worked for me.\nEven after applying above defined project specific settings on IntelliJ as well as Eclipse, it was still failing for me !Possible Cause #1 (same as the first 3 answers for this question): Project Structure SettingsIf the above does not work, check the  of your compiler and move on to Possible Cause #2.Possible Cause #2: CompilerBest wishes :)Adding following block to pom file worked for me :Ctrl + Alt + Shift + S and then from project select the language level 1.8, read more about Lambda Expressions 
Java

I'm trying to mess with the new RecyclerView and whenever I try to run it, my app immediately crashes. It gives me NullPointerException for trying to access methods from . I've looked at other posts and saw that most people didn't have  but I tried that and it hasn't helped at all. Not really sure what to do at this point, any help would be appreciated. Here the error log: (I would post a picture but I don't have 10 rep yet)This issue usually occurs when no  was provided for the . You can do it like so:  In my case it was not connected to 'final', but to the issue mentioned in @NemanjaKova\u010devi\u0107 comment to @aga answer.\nI was setting a layoutManager on data load and that was the cause of the same crash. \nAfter moving the layoutManager setup to onCreateView of my fragment the issue was fixed.Something like this:For me, I was having the same issue, the issue was that there was an unused RecyclerView in xml with view gone but I am not binding it to any adapter in Activity, hence the issue. It was solved as soon as I removed such unused recycler views in xmli.e - I removed this view as this was not called in code or any adapter has been setI experienced this crash even though I had the  properly set. I had to move the   initialization code into the  callback to fix this issue.You need to use  in the  method. Before adding  to a view, it must have the  set.Since LinearLayoutManager is vertical by default, an easier way to do this is:If you want to change the orientation you could use this constructor:I got this issue due to wrong reference recycler view id.recyclerView = (RecyclerView) findViewById(R.id.rv_followers_list);torecyclerView = (RecyclerView) findViewById(R.id.rv_search_list);Check with you recycler view ID, pointing to actual recycler view solved my issueI think the problem in your Adapter.\nMake sure you have returned ViewHolder in onCreateViewHolder().\nLike below
Java

I do not understand this process at all. I have been able to navigate to the folder containing the keytool in the Java sdk. Although I keep getting the error openssl not recognised as an internal or external command. The problem is even if I can get this to work, what would I do and with what afterwards?Any help would be much appreciated.Here is what you need to do -Download openSSl from \nExtract it. create a folder- OpenSSL in C:/ and copy the extracted code here.detect debug.keystore file path. If u didn't find, then do a search in C:/ and use the Path in the command in next step.detect your keytool.exe path and go to that dir/ in command prompt and run this command in 1 line-it will ask for password, put android\nthat's all. u will get a key-hashOpen Terminal : You will find  in the \".android\" folder. Copy it and paste onto the desktop and run the above command. Make sure that in both cases it asks for a password. If it does not ask for a password, it means that something is wrong in the command. Password for  is  and for release you have to enter password that you .OpenSSL: You have to install that if it doesn't come preinstalled with your operating system . How to install that depends on your OS (for Windows check the  provided by coder_For_Life22). The easiest way without fiddling around is copying that openssl.exe binary to your keytool path if you are on Windows. If you don't want to do that, you have to add it to your  environment variable. Then execute the command provided in the docs.Note that the argument after  points to your debug keystore. This location also depends on your operating system. Should be in one of the following locations:If you did everything right, you should be prompted for a password. That is  for the debug certificate. If the password is correct the console prints a hash (somewhat random chars and numbers). Take that and copy it into the  field inside the preferences of your app on facebook. To get there, go to , select your app, go to  and scroll down. After that, wait a few minutes until the changes take effect.Please try this:to generate your key hash on your local computer, run Java's keytool utility (which should be on your console's path) against the Android debug keystore. This is, by default, in your home .android directory). On OS X, run:On Windows, use:-hope this will help youRef - developer facebook siteThat's how I obtained my: So when you re trying to enter without the key, an exception will occur. Facebook put the RIGHT key into this exception. All you need to do is to copy it. :My computer -> properties -> Advanced configurations -> Advanced -> System variables -> under system variables find path, and  add this to its endings:\n;yourFullOpenSSLDir\\binNow open a command line on your jdk\\bin folder C:\\Program Files\\Java\\jdk1.8.0_40\\bin (on windows hold shift and right click -> open command line here) and use:And copy the 28 lenght number it generates after giving the password.For easy vedio tutorial link for the generate KeyHash Download openssl from I was having the same exact problem, I wasnt being asked for a password, and it seems that I had the wrong path for the keystore file.In fact, if the keytool doesn't find the keystore you have set, it will create one and give you the wrong key since it isn't using the correct one.The general rule is that if you aren't being asked for a password then you have the wrong key being generated.
Java

I intend to develop a small (Java) application for managing my finances. I believe I need to use an embedded database, but I have no experience regarding this issue. I tried to look at , but I can't decide which one would be more suitable for me. , ,  and  seem to be good candidates, but I still don't see how they compare to each other. I appreciate your help comparing them and helping me decide which one to use.I intend to use Hibernate for my application (unless you would recommend using DBMS-provided API), but I also want to have the ability to edit the database easily using a SQL browsing tool (modifying schema and changing data).Thank you.EitherorWhich one you use is up to you, depending how much performance and how much stability you need.The developer of H2 has put up a nice performance evaluation:\nI use  for pretty much all of my embedded database needs. You can also use Sun's Java DB that is based on Derby but the latest version of Derby is much newer. It supports a lot of options that commercial, native databases support but is much smaller and easier to embed. I've had some database tables with more than a million records with no issues.I used to use HSQLDB and Hypersonic about 3 years ago. It has some major performance issues at the time and I switch to Derby from it because of those issues. Derby has been solid even when it was in incubator at Apache.I needed to use Java embedded database in one of my projects and I did lot of research understanding pros and cons of each database. I wrote a blog listing pros and cons of popular embedded java databases (H2, HSQLDB, Derby, ObjectDB, Neo4j, OrientDB), you can have a look at it. I chose H2 as I thought it best suited my requirements.\nLink for the blog: \nHope it helps!I'd go with H2, the performance is meant to much better than Derby. Read  for more info. is a good candidate (the fact that it is used in OpenOffice may convinced some of you), but for such a small personnal application, why not using an object database (instead of a classic relationnal database) ?I used  in one of my projects, and I'm very satisfied with it. Being object-oriented, you don't need the whole Hibernate layer, and can directly insert/update/delete/query objects ! Moreover, you don't need to worry about the schema, you directly work with the objects and DB4O does the rest !I agree that it may take some time to get used to this new type of database, but check the  to see how easy it makes working with the DB !EDIT: As said in the comments, DB4O handles automatically the newer versions of the classes. Moreover, a tool for browsing and updating the database outside of the application is available here :  (Sun's distribution of Apache Derby) now ships  JDK 6!  I've been wanted to do something like Jason Cohen and have been thinking this looks like the easiest way being in the JDK distro (which of last week is now a requirement for my app).  Or maybe I am just lazy that way.We use HSQLDB in production as a \"no-configuration\" option for our application.  It allows people to trial without the hassle of setting up a real database.However we do  support it for normal use.  The reasons are several:For at least (2) and (3), there are ways around it but it's difficult; it's much easier to e.g. install MySQL. is: I haven't had a chance to try it yet - but it looks very promising.  Note this is not an SQL database - your object graph is persisted for you - so it might not be appropriate for your existing app.Good comparison tool can be found here: Notice also the Head to Head DBMS/JPA ComparisonsI am a big fan of .Performance has become much better since the early releases. The licensing model isnt too bad, either. I particularly like the options available for querying your objects. Query by example is very powerful and easy to get used to.What criteria will you use to evaluate these ? If you don't know yet, then you don't need to decide right now. Try to make your application as database-implementation-agnostic as you can - providing the appropriate wrappers, data access objects etc., and make this decision when you have all the facts to hand and you have to decide.If you're using relational databases and SQL then the above shouldn't be too hard (using JDBC etc). Make sure you have plenty of surrounding tests so that when you want to switch between databases, you can determine that your application's functionality remains the same.I ran into the same issue some time ago. I didn't know which database to go for, so my first solution used Derby (or HSQLDB?), and I was later able to switch to HSQLDB (or Derby ? Can't remember which solution worked) once I'd determined where I had issues (relating to performance) and which solution would really work for me.HSQLDB may cause problems for large applications, its not quite that stable. The best I've heard (not first hand experience however) is berkleyDB. But unless you opensource it, it will cost you an arm and a leg to use due to licensing...see this  for details. ps. berkleyDB is not a relational database in case you didnt know.I have used Derby and i really hate it's data type conversion functions, especially date/time functions. (Number Type)<--> Varchar conversion it's a pain.So that if you plan use data type conversions in your DB statements consider the use of othe embedded DB, i learn it too late.Most things have been said already, but I can just add that I've used HSQL, Derby and Berkely DB in a few of my pet projects and they all worked just fine. So I don't think it really matters much to be honest. One thing worth mentioning is that HSQL saves itself as a text file with SQL statements which is quite good. Makes it really easy for when you are developing to do tests and setup data quickly. Can also do quick edits if needed. Guess you could easily transfer all that to any database if you ever need to change as well :)If I am correct H2 is from the same guys who wrote HSQLDB. Its a lot better if you trust the benchmarks on their site. Also, there is some notion that sun community jumped too quickly into Derby.I personally favor HSQLDB, but mostly because it was the first I tried.H2 is said to be faster and provides a nicer GUI frontend (which is generic and works with any JDBC driver, by the way).At least HSQLDB, H2 and Derby provide server modes which is great for development, because you can access the DB with your application and some tool at the same time (which embedded mode usually doesn't allow).I realize you mentioned SQL browsing, but everything else in your question makes me want to suggest you also consider , which is .I guess I'm a little late (a lot late;-)) to this post, but I'd like to add Perst, an open source, object-oriented embedded database for Java &.NET. for your consideration. Perst is an open source / dual license embedded database for Java. The distribution is compatible with Google's Android platform, and also includes Perst Lite for Java ME. We've even built an Android benchmark and produced a whitepaper on the subject...you can take a look here: All the best,\nChris
Java

Since the method  is deprecated, which method are we supposed to use now? The following code:Gives the following warnings:You're using  instead of .If you are using org.junit.Assert.assertEquals(float expected,float actual) but still encounter this deprecate warning, it is because currently junit prefer a third parameter rather than just two float variables input.The third parameter is delta:\npublic static void assertEquals(double expected,\n                                double actual,\n                                double delta)\nfor more information, please refer this problem: 
Java

I'm trying to use javac with the windows command prompt, but its not working.After adding the directory \"C:\\Program Files\\Java\\jdk1.6.0_16\\bin\\\" to the end of the environment path variable, the java command works fine, but using javac gives me the error:Any ideas? Thanks.If you added it in the control panel while your command prompt was open, that won't affect your current command prompt. You'll need to exit and re-open or simply do:By way of checking, execute:from your command prompt and let us know what it is.Otherwise, make sure there  a javac in that directory by trying:from the command prompt. You can also tell  executable (if any) is being used with the command:This is a neat trick similar to the  and/or  commands in some UNIX-type operating systems.Windows OS searches the current directory and the directories listed in the PATH environment variable for executable programs. JDK's programs (such as Java compiler javac.exe and Java runtime java.exe) reside in directory \"\\bin\" (where  denotes the JDK installed directory, e.g., C:\\Program Files\\Java\\jdk1.8.0_xx). You need to include the \"\\bin\" directory in the PATH.To edit the PATH environment variable in Windows XP/Vista/7/8:(( now read the following 3 times before proceeding,  ))In \"Variable value\" field, INSERT \"c:\\Program Files\\Java\\jdk1.8.0_xx\\bin\" (Replace xx with the upgrade number and VERIFY that this is your JDK's binary directory!!!) IN FRONT of all the existing directories, followed by a semi-colon (;) which separates the JDK's binary directory from the rest of the existing directories.\nDO NOT DELETE any existing entries; otherwise, some existing applications may not run.After long Google, I came to know that javac.exe must be inside (C:\\Program Files\\Java\\jdk(version number)\\bin) not inside  (C:\\Program Files (x86)\\Java\\jre7\\bin)   in order to use  compiler javacjavac will not work if you are pointing bin inside jreIn order to use javac in cmd , JDK must be installed in your system...  this is wrong   this is correctMake sure that \"javac.exe\" is inside your Dont confuse with JRE and JDK  both are totally different if you dont have JDK pls download from this link reference thread for JDK VS JRE  I know this may not be your specific error, but I once had a leading space in my path and java would work but javac would not. For what it's worth, I offer the sage advice: \"Examine your Path closely\".Try the solutions here: These are much more robust to change -- like when you upgrade the JDK or JRE, since there is no hard coded path.The quick solution (if you don't want to read the blog) isYou can then add these lines to a startup/login script.I just had to do this to get this to work on windows 7 64.Open up a command prompt (cmd.exe) and type:Make sure you reopen all running command prompt Windows to get the environment variable updated as well.Okay this can not be the case always but many of us have done this mistake in the past and few out of those are still not aware of it, which is, every time you append a path (any path) of any environment variable, you're likely to hit the space bar right after the \"semicolon\" (as you normally would, after the \"period\" while typing in an editor).  This will create a leading space in the path e.g \" C:\\Program Files\\Java\\jdk1.6.0\\bin\" and therefore \"javac.exe\" won't be found by the system.Change the folder \"jdk1.7.0_45\" \"jdk1_7_0_60\" and update the path in Windows environment. Otherwise, the path ignores the dot at the front which stands for hidden file and so the folder is not displayed in PATH strings.I faced the exact same problem that java would work but javac would not on a cmd prompt in Windows 8.The problem occured because I forgot to remove  at the end of the path name, i.e., it was like this:where it was suppose to be like this:The path will only be set for the administrator account. Therefore it is important to launch command prompt as administrator, if you are not already.Ensure you don't allow spaces (white space) in between paths in the Path variable. My problem was I had white space in and I believe Windows treated it as a NULL and didn't read my path in for Java.I was having the same problem posted in this title. Java would work, but  would not in the Windows command prompt ().For me, it was simply that I had placed a space when adding  to the end of my  environment variable.\nRemove the space between the  and the next file path.I appreciate this is an old question now but my solution wasn't an answer on here so posting it in case anyone else tries all the rest.In my case, a previous install of the Java JRE (in ProgramData/Oracle/Java) had a path variable at the top of my list of path variables. The contents of that \"Oracle\" path had a java.exe but not a javac.exe.\nI added my full JDK path to the top of the list of path variables, ahead of the \"Oracle\" one, and it then picked up javac.exe as well as java.\";C:\\Program Files\\Java\\jdk1.6.0\\bin\" sometime you may forget to put semicolon on last existing path.When i tried to make the .java to .class the command Javac didnt work. I got it working by going to C:\\Program Files (x86)\\Java\\jdk1.7.0_04\\bin and when i was on that directory I typed Javac.exe C\\Test\\test.java and it made the class with that tactic. Try that out.Give it as \"C:\\Program Files\\Java\\jdk1.6.0_16\\bin\". Remove the backslash it will work
Java

I am looking into Spring Data JPA. Consider the below example where I will get all the crud and finder functionality working by default and if I want to customize a finder then that can be also done easily in the interface itself.I would like to know how can I add a complete custom method with its implementation for the above AccountRepository? Since its an Interface I cannot implement the method there.You need to create a separate interface for your custom methods:and provide an implementation class for that interface:In addition to axtavt's , don't forget you can inject Entity Manager in your custom implementation if you need it to build your queries:Im using the following code in order to access generated find methods from my custom implementation. Getting the implementation through the bean factory prevents circular bean creation problems.If you want to be able to do more sophisticated operations you might need access to Spring Data's internals, in which case the following works (as my interim solution to ):This is limited in usage, but for simple custom methods you can use  interface methods like:EDIT: In  tutorial it is written:So it is even possible to just declare method like:and if object  is a property of Customer then Spring will automatically define method for you.Considering your code snippet, please note that you can only pass Native objects to the  findBy### method, lets say you want to load a list of accounts that belongs  certain costumers, one solution is to do this, Make sure the name of the table  to be queried is thesame as the Entity class. that is all you need spring-data-jpa does the rest of the magic for you, just inject  this bean in your service class and use it.\nFor further implementations please take a look at  There is another issue to be considered here. Some people expect that adding custom method to your repository will automatically expose them as REST services under '/search' link. This is unfortunately not the case. Spring doesn't support that currently. This is 'by design' feature, spring data rest explicitly checks if method is a custom method and doesn't expose it as a REST search link:This is a qoute of Oliver Gierke:For more details see this issue: 
Java

How to make a  non-editable? I don't want my users to be able to edit the values in cells by double-clicking them.Any help would be greatly appreciated.Thanks.You can use a .Define a class like this:actually  is  by default so you may ommit it. (see: )Then use  method of your .You can override the method isCellEditable and implement as you want\nfor example:orIf your  is disappearing when you use this it is most likely because you need to use the  constructor instead.just add it works fine for me.If you are creating the TableModel automatically from a set of values (with \"new JTable(Vector, Vector)\"), perhaps it is easier to remove editors from columns:Without editors, data will be not editable.create new DefaultCellEditor class :and use setCellEditor : it is very simple and works fine.
Java

I'm generating a CSV file (delimited by commas rather than tabs). My users will most likely open the CSV file in Excel by double clicking it. My data may contain commas and speech marks, so I'm escaping those as follows.As far as I know that's always been the way to do it. Here's my boggle: when I open this file in Excel 2010 my escaping is not respected. Speech marks appear on the sheet, and the comma causes new columns.We eventually found the answer to this.Excel will only respect the escaping of commas and speech marks if the column value is NOT preceded by a space. So generating the file without spaces like this...... fixed the problem. Hope this helps someone!Below are the rules if you believe it's random. A utility function can be created on the basis of these rules.According to Yashu's instructions, I wrote the following function (it's PL/SQL code, but it should be easily adaptable to any other language).Even after double quotes, I had this problem for a few days.Replaced Pipe Delimiter with Comma, then things worked fine.
Java

I need a small code snippet which unzips a few files from a given .zip file and gives the separate files according to the format they were in the zipped file. Please post your knowledge and help me out. Had peno's version optimised a bit. The increase in performance is perceptible.Based on Vasily Sochinsky's answer a bit tweaked & with a small fix:Notable differencesSoshould do the equivalent of the originalThis is my unzip method, which I use:Android has build-in Java API. Check out  package.The class  is what you should look into. Read ZipEntry from the ZipInputStream and dump it into filesystem/folder. Check  file.While the answers that are already here work well, I found that they were slightly slower than I had hoped for. Instead I used , which I think is the best solution because of its speed. It also allowed for different options for the amount of compression, which I found useful.->Helper Class(Unzipper.java)->xml layout(activity_main.xml):->permission in Menifest file:According to @zapl answer,Unzip with progress report:UPDATE 2016 \n  use the following classHow to usePermissionsHere is a ZipFileIterator (like a java Iterator, but for zip files):Minimal example I used to unzip a specific file from my zipfile into my applications cache folder. I then read the manifest file using a different method.Use this library.add this jar file in lib folder of app. 
Java

I have just made a clean installation of , and I have downloaded  , but if I execute it, gives me this message:Asking me to install ; I have already installed , and if I press  in that dialog, download and install it, and open Eclipse again, the dialog appears again. How I can fix it?This is in part due to Oracle's missing definitions of the JRE8 VM capabilities.In case you don't want to install JRE6 at all and simply use JRE8 without symlinking it to the JRE6 either you can do the following:Copy the Info.plist located at the path named below to e.g. ~/Downloads/:and then replacewith the following:Afterwards copy the file back to its original location (you need administrator rights). For this change to take effect you need to log out of your account (and back in) or restart your computer. The dialog for Java 6 should shouldn't appear anymore and Eclipse should launch just fine using JRE8 (or JRE7). The same holds true for any other application that initially asks for Java, e.g. Adobe's Creative Suite.On a related note it appears that this plist change sticks even after updates done through the Java Preference Panel in the System Preferences.If it still doesn't work. You might need to add some folders and a symlink ():I had this problem after a Mavericks install.  I was able to solve it by installing Java from the Apple download at I hope this helps.To be able to run Eclipse with Java 7 (Oracle), I launch Eclipse using this file: eclipse/Eclipse.app/Contents/MacOS/eclipse. \"eclipse\" folder contains alias for this file by default. So all that you need to do is to double-click the alias named \"eclipse\".Also Oracle warns that Oracle's Java version 7u25 and below have been disabled by Apple on OS X (see ). I had upgraded to the latest JDK version before I found out the way of launching Eclipse with Java 7. So I don't know if the upgrade is necessary or not. You need to download and install the JAVA for MAC manually.  That is what worked for me.Download here: I happened to get it running without a procedure like the suggestions above. I erased the eclipse folder and then copied it back from the trashcan. Please verify if it works for you.On MAC OS X, after installing JRE 7 from Oracle using the .dmg download, on opening Eclipse, it still pointed back to my old JRE 6. After numerous google searches for the problem, and getting here, in desperation I clicked on \"Search\" in Eclipse --> Preferences --> Installed JREs and voila - it picked up JRE 7.  In my case, with  (installed from the OS X installer, downloaded from eclipse.org) and :
Java

I have a ArrayList made up of different elements imported from a db, made up of strings, numbers, doubles and ints. Is there a way to use a reflection type technique to find out what each type of data each element holds?  FYI: The reason that there is so many types of data is that this is a piece of java code being written to be implemented with different DB's.In C#:Fixed with recommendation from In Java:You can use the  method, or you can use instanceof. For exampleorNote that instanceof will match subclasses. For instance, of  is a subclass of , then the following will be true:However, the following will be false:You almost never want you use something like:because you aren't accounting for possible subclasses.  You really want to use Class#isAssignableFrom:In Java just use the instanceof operator. This will also take care of subclasses.Just call  on each  in a loop.Unfortunately, Java doesn't have . :)Instanceof works if you don't depend on specific classes, but also keep in mind that you can have nulls in the list, so obj.getClass() will fail, but instanceof always returns false on null.Since Java 8instead of using  you can use , because it returns a simple class name without a package name included.for instance,gives,You say \"this is a piece of java code being written\", from which I infer that there is still a chance that you could design it a different way.  Having an ArrayList is like having a collection of stuff.  Rather than force the instanceof or getClass every time you take an object from the list, why not design the system so that you get the type of the object when you retrieve it from the DB, and store it into a collection of the appropriate type of object?Or, you could use one of the many data access libraries that exist to do this for you.If you expect the data to be numeric in some form, and all you are interested in doing is converting the result to a numeric value, I would suggest:
Java

I am using persisting objects using JPA. The Main object has an owning One-Many relationship with another object. The other object is stored in a HashMap.  What sort of synchronisation would fix this problem?  It seems to happen at completely random times and is very unpredictable.  Here is the exception I get:This is not a synchronization problem.  This will occur if the underlying collection that is being iterated over is modified by anything other than the Iterator itself.This will throw a ConcurrentModificationException when the it.hasNext() is called the second time.The correct approach would be Assuming this iterator supports the remove() operation.Try using a ConcurrentHashMap instead of a plain HashMapIt sounds less like a Java synchronization issue and more like a database locking problem.I don't know if adding a version to all your persistent classes will sort it out, but that's one way that Hibernate can provide exclusive access to rows in a table.  Could be that isolation level needs to be higher.  If you allow \"dirty reads\", maybe you need to bump up to serializable.Try either CopyOnWriteArrayList or CopyOnWriteArraySet depending on what you are trying to do.
Java

I am trying to convert a long value (The number of milliseconds elapsed from 1/1/1970) to a time of format \nThe long value I use as timestamp, I get from the field  of logging event from log4j.\nHow do I do the conversion?\nFor example to get the minutes I tried the following and all fail:\n   and\n \nbut I get garbage:\nI get   How can I convert this?  ThanksTry this:List of other I'll show you three ways to (a) get the minute field from a long value, and (b) print it using the Date format you want. One uses , another uses , and the last uses the java.time framework built into Java 8 and later. The java.time framework supplants the old bundled date-time classes, and is inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project.The java.time framework is the way to go when using Java 8 and later. Otherwise, such as Android, use Joda-Time. The java.util.Date/.Calendar classes are notoriously troublesome and should be avoided.It is possible to use apache commons (commons-lang3) and its DurationFormatUtils class.For example:Hope it can help ...Doingwill give you hours, not minutes. Try:and you will end up with the same answer asTry this:
Java

My Java test worked well from Eclipse. But now, when I relaunch test from the run menu, I get the following message: In the  file I have all  files, and at the end have: How can I resolve this error and get tests running again?this just happened to me. Rebuilding or restarting Eclipse didn't help.I solved it by renaming one of the test methods to start with \"test...\" (JUnit3 style) and then  tests are found. I renamed it back to what it was previously, and it still works.When we get these errors it seems like Eclipse is just confused.  Restart Eclipse, refresh the project, clean it, let Eclipse rebuild it, and try again.  Most times that works like a charm.In context menu of your 'test' directory choose 'Build path' -> 'Use as a source folder'.\nEclipse should see your unitTests.java files as a source files.\nWarning 'No JUnit tests found' occures because there is no unitTests.class files in your 'build' directoryCheck if your test class extends \"TestCase\". if so, remove that clause. Your class does not need to extend from \"TestCase\" class. It's most of the cases I've met. Following TestCase should be fine.I was facing the same problem and I debugged it to bad examples on the web and internals of junit. Basically don't make your class extend TestCase as some examples show for Junit 4.x. Use some naming convention  or if you want to have an annotation you can use @RunWith(JUnit4.class).If you need access to assert methods extend Assert or use static imports.If your class extends TestCase then even if you use Junit 4 Runner it will be run as 3. This is because in the initialization code there is detection:See JUnit3Builder and the lines:This returns true and the test for junit4 compatibility won't be tried.Try Adding @Test above the method for the test like thisI have found out the answer:I got this error when I executed the test standalone from eclipse (right click on the method and choose to run as junit test), When I executed the complete class as junit test the test executed correctly with the parameters.No testsuits in JUnit4. Use annotations instead or use old JUnit3 name conventions.Example:When I face this problem I just edit the file and save it... works like charmMy problem was that declaration  has disappeared (or wasn't added?). After adding it, I had to remove another  declaration (Eclipse'll hint you which one) and everything began to work again.Very late but what solved the problem for me was that my test method names all started with captial letters: \"public void Test\". Making the t lower case worked.I tried the solution from Germ\u00e1n.\nIt worked for all the method from my class but i have a lot of classes in my project.So I tried removing from build path and then re-adding it.\nIt worked perfectly.Hope it helps.This happened to me as well. I tried restarting Eclipse and also prefixed my test-methods with tests. Neither worked.The following step worked:\nChange all your test methods present in @BeforeClass and @AfterClass to static methods.i.e. if you have your test method in the below format:then change it to:This worked for me.Yet another possible solution I'll throw into the ring: I wasn't able to run the test class either from the editor window, nor the Package Explorer, but right-clicking on the class name in the Outline view and selecting Run As JUnit Test did work... Go figure!May be your JUnit launch configuration was for a individual test class, and you somehow changed that config to \"run all tests in a source folder, package or project\"But that could trigger the \"No tests found with test runner 'JUnit 4'\" error message.Or you did a modification in your test class, removing the  annotation.\nSee this .I also faced the same issue while running JUnit test. I resolved this by putting the annotation @Test just above the main test function.What fixed my case was similar to @JamesG's answer:  I restarted Eclipse, rebuilt the project, and refreshed it; BUT before I did any of that, I 1st closed the project (right-click project in package explorer -> Close Project) and then re-opened it.  Then it worked.A workaround solution I found before finding that ultimate solution I just described:  Copy the test class, and run the test class as JUnit.Check if the folder your tests are in is a source folder. If not - right click and use as source folder.Close and open the project worked for me.Six years later ... and there are still problems with Eclipse and occasionally not finding JUnits.In my Eclipse Mars 2 I discovered that it won't recognise test classes pulled in from git if there are more than 9 or 10  annotations in the file. I need to comment out any extra tests, run the test class, then uncomment them and re-run the class. Go figure...Is your Eclipse project maven based? If so, you may need to update the m2eclipse version. From here: This happened to me too. I found that in Eclipse I didn't make a new Java Class file and so that's why it wasn't compiling. Try copying your code into a java class file if it's not already there and then compile.I found out that Eclipse seems to only perform JUnit 3 style tests if your test-class extends from . If you remove the inheritance, the annotations worked for me.Beware that you need to statically import all the required  methods like .I'm also running Eclipse with Maven (m2e 1.4). The tests were running with Maven, but not with Eclipse... even after several application of .My solution was to add some lines in the .classpath generated by m2e. The lines are now sticking.I have this problem from time to time. The thing that resolves the issue most for me is to run the JUnit test from Run configurations... ensuring that JUnit 4 is set as the test runner.Generally, I see this issue when attempting to Run As... Junit test from the context menu on the Package Explorer. If you right click the code for the test you are trying to run and instead of selecting Run As... Junit Test you select Run configurations... ensure the Project, Test Class and test runner are set correctly, clicking apply, then run works all the time for me.I started to work with Selenium and Eclipse in my job and I was doing my first automated test and I deleted from the code @Before, @Test, and @After notes and I was having this issue \"No tests found with test runner junit4\".My solution it was simply to add again the @Before, @Test and @After notes and with that my script worked. Is important to not delete this from the code.This is a simple test that uses Google to search something:Using ScalaIDE (3.0.4-2.11-20140723-2253-Typesafe) I was having a similar problem with the  context menu.I tried editting the class(but not for a compile failure), cleaning, closing the project, closing Eclipse.  None of those worked to restore the context menu for classes that had previously worked well.  The test classes don't use the  annotation and instead use the  annotation at the top of the class using ScalaTest code.When I tried choosing  from the Run Configuration launch editor directly, I received the dialog from the question.  Footix29's answer was the key for me.I noticed that even though I had cleaned my project a few times, my classes in the /bin directory hadn't actually been rebuilt in a while.Here's how I got back the context menu, and was able to once again run s:I suspect that a class edit in general is able to clean some saved state of Eclipse and get it going again.  In my case all of the previously working classes I tried had failed so the  clean step was just the hammer I needed.  However, other tricks that affect Eclipse's concept of the class path/build state should also work.Further, I think that this behaviour was triggered in part by attempting to refactor a Scala class by renaming it( which the Scala Eclipse IDE sucks at ), where all the cleanup after the initial file change is manual.  There were no build errors, but there were also no warnings that I was expecting meaning something was definitely stuck in Eclipse's build state info.There is another chance, you might have changed Junit Test from lower version(e.g. Junit 3) to Junit 4 .\nIs so follow below steps:-Right Click the Project -> Build Dependencies -> remove the ones which have been excluded from the build path -> Click OKRight Click the Project -> Maven -> Update Project.You should be good to go..You can fix this issue by do as following:This issue happened because of junit cannot recognize your source code :D
Java

I have a Java bean. Now, I want to be sure that the field should be unique.\nI am using following code:But am getting some error:Whats the proper way to use unique constraints? I am using play framework.To ensure a field value is unique you can writeThe @UniqueConstraint annotation is for annotating multiple unique keys at the table level, which is why you get an error when applying it to a field.References (JPA TopLink):You can use at class level with following syntaxI'm currently using play framework too with hibernate and JPA 2.0 annotation and this model works without problems        Hope it helped. In Kotlin the syntax for declaring the arrays in annotations uses  instead of Unique constraints used only for creating composite key ,which will be unique.It will represent the table as primary key combined as unique. you can use  @UniqueConstraint   on class level, for combined primary key in a table. for example:public class ProductAttribute{}
Java

I want to change the automatic author that appears when I create a file in AndroidStudio.The author takes 'a556520' but I want that appears my name, and not the number of employee. Is that possible?\nI didnt found in the settings.You can overwrite the  variable in the template file with the  function. Go to Settings -> File and Code Templates -> Includes -> File Header prepend the  function call, for example:The above answers are correct. But you can go even further and define your own variables - such as User, Company, Email etc.:1)Open Android Studio  dialog.2)In the search box, write \"File and Code Templates\".3)Select the left menu item \"File and Code Templates\".4)From the middle tabular navigation section, select .5)Select  item that applies to the Java files.6)You will find an editor section that allow you to edit it for the required pattern. Use the description section below to understand the different parameters that can be used.Note: For the  attribute, you can simply write it directly without using attributes. Also you can add your company name or project name in the same way also such as:Press ++ then go to . Here you can set up what you want. E.g. replace  to your name.You can change template for file header by going to  Preferences -> Editor -> File and Code Templates. Then change  in File Header under Includes tab. However this is hardcoding solution it would be better to change actual value of  variable.Actually the correct way to change the username is to change the name\nof the current user logged in into Windows. (if you're using windows)Android Studio uses the name saved in %USERNAME% variable.\nThis is the name you get if you type  into a command console\nor batch file. And it is the name that is stored under C(orWhatEver):\\User.To change the name you can  just change the name of the profile \nyou are logged in. \nYou need to create a new user and give it the correct name.\nThis way, even if you reinstall AndroidStudio some day, you will end with\nthe correct  again.The easier way surely is to just hard code your name into the template.\nBut that is just treating the symptoms and you should use the way to fix the root cause.
Java

During my work with databases I noticed that I write query strings and in this strings I have to put several restrictions in the where-clause from a list/array/collection. Should look like this:You can simplify this by reducing this to the question that you have collection of strings and want to create a comma-separated list of this strings in just one string.My approach I have used so far is something like that:But this is as you can see very ugly. You cannot see what happens there on the first look, especially when the constructed strings (like every SQL query) is getting complicated.What is your (more) elegant way?Since strings are immutable, you may want to use the StringBuilder class if you're going to alter the String in the code.The StringBuilder class can be seen as a mutable String object which allocates more memory when its content is altered.The original suggestion in the question can be written even more clearly and efficiently, by taking care of the :Use the 's  method:I just looked at code that did this today.  This is a variation on AviewAnew's answer.The  ( <-- commons.lang 2.x, or ) we used is from .The way I write that loop is:Don't worry about the performance of sep. An assignment is  fast. Hotspot tends to peel off the first iteration of a loop anyway (as it often has to deal with oddities such as null and mono/bimorphic inlining checks).If you use it lots (more than once), put it in a shared method.There is another question on stackoverflow dealing with how to insert a list of ids into an SQL statement.Since Java 8, you can use:I found the iterator idiom elegant, because it has a test for more elements (ommited null/empty test for brevity):There's a lot of manual solutions to this, but I wanted to reiterate and update Julie's answer above. Use .It handles var args, iterables and arrays and properly handles separators of more than one char (unlike gimmel's answer). It will also handle null values in your list if you need it to.Here's an incredibly generic version that I've built from a combination of the previous suggestions:available in the Java8 api.alternative to (without the need to add a google guava dependency):I think it's not a good idea contruct the sql concatenating the where clause values like you are doing :Where valueX comes from a list of Strings. First, if you are comparing Strings they must be quoted, an this it isn't trivial if the Strings could have a quote inside. Second, if the values comes from the user,or other system, then a SQL injection atack is posible.It's a lot more verbose but what you should do is create a String like this:and then bind the variables with Statement.setString (nParameter,parameterValue)You could tryThis will be the shortest solution so far, except of using Guava or Apache CommonsGood with 0,1 and n element list. But you'll need to check for null list.\nI use this in GWT, so I'm good without StringBuilder there. And for short lists with just couple of elements its ok too elsewhere ;)In case someone stumbled over this in more recent times, I have added a simple variation using Java 8 . It also includes some of the already mentioned solutions by others:Just another method to deal with this problem. Not the most short, but it is efficient and gets the job done.There are some third-party Java libraries that provide string join method, but you probably don't want to start using a library just for something simple like that. I would just create a helper method like this, which I think is a bit better than your version, It uses StringBuffer, which will be more efficient if you need to join many strings, and it works on a collection of any type.Another suggestion with using Collection.toString() is shorter, but that relies on Collection.toString() returning a string in a very specific format, which I would personally not want to rely on.If you use Spring, you can do:(package org.springframework.util)In Android you should use this:I'm not sure how \"sophisticated\" this is, but it's certainly a bit shorter. It will work with various different types of collection e.g. Set<Integer>, List<String>, etc.: modify this method so that it correctly handles a null/empty collection :)What makes the code ugly is the special-handling for the first case.  Most of the lines in this small snippet are devoted, not to doing the code's routine job, but to handling that special case.  And that's what alternatives like gimel's solve, by moving the special handling outside the loop.  There is one special case (well, you could see both start and end as special cases - but only one of them needs to be treated specially), so handling it inside the loop is unnecessarily complicated.Join 'methods' are available in Arrays and the classes that extend AbstractCollections but doesn't override toString() method (like virtually all collections in java.util)for instance:\nString s= java.util.Arrays.toString(collectionOfStrings.toArray());s = s.substing(1, s.length()-1);// [] are guaranteed to be therethat's quite weird way since it works only for numbers alike data sql wise.I've just checked-in a test for my library :it create a fluent wrapper around lists/arrays/strings/etc using : .:using ranges the previous list can be re-writed as The nice thing about the IN expression is that if you have repeated values, it does not change the result.  So, just duplicate the first item and process the entire list.  This assumes that there is at least one item in the list.  If there are no items, I'd suggest checking for that first and then not executing the SQL at all.This will do the trick, is obvious in what it is doing and does not rely on any external libraries:While I think your best bet is to use Joiner from Guava, if I were to code it by hand I find this approach more elegant that the 'first' flag or chopping the last comma off.  if you have an array you can do:You may be able to use LINQ (to SQL), and you may be able to make use of the Dynamic Query LINQ sample from MS. List token=new ArrayList(result);\nfinal StringBuilder builder = new StringBuilder();builder.toString();Another option, based on what I see here (with slight modifications).There is an easy way. You can get your result in a single line. To get complete idea check the code below
Java

I thought about this awhile ago and it recently resurfaced as my shop is doing its first real Java web app.As an intro, I see two main package naming strategies.  (To be clear, I'm not referring to the whole 'domain.company.project' part of this, I'm talking about the package convention beneath that.)  Anyway, the package naming conventions that I see are as follows:So I guess the question then would go out to you, how do you name your packages and why?  Please understand that I don't necessarily think that I've stumbled onto the golden goose or something here.  I'm pretty new to all this with mostly academic experience.  However, I can't spot the holes in my reasoning so I'm hoping you all can so that I can move on.For package design, I first divide by layer, then by some other functionality.There are some additional rules:So, for a web application for example, you could have the following layers in your application tier (from top to bottom):For the resulting package layout, these are some additional rules:Here is an example layout.The presentation layer is divided by view technology, and optionally by (groups of) applications.The application layer is divided into use cases.The service layer is divided into business domains, influenced by the domain logic in a backend tier.The integration layer is divided into 'technologies' and access objects.Advantages of separating packages like this is that it is easier to manage complexity, and it increases testability and reusability. While it seems like a lot of overhead, in my experience it actually comes very natural and everyone working on this structure (or similar) picks it up in a matter of days.Why do I think the vertical approach is not so good?In the layered model, several different high-level modules can use the same lower-level module. For example: you can build multiple views for the same application, multiple applications can use the same service, multiple services can use the same gateway. The trick here is that when moving through the layers, the level of functionality changes. Modules in more specific layers don't map 1-1 on modules from the more general layer, because the levels of functionality they express don't map 1-1.When you use the vertical approach for package design, i.e. you divide by functionality first, then you force all building blocks with different  of functionality into the same 'functionality jacket'. You might design your general modules for the more specific one. But this violates the important principle that the more general layer should not know about more specific layers. The service layer for example shouldn't be modeled after concepts from the application layer.I find myself sticking with Uncle Bob's .  In short, classes which are to be reused together and changed together (for the same reason, e.g. a dependency change or a framework change) should be put in the same package.  IMO, the functional breakdown would have better chance of achieving these goals than the vertical/business-specific break-down in most applications.  For example, a horizontal slice of domain objects can be reused by different kinds of front-ends or even applications and a horizontal slice of the web front-end is likely to change together when the underlying web framework needs to be changed.  On the other hand, it's easy to imagine the ripple effect of these changes across many packages if classes across different functional areas are grouped in those packages.  Obviously, not all kinds of software are the same and the vertical breakdown may make sense (in terms of achieving the goals of reusability and closeability-to-change) in certain projects.  There are usually both levels of division present. From the top, there are deployment units. These are named 'logically' (in your terms, think Eclipse features). Inside deployment unit, you have functional division of packages (think Eclipse plugins).For example, feature is , and it consists of ,  and  plugins. Inside plugins, I have very little division to other packages, although that's not unusual too. Btw, there is great talk by Juergen Hoeller about code organization at InfoQ: . Juergen is one of architects of Spring, and knows a lot about this stuff.Most java projects I've worked on slice the java packages functionally first, then logically.Usually parts are sufficiently large that they're broken up into separate build artifacts, where you might put core functionality into one jar, apis into another, web frontend stuff into a warfile, etc. I personally prefer grouping classes logically then within that include a subpackage for each functional participation. Packages are after all about grouping things together - the idea being related classes live close to each other. If they live in the same package they can take advantage of package private to limit visibility. The problem is lumping all your view and persitance stuff into one package can lead to a lot of classes being mixed up into a single package. The next sensible thing to do is thus create view, persistance, util sub packages and refactor classes accordingly. Underfortunately protected and package private scoping does not support the concept of the current package and sub package as this would aide in enforcing such visibility rules.I see now value in separation via functionality becase what value is there to group all the view related stuff. Things in this naming strategy become disconnected with some classes in the view whilst others are in persistance and so on.For purposes of illustration lets name two modules - ill use the name module as a concept that groups classes under a particular branch of a pacckage tree.A client using the Banana.store.BananaStore is only exposed to the functionality we wish to make available. The hibernate version is an implementation detail which they do not need to be aware nor should they see these classes as they add clutter to storage operations.The further up towards the root the broader the scope becomes and things belonging to one package start to exhibit more and more dependencies on things belonging to toher modules. If one were to examine for example the \"banana\" module most of the dependencies would be limited to within that module. In fact most helpers under \"banana\" would not be referenced at all outside this package scope. What value does one achieve by lumping things based on functionality. Most classes in such a case are independent of each other with little or no need to take advantage of  package private methods or classes. Refactoring them so into their own subpackages gains little but does help reduce the clutter.When developers are tasked to make changes that are a bit more than trivial it seems silly that potentially they have changes that include files from all areas of the package tree. With the logical structured approach their changes are more local within the same part of the package tree which just seems right.Both  (architectural) and  (feature) approaches to packaging have a place. Many example applications (those found in text books etc.) follow the functional approach of placing presentation, business services, data mapping, and other architectural layers into separate packages. In example applications, each package often has only a few or just one class. This initial approach is fine since a contrived example often serves to: 1) conceptually map out the architecture of the framework being presented, 2) is done so with a single logical purpose (e.g. add/remove/update/delete pets from a clinic).  The problem is that many readers take this as a standard that has no bounds.As a \"business\" application expands to include more and more features, following the  approach becomes a burden. Although I know where to look for types based on architecture layer (e.g. web controllers under a \"web\" or \"ui\" package, etc.), developing a single  feature begins to require jumping back and forth between many packages. This is cumbersome, at the very least, but its worse than that. Since logically related types are not packaged together, the API is overly publicized; the interaction between logically related types is forced to be 'public' so that types can import and interact with each other (the ability to minimize to default/package visibility is lost).If I am building a framework library, by all means my packages will follow a functional/architectural packaging approach. My API consumers might even appreciate that their import statements contain intuitive package named after the architecture.Conversely, when building a business application I will package by feature. I have no problem placing Widget, WidgetService, and WidgetController all in the same \"\" package and then takomg advantage of default visibility (and having fewer import statements as well as inter-package dependencies).There are, however, cross-over cases. If my WidgetService is used by many logical domains (features), I might create a \"\" package. There is also a good chance that I create classes with intention to be re-usable across features and end up with packages such as \"\" and \"\". I may even end up moving all these later \"common\" classes in a separate project and include them in my business application as a myorg-commons.jar dependency.It depends on the granularity of your logical processes?If they're standalone, you often have a new project for them in source control, rather than a new package.The project I'm on at the moment is erring towards logical splitting, there's a package for the jython aspect, a package for a rule engine, packages for foo, bar, binglewozzle, etc. I'm looking at having the XML specific parsers/writers for each module within that package, rather than having an XML package (which I have done previously), although there will still be a core XML package where shared logic goes. One reason for this however is that it may be extensible (plugins) and thus each plugin will need to also define its XML (or database, etc) code, so centralising this could introduce problems later on.In the end it seems to be how it seems most sensible for the particular project. I think it's easy to package along the lines of the typical project layered diagram however. You'll end up with a mix of logical and functional packaging.What's needed is tagged namespaces. An XML parser for some Jython functionality could be tagged both Jython and XML, rather than having to choose one or the other.Or maybe I'm wibbling.Packages are to be compiled and distributed as a unit. When considering what classes belong in a package, one of the key criteria is its dependencies. What other packages (including third-party libraries) does this class depend on. A well-organized system will cluster classes with similar dependencies in a package. This limits the impact of a change in one library, since only a few well-defined packages will depend on it.It sounds like your logical, vertical system might tend to \"smear\" dependencies across most packages. That is, if every feature is packaged as a vertical slice, every package will depend on every third party library that you use. Any change to a library is likely to ripple through your whole system.I would personally go for functional naming. The short reason: it avoids code duplication or dependency nightmare.Let me elaborate a bit. What happens when you are using an external jar file, with its own package tree? You are effectively importing the (compiled) code into your project, and with it a (functionally separated) package tree. Would it make sense to use the two naming conventions at the same time? No, unless that was hidden from you. And it is, if your project is small enough and has a single component. But if you have several logical units, you probably don't want to re-implement, let's say, the data file loading module. You want to share it between logical units, not have artificial dependencies between logically unrelated units, and not have to choose which unit you are going to put that particular shared tool into.I guess this is why functional naming is the most used in projects that reach, or are meant to reach, a certain size, and logical naming is used in class naming conventions to keep track of the specific role, if any of each class in a package.I will try to respond more precisely to each of your points on logical naming.I try to design package structures in such a way that if I were to draw a dependency graph, it would be easy to follow and use a consistent pattern, with as few circular references as possible.For me, this is much easier to maintain and visualize in a vertical naming system rather than horizontal. if component1.display has a reference to component2.dataaccess, that throws off more warning bells than if display.component1 has a reference to dataaccess. component2.Of course, components shared by both go in their own package.I totally follow and propose the logical (\"by-feature\") organization! A package should follow the concept of a \"module\" as closely as possible. The functional organization may spread a module over a project, resulting in less encapsulation, and prone to changes in implementation details.Let's take an Eclipse plugin for example: putting all the views or actions in one package would be a mess. Instead, each component of a feature should go to the feature's package, or if there are many, into subpackages (featureA.handlers, featureA.preferences etc.)Of course, the problem lies in the hierarchical package system (which among others Java has), which makes the handling of orthogonal concerns impossible or at least very difficult - although they occur everywhere!From a purely practical standpoint, java's visibility constructs allow classes in the same package to access methods and properties with  and  visibility, as well as the  ones. Using non-public methods from a completely different layer of the code would definitely be a big code smell. So I tend to put classes from the same layer into the same package.I don't often use these protected or default methods elsewhere - except possibly in the unit tests for the class - but when I do, it is  from a class at the same layerIt depends. In my line of work, we sometimes split packages by functions (data access, analytics) or by asset class (credit, equities, interest rates). Just select the structure which is most convenient for your team.It is an interesting experiment not to use packages at all (except for the root package.)The question that arises then, is, when and why it makes sense to introduce packages. Presumably, the answer will be different from what you would have answered at the beginning of the project.I presume that your question arises at all, because packages are like categories and it's sometimes hard to decide for one or the other. Sometimes tags would be more appreciate to communicate that a class is usable in many contexts.From my experience, re-usability creates more problems than solving. With the latest & cheap processors and memory, I would prefer duplication of code rather than tightly integrating in order to reuse.
Java

In Java, I want to convert a double to an integer, I know if you do this:you get y=1. If you do this:You'll likely get 2. However, I am wondering: since double representations of integers sometimes look like 1.9999999998 or something, is there a possibility that casting a double created via Math.round() will still result in a truncated down number, rather than the rounded number we are looking for (i.e.: 1 instead of 2 in the code as represented) ?(and yes, I do mean it as such: Is there  value for x, where y will show a result that is a truncated rather than a rounded representation of x?)If so: Is there a better way to make a double into a rounded int without running the risk of truncation?Figured something: Math.round(x) returns a long, not a double. Hence: it is impossible for Math.round() to return a number looking like 3.9999998. Therefore, int(Math.round()) will never need to truncate anything and will always work.No,  will always round your double to the correct value, and then, it will be cast to an  which will truncate any decimal places.  But after rounding, there will not be any fractional parts remaining.Here are the docs from :For the datatype  to , you can use the following:
Java

I understand the difference between runtime and compile-time and how to differentiate between the two, but I just don't see the need to make a distinction between compile-time and runtime .What I'm choking on is this: how can a program  on something at runtime that it depended on during compilation? If my Java app uses log4j, then it needs the log4j.jar file in order to compile (my code integrating with and invoking member methods from inside log4j) as well as runtime (my code has absolutely no control over what happens once code inside log4j.jar is ran).I'm reading up on dependency resolution tools such as Ivy and Maven, and these tools clearly make the distinction between these two types of dependencies. I just don't understand the need for it.Can anyone give a simple, \"King's English\"-type explanation, preferably with an actual example that even a poor sap like me could understand?A compile-time dependency is generally required at runtime. In maven, a  scoped dependency will be added to the classpath on runtime (e.g. in wars they will be copied to WEB-INF/lib).It is not, however, strictly required; for instance, we may compile against a certain API, making it a compile-time dependency, but then at runtime include an implementation that also includes the API.There may be fringe cases where the project requires a certain dependency to compile but then the corresponding code is not actually needed, but these will be rare.On the other hand, including runtime dependencies that are not needed at compile-time is very common. For instance, if you're writing a Java EE 6 application, you compile against the Java EE 6 API, but at runtime, any Java EE container can be used; it's this container that provides the implementation.Compile-time dependencies can be avoided by using reflection. For instance, a JDBC driver can be loaded with a  and the actual class loaded be configurable through a configuration file.Each Maven dependency has a scope that defines which classpath that dependency is available on. When you create a JAR for a project, dependencies are not bundled with the generated artifact; they are used only for compilation. (However, you can still make maven include the dependencies in the built jar, see: )When you use Maven to create a WAR or an EAR file, you can configure Maven to bundle dependencies with the generated artifact, and you can also configure it to exclude certain dependencies from the WAR file using the provided scope.The most common scope \u2014  \u2014 indicates that the dependency is available to your project on the compile classpath, the unit test compile and execution classpaths, and the eventual runtime classpath when you execute your application. In a Java EE web application, this means the dependency is copied into your deployed application. In a .jar file however, dependencies will not be included with compile scope..  indicates that the dependency is available to your project on the unit test execution and runtime execution classpaths,\nbut unlike compile scope it  or its unit tests.  This is good for making sure you do not mistakenly depend on a specific library. (See for example: ) Finally,  indicates that the container in which your application executes provides the dependency on your behalf. In a Java EE application, this means the dependency is already on the Servlet container\u2019s or application server\u2019s classpath and  It also means that you need this dependency for compiling your project.You need at compile time dependencies which you might need at runtime.  However many libraries run without all its possible dependencies. i.e. a libraries which can use four different XML libraries, but only needs one to work.Many libraries, need other libraries in turn.  These libraries are not needed at compile time but are needed at runtime. i.e. when the code is actually run.Generally you are right and probasbly it is the ideal situation if runtime and compile time dependencies are identical. I will give you 2 example when this rule is incorrect.If class A depends on class B that depends on class C that depends on class D where A is your class and B, C and D are classes from different third party libraries you need only B and C at compile time and you need also D at runtime.\nOften programs use dynamic class loading. In this case you do not need classes dynamically loaded by library you are using at compile time. Moreover often the library chooses which implementation to use at runtime. For example SLF4J or Commons Logging can change the target log implementation at runtime. You need only SSL4J itself at compile time. Opposite example when you need more dependencies at compile time than at runtime.\nThink that you are developing application that has to work at different environments or operating systems. You need all platform specific libraries at compile time and only libraries needed for current environment at runtime.I hope my explanations help.Usually, the static dependencies graph is a sub-graph of the dynamic one, see e.g. . That said, there are some exceptions, mainly dependencies that add compiler-support, which becomes invisible at runtime. For instance for code generation as via  or additional checks as via the .Just ran into an issue that answers your question.  is a transient dependency in my web project and is needed both at compile time and runtime. But  is also included in my Tomcat library.The solution here is to make  in maven available only at compile time and not packaged in my war file so that it would not clash with the  contained in my Tomcat library. I hope this explains Compile time and Runtime dependency.At compile time you enables contracts/api that you are expected from your dependencies.\n(eg: here you just sign for a contract with broadband internet provider)\nAt run-time actually you are using the dependencies. \n(eg: here you actually are using the broadband internet) 
Java

The  has the following concepts:I'm trying to understand the relationship, , the  between them.Thanks in advance for any help here!I found this article which explains all aspects of the AMQP model, of which, channel is one. I found it very helpful in rounding out my understanding
Java

 This question and most of its answers date to before the release of Java 7. Java 7 provides  functionality for doing this easilly. If you are using Java 7 or later you should advance to .What is considered the best, most comprehensive way to close nested streams in Java? For example, consider the setup:I understand the close operation needs to be insured (probably by using a finally clause). What I wonder about is, is it necessary to explicitly make sure the nested streams are closed, or is it enough to just make sure to close the outer stream (oos)?One thing I notice, at least dealing with this specific example, is that the inner streams only seem to throw FileNotFoundExceptions. Which would seem to imply that there's not technically a need to worry about closing them if they fail.Here's what a colleague wrote:Technically, if it were implemented right, closing the outermost\nstream (oos) should be enough. But the implementation seems flawed.Example:\nBufferedOutputStream inherits close() from FilterOutputStream, which defines it as:However, if flush() throws a runtime exception for some reason, then\nout.close() will never be called. So it seems \"safest\" (but ugly) to\nmostly worry about closing FOS, which is keeping the file open.What is considered to be the hands-down best, when-you-absolutely-need-to-be-sure, approach to closing nested streams?And are there any official Java/Sun docs that deal with this in fine detail?I usually do the following. First, define a template-method based class to deal with the try/catch messNote the \"pending\" exception -- this takes care of the case where an exception thrown during close would mask an exception we might really care about.The finally tries to close from the outside of any decorated stream first, so if you had a BufferedWriter wrapping a FileWriter, we try to close the BuffereredWriter first, and if that fails, still try to close the FileWriter itself. (Note that the definition of Closeable calls for close() to ignore the call if the stream is already closed)You can use the above class as follows:Using this approach you never have to worry about the try/catch/finally to deal with closing files again.If this is too heavy for your use, at least think about following the try/catch and the \"pending\" variable approach it uses.When closing chained streams, you only need to close the outermost stream.  Any errors will be propagated up the chain and be caught.Refer to  for details.This isn't right.  After you catch and ignore that exception, execution will pick back up after the catch block and the  statement will be executed.Your colleague makes a good point about the Exception.  If you absolutely need the stream to be closed, you can always try to close each one individually, from the outside in, stopping at the first exception.In the Java 7 era,  is certainly the way to go. As mentioned in several previous answers, the close request propagates from the outermost stream to the innermost stream. So a single close is all that is required.There is however a problem with this pattern. The try-with-resources is not aware of the inner FileInputStream, so if the ObjectInputStream constructor throws an exception, the FileInputStream is never closed (until the garbage collector gets to it). The solution is...This is not as elegant, but is more robust. Whether this is actually a problem will depend on what exceptions can be thrown during construction of the outer object(s). ObjectInputStream can throw IOException which may well get handled by an application without terminating. Many stream classes only throw unchecked exceptions, which may well result in termination of the application.It is a good practice to use Apache Commons to handle IO related objects.In the  clause use  Code snippet below.This is a surprisingly awkward question. (Even assuming the  code is correct.)If the construction of the decorator fails, then you wont be closing the underlying stream. Therefore you do need to close the underlying stream explicitly, whether in the finally after use or, more diifcult after successfully handing over the resource to the decorator).If an exception causes execution to fail, do you really want to flush?Some decorators actually have resources themselves. The current Sun implementation of  for instance has non-Java heap memory allocated.It has been claimed that (IIRC) two thirds of the resources uses in the Java library are implemented in a clearly incorrect manner.Whilst  closes even on an  from ,  closes correctly.My advice: Close resources as directly as possible and don't let them taint other code. OTOH, you can spend too much time on this issue - if  is thrown it's nice to behave nicely, but other aspects of your program are probably a higher priority and library code is probably broken in this situation anyway. But I'd always write:(Look: No catch!)And perhaps use the Execute Around idiom.The colleague raises an interesting point, and there are grounds for arguing either way.Personally, I would ignore the , because an unchecked exception signifies a bug in the program. If the program is incorrect, fix it. You can't \"handle\" a bad program at runtime.Also you dont have to close all nested streamscheck this\nThe Java SE 7  doesn't seem to be mentioned. It eliminates needing to explicitly do a close completely, and I quite like the idea.Unfortunately, for Android development this sweet only becomes available by using Android Studio (I think) and .I use to close streams like this,  blocksSun's JavaDocs include s in their documentation, as shown by InputStream's  method; documented as throwing NullPointerException and IndexOutOfBoundsException.FilterOutputStream's  is only documented as throwing IOException, thus it doesn't actually throw any s.  Any that could be thrown would most likely be wrapped in an .It could still throw an , but there's not much you can do about those; Sun recommends that you don't try to catch them.
Java

What is the use of Collections.singletonList() in Java? (I understand that it returns a list with one element. Why would I want to have a separate method to do that? How does immutability play a role here?)Are there any special useful use-cases for this method, rather than just being a convenience method?The  says this:You ask:As a convenience ... to save you having to write a sequence of statements to:Clearly, there are use-cases where it is convenient to use the  method. But I don't know how you would (objectively) distinguish between an ordinary use-case and a \"specially useful\" one ... Here's one  on the singleton methods:If an Immutable/Singleton collections refers to the one which having only one object and which is not further gets modified, then the same functionality can be achieved by making a collection \"UnmodifiableCollection\" having only one object. Since the same functionality can be achieved by Unmodifiable Collection with one object, then what special purpose the Singleton Collection serves for?
Java

Was there any reason why the designers of Java felt that local variables should not be given a default value? Seriously, if instance variables can be given a default value, then why can't we do the same for local variables?And it also leads to problems as explained in :Local variables are declared mostly to do some calculation. So its the programmer's decision to set the value of the variable and it should not take a default value. If the programmer, by mistake, did not initialize a local variable and it take default value, then the output could be some unexpected value. So in case of local variables, the compiler will ask the programmer to initialize with some value before they access the variable to avoid the usage of undefined values. seems to be describing this situation:The commenter's complaint is that the compiler balks at the line in the  section, claiming that  might be uninitialized. The comment then mentions another way of writing the code, probably something like this:The commenter is unhappy with that solution because the compiler then says that the code \"must be within a try.\" I guess that means some of the code may raise an exception that isn't handled anymore. I'm not sure. Neither version of my code handles any exceptions, so anything exception-related in the first version should work the same in the second.Anyway, this second version of code is the  way to write it. In the first version, the compiler's error message was correct. The  variable might be uninitialized. In particular, if the  constructor fails,  will not be initialized, and so it will be an error to attempt to call . Always enter the  section  you have acquired the resource that the  section finalizes.The - block after the  initialization is there  to protect the  instance, to make sure it gets cleaned up no matter what else happens. If there are  things that need to run, but they aren't related to whether the  instance was property allocated, then they should go in  - block, probably one that wraps the one I've shown.Requiring variables to be assigned manually before use does not lead to real problems. It only leads to minor hassles, but your code will be better for it. You'll have variables with more limited scope, and - blocks that don't try to protect too much.If local variables had default values, then  in the first example would have been . That wouldn't really have solved anything. Instead of getting a compile-time error in the  block, you'd have a  lurking there that might  whatever other exception could occur in the \"Do some work here\" section of the code. (Or do exceptions in  sections automatically chain to the previous exception? I don't remember. Even so, you'd have an extra exception in the way of the real one.)Moreover, in the example below, an exception may have been thrown inside the SomeObject construction, in which case the 'so' variable would be null and the call to CleanUp will throw a NullPointerExceptionWhat I tend to do is this:Notice that the final instance/member variables don't get initialized by default. Because those are final and can't be changed in the program afterwards. That's the reason that Java doesn't give any default value for them and force the programmer to initialize it. On the other hand, non-final member variables can be changed later. Hence the compiler doesn't let them remain uninitialised, precisely, because those can be changed later. Regarding local variables, the scope of local variables is much narrower. Compiler knows when its getting used. Hence, forcing programmer to initialize the variable makes sense.The actual answer to your question is because method variables are instantiated by simply adding a number to the stack pointer.  To zero them would be an extra step.  For class variables they are put into initialized memory on the heap.Why not take the extra step?  Take a step back--Nobody mentioned that the \"warning\" in this case is a Very Good Thing.You should never initialize your variable to zero or null on the first pass (when you are first coding it).  Either assign it to the actual value or don't assign it at all because if you don't then java can tell you when you really screw up.  Take Electric Monk's answer as a great example.  In the first case, it's actually amazingly useful that it's telling you that if the try() fails because SomeObject's constructor threw an exception, then you would end up with an NPE in the finally.  If the constructor can't throw an exception, it shouldn't be in the try.This warning is an awesome multi-path bad programmer checker that has saved me from doing stupid stuff since it checks every path and makes sure that if you used the variable in some path then you had to initialize it in every path that lead up to it.  I now never explicitly initialize variables until I determine that it is the correct thing to do.On top of that, isn't it better to explicitly say \"int size=0\" rather than \"int size\" and make the next programmer go figure out that you intend it to be zero?On the flip side I can't come up with a single valid reason to have the compiler initialize all uninitialized variables to 0.I think the primary purpose was to maintain similarity with C/C++. However the compiler detects and warns you about using uninitialized variables which will reduce the problem to a minimal point. From a performance perspective, it's a little faster to let you declare uninitialized variables since the compiler will not have to write an assignment statement, even if you overwrite the value of the variable in the next statement.It is more efficient not to initialize variables, and in the case of local variables it is safe to do so, because initialization can be tracked by the compiler.In cases where you need a variable to be initialized you can always do it yourself, so it is not a problem.(It may seem strange to post a new answer so long after the question, but a  came up.)For me, the  comes down to this this: The purpose of local variables is different than the purpose of instance variables. Local variables are there to be used as part of a calculation; instance variables are there to contain state. If you use a local variable without assigning it a value, that's almost certainly a logic error.That said, I could totally get behind requiring that instance variables were always explicitly initialized; the error would occur on any constructor where the result allows an uninitialized instance variable (e.g., not initialized at declaration and not in the constructor). But that's not the decision Gosling, et. al., took in the early 90's, so here we are. (And I'm not saying they made the wrong call.)I could  get behind defaulting local variables, though. Yes, we shouldn't rely on compilers to double-check our logic, and one doesn't, but it's still handy when the compiler catches one out. :-)Eclipse even gives you warnings of uninitialized variables, so it becomes quite obvious anyway.  Personally I think it's a good thing that this is the default behaviour, otherwise your application may use unexpected values, and instead of the compiler throwing an error it won't do anything (but perhaps give a warning) and then you'll be scratching your head as to why certain things don't quite behave the way they should.The local variables are stored on a stack, but instance variables are stored on the heap, so there are some chances that a previous value on the stack will be read instead of a default value as happens in the heap. For that reason the jvm doesn't allow to use a local variable without initialize it.The answer is instance variables can be initialized in class constructor or any class method, But in case of local variables, once you defined whatever in the method that remains forever in the class.I could think of following 2 reasons
Java

Quite a stupid question. Given the code:Could you tell if it's good Java or not? What I'm talking about is,  is an unchecked exception. You  to specify it as part of  signature. Moreover, as far as I understand, the idea of unchecked exceptions is just to signal that program's implementation is incorrect, and even more, catching unchecked exceptions is a bad idea, since it's like .Would somebody please clarify whether::Imagine, it's not an open-source framework, that you should use for some reason. You look at method's signature and think - \"OK, it never throws\". Then, some day, you got an exception. Is it normal?:There are some comments saying my  is a bad design. I do absolutely agree, but for those who believe that original problem would just never appear if we had good design, here's an extra question:The problem definition is like this: you have a data source where numbers are stored as s. This source may be XML file, web page, desktop window with 2 edit boxes, whatever. Your goal is to implement the logic that takes these 2 s, converts them to s and displays message box saying \"the sum is xxx\".No matter what's the approach you use to design/implement this, you'll :The primary question of my original post is:This is a good question. I wish more people would think about such things.IMHO, throwing unchecked exceptions is acceptable if you've been passed rubbish parameters.Generally speaking, you shouldn't throw  because you shouldn't use Exceptions to control program flow. Exceptions are for the exceptional. Callers to your method can know  they call it if their strings are numbers or not, so passing rubbish in is avoidable and therefore can be considered a , which means it's OK to throw unchecked exceptions.Regarding declaring  - this is not that useful, because few will notice due to NumberFormatException being unchecked. However, IDE's can make use of it and offer to wrap in  correctly. A good option is to use javadoc as well, eg::\nThe commenters have made valid points. You need to consider how this will be used and the overall design of your app.  If the method will be used all over the place, and it's important that all callers handle problems, the declare the method as throwing a checked exception (forcing callers to deal with problems), but cluttering the code with  blocks.If on the other hand we are using this method with data we trust, then declare it as above, because it is not expected to ever explode and you avoid the code clutter of essentially unnecessary  blocks.In my opinion it would be preferable to handle exception logic as far up as possible. Hence I would prefer the signatureWith your method signature I would  change anything. Either you areHence, exception handling in this case becomes a  issue. Number 4.  As given, this method should not take strings as parameters it should take integers.  In which case (since java wraps instead of overflowing) there's no possibility of an exception.is a lot clearer as to what is meant than \n     You want the exception to happen as close to the source (input) as possible.  As to options 1-3, you don't define an exception because you expect your callers to assume that otherwise your code can't fail, you define an exception to define what happens under known failure conditions WHICH ARE UNIQUE TO YOUR METHOD. I.e. if you have a method that is a wrapper around another object, and it throws an exception then pass it along.  Only if the exception is unique to your method should you throw a custom exception (frex, in your example, if sum was supposed to only return positive results, then checking for that and throwing an exception would be appropriate, if on the other hand java threw an overflow exception instead of wrapping, then you would pass that along, not define it in your signature, rename it, or eat it).Update in response to update of the question:The solution to this is to to wrap the MUST library, and return a SHOULD value.  In this case, a function that returns an Integer.  Write a function that takes a string and returns an Integer object -- either it works, or it returns null (like guava's Ints.tryParse).  Do your validation seperate from your operation, your operation should take ints.  Whether your operation gets called with default values when you have invalid input, or you do something else, will depend upon your specs -- most I can say about that, is that it's really unlikely that the place to make that decision is in the operation method.I think so. It's a nice documentation.Sometimes yes. The checked exceptions are consider to be better in some cases, but working with them is quite a PITA. That's why many frameworks (e.g., Hibernate) use runtime exceptions only.Never. More work, less speed (unless you expect throwing the exception to be a rule), and no gain at all.None at all.Nr 4.I think I wouldn't change the method at all.\nI would put a try catch around the calling method or higher in the stack-trace where I'm in a context where I can gracefully recover with business logic from the exception.I wouldn't certainty do #3 as I deem it overkill.Assuming that what you are writing is going to be consumed (like as an API) by someone else, then you should go with 1, NumberFormatException is specifically for the purpose of communicating such exceptions and should be used.Depends a lot on the scenario you are in.Case 1. Its always you who debug the code and no one else and exception wont cause a bad user experienceThrow the default NumberFormatExceptionCase2: Code should be extremely maintainable and understandableDefine your own exception and add lot more data for debugging while throwing it.You dont need regex checks as, its gonna go to exception on bad input anyway.If it was a production level code, my idea would be to define more than one custom exceptions, likeand deal with all these seperatelyOveral, a NumberFormaException is unchecked because it is expected that correctly parseable input is provided. Input validation is something you should handle. However, actually parsing the input is the easiest way to do this. You could simply leave your method as it is and warn in the documentation that correct input is expected and anyone calling your function should validate both inputs before using it.Any exceptional behaviour should be clarified in the documentation. Either it should state that this method returns a special value in case the of failure (like , by changing the return type to ) or case 1 should be used. Having it explicit in the method's signature lets the user ignore it if he ensures correct strings by other means, but it still is obvious that the method doesn't handle this kind of failure by itself. Answer to your updated question.Yes it's perfectly normal to get \"surprise\" exceptions.\nThink about all the run time errors one got when new to programming.Also a common surprise exception from the for each loop.While I agree with the answer that the runtime exception should be allowed to be percolated, from a design and usability perspective, it would be a good idea to wrap it into a IllegalArgumentException rather than throw it as NumberFormatException. This then makes the contract of your method more clear whereby it declares an illegal argument was passed to it due to which it threw an exception.Regarding the update to the question \"Imagine, it's not an open-source framework, that you should use for some reason. You look at method's signature and think - \"OK, it never throws\". Then, some day, you got an exception. Is it normal?\" the javadoc of your method should always spill out the behavior of your method (pre and post constraints). Think on the lines of say collection interfaces where in if a null is not allowed the javadoc says that a null pointer exception will be thrown although it is never part of the method signature. As you are talking about good java practice ,in my opinion it is always better I think it depends on your purpose, but I would document it at a minimum:Or, take a page from the Java source code for the java.lang.Integer class:How about the input validation pattern implemented by  or  ()?In my experience, it is considered good practice to validate a function's parameters at the beginning of the function and throw Exceptions where appropriate.Also, I would consider this question to be largely language independent. The 'good practice' here would apply to all languages that have functions which can take parameters which may or may not be valid.I think your very first sentence of \"Quite a stupid question\" is very relevant. Why would you ever write a method with that signature in the first place? Does it even make sense to sum two strings? If the calling method wants to sum two strings, it is the calling method's responsibility to make sure they are valid ints and to convert them before calling the method.In this example, if the calling method cannot convert the two Strings into an int, it could do several things. It really depends at what layer this summation occurs at. I am assuming the String conversion would be very close to front-end code (if it was done properly), such that case 1. would be the most likely:There are lots of interesting answers to this question. But I still want to add this :For string parsing, I always prefer to use \"regular expressions\". The java.util.regex package is there to help us. So I will end up with something like this, that never throws any exception. It's up to me to return a special value if I want to catch some error :As one can see, the code is just a bit longer, but we can handle what we want (and set default values for x and y, control what happens with else clauses, etc...) \nWe could even write a more general transformation routine, to which we can pass strings, defaut return values, REGEX code to compile, error messages to throw, ...Hope It was usefull.Warning : I was not able to test this code, so please excuse eventual syntax problems.You face this issue because you let user errors propagate too deep into the core of the application and partly also because you abuse Java data types.You should have a clearer separation between user input validation and business logic, use proper data typing, and this problem will disappear by itself.The fact is the semantics of  are known - it's primary purpose it to parse  integers. You're missing an explicit user input validation/parsing step.
Java

I have created a JAR file in this way . Now, I'm trying to run it. Running it does not work (jre command is not found):This does not work either:(Failed to load Main-Class manifest attribute from main.jar).I also found out thatWhat is the \"Main-Class manifest header\"? How do I create it and where do I put it?I'm not sure I believe your symptoms:I'd expect you to see this error if you run:The Main-Class header needs to be in the manifest for the JAR file - this is metadata about things like other required libraries. See the  for how to create an appropriate manifest. Basically you need to create a text file which includes a line like this:Then runYou can run with:It works for me if there is no manifest in the JAR file.I got this error, and it was because I had the arguments in the wrong order:CORRECTWRONGTake a look at the tutorial .The easiest way to be sure that you have created the runnable JAR file correctly, with the appropriate manifest file, is to use  to build it for you. In your Eclipse project, you basically just select File/Export from the menu, and follow the prompts. That way, you can be sure that your JAR file is correct and will know to look elsewhere if there is still an issue. The process is described in full in .I discovered that I was also having this error in NetBeans. \nI hope the following is helpful.This was the problem I was getting because I had other \"test\" programs I was using in NetBeans and I had to make sure the Main Class under the Run portion of the Project configuration was set correctly.many blessings,\nJohn PI was getting the same error when i ran:\nWhat resolved it was this:\nMy manifest has the entry point as given in oracle docs (make sure there is a new line character at the end of the file):\nTryno need to have  file.I faced the same problem. This unix command is not able to find the main class. This is because the runtime and compile time JDK versions are different. Make the jar through eclipse after changing the java compiler version. The following link helped me.Try running the jar created after this step and then execute itIf your class path is fully specified in manifest,\nmaybe you need the  of java runtime environment.\nMy problem fixed when i reinstalled the jre 8.  If you using eclipse, try below:\n1. Right click on the project -> select Export\n2. Select Runnable Jar file in the select an export destination\n3. Enter jar's name and Select \"Package required ... \" (second radio button) -> FinishHope this helps...!
Java

I've been using Guice's AOP to intercept some method calls. My class implements an interface and I would like to annotate the interface methods so Guice could select the right methods. Even if the annotation type is annotated with  annotation implementing class doesn't inherit the annotation as stated in Inherited's java doc:What could be the reason for this? Getting to know all interfaces that an object's class does implement in runtime is not that hard thing to do so there must be a good reason behind this decision.I'd say the reason is that otherwise a multiple-inheritance problem would occur.If I do this:what's the result going to be? 'baz', 'phleem' or 'flopp'?For this reason, annotations on interfaces are rarely useful.From the  for @Inherited:On the other hand, JSR 305 validators do some sort of inheritance lookup. If you have a hierarchy of classes:Then the effective validations on  are .  has no  meta-annotation.
Java

I was reading through some JMockit examples and found this code:What does the tilde in the generic identifier mean? I know it's the unary bitwise NOT operator, but I don't see an operand here.Also, I tried compiling it and got an error. Am I just missing something?It is just a shorthand for \"same as in declaration\". Some IDEs, e.g. Intellij use this too.The files on disk do not have this notation, which is only a compaction in the IDE GUI.If there wasn't a tilde, I'd say, the code was already Java 7.  so this is/will be legal Java code:(but - no tilde with this syntax)In IntelliJ IDEA, the  here:means , which is the same as in the declaration on the left side.I think that is shorthand to mean whatever the type is, in this case .
Java

In our project I have several  tests that e.g. take every file from a directory and run a test on it. If I implement a  method in the  this shows up as only one test that may fail or succeed. But I am interested in the results on each individual file. How can I write a  /  such that each file shows up as a separate test e.g. in the graphical TestRunner of Eclipse? (Coding an explicit test method for each file is not an option.)Compare also the question .Take a look at  in JUnit 4.Actually I did this a few days ago. I'll try to explain ...First build your test class normally, as you where just testing with one input file.\nDecorate your class with:Build one constructor that takes the input that will change in every test call (in this case it may be the file itself)Then, build a static method that will return a  of arrays. Each array in the collection will contain the input arguments for your class constructor e.g. the file. Decorate this method with:Here's a sample class.Also check this Should be possible in JUnit 3 by inheriting from  and overriding the  method to list the files and for each return an instance of a subclass of  that takes the filename as constructor parameter and has a test method that tests the file given in the constructor.In JUnit 4 it might be even easier.If TestNG is an option, you could use .Each individual file's test will have its result shown in the text-based report or Eclipse's TestNG plugin UI. The number of total tests run will count each of your files individually.This behavior differs from JUnit , in which all results are lumped under one \"theory\" entry and only count as 1 test. If you want separate result reporting in JUnit, you can try .You could consider using , so you would have a few more (cleaner) options:You can see more .In addition : supports this through the notion of a , which is to be generated in a , by means of the static method .The tests run in your IDE (IntelliJ here) will be displayed like this:I had a similar problem and ended up writing a simple JUnit 4 runner that allows med to dynamically generate tests. 
Java

Ok, I read the Java Documentation and I just can't figure out what is the main difference between those two methods. Sometimes I used , sometimes , sometimes one does what I want, sometimes the other.So, what is the main difference between the two? Which one should I use for  and ?ThanksThe short answer is: it's complicated.The slightly longer answer is: use  if your component's parent has no layout manager, and  and its related  and  if it does. probably won't do anything if the component's parent is using a layout manager; the places this will typically have an effect would be on top-level components ( and ) and things that are inside of .  You also must call  if you've got components inside a parent without a layout manager.As a general rule,  should do the \"right thing\" if you've got a layout manager; most layout managers work by getting the preferred (as well as minimum and maximum) sizes of their components, and then using  and  to position those components according to the layout's rules.  So (as an example) a  will try to make the bounds of its \"north\" region equal to the  of its north component - they may end up larger or smaller than that, depending on the size of the , the size of the other components in the layout, and so on. or  can be used when no layout manager is being used.However, if you are using a layout manager you can provide hints to the layout manager using the  methods like  and  etc. And be sure that the component's container uses a layout manager that respects the requested size. The , , and  managers use the component's preferred size (the latter two depending on the constraints you set), but  and  usually don't.If you specify new size hints for a component that's already visible, you need to invoke the revalidate method on it to make sure that its containment hierarchy is laid out again. Then invoke the repaint method. will resize the component to the specified size. sets the preferred size.  The component may not actually be this size depending on the size of the container it's in, or if the user re-sized the component manually.IIRC ... sets the size of the component. sets the preferred size. \nThe Layoutmanager will try to arrange that much space for your component.It depends on whether you're using a layout manager or not ...
Java

I want to manipulate a Microsoft Access database (.accdb or .mdb file) from my Java project. I don't want to use the JDBC-ODBC Bridge and the Access ODBC driver from Microsoft because:I have seen other answers mentioning a JDBC driver for Access databases named . How can I set up my Java project to use this approach?(Answers suggesting better ways of working with Access databases from Java would also be most welcome.) is a pure Java JDBC driver that allows us to read from and write to Access databases without using ODBC. It uses two other packages,  and , to perform these tasks. The following is a brief overview of how to get it set up.\u00a0If your project uses  you can simply include UCanAccess via the following coordinates: net.sf.ucanaccess\n ucanaccess\u00a0As mentioned above, UCanAccess requires Jackcess and HSQLDB. Jackcess in turn has its own . So to use UCanAccess you will need to include the following components: (ucanaccess-x.x.x.jar)\n (hsqldb.jar, version 2.2.5 or newer)\n (jackcess-2.x.x.jar)\n (commons-lang-2.6.jar, or newer )\n (commons-logging-1.1.1.jar, or newer )Fortunately, UCanAccess includes all of the required JAR files in its distribution file. When you unzip it you will see something likeAll you need to do is add all  JARs to your project. Right-click the project in Package Explorer and choose . Click the \"Add External JARs...\" button to add each of the five (5) JARs. When you are finished your Java Build Path should look something like this Expand the tree view for your project, right-click the \"Libraries\" folder and choose \"Add JAR/Folder...\", then browse to the JAR file. After adding all five (5) JAR files the \"Libraries\" folder should look something like this: Choose  from the main menu. In the \"Libraries\" pane click the \"Add\" () button and add the five (5) JAR files. Once that is done the project should look something like this:\u00a0Now \"U Can Access\" data in .accdb and .mdb files using code like this\u00a0At the time of writing this Q&A I had no involvement in or affiliation with the UCanAccess project; I just used it. I have since become a contributor to the project.
Java

Is there a reason there'sbut no?How do I filter a list correctly? I could useof course, but this way it's not guaranteed that my ordering stays the same, if I understand correctly.It wasn't implemented because it would expose a perilous large number of slow methods, such as #get(index) on the returned List view (inviting performance bugs). And ListIterator would be a pain to implement as well (though I submitted a  years ago to cover that).Since indexed methods can't be efficient in the filtered List view, it's better to just go with a filtered Iterable, which doesn't have them.You can use , which will definitely maintain ordering.Note that by constructing a new list, you'll be  the elements (just references, of course) - so it won't be a live view onto the original list. Creating a view would be pretty tricky - consider this situation:That would have to iterate over the whole original list, applying the filter to everything. I suppose it could require that the predicate matching didn't change over the lifetime of the view, but that would be not-entirely-satisfactory.(This is just guessing, mind you. Maybe one of the Guava maintainers will chip in with the  reason :)This isn't true.   is a lazily-evaluated function - it doesn't actually filter your collection until you start accessing the filtered version. For example, if you iterate over the filtered version, then the filtered elements will pop out of the iterator in the same order as your original collection (minus the ones filtered out, obviously). Perhaps you were thinking that it does the filtering up front, then dumps the results into an arbitrary, unordered Collection of some form - it doesn't.So if you use the output of  as the input to a new list, then your original order  be retained.Using static imports (and the  function), it becomes fairly succinct:Note that while  will not eagerly iterate over the underlying collection,   - it will extract all elements of the filtered collection and copy them into a new .As mentioned by Jon, you can use  or  and if you don't need a live view you can use  or  and yes ordering will be maintained.\n\nIf you are really interested in  part, you can visit  for more details.Summing up what the others said, you can easily create a generic wrapper to filter lists:
Java

I am just trying to understand why all fields defined in an Interface are implicitly  and . The idea of keeping fields  makes sense to me as you can't have objects of an interface but why they are  (implicitly)?Any one knows why Java designers went with making the fields in an interface  and ?An interface can't have behavior or state because it is intended to specify only an interaction contract, no implementation details. No behavior is enforced by not allowing method/constructor bodies or static/instance initializing blocks. No state is enforced by only allowing constants. A constant in Java is defined by a static final field (and by convention the name uses UPPER_CASE_AND_UNDERSCORES).There are a couple of points glossed over here:Just because fields in an interface are implicitly static final does not mean they must be compile-time constants, or even immutable. You can define e.g.(Beware that doing this inside an annotation definition can , relating to the fact that the above actually compiles to a static initializer.)Also, the reason for this restriction is more stylistic than technical, and a lot of people would .REASON FOR BEING FINAL--Any implementations can change value of fields if they are not defined as final. Then they would become a part of the implementation.An interface is a pure specification without any implementation.REASON FOR BEING STATIC--If they are static, then they belong to the interface, and not the object, nor the run-time type of the object.The fields must be static because they can't be abstract (like methods can). Because they can't be abstract, the implementers will not be able to logically provide the different implementation of the fields.The fields must be final, I think, because the fields may be accessed by many different implementers allows they to be changeable might be problematic (as synchronization). Also to avoid it to be re-implemented (hidden).Just my thought.I consider the requirement that the fields be final as unduly restrictive and a mistake by the Java language designers. There are times, e.g. tree handling, when you need to set constants in the implementation which are required to perform operations on an object of the interface type. Selecting a code path on the implementing class is a kludge. The workaround which I use is to define an interface function and implement it by returning a literal:However, it would be simpler, clearer and less prone to aberrant implementation to use this syntax:Specification, contracts... The machine instruction for field access uses object address plus field offset. Since classes can implement many interfaces, there is no way to make non-final interface field to have the same offset in all classes that extend this interface. Therefore different mechanism for field access must be implemented: two memory accesses (get field offset, get field value) instead of one plus maintaining kind of virtual field table (analog of virtual method table). Guess they just didn't want to complicate jvm for functionality that can be easily simulated via existing stuff (methods).In scala we can have fields in interfaces, though internally they are implemented as I explained above (as methods).:Anything (variable or method) that is  in Java can be invoked as  or  or directly. It is not compulsory to invoke it only by using object name.In interface, objects cannot be declared and  makes it possible to invoke variables just through class name without the need of object name.:It helps to maintain a constant value for a variable as it can't be overridden in its subclasses.
Java

I am working with tomcat 6.0, and while I am indexing (not while i am starting tomcat), I have a permgen space error.\nHow could I increase that space??ThanksYou can use :to increase the space. But this usually only postpones the inevitable.You can also enable the PermGen to be garbage collectedUsually this occurs when doing lots of redeploys. I am surprised you have it using something like indexing. Use virtualvm or jconsole to monitor the Perm gen space and check it levels off after warming up the indexing.Maybe you should consider changing to another JVM like the IBM JVM. It does not have a Permanent Generation and is immune to this issue.For tomcat you can increase the permGem space by using For this you need to create (if not already exists) a file named setenv.sh in tomcat/bin folder and include following line in it Reference : You can also increase it via the VM arguments in your IDE. In my case, I am using Tomcat v7.0 which is running on Eclipse. To do this, double click on your server (Tomcat v7.0). Click the 'Open launch configuration' link. Go to the 'Arguments' tab. Add -XX:MaxPermSize=512m to the VM arguments list. Click 'Apply' and then 'OK'. Restart your server.if you found out that the memory settings were not being used and in order to change the memory settings, I used the tomcat7w or tomcat8w in the \\bin folder.Then the following should pop up:Click the Java tab and add the arguments.restart tomcatOn Debian-like distributions you set that in 
Java

I'm trying to send an email using Java:I am getting the error :Will this code work to send email?The following code works very well with Google SMTP server. You need to supply your Google username and password.Username + password is no longer a recommended solution. This is due toGoogle had released Gmail API - . We should use oAuth2 method, instead of username + password.Here's the code snippet to work with Gmail API.To construct an authorized Gmail service through oAuth2, here's the code snippet.To provide a user friendly way of oAuth2 authentication, I made use of JavaFX, to display the following input dialogThe key to display user friendly oAuth2 dialog can be found in  and Following code worked for me.Required jar filesThe short answer - No.The long answer - no, since the code relies on the presence of a SMTP server running on the local machine, and listening on port 25. The SMTP server (technically the MTA or Mail Transfer Agent) is responsible for communicating with the Mail User Agent (MUA, which in this case is the Java process) to receive outgoing emails.Now, MTAs are typically responsible for receiving mails from users for a particular domain. So, for the domain gmail.com, it would be the Google mail servers that are responsible for authenticating mail user agents and hence transferring of mails to inboxes on the GMail servers. I'm not sure if GMail trusts open mail relay servers, but it is certainly not an easy task to perform authentication on behalf on Google, and then relay mail to the GMail servers.If you read the , you'll notice that the hostname and the port happen to be pointing to the GMail servers, and certainly not to localhost. If you intend to use your local machine, you'll need to perform either relaying or forwarding.You'll probably need to understand the SMTP protocol in depth if you intend to get anywhere when it comes to SMTP. You can start with the , but any further progress will actually necessitate programming against a SMTP server.It has been quite a while since this has been posted. But as of Nov 13,2012 I can verify that port 465 still works.Refer to GaryM's answer on .\nI hope this helps few more people.You need a SMTP server for sending mails. There are servers you can install locally on your own pc, or you can use one of the many online servers. One of the more known servers is Google's:I just successfully tested the allowed  using the first example from :Notice the various ports and transport strategies (which handle all the necessary properties for you).Curiously, Google require TLS on port 25 as well, even though Google's instructions .The following code works very well.Try this as a java application with javamail-1.4.5.jarTry this out. it works well for me. Make sure that before send email u need to give the access for less secure app in your gmail account. So go to the following link and try out with this java code.\nYou need to import javax.mail.jar file and activation.jar file to your project.Well, no, not without changing some parts since you're getting an error. You are currently trying to send mail via a SMTP server running on localhost but you aren't running any  hence the . Assuming the code is OK (I didn't really check), you'll have to either run a local SMTP server, or to use a (remote) one (from your ISP).Regarding the code, you can find samples in the JavaMail download package as mentioned in the :I have put my working gmail java class up on pastebin for your review, pay special attention to the \"startSessionWithTLS\" method and you may be able adjust JavaMail to provide the same functionality. Your code works, apart from setting up the connection with the SMTP server. You need a running mail (SMTP) server to send you email for you.Here is your modified code. I commented out the parts that are not needed and changed the Session creation so it takes an Authenticator. Now just find out the SMPT_HOSTNAME, USERNAME and PASSWORD you want to use (your Internet provider usually provides them).I always do it like this (using a remote SMTP server I know) because running a local mailserver is not that trivial under Windows (it's apparently quite easy under Linux).Indeed 465 works and the exception that you're getting is may be due to the un open SMTP port 25. By default the port number is 25. Yet you can configure it using the mail agent that is available as open source - For simplicity, just use the following configuration and you'll be fine. For even more: check out the complete working example from scratch Here is the working solution bro. it's guranteed1) First of all open your gmail account from which you wanted to send mail, like in you case \"\"xyz@gmail.com\"2) open this link below 3) click on \"Go to the \"Less secure apps\" section in My Account.\" option4) Then turn on it5) that's it (:here is my codeI got the same exception as you got.\nReason for this is not having up and running smpt server in your machine(since your host is localhost). If you use windows 7 it does not have SMTP server . so you will have to download, install and configure with domain and creating accounts.I used hmailserver as smtp server installed and configure in my local machine. \nYou can find a complete and very simple java class for sending emails using Google(gmail) account here,It uses following  properties
Java

Someone explain to me the differences between the following two statements?A  variable initialized by a  code block:A  variable initialized by an assignment:In this example, there's one  difference - in your first example,  isn't determined to be a compile-time constant, so it can't be used as a case in  blocks (and wouldn't be inlined into other code); in your second example it, is. So for example:That's valid when  is deemed to be a constant expression, but not when it's \"just\" a static final variable.However, static initializer blocks are  used when you have more complicated initialization code - such as populating a collection.The  for initialization is described in ; any static final fields which are considered as compile-time constants are initialized first (step 6) and initializers are run later (step 9); all initializers (whether they're field initializers or static initializers) are run in textual order.The value of  is  when the class is  and .Here, the value of  will be a  constant. So, in reality  will be available as part of th  itself. In IInd case- value of  ie compiler identifies and assign value foo to variable , which cant be changed,and this will be .and In Ist case-value of foo initialize  as a very first assignment before instance variable assigned,also here you  or static field can be  in static block.So whenever there is a condition arrive  of variable foo, condition II will work,for ex-.The JLS describes a few special behaviors of what it calls , which are  variables (whether  or not) which are initialized with constant expressions of  or primitive type.Constant variables have a major difference with respect to binary compatibility: the  of constant variables become part of the class's API, as far as the compiler is concerned.An example:Here,  is a \"constant variable\" and  is not, but they are otherwise equivalent. Class  prints out each of them. Compile those classes, then disassemble them with , and here is the output:Class X:Class Y:Class Z:Things to notice in the disassembly, which tell you the differences between  and  run deeper than syntactic sugar:Other differences you will find:The JLS describes the above effects constant variables have on compiled class files in :And in :The upshot is that if your public library exposes any constant variables, you  change their values if your new library version is otherwise supposed to be compatible with code compiled against old versions of the library. It won't necessarily cause an error, but the existing code will probably malfunction since it will have outdated ideas about the values of constants. (If your new library version needs for classes which use it to be recompiled anyway, then changing constants doesn't cause this problem.)Thus, initializing a constant with a block gives you more freedom to change its value, because it prevents the compiler embedding the value into other classes.The only difference is the initialization time.Java first initializes the members and then the static blocks.An additional aspect: Consider the case when you have multiple static fields, and yes this is a corner case...As stated in Jon Skeet's answer, the JLS defines the exact order of initialization.\nHowever, if for some reason you have to initialize multiple static attributes in a specific order, you may want to make the initialization sequence clearly visible in the code.\nWhen using direct field initialization: Some code formatters (and developers) may decide at some point to sort fields differently, this will directly impact how the fields get initialized and introduce unwanted effects.By the way, if you want to follow common java coding conventions, you should use capital letters when defining 'constants' (final static fields).--- edited reflecting Jon Skeet's comments ---Static block give you more than simple statement. In this particular case is the same thing.\nStatic section will be executed at class load time, before any instances constructed. You can call methods here and assign their results to static fields. And you can catch exceptions in static blocks.
Java

My company has been evaluating Spring MVC to determine if we should use it in one of our next projects. So far I love what I've seen, and right now I'm taking a look at the Spring Security module to determine if it's something we can/should use. Our security requirements are pretty basic; a user just needs to be able to provide a username and password to be able to access certain parts of the site (such as to get info about their account); and there are a handful of pages on the site (FAQs, Support, etc) where an anonymous user should be given access.In the prototype I've been creating, I have been storing a \"LoginCredentials\" object (which just contains username and password) in Session for an authenticated user; some of the controllers check to see if this object is in session to get a reference to the logged-in username, for example. I'm looking to replace this home-grown logic with Spring Security instead, which would have the nice benefit of removing any sort of \"how do we track logged in users?\" and \"how do we authenticate users?\" from my controller/business code. It seems like Spring Security provides a (per-thread) \"context\" object to be able to access the username/principal info from anywhere in your app...... which seems very un-Spring like as this object is a (global) singleton, in a way.My question is this: if this is the standard way to access information about the authenticated user in Spring Security, what is the accepted way to inject an Authentication object into the SecurityContext so that it is available for my unit tests when the unit tests require an authenticated user?Do I need to wire this up in the initialization method of each test case?This seems overly verbose. Is there an easier way? The  object itself seems very un-Spring-like...The problem is that Spring Security does not make the Authentication object available as a bean in the container, so there is no way to easily inject or autowire it out of the box.Before we started to use Spring Security, we would create a session-scoped bean in the container to store the Principal, inject this into an \"AuthenticationService\" (singleton) and then inject this bean into other services that needed knowledge of the current Principal.If you are implementing your own authentication service, you could basically do the same thing: create a session-scoped bean with a \"principal\" property, inject this into your authentication service, have the auth service set the property on successful auth, and then make the auth service available to other beans as you need it.I wouldn't feel too bad about using SecurityContextHolder. though.  I know that it's a static / Singleton and that Spring discourages using such things but their implementation takes care to behave appropriately depending on the environment: session-scoped in a Servlet container, thread-scoped in a JUnit test, etc.  The real limiting factor of a Singleton is when it provides an implementation that is inflexible to different environments.Just do it the usual way and then insert it using  in your test class, for example:Controller:Test:You are quite right to be concerned - static method calls are particularly problematic for unit testing as you cannot easily mock your dependencies. What I am going to show you is how to let the Spring IoC container do the dirty work for you, leaving you with neat, testable code. SecurityContextHolder is a framework class and while it may be ok for your low-level security code to be tied to it, you probably want to expose a neater interface to your UI components (i.e. controllers).cliff.meyers mentioned one way around it - create your own \"principal\" type and inject an instance into consumers. The Spring </> tag introduced in 2.x combined with a request scope bean definition, and the factory-method support may be the ticket to the most readable code.It could work like following:Nothing complicated so far, right? In fact you probably had to do most of this already. Next, in your bean context define a request-scoped bean to hold the principal:Thanks to the magic of the aop:scoped-proxy tag, the static method getUserDetails will be called every time a new HTTP request comes in and any references to the currentUser property will be resolved correctly. Now unit testing becomes trivial:Hope this helps!Personally I would just use Powermock along with Mockito or Easymock to mock the static SecurityContextHolder.getSecurityContext() in your unit/integration test e.g.Admittedly there is quite a bit of boiler plate code here i.e. mock an Authentication object, mock a SecurityContext to return the Authentication and finally mock the SecurityContextHolder to get the SecurityContext, however its very flexible and allows you to unit test for scenarios like null Authentication objects etc. without having to change your (non test) codeWithout answering the question about how to create and inject Authentication objects, Spring Security 4.0 provides some welcome alternatives when it comes to testing. The  annotation enables the developer to specify a mock user (with optional authorities, username, password and roles) in a neat way:There is also the option to use  to emulate a  returned from the , e.g.More details can be found in the  and the  chapters in the Spring Security reference docs (from which the above examples where copied)Using a static in this case is the best way to write secure code.Yes, statics are generally bad - generally, but in this case, the static is what you want.  Since the security context associates a Principal with the currently running thread, the most secure code would access the static from the thread as directly as possible.  Hiding the access behind a wrapper class that is injected provides an attacker with more points to attack.  They wouldn't need access to the code (which they would have a hard time changing if the jar was signed), they just need a way to override the configuration, which can be done at runtime or slipping some XML onto the classpath.  Even using annotation injection would be overridable with external XML.  Such XML could inject the running system with a rogue principal.I asked the same question myself over , and just posted an answer that I recently found.  Short answer is: inject a , and refer to  only in your Spring config to obtain the I would take a look at Spring's abstract test classes and mock objects which are talked about . They provide a powerful way of auto-wiring your Spring managed objects making unit and integration testing easier.Authentication is a property of a thread in server environment in the same way as it is a property of a process in OS. Having a bean instance for accessing authentication information would be inconvenient configuration and wiring overhead without any benefit. Regarding test authentication there are several ways how you can make your life easier. My favourite is to make a custom annotation  and test execution listener, which manages it. Check  for inspiration.In the meantime (since version 3.2, in the year 2013, thanks to ) the authentication can be injected into MVC methods using the annotation :In your unit test you can obviously call this Method directly. In integration tests using  you can use  to inject the user like this:This will however just directly fill the SecurityContext. If you want to make sure that the user is loaded from a session in your test, you can use this:After quite a lot of work I was able to reproduce the desired behavior. I had emulated the login through  MockMvc. It is too heavy for most unit tests but helpful for integration tests. Of course I am willing to see those new features in Spring Security 4.0 that will make our testing easier.
Java

So I know about [](, but it's indexed by the  offset, not by the codepoint offset.  I'm thinking about trying something like:But my concerns areYes, Java uses a UTF-16-esque encoding for internal representations of Strings, and, yes, it encodes characters outside the Basic Multilingual Plane () using the surrogacy scheme.If you know you'll be dealing with characters outside the BMP, then here is the canonical way to iterate over the characters of a Java String:Java 8 added  which returns an  containing the code points.\nYou can use the stream directly to iterate over them:or with a for loop by collecting the stream into an array:These ways are probably more expensive than , but they are faster to read/write and the performance difference will usually be insignificant.Iterating over code points is filed as a feature request at Sun. See There is also an example on how to iterate over String CodePoints there.Thought I'd add a workaround method that works with foreach loops (), plus you can convert it to java 8's new String#codePoints method easily when you move to java 8:Then you can use it with foreach like this:Or alternately if you just want to convert a string to an array of int (which might use more RAM than the above approach):
Java

I know we can use the  method in Java get an individual character in a string by specifying its position. Is there an equivalent method in C#?You can index into a string in C# like an array, and you get the character at that index.Example:In Java, you would say In C#, you would say AndThe above is same as using indexers in c#.you can use LINQ Console.WriteLine allows the user to specify a position in a string.See sample:string str = \"Tigger\";\nConsole.WriteLine( str[0] ); //returns \"T\";\nConsole.WriteLine( str[2] ); //returns \"g\";There you go!please try to make it as a character 
Java

I've recently read about this and seen people using this class, but in pretty much all cases, using  would've worked as well - if not more intuitively. Can someone provide a concrete example where  would achieve something that  couldn't or in a much cleaner way? The only thing I can think of is to use it with  that don't accept  keys, but even that could be done with a side \"mapping\" of null's value. Can anyone provide me with a more convincing argument? Thank you.Guava team member here.Probably the single biggest disadvantage of  is that it's not obvious what it should mean in any given context: it doesn't have an illustrative name. It's not always obvious that  means \"no value for this parameter\" -- heck, as a return value, sometimes it means \"error\", or even \"success\" (!!), or simply \"the correct answer is nothing\".  is frequently the concept you actually mean when you make a variable nullable, but not always. When it isn't, we recommend that you write your own class, similar to  but with a different naming scheme, to make clear what you actually mean.But I would say the biggest advantage of  isn't in readability: the advantage is its idiot-proof-ness. It forces you to actively think about the absent case if you want your program to compile at all, since you have to actively unwrap the  and address that case. Null makes it disturbingly easy to simply forget things, and though FindBugs helps, I don't think it addresses the issue nearly as well. This is especially relevant when you're returning values that may or may not be \"present.\" You (and others) are far more likely to forget that  could return a  value than you're likely to forget that  could be  when you're implementing . Returning  makes it impossible for callers to forget that case, since they have to unwrap the object themselves.For these reasons, we recommend that you use  as a return type for your methods, but not necessarily in your method arguments.(This is totally cribbed, by the way, from the discussion .)It really looks like the  Monad pattern from Haskell.You should read the following, Wikipedia :And read  on   which discusses about the Optional of Guava used as a Monad:\nWith Java8, there's a built-in Optional that has monadic operators like . This has been a controversial subject but finally has been implemented.See The  operator is essential to allow monadic operations, and permits to easily chain calls that all return Optional results.Think about it, if you used the  operator 5 times you would end up with an , while using  would give you Since Java8 I would rather not use Guava's Optional which is less powerful.One good reason to use it is that it makes your nulls very meaningful.  Instead of returning a null that could mean many things (like error, or failure, or empty,etc) you can put a 'name' to your null. Look at this example:lets define a basic POJO:}Now lets make use of this simple POJO:Now lets avoid using null and do our checks with Optional so its meaningfulthus in the end its a way to make nulls meaningful, & less ambiguity. The most important advantage of Optional is that it adds more details to the contract between the implementer and caller of a function. For this reason is both useful for parameters and return type.If you make the convention to always have  for possible null objects you add more clarifications to cases like:So the good part of using Optional is that the contract became both descriptive (similar with  annotation) but also formal since you must write code  to cope with .
Java

I get this when I call  on an object I received from a function call. I know the type of the object is encoded in this string, but I don't know how to read it. What is this type of encoding called? is the name for , the  representing the class of array of .The naming scheme is documented in :Here are some examples:The reason why the  method on arrays returns  in this format is because arrays do not  the method inherited from , which is specified as follows:: you can not rely on the  of any arbitrary object to follow the above specification, since they can (and usually do)  it to return something else. The more reliable way of inspecting the type of an arbitrary object is to invoke  on it (a  method inherited from ) and then  on the returned  object. Ideally, though, the API should've been designed such that reflection is not necessary (see ). provides  overloads for primitive arrays and . There is also  that you may want to use for nested arrays.Here are some examples:There are also  and  that perform array equality comparison by their elements, among many other array-related utility methods.
Java

So, if I try to remove elements from a Java  while iterating, I get a .  What is the best way to remove a subset of the elements from a  as in the following example?Here is a solution, but I don't think it's very elegant:Thanks!You can manually iterate over the elements of the set:You will often see this pattern using a  loop rather than a  loop:As people have pointed out, using a  loop is preferred because it keeps the iterator variable ( in this case) confined to a smaller scope.The reason you get a  is because an entry is removed via  as opposed to .  If an entry is removed via  while an iteration is being done, you will get a ConcurrentModificationException.  On the other hand, removal of entries via  while iteration is supported in this case.The new for loop is nice, but unfortunately it does not work in this case, because you can't use the Iterator reference.If you need to remove an entry while iteration, you need to use the long form that uses the Iterator directly.you can also refactor your solution removing the first loop:Does it need to be whilst iterating?  If all you're doing is filtering or selecting I would suggest using Apache Commons .  There are some powerful tools there and it makes your code \"cooler.\"Here's an implementation that should provide what you need:If you find yourself using the same kind of predicate frequently you can pull that out into a static variable for reuse... name it something like .  Some may see that code and declare it \"hard to read\" but it looks cleaner when you pull out the Predicate into a static.  Then it's easy to see that we're doing a  and that seems more readable (to me) than a bunch of loops all over creation.Java 8 Collection has a nice method called removeIf that makes things easier and safer. From the API docs:Interesting note:From:\nAn other possible solution:Or:Like timber said - \"Java 8 Collection has a nice method called removeIf that makes things easier and safer\"Here is the code that solve your problem:Now your set contains only odd values.
Java

When you have \"Mark occurrences\" enabled in Eclipse, placing the cursor on any type/variable/method/etc will highlight all occurrences in the text editor and place a faint bar in the right ruler to show you the location of other occurrences in the file.Does anyone know where in the Preferences you can change what color is used to highlight the other occurrences in the side ruler? The color is way too faint for me with my current monitor/Windows Aero theme.I tried to go into Preferences > General > Appearance > Color and Fonts change the color for \"Color labels - match highlight\" but this didn't seem to apply.Here is a screenshot with what I am talking about:The color in the bar is the same as the color the text is highlighted with in the editor. It is set by going toPreferences > General > Editors > Text Editors > Annotationsand changing the Occurrences and Write Occurrences colors.Right click on the marker and select the only menu item \"preferences\", this opens the preferences dialog: General/Editors/text Editor/Annotation.The updates do not apply immediatly after using the Apply button, only after closing with OK and eventually reselect.The bar is called the Overview Bar or Overview Ruler (in case you need to reference it) and, as has been mentioned, the color of occurences can be changed by navigating to:and changing the color for Occurrences.One difference to note in Eclipse Juno (most other responses seem to refer to Indigo) is that the change won't take effect until you restart the program.You'll want to change the \"Occurrences\" and \"Write Occurrences\" colors. This can be done in the Annotations menu, which is located \u2014 as Colin said \u2014 in the Preferences menu under the pathGeneral > Editors > Text Editors > AnnotationsIf you have an occurrence marked in the overview ruler (the column to the right of the scrollbar), you can open the Annotations menu directly by right-clicking on the occurrence and selecting Preferences from the context menu.The color of \"occurrences\" is used for instances where the variable is being read, but not modified, in the code (e.g.  in ). The color of \"write occurrences\" is used where the variable gets modified/written to in the code (e.g.  in ).See also the , about halfway down the page (link is for Indigo, but should be good for other recent versions as well).Go to Windows/Preferences/Java/Editor/Mark Occurrences and check the box \"Mark Occurrences of the selected element in the current file.\"After changed the color of \"occurances\", restart your Eclipse IDE
Java

I'm currently using the jar-with-dependencies assembly to create such a jar.  However, the name of my jar is a bit long.  Since this jar is being used by RPG programs on an AS400, I'd like to shorten it to make life a bit easier for those developers.  But, other than by hand, I've not found a way to rename the jar from the usual .  I'd like something like  Is there anyway to do this without basically copying the jar-with-dependencies assembly descriptor and calling it full? Additionally, I want to continue to have the jar without the classpath assembled stored in the repository.I need two artifacts.  The jar with my classifier holding the region which the build is for.  The jar with all dependencies which also includes the region. and  should be stored in the repository.  In the first example the classifier is region-full, in the 2nd it's region.  The latter is working.You can specify the  property to give the jar the name you want, and specify that  should be false to avoid the \"jar-with-dependencies\" suffix.The configuration below will output a jar called \"test.jar\"Update: based on your comments, using the built-in descriptor won't work . I believe this is down to a bug in the recent versions of the assembly-plugin - they've removed support for classifiers, but the id is fixed if you use a built-in descriptor, so you end up with a big daft name.As a workaround, you can copy the assembly descriptor used by the  descriptor and modify the id.This example would result in the assembly id being appended to the finalName, so if you need to have a name of , you can specify the finalName as  and the assembly id as . This will result in a file in target called region-full.jar, but note it will still be installed to the Maven repository as an attached artifact with  used as the classifier. As long as this id is different to that for your other assembly there should be no collision though.The pom configuration would look like this.and the jar-assembly.xml in src/main/assembly like this:Thanks to the posts here and some digging in the  I've come up with the following configuration for a general one-off repacked executable jar assembly with a custom name.In pom.xml:In assembly.xml:This will produce  with all of its dependencies re-packaged into that same jar and the specified .I think I've found a way to configure this directly in the pom without needing a separate jar-assembly.xml.It's basically the same as Rich's answer, except the finalName is specified with the artifactId and version.I'm going to give Rich the credit for pointing me in the right direction, but wanted to post the solution that worked for me as Rich's was slightly off:My jar-assembly.xml looked like this which allowed the assembly id to change for the region which was stored as an property in my profile:I did not use the finalName parameter in the maven-assembly-plugin settings as this built my project with my project-name-version-env-full.jar name where env-full was the classifier.  Imagine my surprise when I learned the assembly xml could be parameterized by items in the build.  This was exactly what I was looking for.This worked for me
Java

I'm not a good java programmer, it's just my hobby, but I'm eager to know more than average stuff.I want to solve a mathematical problem with multiple threads in java. my math problem can be separated into work units, that I want to have solved in several threads.but I don't want to have a fixed amount of threads working on it, but instead a coresponding amount of threads to the amount of cpu cores.\nand my problem is, that I couldn't find an easy tutorial in the internet for this. all I found are examples with fixed threads.So could you help me with a link to a good tuturial or could give me an easy and good example? That would be really nice :)You can determine the number of processes available to the Java Virtual Machine by using the static Runtime method, .  Once you have determined the number of processors available, create that number of threads and split up your work accordingly.: To further clarify, a Thread is just an Object in Java, so you can create it just like you would create any other object.  So, let's say that you call the above method and find that it returns 2 processors.  Awesome.  Now, you can create a loop that generates a new Thread, and splits the work off for that thread, and fires off the thread.  Here's some psuedocode to demonstrate what I mean:For more information on creating your own thread, .  Also, you may want to look at  for the creation of the threads.You probably want to look at the java.util.concurrent framework for this stuff too.\nSomething like:orThis is a lot nicer than coping with your own thread pools etc.Doug Lea (author of the concurrent package) has this paper which may be relevant:\nThe Fork Join framework has been added to Java SE 7. Below are few more references:\nArticle by Brian GoetzOn the Runtime class, there is a method called availableProcessors().  You can use that to figure out how many CPUs you have.  Since your program is CPU bound, you would probably want to have (at most) one thread per available CPU.The standard way is the Runtime.getRuntime().availableProcessors() method.\nOn most standard CPUs you will have returned the optimal thread count (which is not the actual CPU core count) here. Therefore this is what you are looking for.Example:Do NOT forget to shut down the executor service like this (or your program won't exit):Here just a quick outline how to set up a future based MT code (offtopic, for illustration):Then you need to keep track on how many results you expect and retrieve them like this: from With this API, you don't need to pass number of cores to .Implementation of this API from  API from  or , which returns  pass  as parameter to .
Java

Suppose we have the following classes:Now lets call  in class A:The output is, as expected counting down from 10.   Let's get to the the confusing part. Now we call  in class B.::How does this happen? I know this is a devised example, but it makes me wonder.Older question with a .This is expected. This is what happens for an instance of .As such, the calls are alternating between  and .This doesn't happen in the case of an instance of  because the overriden method won't be called.Because  in  refers to  which is  in second case. So,  and  will be called in  function .in The other answers have all explained the essential point, that once an instance method is overridden it stays overridden and there's no getting it back except through .  invokes .  then invokes , which resolves to the override in . And we ping pong back and forth until the end of the universe or a , whichever comes first.It would be nice if one could write  in  to get its own implementation, but that would probably break things and have other unfortunate consequences, so  in  invokes  and so forth.There is a way to get the expected behavior, but it requires foresight. In other words, you must know in advance that you want a  in a subtype of  to get trapped, so to speak, in the  implementation. It is done like so:Since  invokes  and  can never be overridden,  is assured that it is calling its own logic. in class  calls the super class's method explicitly, so  of  is called once.Then,  in class A would call the  method in class  which overrides  of class , since it is executed on an instance of class .Then 's  would call 's  explicitly, and so on.That actually cannot go any other way.When you call , then it prints  then calls the implementation of this method in  with . So you call , which prints  which calls the  method on the current instance which is  with input parameter , so it calls , which then calls the super implementation with  which is , which then recursively calls the current instance recursive with  which is , and you'll get the loop that you see here.This is all because if you call the method of the instance in the superclass, you'll still call the implementation of the instance on which you're calling it.Imagine this,You'll get \"BARK\" instead of a compilation error such as \"the abstract method cannot be called on this instance\" or a runtime error  or even  or something like that. So this is all to support .When a  instance's  method calls the class implementation, the instance being acted on is still of . Therefore when the super class's implementation calls  without further qualification, . The result is the never-ending loop you're seeing. 
Java

I have added three methods with parameters:When I am calling  , then compiler throws error as . So is the issue because  and  methods or  and  methods?Java will always try to use the most specific applicable version of a method that's available (see ).,  and  can all take  as a valid value. Therefore all 3 version are applicable, so Java will have to find the most specific one.Since  is the super-type of , the array version is more specific than the -version. So if only those two methods exist, the  version will be chosen.When both the  and  versions are available, then  of them are more specific than  but none is more specific than the other, so Java can't decide which one to call. In this case you'll have to explicitly mention which one you want to call by casting the argument to the appropriate type.Note that in practice this problem occurs far more seldom than one might think. The reason for this is that it only happens when you're explicitly calling a method with  or with a variable of a rather un-specific type (such as ).On the contrary, the following invocation would be perfectly unambiguous:Although you're still passing the value , Java knows exactly which method to call, since it will take the type of the variable into account.Each pair of these three methods is ambiguous by itself when called with a  argument. Because each parameter type is a reference type. The following are the three ways to call one specific method of yours with null.May I suggest to remove this ambiguity if you actually plan to call these methods with  arguments. Such a design invites errors in the future. is a valid value for any of the three types; so the compiler cannot decide which function to use. Use something like  or  instead.Every class in Java extends Object class.Even Integer class also extends Object. Hence both Object and Integer are considered as Object instance. So when you pass null as a parameter than compiler gets confused that which object method to call i.e. With parameter Object or parameter Integer since they both are object and their reference can be null. But the primitives in java does not extends Object.I Have tried this and when there is exactly one pair of overloaded method and one of them has a parametar type Object then the compiler will always select the method with more specific type.  But when there is more than one specific type, then the compiler throws an ambiguous method error. Since this is a compile time event, This scenario can only happen when one intentionally pass null to this method.  If this is intentionally then it is better to overload this method again with no parameter or create another method altogether.  
Java

How do I connect to Gmail and determine which messages have attachments?  I then want to download each attachment, printing out the Subject: and From: for each message as I process it.Hard one :-)Wowww! That was something. ;-) But try the same in Java, just for fun!By the way, I tested that in a shell, so some errors likely remain.EnjoyBecause mail-box names can change from one country to another, I recommend doing  and picking an item in it before  to avoid this error:I'm not an expert on Perl, but what I do know is that GMail supports IMAP and POP3, 2 protocols that are completely standard and allow you to do just that. Maybe that helps you to get started. untestedTake a look at :There are two ways to get an attachment:1 -> By sending a reference to a specific attachment returned by 2 -> Or by sending the attachment ID and message ID( Returns a reference to a scalar that holds the data from the attachment. )Within gmail, you can filter on \"has:attachment\", use it to identify the messages you should be getting when testing. Note this appears to give both messages with attached files (paperclip icon shown), as well as inline attached images (no paperclip shown).There is no Gmail API, so IMAP or POP are your only real options. The  may be of some assistance as well as this very terse article on . Some  here on SO may also help.This  may help too. Unfortunately from what I can see, there is no attachment information contained within the imap_header, so downloading the body is required to be able to see the X-Attachment-Id field. (someone please prove me wrong).If any of you have updated to python 3.3 I took the 2.7 script from  and updated it to 3.3.  Also fixed some issues with the way gmail was returning the information.The question is quite old and at that time Gmail API was not available.  But now Google provides Gmail API to access IMAP.  See Google's Gmail API . Also see  on pypi.Maven Dependency:Since Gmail supports the standard protocols POP and IMAP, any platform, tool, application, component, or API that provides the client side of either protocol should work.I suggest doing a Google search for your favorite language/platform (e.g., \"python\"), plus \"pop\", plus \"imap\", plus perhaps \"open source\", plus perhaps \"download\" or \"review\", and see what you get for options.There are numerous free applications and components, pick a few that seem worthy, check for reviews, then download and enjoy.You should be aware of the fact that you need SSL to connect to GMail (both for POP3 and IMAP - this is of course true also for their SMTP-servers apart from port 25 but that's another story).Here's something I wrote to download my bank statements in  (dynamic language for the Java Platform).Have you taken a look at the  at wikipedia?In particular,  is an open source add-on that you may be able to use as-is, or perhaps study for inspiration?For Java, you will find  of use. It's a set of APIs to communicate with Google Mail via Java (the screenshot on the homepage is a demonstration email client built around this)
Java

When I run maven test, java.lang.OutOfMemoryError happens. I google it for solutions and have tried to , but it did not work. \nAnyone know other solutions for this problem ,BTW I am using maven 3.0Thanks in advancePaste the error message here when run \"mvn test -e\"Setting the  options using  does work, it does configure the JVM used to start Maven. That being said, the maven-surefire-plugin  a new JVM by default, and your  are thus not passed.To configure the sizing of the JVM used by the maven-surefire-plugin, you would either have to: In the later case, something like this: I have to say that I tend to agree with Stephen here, there is very likely something wrong with one of your test and I'm not sure that giving more memory is the right solution to \"solve\" (hide?) your problem.For those new to Maven (like me) here is the whole config that goes in the build section of your pom. Cheers. The chances are that the problem is in one of the unit tests that you've asked Maven to run.As such, fiddling with the heap size is the wrong approach.  Instead, you should be looking at the unit test that has caused the OOME, and trying to figure out if it is the fault of the unit test or the code that it is testing.Start by looking at the stack trace.  If there isn't one, run  again with the  option.I have solved this problem on my side by 2 ways:Set the environment variable:MAVEN_OPTS=\"-Xmx1024m\"Not only heap memory. also increase perm size  to resolve that exception in maven use these variables in environment variable.Example  : 
Java

I'm trying to work with  in Java. I want to implement arithmetic functions.  For this, I will first require a way to normalize the functions.  I know I can't add 1/6 and 1/2 until I have a common denominator. I will have to add 1/6 and 3/6.  A naive approach would have me add 2/12 and 6/12 and then reduce.  How can I achieve a common denominator with the least performance penalty?  What algorithm is best for this?Version 8 (thanks to ):I have removed all previous versions.  My thanks to:It just so happens that I wrote a BigFraction class not too long ago, for .  It keeps a BigInteger numerator and denominator, so it'll never overflow.  But it'll be a tad slow for a lot of operations that you know will never overflow.. anyway, use it if you want it.  I've been dying to show this off somehow. :): Latest and greatest version of this code, including unit tests is  and also . I'm leaving my original code here so that this answer isn't just a link...In fact, try this on for size.  It runs but may have some issues:Output is:Please make it an immutable type! The value of a fraction doesn't change - a half doesn't become a third, for example. Instead of setDenominator, you could have withDenominator which returns a  fraction which has the same numerator but the specified denominator.Life is  easier with immutable types.Overriding equals and hashcode would be sensible too, so it can be used in maps and sets. Outlaw Programmer's points about arithmetic operators and string formatting are good too.As a general guide, have a look at BigInteger and BigDecimal. They're not doing the same thing, but they're similar enough to give you good ideas. has had a  class for quite some time. Most times the answer to, \"Boy I wish Java had something like  in the core library!\" can be found under the umbrella of the .Well, for one, I'd get rid of the setters and make Fractions immutable.You'll probably also want methods to add, subtract, etc., and maybe some way to get the representation in various String formats.EDIT: I'd probably mark the fields as 'final' to signal my intent but I guess it's not a big deal...Not strictly necessary. (In fact if you want to handle equality correctly, don't rely on double to work properly.) If b*d is positive, a/b < c/d if ad < bc. If there are negative integers involved, that can be handled appropriately...I might rewrite as:The use of  here is to ensure there's not an overflow if you multiply two large s. handle If you can guarantee that the denominator is always nonnegative (if it's negative, just negate both numerator and denominator), then you can get rid of having to check whether b*d is positive and save a few steps. I'm not sure what behavior you're looking for with zero denominator.Not sure how performance compares to using doubles to compare. (that is, if you care about performance that much) Here's a test method I used to check. (Appears to work properly.)(p.s. you might consider restructuring to implement  or  for your class.)One very minor improvement could potentially be to save the double value that you're computing so that you only compute it on the first access.  This won't be a big win unless you're accessing this number a lot, but it's not overly difficult to do, either.One additional point might be the error checking you do in the denominator...you automatically change 0 to 1.  Not sure if this is correct for your particular application, but in general if someone is trying to divide by 0, something is very wrong.  I'd let this throw an exception (a specialized exception if you feel it's needed) rather than change the value in a seemingly arbitrary way that isn't known to the user.In constrast with some other comments, about adding methods to add subtract, etc...since you didn't mention needing them, I'm assuming you don't.  And unless you're building a library that is really going to be used in many places or by other people, go with YAGNI (you ain't going to need it, so it shouldn't be there.)There are several ways to improve this or any value type:Basically, take a look at the API for other value classes like , Integer and do what they do :)If you multiply the numerator and denominator of one Fraction with the denominator of the other and vice versa, you end up with two fractions (that are still the same values) with the same denominator and you can compare the numerators directly. Therefore you wouldn't need to calculate the double value:how I would improve that code:You have a compareTo function already ... I would implement the Comparable interface.May not really matter for whatever you're going to do with it though.If you're feeling adventurous, take a look at . It has a  class that represents fractions.I would say throw a ArithmeticException for divide by zero, since that's really what's happening:Instead of \"Divide by zero.\", you might want to make the message say \"Divide by zero: Denominator for Fraction is zero.\"Once you've created a fraction object why would you want to allow other objects to set the numerator or the denominator?  I would think these should be read only.  It makes the object immutable...Also...setting the denominator to zero should throw an invalid argument exception (I don't know what it is in Java)Timothy Budd has a fine implementation of a Rational class in his \"Data Structures in C++\".  Different language, of course, but it ports over to Java very nicely.I'd recommend more constructors.  A default constructor would have numerator 0, denominator 1.  A single arg constructor would assume a denominator of 1.  Think how your users might use this class.No check for zero denominator?  Programming by contract would have you add it.I'll third or fifth or whatever the recommendation for making your fraction immutable.  I'd also recommend that you have it extend the  class.  I'd probably look at the  class, since you're probably going to want to implement many of the same methods.  You should probably also implement  and  since this behavior will probably be expected.  Thus, you will need to implement compareTo().  You will also need to override equals() and I cannot stress strongly enough that you also override hashCode().  This might be one of the few cases though where you don't want compareTo() and equals() to be consistent since fractions reducable to each other are not necessarily equal.A clean up practice that I like is to only have only one return.  Use Rational class from  library. It's the best thing for fractional arithmetic I seen in Java.I cleaned up :Initial remark:Never write this:This is much better Just create to create a good habit.By making the class immutable as suggested, you can also take advantage of the double to perform the equals and hashCode and compareTo operations Here's my quick dirty version:About the static factory method, it may be useful later, if you subclass the Fraction to handle more complex things, or if you decide to use a pool for the most frequently used objects. It may not be the case, I just wanted to point it out. :) See  first item.Might be useful to add simple things like reciprocate, get remainder and get whole.Even though you have the methods compareTo(), if you want to make use of utilities like Collections.sort(), then you should also implement Comparable.Also, for pretty display I recommend overriding toString()And finally, I'd make the class public so that you can use it from different packages.This function simplify using the eucledian algorithm is quite useful when defining fractionsFor industry-grade Fraction/Rational implementation, I would implement it so it can represent NaN, positive infinity, negative infinity, and optionally negative zero with operational semantics exactly the same as the IEEE 754 standard states for floating point arithmetics (it also eases the conversion to/from floating point values). Plus, since comparison to zero, one, and the special values above only needs simple, but combined comparison of the numerator and denominator against 0 and 1 - i would add several isXXX and compareToXXX methods for ease of use (eg. eq0() would use numerator == 0 && denominator != 0 behind the scenes instead of letting the client to compare against a zero valued instance). Some statically predefined values (ZERO, ONE, TWO, TEN, ONE_TENTH, NAN, etc.) are also useful, since they appear at several places as constant values. This is the best way IMHO.
Java

This Java code:will output this:In C++ I can pass the  variable as pass by reference to avoid shadowing i.e. creating a copy of the same variable as below:and the C++ output will be this:My question is - What's the equivalent code in Java to get the same output as the C++ code, given that ?You have several choices.  The one that makes the most sense really depends on what you're trying to do.then pass a reference to a MyToy to your method.This choice would require a small change to the callsite in main so that it reads, .If the two functions are methods on the same class or class instance, you could convert toyNumber into a class member variable.This is considered a hack, but is sometimes employed to return values from inline class invocations.Java is not  it is But all variables of object type are actually pointers.So if you use a Mutable Object you will see the behavior you wantOutput of this code:You can see this behavior in Standard libraries too.\nFor example Collections.sort(); Collections.shuffle();\nThese methods does not return a new list but modifies it's argument object.Output of this code:Make athen pass a reference to an instance of it. Note that a method that mutates state through its arguments is best avoided, especially in parallel code.You cannot pass primitives by reference in Java. All variables of object type are actually pointers, of course, but we call them \"references\", and they are also always passed by value.In a situation where you really need to pass a primitive by value, what people will do sometimes is declare the parameter as an array of primitive type, and then pass a single-element array as the argument. So you pass a reference int[1], and in the method, you can change the contents of the array.For a quick solution, you can use AtomicInteger or any of the atomic variables which will let you change  the value inside the method using the inbuilt methods. Here is sample code:Output:
Java

I'm trying to implement a TCP connection, everything works fine from the server's side but when I run the client program (from client computer) I get the following error:I tried changing the socket number in case it was in use but to no avail, does anyone know what is causing this error & how to fix it.The Server Code:The Client Code:This exception  occurs when there is no service listening on the IP/port you are trying to connect to. However, a number of things could be causing the error:I would check:The simplest starting point is probably to try to connect manually from the client machine using telnet or Putty. If that succeeds, then the problem is in your client code. If it doesn't, you need to work out  it hasn't.  may help you on this front.You have to connect your client socket to the remote ServerSocket. Instead ofdo The client must connect to  which should match the name or IP of the box on which your  was instantiated (the name must be reachable from the client machine). BTW: It's not the name that is important, it's all about IP addresses...I tried your code out and I didn't have any problems on my machine. it has to be something blocking your connection or else you are starting them in the wrong order. Are you making sure that your server isn't getting closed when you start the client up. My process was this. put both class file in one directory, then opened 2 command prompts to that directory to execute them separately. if your using an IDE it may be closing the server automatically which is why i recommend doing it this wayI had the same problem with Mqtt broker called vernemq.but solved it by adding the following.to show the list o allowed ips and ports for vernemqto add any ip and your new port. now u should be able to connect without any problem. Hope it solves your problem.\nI had the same problem, but running the Server before running the Client fixed it. Hope my experience may be useful to someone. I faced the problem with the same exception stack trace and I couldn't understand what the issue was. The Database server which I was trying to connect was running and the port was open and was accepting connections.The issue was with internet connection. The internet connection that I was using was not allowed to connect to the corresponding server. When I changed the connection details, the issue got resolved.i got this error because  that try to accept number of clients inside it (I did not finished accepting all clints)so be careful where to close your SocketIn my case, I gave the socket the name of the server (in my case \"raspberrypi\"), and instead an IPv4 address made it, or to specify, IPv6 was broken (the name resolved to an IPv6)Port number always diffrent at both endI had same problem and the problem was that I was not closing socket object.After using socket.close(); problem solved.\nThis code works for me.ClientDemo.javaand \nServerDemo.javaIt could be that there is a previous instance of the client still running and listening on port 5000.try  from the Internet (you can turn off wifi).
Java

I'm trying to figure out what a Java applet's class file is doing under the hood. Opening it up with Notepad or Textpad just shows a bunch of gobbledy-gook.Is there any way to wrangle it back into a somewhat-readable format so I can try to figure out what it's doing? is the best decompiler at the moment. it can handle newer features in Java, as compared to the getting-dusty JAD.If you don't mind reading bytecode, javap should work fine. It's part of the standard JDK installation.You want a java decompiler, you can use the command line tool  to do this.  Also,  describes how you can decompile a class file.Using  to decompile it is probably your best option. Unless the code has been obfuscated, it will produce an okay result.cpuguru, if your applet has been compiled with javac 1.3 (or less), your best option is to use Jad.Unfortunately, the last JDK supported by JAD 1.5.8 (Apr 14, 2001) is JDK 1.3.If your applet has been compiled with a more recent compiler, you could try  : this decompiler is under development, nevertheless, it generates correct Java sources, most of time, for classes compiled with the JDKs 1.4, 1.5 or 1.6.DarenW, thank you for your post. JD-GUI is not the best decompiler yet ... but I'm working on :)That's compiled code, you'll need to use a decompiler like JAD: what you are looking for is a java de-compiler.  I recommend JAD   It's free for non commercial use and gets the job done. Note: this isn't going to make the code exactly the same as what was written. i.e. you're going to lose comments and possibly variable names, so it's going to be a little bit harder than just reading normal source code.    If the developer is really secretive they will have obfuscated their code as well, making it even harder to read. As suggested you can use JAD to decompile it and view the files. To make it easier to read you can use the JADclipse plugin for eclipse to integrate JAD directly to eclipse or use DJ Java Decompiler which is much easier to use than command line JADJAD is an excellent option if you want readable Java code as a result.  If you really want to dig into the internals of the  file format though, you're going to want .  It's bundled with the JDK and allows you to \"decompile\" the hexadecimal bytecode into readable ASCII.  The language it produces is still bytecode (not anything like Java), but it's fairly readable and extremely instructive.Also, if you  want to, you can open up any  file in a hex editor and read the bytecode directly.  The result is identical to using .You need to use a decompiler.  Others have suggested JAD, there are other options, JAD is the best.I'll echo the comments that you may lose a bit compared to the original source code.  It is going to look especially funny if the code used generics, due to erasure.JAD and/or JADclipse Eclipse plugin, for sure.There is no need to decompile Applet.class. The public Java API classes sourcecode comes with the JDK (if you choose to install it), and is better readable than decompiled bytecode. You can find compressed in src.zip (located in your JDK installation folder).If the class file you want to look into is open source, you should not decompile it, but instead attach the source files directly into your IDE. that way, you can just view the code of some library class as if it were your ownjd-gui \"\" is the best and user friendly option for decompiling .class file.... is a great decompiler for modern Java written i Java 6.
Java

I am considering creating my own website using Java and am trying to decide what framework to use. However, doing a quick search for Java frameworks returns more than 50 to choose from!My website is just going to be for my own enjoyment of building it in the beginning, but if it becomes popular, it would be good for it to have some scalability, or to at least be able to redesign for that.What are the main differences between the more popular frameworks? Are there instances where one significantly outperforms the others? For example, high-traffic enterprise applications versus low-traffic small applications. I'm also wondering if some are much easier to learn and use than others.Is there anyone who has experience with some of these frameworks and can make a recommendation? Does the sheer number of choices just serve as an early warning to avoid Java-based web development where possible?I've used , , , and  fairly extensively.  I'd really recommend you look those over and pick the one that appears the easiest for you, and to most closely fit the way you prefer to work.Of them, the most comfortable for me to work with was , due to the lightweight nature of component building and simplicity of page templating.  That goes doubly so if you are using your own db code instead of Hibernate or some other framework (I was never completely happy with Wicket Hibernate or Spring Integration). is great if you don't mind writing all of your layout in Java.  I know that is different now, but I still think that product serves a fairly narrow niche.  They change the development model with every major release as well it seems. is a great product, but it is obviously very different from the others in terms of development model as it is led mainly by one dude.  Howard Lewis Ship is no doubt quite smart, but I am disappointed with their decision to basically forget backwards compatibility with each release.  Again, though, for your needs this may not matter, and I've always found the Tapestry products pleasurable to work against. has been out for years, and still feels like something that a  guy built to fix all of the problems of Struts.  Without really understanding all of the problems with Struts.  It still has an unfinished feel to it, although the product is obviously very flexible.  I use it and have some fondness for it, with great hopes for its future.  I think the next release (2.0) to be delivered in JEE6 will really bring it into its own, with a new template syntax (similar to Facelets) and a simplified component model (custom components in only 1 file... finally).And, of course, there are a million smaller frameworks and tools that get their own following ( for basic needs, raw , Struts, etc).  I generally prefer component oriented frameworks myself, though.  In the end, I'd recommend just taking a look at Tapestry, Wicket, and JSF and just picking the one that feels the best to you.  You'll probably find one that just fits the way you like to work very quickly.My favorite is the Spring Framework. With 2.5 Spring MVC is soooo kick ass, with new annotations, convention over configuration features, etc.If you're just doing something super simple you could also just try using the regular Servlet API and not bother with a framework.I recommend the component oriented  framework. It allows you to write your web application in plain old Java code, you can use POJOs as the model for all components and don't need to mess around with huge XML configuration files. I had successfully developed an online banking application with Struts when I discovered Wicket and saw how easy web application development can be!I've recently started using the . If you're looking for a request based framework that's really easy to use, but doesn't impose any limits on what you are doing I'd highly recommend it.It's similar to struts, but it goes way beyond it. There are even some plugin projects that enable you to do use hibernate or jpa with very little configuration.There are a lot of good frameworks out there though I've heard wicket is a good one as well, but I haven't used it.Another one to consider would be Grails.Although it isn't strictly a Java framework, it depends on Groovy (if you haven't seen this before, this is a dynamic language that runs on the JVM). Most valid Java is also valid Groovy, so it is pretty easy to learn.My last project used Grails, and whilst I'd never used Groovy before, I discovered:There is a downside: it is a very \"clever\" framework that hides a lot from you, so when things go wrong it can be very time consuming to find the problem.The project I mentioned would simply not have shipped on time or on budget if we'd gone for a more traditional framework (even one that we're familar and skilled with such as SpringMVC), so Grails is definitely one that we'll continue to pick in the future.(but +1 for Wicket and Stripes, two excellent frameworks).Haven't tried it myself, but I thinkhas a lot of potential...coming from php and classic asp, it's the first java web framework that sound promising to me....UPDATE: Tapestry 5.2 is out, so it's not abandoned, as it previously appeared to be. My experience is with Tapestry 4, not 5, so your mileage may vary. My opinion of Tapestry has changed over the years; I have modified this post to reflect it.I can no longer recommend Tapestry as I did previously. Tapestry 5 appears to be a significant improvement, but my main issue with Tapestry is not with platform itself; it's with the people behind it.Historically, every major version update of Tapestry has broken backwards compatibility with extreme prejudice, far more than one might expect. This seems to be due to the incorporation of new coding techniques or technologies that require significant rewrites.Howard Lewis Ship (the principal author of Tapestry) is certainly a brilliant developer, but I can't say I care for his management of the Tapestry project. Development of Tapestry 5 began almost immediately after Tapestry 4 shipped. From what I can tell, Ship pretty much devoted himself to that, leaving Tapestry 4 in the hands of other contributors, who I feel are not nearly as capable as Ship. After having made the painful switch from Tapestry 3 to Tapestry 4, I felt that I had been abandoned almost immediately.Of course, with the release of Tapestry 5, Tapestry 4 became a legacy product. I wouldn't have a problem with this if the upgrade path wasn't so brutal . So now our development team is in the rather unenviable position: We could continue to use an essentially abandoned web platform (Tapestry 4), make the heinous upgrade to Tapestry 5, or give up on Tapestry entirely and rewrite our application using another platform. None of these options is very attractive.Tapestry 5 is supposedly written so as to reduce the likelihood of update breakage from this point forward. A good example is in the page classes: in previous incarnations, page classes descended from a base class provided by Tapestry; incompatible API changes in this class were the cause of a large number of backward compatibility problems. In Tapestry 5, pages are POJOs which are enhanced at runtime with the \"magic Tapestry fairy dust\" via annotations. So as long as the contract for the annotations is maintained, changes to Tapestry won't affect your page classes.If this is right, then writing a new application using Tapestry 5 could turn out well. But personally, I don't feel like putting my hand on the burner again. If you are doing something RIAish, you might want to take look at . It's an open source UI-oriented AJAX framework that, to me, is nice to use (I come from a PHP background myself).There's a  that compares doing the same application (i.e. two applications with the same set of features) in Icefaces and Vaadin. In a nutshell, it states that the UI development was considerably faster. Even though the study is hosted at the company's wiki, I can assure that it's objective, genuine and truthful, although I can't force you in believing me.After a long while of testing various solutions, for me it turned out to be:One month of an extraordinarily steep learning curve, but now I am happy.I would also like to mention that I was just a little step away from skipping all that Java stuff and learing Scala/LIFT instead. As far as I am concerned, everything in Java that is related with cutting edge web development (comet, async communication,  (yes, even with Spring Security!)) still is a bit of a hack (proove me wrong by evidence, pleeease!). To me, Scala/LIFT seems to be a more out-of-the-box and all-in-one solution.The reason why I finally decided  to go with Scala isCheers\nEr My pick is Wicket!!I've heard good things about the Spring Framework too.  In general, though, I've been underwhelmed by most Java web frameworks I've looked at (esp Struts).  For a simple app I'd definitely consider using \"raw\" servlets and JSPs and not worry about adopting a framework.  If the servlets are well written, it should be straightforward in the future to port to a framework if necessary when the app grows in complexity.All of them - that's the problem ;-)I think for your modest requirements, you just need to code up servlets or simple jsp pages that you can serve from Tomcat server. I dont think you need any kind of web-framework (like struts) for personal web-site dataSaying \"use JSF\" is a little to simple. When you decide to use JSF, you have to choose a component library on top of it. Will you use MyFaces Tomahawk, Trinidad, Tobago ()? Or maybe ICEfaces ()? Oh, and if you use ICEfaces, will you use JSPs or Facelets for your views?In my opinion it is to hard to tell. Nobody has the time to evaluate all the promising alternatives, at least in the projects I work on, because they are not big enough to do three month evaluation phases. However, you should look around for some that has a big and active community and isn't gone in a year. JSF is around for some time, and since it gets pushed by sun, it will be around for some more. I can't say if it's the best choice, but it will be a good one. - the good oneFor high traffic sites I'd use a framework that doesn't manage client state on the server - Wicket, JSF and Tapestry are managing client state on the server. I'd only use those frameworks (Wicket is my favourite) if the application should be more like a desktop application. But I'd try to use a more scalable and simple REST+AJAX approach though.Spring MVC would be a candidate, but since Spring MVC 3 it has a strange annotation overloaded programming model which doesn't use the benefits of static typing. There ore other ugly things like output parameters in methods combined with a usual return, so there are two output channels of one method. Spring MVC also tends to reeinvent the wheel and you'll have more to configure compared to other frameworks. I cannot really recommend Spring MVC though it has some nice ideas.Grails is a convenient way to use Spring MVC and other established frameworks like Hibernate. Coding is fun and you'll quickly see results.And don't forget that the Servlet API with a few little helpers like FreeMarker for templating is very powerful.I have evaluated quite a few frameworks and Vaadin () has percolated all the way to the top. You should at least give it a short evaluation. Cheers! My pick would be Wicket (for large projects and a predictable user base), GWT (for large projects that are mostly public facing) or just a service framework (like Jersey/ JAXRS) together with a JavaScript toolkit (for small to medium projects).I recommend Seam, especially if you need persistence.See a few comments on some Java application Frameworks (second paragraph):For  GUI you can use JSF with  library.\nRichfaces UI components are easy to use and handy references available with code demonstration in the demo site. Probably later when your site has more data to handle and lot of information has to be transacted in database you can plug any database access framework (ORM) with it. Can't believe no one has mentioned GWTMy favorite way to go for really simple apps is Apache VelocityTools (VelocityLayoutServlet) with Velosurf ().For more complex apps, Spring MVC or Struts 2.Try HybridJava - that is much simpler than anything else.I would say  or 
Java

So I'm declaring and initializing an int array:Say I do this instead... ...  will print to standard out. Also, if I do this:...  will print to standard out. So how is Java initializing my array by default? Is it safe to assume that the default initialization is setting the array indices to  which would mean I don't have to loop through the array and initialize it? Thanks.Everything in a valid Java program not explicitly set to something by the programmer, is initialized to a zero value.  When you create an array of something, all entries are also zeroed.  So your array contains five zeros right after it is created by .From the : clearly says and this is irrespective of whether the array is an instance variable or local variable or class variable.Default values for primitive types : For objects default values is .According to java,Java says that the default length of a JAVA array at the time of initialization will be 10.But the  method returns the number of inserted elements in the array, and since at the time of initialization, if you have not inserted any element in the array, it will return zero.Every class in Java have a constructor ( A constructor is a method which is called when a new object is created , which initializes the fields of the class variables ) . So when you are creating an instance of the class , constructor method is called while creating the object and all the data values are initialized at that time .For object of integer array type all values in the array are initialized to 0(zero) in the constructor method .\nSimilarly for object of boolean array , all values are initialized to false . Thorbj\u00f8rn Ravn Andersen answered for most of the data types. Since there was a heated discussion about array,Quoting from the jls spec \n\"array component is initialized with a default value when it is created\"I think irrespective of whether array is local or instance or class variable it will with default values
Java

I know that multiple inheritance is not allowed in Java and C#. Many books just say, multiple inheritance is not allowed. But it can be implemented by using interfaces. Nothing is discussed about why it is not allowed. Can anybody tell me precisely why it is not allowed?The short answer is: because the language designers decided not to.Basically, it seemed that both the .NET and Java designers did not allow multiple inheritance because they reasoned that adding MI  to the languages while providing .For a more fun and in-depth read, there are some articles available on the web with interviews of some of the language designers. For example, for .NET, Chris Brumme (who worked at MS on the CLR) has explained the reasons why they decided not to:For Java, you can read :Multiple inheritance of  is what is not allowed.  The problem is that the compiler/runtime cannot figure out what to do if you have a Cowboy and an Artist class, both with implementations for the draw() method, and then you try to create a new CowboyArtist type.  What happens when you call the draw() method?  Is someone lying dead in the street, or do you have a lovely watercolor?I believe it's called the double diamond inheritance problem.Because Java has a greatly different design philosophy from C++.  (I'm not going to discuss C# here.)In designing C++, Stroustrup wanted to include useful features, regardless of how they could be misused.  It's possible to screw up big-time with multiple inheritance, operator overloading, templates, and various other features, but it's also possible to do some very good things with them.The Java design philosophy is to emphasize safety in language constructs.  The result is that there are things that are a lot more awkward to do, but you can be a lot more confident that the code you're looking at means what you think it does.Further, Java was to a large extent a reaction from C++ and Smalltalk, the best known OO languages.  There are plenty of other OO languages (Common Lisp was actually the first one to be standardized), with different OO systems that handle MI better.Not to mention that it's entirely possible to do MI in Java, using interfaces, composition, and delegation.  It's more explicit than in C++, and therefore is clumsier to use but will get you something you're more likely to understand at first glance.There is no right answer here.  There are different answers, and which one is better for a given situation depends on applications and individual preference.\nJava is very popular and easy to code, because of its simplicity.So what ever java developers feel difficult and complicated to understand for programmers, they tried to avoid it. One such kind of property is multiple inheritance. Diamond problem.: This is the ambiguity existing in diamond problem.It is not impossible to solve this problem, but it creates more confusion and complexities to the programmer while reading it.\n: But any way you can always implement multiple inheritance indirectly by using interfaces.The main (although by no means the only) reason people steer away from MI is the so called \"diamond problem\" leading to ambiguity in your implementation. This  discusses it and explains better than I could. MI can also lead to more complex code, and a lot of OO designers claim that you do't need MI, and if you do use it your model is probably wrong. I'm not sure I agree with this last point, but keeping things simple is always a good plan.In C++ multiple inheritance was a major headache when used improperly. To avoid those popular design issues multiple interfaces \"inheritance\" was forced instead in modern languages (java, C#).Another reason is that single-inheritance makes casting trivial, emitting no assembler instructions (other than checking for the compatibility of the types where required). If you had multiple-inheritance, you'd need to figure out where in the child class a certain parent starts. So performance is certainly a perk (although not the only one).Multiple Inheritance isTherefore, it can be considered a wise choice to  include Multiple Inheritance into the Java language.I take the statement that \"Multiple inheritance is not allowed in Java\" with a pinch of salt.Multiple Inheritance is defined when a \"Type\" inherits from more than one \"Types\". And interfaces are also classified as types as they have behavior. So Java does have multiple inheritance. Just that it is safer.Dynamic loading of classes makes the implementation of multiple inheritance difficult.In java  actually they avoided the complexity of multiple inheritance instead by using single inheritance and interface. \nComplexity of multiple inheritance is very high in a situation like below explained\nWe have two classes B and C inheriting from A. Assume that B and C are overriding an inherited method and they provide their own implementation. Now D inherits from both B and C doing multiple inheritance. D should inherit that overridden method, jvm can't able to decide which overridden method will be used?In c++ virtual functions are used to handle and we have to do explicitly.This can be avoided by using interfaces, there are no method bodies. Interfaces cannot be instantiated\u2014they can only be implemented by classes or extended by other interfaces.Java has concept, i.e. polymorphism. There are 2 types of polymorphism in java. There are method overloading and method overriding. Among them, method overriding happens with super- and subclass relationship. If we are creating an object of a subclass and invoking the method of superclass, and if subclass extends more than one class, which super class method should be called?Or , while calling superclass constructor by , which super class constructor will get called?This decisions are impossible by current java API features. so multiple inheritance is not allowed in java.Back in the old days ('70s) when Computer Science was more Science and less mass production the programmers had time to think about good design and good implementation and as a result the products (programms) had high quality ( eg. TCP/IP design and implementation ). \nNowadays, when everybody is programming, and the managers are changing the specs before deadlines, subtle issues like the one descriped in the wikipedia link from Steve Haigh post are difficult to track; therefore, the \"multiple inheritance\" is limited by compiler design. If you like it, you can still use C++ .... and have all the freedom you want :) Actually multiple inheritance will arise a the complexity if the inherited classes have same function. ie the compiler will have a confusion which one has to chose (diamond problem). So in Java that complexity removed and gave interface to get the functionality like multiple inheritance gave. We can use interface Multiple Inheritance is not allowed in Java directly , but through interfaces it is allowed.Reason :  Introduces more complexity and ambiguity. Interfaces are completely abstract classes in Java that provide you with a uniform way to properly delineate the structure or inner workings of your program from its publicly available interface, with the consequence being a greater amount of flexibility and reusable code as well as more control over how you create and interact with other classes. More precisely, they are a special construct in Java with the additional characteristic that allow you to perform a kind of multiple inheritance i.e. classes that can be upcast to more than one class.Lets take simple example.You can find answer from this documentation  If multiple inheritance is allowed and when you create an object by instantiating that class, that object will inherit fields from all of the class's super classes. It will cause two issues.Even though multiple inheritance of state is now allowed, still you can implement : Ability of a class to implement more than one interface. (through default methods in interfaces) : Ability to inherit method definitions from multiple classesRefer to this related SE question for additional info:Imagine this Example:\nI have a class It has  method:There is another class  that one also has same method Now I have a child class Circle, it derives from both Shape1 and Shape2;Now when I create object for Circle, and call the method, system does not know which calculate area method to be called. Both has same signatures. So compiler will get confuse. That's why multiple inheritances are not allowed.But there can be multiple interfaces because interfaces do not have method definition. Even both the interfaces have same method, both of them do not have any implementation and always method in the child class will be executed.
Java

I often encounter methods which look like the following:What happens if this method is called without passing it final parameters. i.e. an Object1 that is later changed (so is not declared as final) can be passed to this method just fineJava always makes a copy of parameters before sending them to methods. This means the final doesn't mean any difference for the calling code. This only means that inside the method the variables can not be reassigned. (note that if you have a final object, you can still change the attributes of the object).There is a circumstance where you're  to declare it final --otherwise it will result in compile error--, namely passing them through into anonymous classes. Basic example:Removing the  modifier would result in compile error, because it isn't guaranteed anymore that the value is a runtime constant. Changing the value from outside the anonymous class would namely cause the anonymous class instance to behave different after the moment of creation.Java is only pass-by-value. (or better - pass-reference-by-value)So the passed argument and the argument within the method are  handlers pointing to the same object (value). Therefore if you change  of the object, it is reflected to every other variable that's referencing it. But if you re-assign a new object (value) to the argument, then other variables pointing to this object (value) do not get re-assigned.The  keyword on a method parameter means absolutely nothing to the caller. It also means absolutely nothing to the running program, since its presence or absence doesn't change the bytecode. It only ensures that the compiler will complain if the parameter variable is reassigned within the method. That's all. But that's enough.Some programmers (like me) think that's a very good thing and use  on almost every parameter. It makes it easier to understand a long or complex method (though one could argue that long and complex methods should be refactored.) It also shines a spotlight on method parameters that  marked with .Consider this implementation of foo():Because the  instance would outlive the method, this wouldn't compile without the  keyword --  tells the compiler that it's safe to take a copy of the reference (to refer to it later). Thus, it's the  that's considered final, not the . In other words: As a caller, you can't mess anything up... means you can't change the value of that variable once it was assigned.Meanwhile, the use of  for the arguments in those methods means .\nThis only means that inside the method the  variables can not be reassigned.If you declare any parameter as final, you cannot change the value of it.Ouput : Compile Time Error For more detail visit: Nearly all of the things have been said about  method parameters in ; but I would like to add a tiny simple thing that you can think of this  method parameter like  pass-by-reference parameters in  like =>@stuXnet, I could make the exact opposite argument. If you pass an object to a function, and you change the properties of the passed object then the caller of the function will see the changed value in its variable. This implies a pass by reference system, not pass by value.What is confusing is the definition of pass by value or pass by reference in a system where the use of pointers is completely hidden to the end user. Java is definitely NOT pass by value, as to be such, would mean one could mutate the passed object and the original would be unaffected. Notice you cannot mutate primitives you can only assign them to variables. So testing a\nPass by reference or by value by using primitives is not a test.  What you cannot do in Java that can be done in other languages is to reassign the caller's variables to a new value because there are no pointers in Java, so this makes it confusing. final keyword in the method input parameter is not needed. Java creates a copy of the reference to the object, so putting final on it doesn't make the object final but just the reference, which doesn't make senseStrings are immutable, so actully you can't change the String afterwards (you can only make the variable that held the String object point to a different String object).However, that is not the reason why you can bind any variable to a  parameter. All the compiler checks is that the parameter is not reassigned  the method. This is good for documentation purposes, arguably good style, and may even help optimize the byte code for speed (although this seems not to do very much in practice). But even if you do reassign a parameter within a method, the caller doesn't notice that, because java does all parameter passing by value. After the sequencethe fields of a may have changed, but a is still the same object it was before. In pass-by-reference languages this may not be true.
Java

How can I open a link in default browser with a button click, along the lines of?Use the  method.  It opens a URI in the user's default browser.note: you have to include necessary imports from A solution without the Desktop environment is . This solution is more general as on Linux, Desktop is not always available.The lenghty answer is posted at 
Java

I always thought that  operator in Java is used for verifying whether both its boolean operands are , and the  operator is used to do Bit-wise operations on two integer types.Recently I came to know that  operator can also be used verify whether both its boolean operands are , the only difference is that it checks the RHS operand even if the LHS operand is false.Is the  operator in Java internally overloaded? Or is there some other concept behind this? & <-- verifies both operands\n&& <-- stops evaluating if the first operand evaluates to false since the result will be false <-- this means evaluate  then evaluate  then do the &. the problem is that for x=0 this will throw an exception. <-- this means evaluate  and only if this is true then evaluate  so if you have x=0 then this is perfectly safe and won't throw any exception if (x != 0) evaluates to false the whole thing directly evaluates to false without evaluating the .EDIT: <-- this means evaluate  then evaluate  then do the . <-- this means evaluate  and only if this is  then evaluate  and do the .Besides not being a lazy evaluator by evaluating both operands, I think the main characteristics of bitwise operators compare each bytes of operands like in the following example:It depends on the type of the arguments...For integer arguments, the single ampersand (\"&\")is the \"bit-wise AND\" operator. The double ampersand (\"&&\") is not defined for anything but two boolean arguments.For boolean arguments, the single ampersand constitutes the (unconditional) \"logical AND\" operator while the double ampersand (\"&&\") is the \"conditional logical AND\" operator. That is to say that the single ampersand always evaluates both arguments whereas the double ampersand will only evaluate the second argument if the first argument is true.For all other argument types and combinations, a compile-time error should occur.&& is a short circuit operator whereas & is a AND operator.Try this.it's as specified in the :The \"trick\" is that  is an  as well as an . So why not, seeing this as an example for  is reasonable. and  are called short circuit operators. When they are used, for  - if the first operand evaluates to , then the rest of the operands are not evaluated. For  - if the first operand evaluates to , the rest of them don't get evaluated at all.so  in this example the variable x won't get incremented if a was .\u2018&&\u2019 : - is a Logical AND operator produce a boolean value of true or false based on the logical relationship of its arguments.For example: - Condition1 && Condition2If Condition1 is false, then (Condition1 && Condition2) will always be false, that is the reason why this logical operator is also known as Short Circuit Operator because it does not evaluate another condition. If Condition1 is false , then there is no need to evaluate Condtiton2.If Condition1 is true, then Condition2 is evaluated, if it is true then overall result will be true else it will be false.\u2018&\u2019 : - is a Bitwise AND Operator. It produces a one (1) in the output if both the input bits are one. Otherwise it produces zero (0).For example:-int a=12; // binary representation of 12 is 1100int b=6; // binary representation of 6 is 0110int c=(a & b); // binary representation of (12 & 6) is 0100The value of c is 4.for reference , refer this With booleans, there is no output difference between the two. You can swap && and & or || and | and it will never change the result of your expression.The difference lies behind the scene where the information is being processed. When you right an expression \"(a != 0) & ( b != 0)\"  for a= 0 and b = 1, The following happens:When you write an expression  when a= 0 and b = 1, the following happens:Less steps, less processing, better coding, especially when doing many boolean expression or complicated arguments.I think my answer can be more understandable:There are two difference between   and . and  can be logical , when the  or  left and right expression result all is true, the whole operation result can be true.when  and  as  logical , there is different,:when use  as logical , if the left expression result is false, the right expression will not execute.Take the example :If use :An other more example: can be use as Bitwise  operator,   can not.From the wiki page:& is a bitwise operator plus used for checking both conditions because sometimes we need to evaluate both condition.\nBut && logical operator go to 2nd condition when first condition give true.all answers are , and it seems that  more answer \nbut I just wonted to point out something about  operator called In expressions using operator &&, a condition\u2014we\u2019ll call this the \u2014may require another condition to be true for the evaluation of the dependent condition to be meaningful. In this case, the dependent condition should be placed after the && operator to prevent errors.Consider the expression . The dependent condition  must  the  operator to prevent the possibility of division by zero.another example   and another thing:  and  are called  because the second argument is executed or evaluated  the  argument does  to  the  of the References:  
Java

I have switched to JUnit4.4 from JUnit3.8. I run my tests using ant, all my tests run successfully but test utility classes fail with \"No runnable methods\" error. The pattern I am using is to include all classes with name *Test* under test folder.I understand that the runner can't find any method annotated with @Test attribute. But they don't contain such annotation because these classes are not tests.\nSurprisingly when running these tests in eclipse, it doesn't complain about these classes.In JUnit3.8 it wasn't a problem at all since these utility classes didn't extend TestCase so the runner didn't try to execute them. I know I can exclude these specific classes in the junit target in ant script. But I don't want to change the build file upon every new utility class I add. I can also rename the classes (but giving good names to classes was always my weakest talent :-) )Is there any elegant solution for this problem?Assuming you're in control of the pattern used to find test classes, I'd suggest changing it to match  rather than . That way  won't get matched, but  will.Annotate your util classes with @Ignore. This will cause JUnit not to try and run them as tests.My specific case has the following scenario.  Our tests all extend and JUnit was trying to run BaseTixContainerTest.  Poor BaseTixContainerTest was just trying to setup the container, setup the client, order some pizza and relax... man.  As mentioned previously, you can annotate the class with But that caused JUnit to report that test as skipped (as opposed to completely ignored).  That kind of irritated me. So I made BaseTixContainerTest abstract, and now JUnit truly ignores it.To prevent JUnit from instantiating your test base class just make it (@Ignore reports it as ignored which I reserve for  ignored tests.)Ant now comes with the  attribute which was designed to do exactly what you seem to be looking for. No need to change your base classes to abstract or add annotations to them.What about adding an empty test method to these classes? Be careful when using an IDE's code-completion to add the import for . It has to be  and not , for example. If you do the latter, you'll get the \"no runnable methods\" error.I was also facing a similar issue (\"no runnable methods..\") on running the simplest of simple piece of code (Using @Test, @Before etc.) and found the solution nowhere. I was using Junit4 and Eclipse SDK version 4.1.2. Resolved my problem by using the latest Eclipse SDK 4.2.2. I hope this helps people who are struggling with a somewhat similar issue.
Java

When trying to start my JUnit-Test out of Eclipse, I get a \"ClassNotFoundException\". When running \"mvn test\" from console - everything works fine. Also, there are no problems reported in Eclipse.My project structure is the following:edit: How can the class not be found? It's a simple HelloWorld-Application with no special libraries.Here's my JUnit's run-configuration:\nTestclass (but as I said; it doesn't work with a simple HelloWorld either...):Carlos approach helped!\nTry to check the classpath of the junit run configuration:works for me.I've come across that situation several times and, after a lot of attempts, I found the solution. Go one by one though each source-folder of your project and set the output folder that maven would use. For example, your web project's  should have  under the web project, test classes should have  also under the web project and so.Using this configuration will allow you to execute unit tests in eclipse.Just one more advice, if your web project's tests require some configuration files that are under the resources, be sure to include that folder as a source folder and to make the proper build-path configuration.Hope it helps.your build classpath is correct, which is why you can compile.  the classpath for your JUnit needs to be checked.  go to the Run menu and choose 'open run dialog.'  in there you should see a tree on the left with JUnit as an option.  open that node and find and select your test.  on the right pane you will see a tab for classpath.  take a look to ensure that your class that the test is trying to instantiate would be found.this seems to be an issue with maven and its behavior after a release changed the default Eclipse output folders.  i have seen solutions described where with the first three, there were reports of the issue recurring.  the last looks best to me, but if it doesnt work, please try the others. and  is some infoThe problem might be missing the class file in your build folder. One solution is clean the project and rebuild it. This was my solution to the problem. Of course, many things can cause it to occur. For me it was that Maven2 (not the plugin for Eclipse) was setting the eclipse profile up to use a different builder (aspectJ) but I did not have the plugin in eclipse./Cheers\nRamon BucklandThere are many convoluted suggestions here.I've encountered this problem multiple times with Maven projects after moving resources around by drag 'n' drop, or performing refactoring of class names.If this occurs, simply copy (not move) the problem Test Case () via terminal/file browser to another location,  in Eclipse and choose to delete on disk when given the option, move/copy the copied file to the original file location, then select your project in Eclipse and press F5 to refresh resources.This is quick and easy to do, and has fixed the problem permanently for me every time.Sachin's right:\nEven with correct class path, the problems tab will show that some dependency or the Resource/project has error that needs to be fixed in order for maven to automatically build and create classes when you create or make a change in your test class.\"Hi,Its very Old Jul (which year) but I had the same problem .Actual issue found that eclipse was not able to generate class file for the java file , classpath was proper.See the problem tab and check if your project is missing something/file. you can create a new proj and add files one by one and build them until it stops compiling and creating classes ( check the workspace/proj/bin/package/ folder for classes )its wierd but true , ecplise was failing in compliation because 4 of 20 java files were using a single image which was missing. and as result none of the java file was compiled .CLASSPATH is not a issue here.\"We had the exact exception (using SpringSource Tools, tomcat, on Win7) and the cause was that we had refactored a filename (renamed a file) from SubDomain.java to Subdomain.java (D vs d) and somehow it collided though SpringSource was showing the new name Subdomain.java. The solution was to delete the file (via SpringSource) and create it again under the name Subdomain.java and copy-pasting its former content. Simple as that.I had the exact same problem but I figured it out! Go to your project file and right click on it, then click  or hit F5. Then try and run it.  If it still doesn't work then just forget it, as I had the EXACT same problem and it just means you version of Eclipse is garbage.All I did was Properties -> Java Build Path -> Order and Export -> Enabled all unchecked boxes -> moved Junit all the way upHmm, looks a little bizarre, try running it with the following annotation at the top of the class:and let me know how you get on with it.    Check that you have build automatically enabled as well.  If you want to make sure your test classes are being compiled correctly clear out the Maven target folder (and any bin folder that Eclipse may be using).  Are you using m2eclipse as well, as I find it to be a little problematic.The solution to my problem which was similar: the libs were invalid. If you look in the .classpath file of the project, you'll see classpathentry tags with the key/value kind=\"lib\". Some of mine were incorrect.I didn't discover this until I turned off Validation settings. That is, there were so many errors in the JSP files, etc, that the classpath errors weren't evident (or possibly even showing up). As a result, nothing was being compiled into the destination output folders, but no helpful errors on why.click on  and check each  folder is still valid exist or recently removed. Correct any missing path or incorrect path and rebuild and run the test. It will fix the problem.  Maven 2 LifeCycle >> test I had tried all of the solutions on this page: refresh project, rebuild, all projects clean, restart Eclipse, re-import (even) the projects, rebuild maven and refresh.  Nothing worked.  What  work was copying the class to a  which runs fine -- bizarre but true.After putting up with this for some time, I just fixed it by:Something must have been screwed up with the cached run configuration.I was hit with this issue also and was able to come up with a sufficient solution for my case.  If your Eclipse project has a .classpath file in your project root (see it in Navigator view instead of Package Explorer view), be sure that your Maven classpathentry appears prior to your JRE Container classpathentry.If your project does not have a .classpath file, you can edit your project's Java Build Path to switch the Order and Export.  If your project has the .classpath file and you only change your ordering in the Java Build Path, you will see that the ordering is not impacted and the issue will continue to occur.And a project->clean never hurts things after you make the change.Deleting the project from eclipse (Not from hard disk) which in a way is cleaning the workspace and reimporting the project into eclipse again worked for me.I solve that Bulit path--->libraries--->add library--->Junit  check junit4Have you tried right clicking on your project root, selecting \"properties\", and making sure that the CLASSPATH is correct?  If I recall correctly, that's how you do it.Anything about the way Eclipse runs unit tests that requires you to add the junit JAR to the runtime CLASSPATH in a special way?I use IntelliJ, so I don't have these issues.  I'd check Eclipse myself, but I prefer not having it on my desktop.Please point to correct JDK from Windows > Preferences > Java > Installed JRE.Do not point to jre, point to a proper JDK. I pointed to JDK 1.6U29 and refreshed the project.Hereafter, the issue is gone and jUnit Tests are working fine.Thanks,\n\n-TapasI've run into a same error in Eclipse recently, i.e., the Eclipse IDE couldn't find the Unit test class no matter how I change the configurations. Learning from the previous posts here and in other web sites, I've double checked and triple checked the classpath and source info, and move up and down the source folder and libraries, in both the \"Run Configuration\" and the \"Java Build Path\" config windows, and I've also cleaned the Project and rebuilt it, but none of the tricks work for me. The specific Java project is an old ANT compiled project and have lots of jars included in Eclipse library.Then, I changed the unit test class to add a main() method and right click it to \"Run As\" a Java Application instead of JUnit test, and suddenly, Eclipse seems to wake up and identified the class correctly. Afterwards, I switched it back to a Unit test application, and it is still working.This seems to be a bug in Eclipse, I am guessing the large number of libraries (>260) may confused the JVM's ability to locate my JUnit class. Make sure your test launch configuration does NOT contain the following lines, OR try enabling automated Maven dependency management.I tried everything I read in this long post and, incredibly, what worked for me was, rather than clicking on the test class and selecting , clicking on the test  and running as . I have no idea why?JUnit test from inside eclipse gave me also NoClassDefFoundError.\nRunning 'mvn clean test' from command line gave me following error on several jars:\ninvalid LOC header (bad signature)\nDeleting these jars from local m2 repository and running 'mvn clean test' again\nsolved my problem.I had the same problem. All what I did was, i). Generated Eclipse artifacts ii). Refresh the project and rerun your junit test. Should work fine. Furthermore, DOUBLE-CHECK the eclipse \"Web Deployment Assembly\" dialog.  This can be found: Project Properties->Deployment Assembly.   Recently I had an eclipse plugin modify one of my web projects, and it added ~mysteriously~ added  the maven test directories  /src/test/java, /src/test/resources to the Deployment Assembly.   UGGGG!!!   Which is why my project worked fine when I built & deployed just straight maven to tomcat, no ClassNotFoundExceptions...  However, when I did the deploy through Eclipse, Whammo!! I start getting ClassNotFoundExceptions because the TestCode is getting deployed.  EricThat means your pom.xml has unresolved issues. Open the problems view solve accordingly. Then you will be able to run the test cases successfully without encountering the classnotfoundexception.Changing the order of classpath artifacts in the Java Build Path resolved it for me.This should fix it.JUnit 4.4 is not supported by the JMockit/JUnit integration. Only\nversions 4.5 or newer are supported that. while running web applications Most of us will get this Exception. When you got this error you have place .class files in proper folder. In web applications all .class files should sit in WEB-INF\\Classes folder.\nif you are running web app in Eclipse please follow the stepsStep 1: Right click on Project folder and Select Properties\nStep 2: Click on \"Java Build Path\" you will see different tabs like \"source\" , \"projects\", \"libraries\" etc\nStep 3: select Source folder. under this you will see your project details\nStep 4: in the \"Source\" folder you will see Default Output Folder option. here you have to give the classes folder under WEB-INF.\njust give the path like projectname/WebContent/WEB-INF/classes\nthe structure depends on your application\nplease do remember here you no need to create \"classes\" folder. Eclipse will create it for you.\nStep 5: click on \"OK\" and do the project clean and Build. that's it your app will run now.
Java

Character.isLetter(c) returns true if the character is a letter. But is there a way to quickly find if a String only contains the base characters of ASCII?Using , you could just write:From Guava 19.0 on, you should use  instead.You can do it with  .Here is another way not depending on a library but using a regex.You can use this single line:Whole example program:Iterate through the string and make sure all the characters have a value less than 128.Java Strings are conceptually encoded as UTF-16.  In UTF-16, the ASCII character set is encoded as the values 0 - 127 and the encoding for any non ASCII character (which may consist of more than one Java char) is guaranteed not to include the numbers 0 - 127Or you copy the code from the  class.commons-lang3 from Apache contains valuable utility/convenience methods for all kinds of 'problems',  including this one. Iterate through the string, and use charAt() to get the char.  Then treat it as an int, and see if it has a unicode value (a superset of ASCII) which you like.Break at the first you don't like.try this:It was possible. Pretty problem.
Java

I have milliseconds in certain log file generated in server, I also know the locale from where the log file was generated, my problem is to convert milliseconds to date in specified format.\nThe processing of that log is happening on server located in different time zone. While converting to \"SimpleDateFormat\" program is taking date of the machine as such formatted date do not represent correct time of the server. Is there any way to handle this elegantly ?Output:You may use  class and then use  to format the .If the millis value is number of millis since Jan 1, 1970 GMT, as is standard for the JVM, then that is independent of time zone. If you want to format it with a specific time zone, you can simply convert it to a GregorianCalendar object and set the timezone. After that there are numerous ways to format it.The easiest way to do this is to use the  and specify both the timestamp in milliseconds and the DateTimeZone you want.I strongly recommend avoiding the built-in Java Date and Calendar classes; they're terrible.The other answers use outmoded or incorrect classes.Avoid the old date-time classes such as java.util.Date/.Calendar. They have proven to be poorly designed, confusing, and troublesome. The  framework comes built into Java 8 and later. Much of the functionality is  and further . Made by the some of the same folks as had made .An  is a moment on the timeline in  with a resolution of . Its  is first moment of 1970 in UTC.Assuming your input data is a count of milliseconds from 1970-01-01T00:00:00Z (not clear in the Question), then we can easily instantiate an .Apply a time zone using a , to get a .You can apply the  of the JVM. Beware that the default can change at any moment . Any code in any thread of any app within the JVM can change the current default. If important, ask the user for their desired/expected time zone.My SolutionThe SimpleDateFormat class has a method called SetTimeZone(TimeZone) that is inherited from the DateFormat class. Easiest way:I do it like this:You can also use  with following parameters:Below is  my solution to get date from miliseconds to date format. You have to use  to get this code run.
Java

When using the Spring 3.0 capability to annotate a scheduled task, I would like to set the  as parameter from my configuration file, instead of hard-wiring it into my task class, like currently...Unfortunately it seems that with the means of the Spring Expression Language (SpEL)  returns a String object which in turn is not able to be auto-boxed to a long value as required by the  parameter.I guess the  annotation is out of question. So maybe a solution for you would be to use  XML configuration. Let's consider this example (copied from ):... or if the cast from String to Long didn't work, something like this would:Again, I haven't tried any of these setups, but I hope it might help you a bit.Spring v3.2.2 has added String parameters to the original 3 long parameters to handle this. ,  and  are now available too.You can use the  annotation, but together with the  parameter only:Your 5 seconds interval could be expressed as . However as I understand you cannot provide less than 1 second precision.I guess you can convert the value yourself by defining a bean. , but I guess the approach similar to the following might be useful for you:where:
Java

I have seen classes which implement both  and .  What does this mean?  Why would I use one over the other?The text below comes from A comparable object is capable of comparing itself with another object. The class itself must implements the  interface in order to be able to compare its instances.A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class\u2019s instances. This comparator class must implement the  interface.Implementing  means \"I can compare myself with another object.\" This is typically useful when there's a single natural default comparison.Implementing  means \"I can compare two other objects.\" This is typically useful when there are multiple ways of comparing two instances of a type - e.g. you could compare people by age, name etc.Comparable lets a class implement its own comparison:By comparison, Comparator is an external comparison:In both implementations, you can still .\nWith generics, you can declare so, and have it checked at compile-time. This improves safety, but it is also a challenge to determine the appropriate value.As a guideline, I generally use the most general class or interface to which that object could be compared, in all use cases I envision... Not very precise a definition though ! :-( is for providing a default ordering on data objects, for example if the data objects have a natural order.A  represents the ordering itself for a specific use.     is usually preferred. But sometimes a class already implements , but you want to sort on a different property. Then you're forced to use a .Some classes actually provide  for common cases; for instance, s are by default case-sensitive when sorted, but there is also a static  called . is for objects with a natural ordering. The object itself knows how it is to be ordered.\n is for objects without a natural ordering or when you wish to use a different ordering.here are few differences between Comparator and Comparable I found on web :site:How to use Comparator and Comparable in Java? With exampleRead more:  is used to compare itself by using with another object. is used to compare two datatypes are objects.If you see then logical difference between these two is  in Java compare two objects provided to him, while  interface compares \"this\" reference with the object specified. in Java is used to implement natural ordering of object. In Java API String, Date and wrapper classes implement  interface.If any class implement  interface in Java then collection of that object either  or  can be sorted automatically by using  or  method and object will be sorted based on there natural order defined by  method.Objects which implement  in Java can be used as keys in a sorted map or elements in a sorted set for example , without specifying any .My annotation lib for implementing Comparable and Comparator:Click the link to see more examples. 
Java

Where can I get an inexpensive Java code signing certificate? Everywhere I look they want USD200 to USD300 per year! Unfortunately I cannot use a self-signed one as I'm trying to get rid of the scary warnings so that users will be more likely to accept my application. And as far as I know (per Stack Overflow question ), it has to be a code signing certificate, it cannot be an  certificate.What about ? They offer code signing certificates for 49.90$ for 2 years (with wild card capabilities). I haven't tried using it, so no guarantees, but it looks good. \nStartSSL is no longer a valid option, even given the previous limitations. ,  and stopped trusting them. So I would encourage everyone their use, given this development. Giving the current state of affairs, this should  be the  anymore. Sorry!How about $80 a year? Tucows  resell for Comodo at their . Again, apparently, they give further discount for 3 years (~$199).I can't confirm any of this without creating an account there (which is, frankly, above my pay grade) but if it is that much and it does work with Java, $66 a year for 3 years doesn't seem too steep.Hopefully GoDaddy will add this to their bag of tricks one day.The prices are as follows:And , they can be used for signing Java apps. Happy days.You can tell if a CA's certs will work for Java code-signing by examining the Java cacerts file, which lists all the CAs known to Java. If their cert is in this file, then Java will not complain about the signed code. If it isn't, then it will warn the users. For example:Note that I had to enter the default keystore password, . This command should work on Windows as well, although you'll have to change the path to the cacerts file and you won't have grep. Use more instead and page through until you find or don't find what you're looking for.As of today, Comodo is in the cacerts file, and startssl aren't. So a startssl cert wouldn't be much good for Java code.You can also get heavily discounted Comodo certificates from:Another good option (don't know how long this will last) is  They give you a real GlobalSign certificate for $99 (usually $229).Despite the lack of branding, the site is run by GlobalSign themselves, and was registered just over two months ago. I have a feeling that they're doing price-testing to see how many more sales they get.Cheapest I can find is $149/year (if you buy 3 years at once) from . Not great, I know! has code-signing certs for $179.95/year and you only need to buy 1 year.  They don't talk about Java.  I don't know if they are different than what you use to sign Microsoft based stuff.
Java

I am looking for a way to view all compile errors in IntelliJ, similar to how they are displayed in Eclipse.  I tried searching here and Google but have not really found a solution.  I really like IntelliJ, I recently converted to it from Eclipse, and I hope this is just something I am missing and not a fundamental deficiency.I think this comes closest to what you wish:(From ):The above can be combined with a recently introduced option in Compiler settings to get a view very similar to that of Eclipse.Things to do:Here is a comparison of what the same project (with a compilation error) looks like in Intellij IDEA 13.xx and Eclipse Kepler: Relevant Links:\nThe maven project shown above : \nFAQ For 'Eclipse Mode' / 'Automatically Compile' a project : 
Java

I'm working on a simple JSP/Servlet/Tomcat webapp for my class. The professor asked us to use a folder structure that is slightly different than the default dynamic web project structure. Rather than using the webcontent folder he wants all of our source code under src/main/java and src/main/webapp.When I run the app my welcome file displays fine, but when I try to access my servlets I get:java.lang.ClassNotFoundException. I'm pretty sure it's a build path error. I have final/src on the build path but I am receiving the warning  I have this in my deployment assembly: When I exclude main/ the warning goes away, but it doesn't fix the problem. I would appreciate any advice. Thanks. I had the same problem even when I created a fresh project. \nI was creating the Java project within Eclipse, then mavenize it, then going into java build path properties removing  and adding  and . When I run Maven update it used to give nested path error. \nThen I finally realized -because I had not seen that entry before- there is a  line in pom file written when I mavenize it. It was resolved after removing it.I wanted to throw in a non-mavenish answer to this thread.Due to version control and strict directory structure reasons, I was unable to follow Acheron's answer (the best answer) of doing something similar to removing  and adding  and  to the build path.I had actually been off-and-on battling this nested build path issue for a couple weeks.  The answer to the problem is hinted in the error message:In your build path, you need to edit your  by clicking on  and then :There you can add  as an .  Then it should allow you to add  to the build path as a separate source folder.Try this:From the libraries tab:Remove your web app libraries:Add them back in:Highlighting \"Web App Libraries\":You have to separate your sources and your target directory where the build output goes. It's also important to note that no class files ever can end up in the source directory. This is not against your professor's advice - actually he's promoting the maven standard source structure going for ./src/main/java and ./src/main/webapp. The second one should hold eg. the mandatory WEB-INF/web.xml file but you will never put actual classes there.What you need to change is your target directory. I suggest going with the same standards and choosing the name \"./target\" for this. All the built files will go in here and packaging that up will result a correct deployable artifact. Should you migrate to using maven later, it'll also help doing this in a scripted, repeatable way.Hope that clears up your issue.For Eclipse compiler to work properly you need to remove final/src from the source path and add final/src/main/java instead. This may also solve your problem as now the build directory won't be inside the Java source folder.I had the same issue and correct answer above did not work for me. What I did to resolve it was to go to  and under the source tab I removed all the sources (which only had one source) and reconfigured them from there. I ended up removing the project from eclipse and import the maven project again in order to clear up the error.Make two folders:  to store the source java code, and\n.You cannot put the source and the webroot together. I think you may misunderstand your teacher.
Java

I have installed java in my  machine using the command . But I am unable to compile a class using javac.Do I need to install any other package? I have tried to locate the  executable but i am unable to locate it. is linked as follows:\n -> \n -> I have seen the following output by :You installed the Java Runtime Environment (JRE) only, which . For , you have to install the . You can install  or , which both include .By the way: you can find out which package provides  with a , e.g.Another note: using  and  is only one possibility to install the JDK. Many people prefer Sun/Oracle's \"original\" SDK. See  and links for alternatives.Worked for me : use the following command:sudo yum install java-1.6.0-openjdk-develI don't know exactly what  will actually install. But to check for javac existence do:preferably as root. If it's not there you've probably only installed the Java runtime (JRE) and not the Java Development Kit (JDK). You're best off getting this from the : as the Linux repos may be slightly behind with latest versions and also they seem to only supply the open-jdk as opposed to the Oracle/Sun one, which I would prefer given the choice.Is the javac executable in a directory that is part of your PATH?I don't know the CentOS equivalent of the Windows path but if you cd to the java sdk directory and run ./javac does anything happen?follow these steps:open terminal go to your root dictionary by typing you will see Library folder Now follow this path Once you get into  you can see the  fileNow you need to get the path of this folder for that just write this command get the path for your .
Java

I've recently overheard people saying that s (DTO) are an . Can someone please explain why? What are the alternatives?. Once as domain objects, and once as data transfer objects. This , so the architecture needs to get a huge benefit from this separation to be worth it.DTOs are not an anti-pattern. When you're sending some data across the wire (say, to an web page in an ajax call), you want to be sure that you conserve bandwidth by only sending data that the destination will use. Also, often it is convenient for the presentation layer to have the data in a slightly different format than a native business object.I know this is a java-oriented question, but in .Net languages anonymous types, serialization, and linq allow DTOs to be constructed on-the-fly, which reduces the setup and overhead of using them. says:I don't think DTO's are an anti-pattern per se, but there are antipatterns associated with the use of DTO's.  Bill Dudney refers to DTO explosion as an example:There are also a number of abuses of DTO's mentioned here:They originated because of three tier systems (typically using EJB as technology) as a means to pass data between tiers.  Most modern day Java systems based on frameworks such as Spring take a alternative simplified view using POJOs as domain objects (often annotated with JPA etc...) in a single tier...  The use of DTO's here is unnecessary.OO purists would say that DTO is anti-pattern because objects become data table representations instead of real domain objects. Some consider DTOs an anti-pattern due to their possible abuses, they're often used when they shouldn't be/don't need to be. vaguely describes some abuses.If you're building a distributed system, then DTO's are certainly not an anti pattern. Not everyone will develop in that sense, but if you have a (for example) Open Social app all running off JavaScript. It will post a load of data to your API. This is then deserialized into some form of object, typically a DTO/Request object. This can then be validated to ensure the data entered is correct before being converted into a model object. In my opinion, it's seen as an anti-pattern because it's mis-used. If you're not build a distributed system, chances are you don't need them. The intention of a  is to store data from different sources and then transfer it into a database (or ) at once. However, , since the DTO not only stores data, but also transfers it from or to the database/facade. The need to separate data objects from business objects is not an antipattern, since it is probably required to  anyway. Instead of DTOs you should use the Aggregate and Repository Patterns, which separates the collection of objects () and the data transfer (). To transfer a group of objects you can use the  pattern, that holds a set of Repositories and a transaction context; in order to transfer each object in the aggregate separately within the transaction. DTO becomes a necessity and not and an ANTI-PATTERN, is when you have all your domain objects load associated objects EAGERly.\nIf you don't make DTOs, you will have unecessary transfered objects from your business layer to your client/web layer.\nTo limit overhead for this case, transfer rather DTOs.I think the people mean it could be an anti-pattern if you implement all remote objects as DTO's. A DTO is merely just a set of attributes and if you have big objects you would always transfer all the attributes even if you do not need or use them. In the latter case prefer using a Proxy pattern.
Java

The following function produces today's date; how can I make it produce only yesterday's date?This is the output:I only need yesterday's date like below. Is it possible to do this in my function?You are subtracting the wrong number:Use  instead:Then, modify your method to the following:You can do following:Note: if you want further backward date multiply number of day with 24*60*60*1000 for example:Similarly, you can get future date by adding the value to System.currentTimeMillis(), for example:Use Calender ApiTry this one:Try this;changed from your code :}but you do better using .There is no direct function to get yesterday's date.To get yesterday's date, you need to use  by subtracting .
Java

I am very familiar with C# but starting to work more in Java. I expected to learn that enums in Java were basically equivalent to those in C# but apparently this is not the case. Initially I was excited to learn that Java enums could contain multiple pieces of data which seems very advantageous (). However, since then I have found a lot of features missing that are trivial in C#, such as the ability to easily assign an enum element a certain value, and consequently the ability to convert an integer to an enum without a decent amount of effort (i.e. ).So my question is this: is there any benefit to Java enums over a class with a bunch of public static final fields? Or does it just provide more compact syntax?EDIT: Let me be more clear. What is the benefit of Java enums over a class with a bunch of public static final fields ? For example, in the planets example at the first link, what is the advantage of an enum over a class with these public constants:As far as I can tell, casablanca's answer is the only one that satisfies this.Technically one could indeed view enums as a class with a bunch of typed constants, and this is in fact how enum constants are implemented internally. Using an  however gives you useful methods () that you would otherwise have to implement yourself, such as .Nobody mentioned the ability to use them in  statements; I'll throw that in as well.This allows arbitrarily complex enums to be used in a clean way without using , potentially confusing  sequences, or non-string/int switching values. The canonical example is a state machine.There is less confusion. Take  for instance. It has a constructor that takes the name of the  you want, its size and its style (). To this day I cannot remember if style or size goes first. If  had used an  for all of its different styles (, , , ), its constructor would look like , preventing any confusion. Unfortunately, s weren't around when the  class was created, and since Java has to maintain reverse compatibility, we will always be plagued by this ambiguity.Of course, this is just an argument for using an  instead of  constants. Enums are also perfect for  and implementing default behavior while allowing for later customization (I.E. the ). An example of the latter is 's  and : if a developer wanted to create his own non-standard , he could.The primary advantage is type safety. With a set of constants, any value of the same intrinsic type could be used, introducing errors.  With an enum only the applicable values can be used.For examplevsThere are many good answers here, but none mentiones that there are  of the Collection API classes/interfaces :These enum specific classes only accept  instances (the  only accept s only as keys), and whenever possible, they revert to compact representation and bit manipulation in their implementation.If our  type has no more that 64 elements (most of real-life  examples will qualify for this), the implementations store the elements in a single  value, each  instance in question will be associated with a bit of this 64-bit long . Adding an element to an  is simply just setting the proper bit to 1, removing it is just setting that bit to 0. Testing if an element is in the  is just one bitmask test! Now you gotta love s for this!The first benefit of enums, as you have already noticed, is syntax simplicity. But the main point of enums is to provide a well-known set of constants which, by default, form a range and help to perform more comprehensive code analysis through type & value safety checks.Those attributes of enums help both a programmer and a compiler. For example, let's say you see a function that accepts an integer. What that integer could mean? What kind of values can you pass in? You don't really know right away. But if you see a function that accepts enum, you know very well all possible values you can pass in.For the compiler, enums help to determine a range of values and unless you assign special values to enum members, they are well ranges from 0 and up. This helps to automatically track down errors in the code through type safety checks and more. For example, compiler may warn you that you don't handle all possible enum values in your switch statement (i.e. when you don't have  case and handle only one out of N enum values). It also warns you when you convert an arbitrary integer into enum because enum's range of values is less than integer's and that in turn may trigger errors in the function that doesn't really accept an integer. Also, generating a jump table for the switch becomes easier when values are from 0 and up.This is not only true for Java, but for other languages with a strict type-checking as well. C, C++, D, C# are good examples.example:Limitation of java Constants1) : First of all it\u2019s not type-safe; you can assign any valid int value to int e.g. 99 though there is no coin to represent that value.2) : printing value of any of these constant will print its numeric value instead of meaningful name of coin e.g. when you print NICKLE it will print \"5\" instead of \"NICKLE\"3) : to access the currencyDenom constant we need to prefix class name e.g. CurrencyDenom.PENNY instead of just using PENNY though this can also be achieved by using static import in JDK 1.5Advantage of enum1) Enums in Java are type-safe and has there own name-space. It means your enum will have a type for example \"Currency\" in below example and you can not assign any value other than specified in Enum Constants.2) Enum in Java are reference type like class or interface and you can define constructor, methods and variables inside java Enum which makes it more powerful than Enum in C and C++ as shown in next example of Java Enum type.3) You can specify values of enum constants at the creation time as shown in below example:\npublic enum Currency {PENNY(1), NICKLE(5), DIME(10), QUARTER(25)};\nBut for this to work you need to define a member variable and a constructor because PENNY (1) is actually calling a constructor which accepts int value , see below example.}; refrence:enum Benefits:\nAdd a method converting int to enum which does that. Just add static HashMap containing the mapping.If you really want to convert ord=VAL_200.ordinal() back to val_200 just use: EnumX.values()[ord]An enum is implictly final, with a private constructors, all its values are of the same type or a sub-type, you can obtain all its values using , gets its  or  value or you can look up an enum by number or name.You can also define subclasses (even though notionally final, something you can't do any other way)You get compile time checking of valid values when you use an enum.  Look at Another important difference is that java compiler treats  fields of  and  as literals. It means these constants become inline. It's similar to   preprocessor. see this SO . This is not the case with enums.The biggest advantage is enum Singletons are easy to write and thread-safe :andboth are similar and it handled Serialization by themselves by implementing  I think an  can't be , because under the hood compiler generates subclasses for each  entry.More information From 
Java

I am struggling with this error:I don't understand why this error occurs.I am trying to appear notification at specific time and after searching for a time i found this . I tried everything but my code gives error.Please help me to solve this problem.Here is my MainActivity code:and here is my ReminderService code:and here is my manifest.xml:I don't know where I am going wrong. Am I missing some code?You need to add an empty constructor to your class Explanation from the :The  is used to name the worker thread.: this is only applicable to intent service.Declare a  for If you have your Service declared as an , you also need to make the class Without that you\u00b4ll get the error even if your constructor is correctYou need to add the  to your  class. This is only implicitly added if you don't write a constructor of your own (which you have). See here: 
Java

What is mutex and semaphore in Java ? What is the main difference ?Semaphore can be counted, while mutex can only count to 1.Suppose you have a thread running which accepts client connections. This thread can handle 10 clients simultaneously. Then each new client sets the semaphore until it reaches 10. When the Semaphore has 10 flags, then your thread won't accept new connectionsMutex are usually used for guarding stuff. Suppose your 10 clients can access multiple parts of the system. Then you can protect a part of the system with a mutex so when 1 client is connected to that sub-system, no one else should have access. You can use a Semaphore for this purpose too. A mutex is a .Unfortunately everyone has missed the most important difference between the semaphore and the mutex; the concept of \"\". Semaphores have no notion of ownership, this means that any thread can release a semaphore (this can lead to many problems in itself but can help with \"death detection\"). Whereas a mutex does have the concept of ownership (i.e. you can only release a mutex you have acquired).\nOwnership is incredibly important for safe programming of concurrent systems. I would always recommend using  mutex in preference to a semaphore (but there are performance implications). Mutexes also may support priority inheritance (which can help with the priority inversion problem) and recursion (eliminating one type of deadlock). It should also be pointed out that there are \"binary\" semaphores and \"counting/general\" semaphores. Java's semaphore is a counting semaphore and thus allows it to be initialized with a value greater than one (whereas, as pointed out, a mutex can only a conceptual count of one). The usefulness of this has been pointed out in other posts. So to summarize, unless you have multiple resources to manage, I would always recommend the mutex over the semaphore. Mutex is basically mutual exclusion. Only one thread can acquire the resource at once. When one thread acquires the resource, no other thread is allowed to acquire the resource until the thread owning the resource releases. All threads waiting for acquiring resource would be blocked.Semaphore is used to control the number of threads executing. There will be fixed set of resources. The resource count will gets decremented every time when a thread owns the same. When the semaphore count reaches 0 then no other threads are allowed to acquire the resource. The threads get blocked till other threads owning resource releases.In short, the main difference is  A mutex is used for serial access to a resource while a semaphore limits access to a resource up to a set number. You can think of a mutex as a semaphore with an access count of 1. Whatever you set your semaphore count to, that may threads can access the resource before the resource is blocked.Feabhas's answer is quite important - the mutex checks the thread attempting to release the mutex actually owns it. I've had this as an interview question so its worth trying to remember it.A semaphore is a counting synchronization mechanism, a mutex isn't. A mutex is often known as a binary semaphore. Whilst a semaphore can be created with any non-zero count a mutex is conceptually a semeaphore with an upper count of 1.This question has relevant answers and link to official Java guidance: You compare the incomparable, technically there is no difference between a Semaphore and mutex  it doesn't make sense.\nmutex it's just a significant name like any name in your application logic, it's mean that you\ninitialize a semaphore at \"1\", it's used generally to protect a resource or a protected variable to ensure the mutual exclusion.Mutex is binary semaphore. It must be initialized with 1, so that the First Come First Serve principle is met. This brings us to the other special property of each mutex: . Ergo we have obtained mutual exclusion over some resource. Now you could see that a mutex is a special case of general semaphore.
Java

I am using the String split method and I want to have the last element.\nThe size of the Array can change.I want to split the above Strings and get the last item:I don't know the sizes of the arrays at rumtime :(Save the array in a local variable and use the array's  field to find its length. Subtract one to account for it being 0-based:Or you could use  method on Stringusing a simple, yet generic, helper method like this:you can rewrite:as:Now  has the value directoryWith :, You mean you don't know the sizes of the arrays at compile-time? At run-time they could be found by the value of  and  .Since he was asking to do it all in the same line using split so i suggest this:I always avoid defining new variables as far as I can, and I find it a very good practiceYou can use the  class in Apache Commons: 
Java

I have two tables: tracks and waypoints, a track can have many waypoints, but a waypoint is assigned to only 1 track. In the way points table I have a column called \"trackidfk\" which inserts the track_ID once a track is made, however I have not setup Foreign Key constraints on this column.When I delete a track I want to delete the assigned waypoints, is this possible?. I read about using Triggers but I don't think they are supported in Android.To create the waypoints table:Foreign key constraints with on delete cascade are supported, but you need to enable them.\nI just added the following to my , which seems to do the trick.I declared my referencing column as follows.Since Android 4.1 (API 16)  supports:As the post from e.shishkin says from API 16 up you should enable foreign key constraints in the  method using the Whatever @phil mentioned is good. But you can use another default method available in \n     Database itself to set the foreignkey. That is setForeignKeyConstraintsEnabled(true). For Docs refer  I don't think SQLite supports this out of the box. What I'm doing in my apps is:That way I'm sure that either all the data is deleted or none.Triggers are supported by android and that type of cascade delete is not supported by sqlite.  An example of using triggers on android can be found .  Though using transactions as Thorsten stated is probably just as easy as a trigger.SQLite version in android 1.6 is 3.5.9 so it doesn't support foreign keys...\n\"This document describes the support for SQL foreign key constraints introduced in SQLite version 3.6.19.\"In Froyo it's SQLite version 3.6.22, so ...EDIT: \nto see sqlite version : adb shell sqlite3 -versionNever too old of a question to answer with a more complete answer.Foreign keys with \"on delete cascade\" are supported in SQLite in Android 2.2 and up. But be careful when using them: sometimes an error is reported when firing up one foreign key on one column, but the real problem lies in either another column foreign key constraint in the child table, or some other table thet references this table.Looks like SQLite checks all constraints when firing up one of them. It is actually mentioned in the documentation. DDL versus DML constraint checks.
Java

I have a string arraylist  which contains names of people. I want to sort the arraylist in alphabetical order.I tried to sort the list in above way. But it is displaying the sorted array as:but I don't want to make it case sensitive. I want the result as:Custom  should helpOr if you are using Java 8:The simplest thing to do is:try this codeYou need to use custom comparator which will use , not compareTo.Based on the above mentioned answers, I managed to compare my custom Class Objects like this:Starting from  you can use :It gets a stream from that , then it sorts it (ignoring the case). After that, the stream is converted to an array which is converted to an .If you print the result using:you get the following output:
Java

Anyone knows some good SQL builder library for Java like  (not maintained anymore it seems). Preferably, a project in active development.Preferably with syntax like , something that will allow to make a query like  and  are two popular choices.I can recommend . It provides a lot of great features, also a intuitive DSL for SQL and a extremly customable reverse-engineering approach. is my best choice:here is create example(groovy):Hibernate Criteria API (not plain SQL though, but very powerful and in active development):You can use the following library:The library is built on the top of the Hibernate \"create sql query\" so it supports all databases supported by Hibernate (the Hibernate session and JPA providers are supported). The builder patter is available and so on (object mappers, result mappers).You can find the examples on github page, the library is available at Maven central of course.
Java

I am working at a commercial android application.\nI am also using some libraries licensed under different license types some of them stating the following:(One of them is licensed under  for example).There is more than one library. When I do the build with  or with  I obtain the following build error:The answers that I found until now on the internet and stackoverflow suggest to remove the license.txt(notice.txt or other files that could interfere like this) from packaging by adding to  file the following:See for example: According to the license of those libraries( for instance), the license and notice files should be .  How can I add multiple files related to licensing(such as ,  etc) from gradle into my project in order to be compliant with the licenses( licences texts will be concatenated)?There is a solution if you have only one license using the name  (read: all  copies are identical):Add following into respective build.gradle file I faced the same issue with my application.\nYou need to make sure you have not added any libraries twice.\nIf you have followed the firebase documentation \nThen you should not add firebase library inside android studio\ni.e.\nfile->project structure->cloud->firebaseYou have to do only one of the both, to use firebase in your android application.At the end clean and rerun your app.You can add multiple licence in gradle Surely it will work
Java

Is there any way to pass class as a parameter in Java and fire some methods from that class?I am using Google Web Toolkit and it does not support reflection. To call the method, you call it this way:UseA  is also a Java object, so you can refer to it by using its type.Read more about it from .I am not sure what you are trying to accomplish, but you may want to consider that passing a class may not be what you really need to be doing.  In many cases, dealing with Class like this is easily encapsulated within a factory pattern of some type and the use of that is done through an interface.  here's one of dozens of articles on that pattern: using a class within a factory can be accomplished in a variety of ways, most notably by having a config file that contains the name of the class that implements the required interface.  Then the factory can find that class from within the class path and construct it as an object of the specified interface.This kind of thing is not easy. Here is a method that calls a static method: \nWait, I just saw the gwt tag on the question. You can't use reflection in GWTAs you said GWT does not support reflection. You should use deferred binding instead of reflection, or third party library such as  for reflection suppport at gwt layer. Have a look at the reflection tutorial and reflection API of Java:and Se these:\nhere is the explaniation for the template methods.
Java

Since weak references can be claimed by the garbage collector at any time, is there any practical reason for using them?If you want to keep a reference to something as long as it is used elsewhere e.g. a Listener, you can use a weak reference.WeakHashMap can be used as a short lived cache of keys to derived data.  It can also be used to keep information about objects used else where and you don't know when those objects are discarded.BTW Soft References are like Weak references, but they will not always be cleaned up immediately.  The GC will always discard weak references when it can and retain Soft References when it can.There is another kind of reference called a Phantom Reference.  This is used in the GC clean up process and refers to an object which isn't accessible to \"normal\" code because its in the process of being cleaned up.Of course there are practical reasons to use it. It would be awfully strange if the framework designers went to the enormous expense of building a weak reference system that was , don't you think?I think the question you intended to ask was:There are many. A common one is to achieve a performance goal. When performance tuning an application one often must make a tradeoff between more memory usage and more time usage. Suppose for example there is a complex calculation that you must perform many times, but the computation is \"pure\" -- the answer depends only on the arguments, not upon exogenous state. You can build a cache -- a map from the arguments to the result -- but that then uses memory. You might never ask the question again, and that memory is would then be wasted.Weak references possibly solve this problem; the cache can get quite large, and therefore time is saved if the same question is asked many times. But if the cache gets large enough that the garbage collector needs to reclaim space, it can do so safely. The downside is of course that the cleanup policy of the garbage collector is tuned to meet the goals of the whole system, not your specific cache problem. If the GC policy and your desired cache policy are sufficiently aligned then weak references are a highly pragmatic solution to this problem.If a  is the  reference to an object, and you want the object to hang around, you should probably be using a  instead.WeakReferences are best used in cases where there will be other references to the object, but you can't (or don't want to have to) detect when those other references are no longer used. Then, the  reference will prevent the object from being garbage collected, and the WeakReference will just be another way of getting to the same object.Two common use cases are:We use it for that reason - in our example, we have a variety of listeners that must register with a service.  The service keeps weak references to the listeners, while the instantiated classes keep strong references.  If the classes at any time get GC'ed, the weak reference is all that remains of the listeners, which will then be GC'ed as well.  It makes keeping track of the intermediary classes much easier.The most common usage of weak references is for values in \"lookup\" Maps.With normal (hard) value references, if the value in the map no longer has references to it elsewhere, you often don't need the lookup any more. With weakly referenced map values, once there are no other references to it, the object becomes a candidate for garbage collectionThe fact that the map itself has a (the only) reference to the object does not stop it from being garbage collected because the reference is a  reference To prevent memory leaks, see this  for details. I use it generally for some type of cache. Recently accessed items are available immediately and in the case of cache miss you reload the item (DB, FS, whatever).I use  to encode links in a graph.  If a node is deleted, the links automatically disappear.
Java

I'm running Windows 8.1 x64 with Java 7 update 45 x64 (no 32 bit Java installed) on a Surface Pro 2 tablet.The code below takes 1688ms when the type of i is a long and 109ms when i is an int. Why is long (a 64 bit type) an order of magnitude slower than int on a 64 bit platform with a 64 bit JVM?My only speculation is that the CPU takes longer to add a 64 bit integer than a 32 bit one, but that seems unlikely. I suspect Haswell doesn't use ripple-carry adders.I'm running this in Eclipse Kepler SR1, btw.Edit: Here are the results from equivalent C++ code compiled by VS 2013 (below), same system.   Those results were in debug 32 bit mode.In 64 bit release mode:  long long:  906ms int: 1047msThis suggests that the result I observed is JVM optimization weirdness rather than CPU limitations.Edit: Just tried this again in Java 8 RTM, no significant change.My JVM does this pretty straightforward thing to the inner loop when you use s:It cheats, hard, when you use s; first there's some screwiness that I don't claim to understand but looks like setup for an unrolled loop:then the unrolled loop itself:then the teardown code for the unrolled loop, itself a test and a straight loop:So it goes 16 times faster for ints because the JIT unrolled the  loop 16 times, but didn't unroll the  loop at all.For completeness, here is the code I actually tried:The assembly dumps were generated using the options .  Note that you need to mess around with your JVM installation to have this work for you as well; you need to put some random shared library in exactly the right place or it will fail.The JVM stack is defined in terms of , whose size is an implementation detail but must be at least 32 bits wide. The JVM implementer  use 64-bit words, but the bytecode can't rely on this, and so operations with  or  values have to be handled with extra care. In particular,  are defined on exactly the type .In the case of your code, disassembly is instructive. Here's the bytecode for the  version as compiled by the Oracle JDK 7:Note that the JVM will load the value of your static  (0), subtract one (3-4), duplicate the value on the stack (5), and push it back into the variable (6). It then does a compare-with-zero branch and returns.The version with the  is a bit more complicated:First, when the JVM duplicates the new value on the stack (5), it has to duplicate two stack words. In your case, it's quite possible that this is no more expensive than duplicating one, since the JVM is free to use a 64-bit word if convenient. However, you'll notice that the branch logic is longer here. The JVM doesn't have an instruction to compare a  with zero, so it has to push a constant  onto the stack (9), do a general  comparison (10), and then branch on the value of  calculation.Here are two plausible scenarios:I recommend you  to eliminate the effect of having the JIT kick in, and also trying this with a final condition that isn't zero, to force the JVM to do the same comparison on the  that it does with the .Basic unit of data in a Java Virtual Machine is word. Choosing the right word size is left upon the implementation of the JVM. A JVM implementation should choose a minimum word size of 32 bits. It can choose a higher word size to gain efficiency. Neither there is any restriction that a 64 bit JVM should choose 64 bit word only.The underlying architecture doesn't rules that the word size should also be the same. JVM reads/writes data word by word. This is the reason why it might be taking longer for a  than an .    you can find more on the same topic.I have just written a benchmark using .The  are quite consistent with the original code: a ~12x speedup for using  over . It certainly seems that the loop unrolling  or something very similar is going on.This is my code; note that it uses a freshly-built snapshot of , since I could not figure out how to code against their existing beta release.For the record, this version does a crude \"warmup\":The overall times improve about 30%, but the ratio between the two remains roughly the same.For the records:if i use(changed \"l--\" to \"l = l - 1l\") long performance improves by ~50%I don't have a 64 bit machine to test with, but the rather large difference suggests that there is more than the slightly longer bytecode at work.I see very close times for long/int (4400 vs 4800ms) on my 32-bit 1.7.0_45. Confirmed to be not causing the issue.EDIT:  (Not the case).
Java

The  state:The levels in descending order are:My example sets the  to , so I was expecting to see 2 messages for each loop.  Instead I see a single message for each loop (the  messages are missing).What needs changing in order to see the  (,  or ) output?Thanks to , this version works according to my expectation.  It displays 3x messages, & 3x messages.Loggers only log the message, i.e. they create the log records (or logging requests). They do not publish the messages to the destinations, which is taken care of by the Handlers. Setting the level of a logger, only causes it to  log records matching that level or higher.You might be using a  (I couldn't infer where your output is System.err or a file, but I would assume that it is the former), which defaults to publishing log records of the level . You will have to configure this handler, to publish log records of level  and higher, for the desired outcome.I would recommend reading the  guide, in order to understand the underlying design. The guide covers the difference between the concept of a Logger and a Handler.The java.util.logging properties file (by default, this is the  file in ) can be modified to change the default level of the ConsoleHandler:This is not recommended, for it would result in overriding the global configuration. Using this throughout your code base will result in a possibly unmanageable logger configuration.java.util.logging has a root logger that defaults to , and a ConsoleHandler attached to it that also defaults to .\n is lower than , so fine messages are not displayed by default.Create a logger for your whole application, e.g. from your package name or use , and hook your own ConsoleLogger to it.\nThen either ask root logger to shut up (to avoid duplicate output of higher level messages), or ask your logger to  to root.Alternatively, you may lower the root logger's bar.You can set them by code:Or with logging configuration file, if you are :By lowering the global level, you may start seeing messages from core libraries, such as from some Swing or JavaFX components.\nIn this case you may set a  on the root logger to filter out messages not from your program.provides a jar file that will help you work out why your logging in not working as expected.\nIt gives you a complete dump of what loggers and handlers have been installed and what levels are set and at which level in the logging hierarchy.I found my actual problem and it was not mentioned in any answer: some of my unit-tests were causing logging initialization code to be run multiple times within the same test suite, messing up the logging on the later tests.
Java

How do I bypass invalid SSL certificate errors with Apache  4.0?You need to create a SSLContext with your own TrustManager and create HTTPS scheme using this context. Here is the code,All of the other answers were either deprecated or didn't work for HttpClient 4.3.Here is a way to allow all hostnames when building an http client.Or if you are using version 4.4 or later, the updated call looks like this: Just for the record, there is a much simpler way to accomplish the same with HttpClient 4.1For the record, tested with httpclient 4.3.6 and compatible with Executor of fluent api:If all you want to do is get rid of invalid hostname errors you can just do:For Apache HttpClient 4.4:  This is extracted from our actual working implementation. The other answers are popular, but for HttpClient 4.4 they don't work. I spent hours trying & exhausting possibilities, but there seems to have been extremely major API change & relocation at 4.4.See also a slightly fuller explanation at: Hope that helps!This is how I did it - Initialising DefaultHTTPClient - Mock SSL Factory - If behind a proxy, need to do this - We are using HTTPClient 4.3.5 and we tried almost all solutions exist on the stackoverflow but nothing,\nAfter thinking and figuring out the problem, we come to the following code which works perfectly,\njust add it before creating HttpClient instance.Just had to do this with httpclient-4.5 and it seems like they've deprecated a few things since 4.4 so here's the snippet that works for me and uses the most recent API:In extension to  it will be nice to override the hostnameverifier.To accept all certificates in HttpClient 4.4.x you can use the following one liner when creating the httpClient:a full working version for Apache HttpClient 4.1.3 (based on oleg's code above, but it still needed an allow_all_hostname_verifier on my system):Note I'm re-throwing all exceptions because really, there's not much I can do if any of this fails in a real system!If you are using the , you need to set it up via the :... where  is the SSLContext created as shown in the 's answer.After that, you can do your http requests as:Tested with 4.3.3}With fluent 4.5.2 i had to make the following modification to make it work.If you encountered this problem when using AmazonS3Client, which embeds Apache HttpClient 4.1, you simply need to define a system property like this so that the SSL cert checker is relaxed:-Dcom.amazonaws.sdk.disableCertChecking=trueMischief managedfwiw, an example using \"RestEasy\" implementation of JAX-RS 2.x to build a special \"trust all\" client...
Java

I want to read a text file containing space separated values. Values are integers.\nHow can I read it and put it in an array list?Here is an example of contents of the text file:I want to have it in an arraylist as . How can I do it in Java?You can use  to get all lines of a text file into a .Tutorial: You can use  to split a  in parts based on a regular expression.Tutorial: You can use  to convert a  into an .Tutorial: You can use  to add an element to a .Tutorial: So, in a nutshell (assuming that the file doesn't have empty lines nor trailing/leading whitespace).If you happen to be at Java 8 already, then you can even use  for this, starting with .Tutorial:  Java 1.5 introduced the  class for handling input from file and streams.It is used for getting integers from a file and would look something like this:Check the API though. There are many more options for dealing with different types of input sources, differing delimiters, and differing data types.This example code shows you how to read file in Java.Look at this example, and try to do your own:Just for fun, here's what I'd probably do in a real project, where I'm already using all my favourite libraries (in this case , formerly known as ).Benefit: Not much own code to maintain (contrast with e.g. ). : Although it is worth noting that in this case  doesn't have any more code!Drawback: you obviously may not want to add new library dependencies just for this. Use  (IO and Lang) for simple/common things like this.Imports:Code:Done.Using Java 7 to read files with NIO.2Import these packages:This is the process to read a file:To read all lines of a file at once:All the answers so far given involve reading the file line by line, taking the line in as a , and then processing the .There is no question that this is the easiest approach to understand, and if the file is fairly short (say, tens of thousands of lines), it'll also be acceptable in terms of efficiency. , it's a very inefficient way to do it, for two reasons:If you care about speed, you are much better off reading a block of data and then processing it byte by byte rather than line by line. Every time you come to the end of a number, you add it to the  you're building.It will come out something like this:The code above assumes that this is ASCII (though it could be easily tweaked for other encodings), and that anything that isn't a digit (in particular, a space or a newline) represents a boundary between digits. It also assumes that the file ends with a non-digit (in practice, that the last line ends with a newline), though, again, it could be tweaked to deal with the case where it doesn't.It's  than any of the -based approaches also given as answers to this question. There is a detailed investigation of a very similar issue . You'll see there that there's the possibility of improving it still further if you want to go down the multi-threaded line.read the file and then do whatever you want \njava8\nFiles.lines(Paths.get(\"c://lines.txt\")).collect(Collectors.toList());
Java

Title is the entire question. Can someone give me a reason why this happens?Yes - because it does begin with the empty string. Indeed, the empty string logically occurs between every pair of characters.Put it this way: what definition of \"starts with\" could you give that would preclude this? Here's a simple definition of \"starts with\" that doesn't:\"x starts with y if the first  characters of x match those of y.\"An alternative (equivalent) definition:\"x starts with y if \"I will try to elaborate on what Jon Skeet said.Let's say  x, y and z are strings and + operator is in fact concatenation, then:If we can split z to write z = x + y that means that z starts with x.\nBecause every string z can be split to z = \"\" + z it follows that every string starts with \"\".So, because (\"\" + \"abcd\") == \"abcd\" it follows that \"abcd\" starts with \"\"This method compares the value parameter to the substring at the beginning of this string that is the same length as value, and returns a value that indicates whether they are equal.  true if the character sequence represented by the argument is a prefix of the character sequence represented by this string; false otherwise.  or is equal to this String object as determined by the equals(Object) method.I'll start with a related fact that is easier to understand.Why? The  of  states that  is a subset of  if every element of  is an element of . Conversely,  is not a subset of  if there is an element of  that is not an element of .Now fix a set . I'll establish that the empty set is a subset of . I'll do this by showing that it is not the case that the empty set is not a subset of . If the empty set were not a subset of  then I could find an element of the empty set that is not in . But the empty set does not have any elements and thus I can not find an element that is not in . Therefore, it is not the case that the empty set is not a subset of . Thus, the empty set must be a subset of .First, we must agree on our definition of . Let  and  be s We say that    if  and the first  characters of  match those of . That is,  and for every  such that ,  is true. Conversely, we would say that  does not start with  if the statement or  and there is an  such that  and is true. In plain English,  is shorter than , or, if not, there is a character in  not matching the character as the same position in .Now fix a string . I'll establish that  starts with the empty string. I'll do this by showing that it is not the case that  does not start with the empty string. If  does not start with the empty string then  or  and there is an  such that . But  and  is equal to zero so it is impossible for  to be true. Similarly, since ``String.Empty.LengthInt32 index0 <= index < String.Empty.Length`. Therefore or  and there is an  such that is false. Therefore, it is not the case that  does not start with the empty string. Thus,  must start with the empty string.The following is an implementation of  coded as an extension to .The above two bolded facts are examples of . They are true by virtue of the fact that the statements defining them ( and ) are  over empty universes. There are no elements in the empty set, so there can not be any elements of the empty set not in some other fixed set. There are no characters in the empty string, so there can not be a character as some position in the empty string not matching the character in the same position in some other fixed string.Let's just say  returns false.if so then what does the following expression eval to, true or false:it turns out that evals to true, so the string does start with the empty string ;-), or put in other words, the substring of \"abcd\" starting at position 0 and having 0 length equals the empty string \"\". Pretty logical imo.In C# this is how the  tells it to react;THE REAL ANSWER:It has to be that way otherwise you'd have the case where and then we'd have Y2K all over again because all the bank software that depends on equal strings starting with themselves will get our accounts mixed up and suddenly Bill Gates will have my wealth and I'd have his, and damn it! Fate just isn't that kind to me.The first N characters of the two strings are identical. N being the length of the second string, i.e. zero.Just for the record,  internally calls the method  which makes the following check explicitly:Because a string begins well with \"nothing\".If you think of it in regular expressions terms, it makes sense.\nEvery string (not just \"abcd\", also \"\" and \"sdf\\nff\") , \nreturns true when evaluating the regular expression of 'starts with empty string'.
Java

Can someone help me with this? Every example I find is about doing this alphabetically, while I need my elements sorted by date.My ArrayList contains objects on which one of the datamembers is a DateTime object. On DateTime I can call the functions:So to compare I could do something like:I don't really know what to do inside the if block. Any ideas?You can make your object comparable:And then you sort it by calling:However sometimes you don't want to change your model, like when you want to sort on several different properties. In that case, you can create comparator on the fly:However, the above works only if you're certain that dateTime is not null at the time of comparison. It's wise to handle null as well to avoid NullPointerExceptions:Or in the second example:You can use Collections.sort method. It's a static method. You pass it the list and a comparator. It uses a modified mergesort algorithm over the list. That's why you must pass it a comparator to do the pair comparisons.Note that if myList is of a comparable type (one that implements Comparable interface) (like Date, Integer or String) you can omit the comparator and the natural ordering will be used.Given  that has a  member with a  method, you can sort an  that contains  elements by the  objects like this:Since Java 8 the  interface provides the  method. Combined with  expression the easiest solution would beAll the answers here I found to be un-neccesarily complex for a simple problem (at least to an experienced java developer, which I am not). I had a similar problem and chanced upon this (and other) solutions, and though they provided a pointer, for a beginner I found as stated above. My solution, depends on where in the the Object your Date is, in this case, the date is the first element of the Object[] where  is the ArrayList containing your Objects.With introduction of Java 1.8, streams are very useful in solving this kind of problems:This is how I solved:Hope it help you.?This may be an old response but I used some examples from this post to create a comparator that would sort an  of  by one object in the list, that being the timestamp.  I have these objects:The map objects are as follows:That mapping is what I use to load all my objects into the array list, using the  function, within a loop.Now, I created my own comparator:I can now just call the Comparator at any time on the array and it will sort my array, giving me the Latest timestamp in position 0 (top of the list) and the earliest timestamp at the end of the list.  New posts get put to the top basically.This may help someone out, which is why I posted it.  Take into consideration the return statements within the compare() function.  There are 3 types of results.  Returning 0 if they are equal, returning >0 if the first date is before the second date and returning <0 if the first date is after the second date.  If you want your list to be reversed, then just switch those two return statements!  Simple =]Pass the ArrayList In argument.The best answer IMHO from Tunaki using Java 8 lambda
Java

I got a native library that needs to be added to . With JVM argument  I can set the path as I want.My problem is that my other library (pentaho reporting) searches fonts based on the default java.library.path (including system directories etc) and the manual setting overrides the default path..So : how can I  a path entry to the default java.library.path instead of overriding it (which seems to be done with -Djava.library.path)? (I wouldn't want to add the default path by hand, which wouldn't be nice for the sake of deployment)EDIT: Sorry for missing details; I'm working with Eclipse. (The deployment is done with JNLP and there I can use   under )Had forgotten this issue... I was actually asking with Eclipse, sorry for not stating that originally.\nAnd the answer seems to be too simple (at least with 3.5; probably with older versions also):Java run configuration's Arguments : VM arguments:Must not forget the quotation marks, otherwise there are problems with spaces in PATH.If you want to add a native library without interfering with  at development time in Eclipse (to avoid including absolute paths and having to add parameters to your launch configuration), you can supply the path to the native libraries location for each Jar in the  dialog under . Note that the native library file name has to correspond to the Jar file name. See also this .SWT puts the necessary native DLLs into a JAR. Search for \"org.eclipse.swt.win32.win32.x86_3.4.1.v3449c.jar\" for an example.The DLLs must be in the root of the JAR, the JAR must be signed and the DLL must appear with checksum in the META-INF/MANIFEST.MF for the VM to pick them up. states that there is no substitution mechanics implemented in Eclipse's launcher, at least no up to release Juno.Thus it is (almost) impossible to append or prepend another library folder to java.library.path when launching Eclipse without prior knowledge of the default setting.I wrote almost, cause it should be possible to let Eclipse startup, dump the content of java.library.path and stop Eclipse in one command. The dump would the be parsed and then taken as the input for launching Eclipse, i.e.In Windows, like this: -Djava.library.path=\"C:/MyLibPath;%PATH%\" %PATH% is your old -Djava.library.pathCan you get round this by calling programmatically to load your native library? This method (unlike ) allows you to specify an absolute path.Window->Preferences->Java->Installed JREs. Then choose your current JRE(JDK) and click Edit.\nFill Default VM Arguments: -Djava.library.path=/usr/local/xuggler/lib.\nDone!As I can't add a comment yet I'll post another reply:The solution offered by Rob Elsner in one of the comments above works perfectly (OSX 10.9, Eclipse Kepler). One has to append their additional paths to that separated by \":\".In UNIX systems, you can append to the LD_LIBRARY_PATH environment variable. On Windows, the JVM automatically sets the system property, java.library.path, to PATH; so if the dll is on your PATH, then you're set.The native library file name has to correspond to the Jar file name. This is very very important.\nPlease make sure that jar name and dll name are same.\nAlso,please see the post from Fabian Steeg\nMy download for jawin was containing different names for dll and jar.\nIt was jawin.jar and jawin.dll, note extra 'd' in dll file name.\nI simply renamed it to jawin.dll and set it as a native library in eclipse as mentioned in post\n\"\"For some reason I couldn't get multiple folders to work (well it did for a while but as soon as I needed more dlls and added more folders, none with white spaces in the path). I then copied all needed dlls to one folder and had that as my  and it worked. I don't have an explanation - if anyone does, it would be great.Many of the existing answers assume you want to set this for a particular project, but I needed to set it for Eclipse  in order to support integrated authentication for the SQL Server JDBC driver.To do this, I followed  for launching Eclipse from the Java commandline instead of its normal launcher.  Then I just modified that script to add my -Djava.library.path argument to the Java commandline.On Windows, I have found that the important thing is to  rather than from the Start Menu or a shortcut, provided that the native DLL is in a directory in your PATH. Apparently, this ensures that the proper directory is on the path.
Java

When writing utility classes in Java, what are some good guidelines to follow?Should packges be \"util\" or \"utils\"? Is it ClassUtil or ClassUtils? When is a class a \"Helper\" or a \"Utility\"? Utility or Utilities? Or do you use a mixture of them?The standard Java library uses both Utils and Utilities:Apache uses a variety of Util and Utils, although mostly Utils:Spring uses a lot of Helper and Utils classes:So, how do you name your utility classes?Like many such conventions, what's important is not so much what convention you use, as that you use it consistently. Like, if you have three utility classes and you call them CustomerUtil, ProductUtils, and StoreUtility, other people trying to use your classes are going to constantly get confused and type CustomerUtils by mistake, have to look it up, curse you a few times, etc. (I heard a lecture on consistency once where the speaker put up a slide showing an outline of his speech with three main points, labeled \"1\", \"2nd\", and \"C\".)Never ever ever make two names that differ only in some subtlety of spelling, like having a CustomerUtil and a CustomerUtility. If there was a good reason to make two classes, then there must be something different about them, and the name should at least give us a clue what that difference is. If one contains utility functions related to name and address and the other contains utility functions related to orders, then call them CustomerNameAndAddressUtil and CustomerOrderUtil or some such. I regularly go nuts when I see meaningless subtle differences in names. Like just yesterday I was working on a program that had three fields for freight costs, named \"freight\", \"freightcost\", and \"frght\". I had to study the code to figure out what the difference between them was.There is no standard rule/convention in Java world for this. However, I prefer adding \"s\" at the end of Class name as @colinD has mentioned. That seems pretty standard to what  ( java collection as well as google collection)As long as Helper and Util goes, I will call something a Helper when it has APIs that help to achieve a specific functionality of a package ( considering a package as to implement a module); mean while a Util may be called in any context. For example in an application related to bank accounts, all number specific utility static APIs would go to All \"Account\" specific business rule helping APIs would go to After all, it is a matter of providing better documentation and cleaner code.I like the convention of just adding \"s\" to the type name when the type is an interface or a class you don't control. Examples of that in the JDK include  and . It's also the convention used in Google Collections.When you're dealing with a  you have control over, I'd say utility methods belong on the class itself generally.I think that 'utils' should be the package name. The class names should specify the purpose of the logic inside it. Adding the sufix -util(s) is redundant. I'm pretty sure the words \"helpers\" and \"utilities\" are used interchangeably. Anyway judging by the examples you provided, I'd say if your classname is an abbreviation (or has abbreviations in it like \"DomUtil\") then call your package \"whatever.WhateverUtil\" (or Utils if there's more than one utility in your package). Else if it has a full name instead of an abbreviation, then call it \"whatever.WhateverUtilities\".It's really up to you, but so long as coders know what you're talking about, you're good-to-go. If you're doing this professionally as a job for somebody though, ask them what their coding standards are before taking my advice. Always go with the shop standards no matter what  as that will help you keep your job. :-)
Java

I'm working on two projects in eclipse and I would like to import some classes from project a to project b. What should I do?Is there a way of doing it without adding the project to the build path ?add project A to project B's build path.Follow these steps:\nEdits by \nRight click on project B's folder in eclipse --> properties --> build path --> projects --> add.\nNow add project A
Java

I am trying to understand what JMS and how it is connected to AMQP terminology.\nI know JMS is an API and AMQP is a protocol. Here are my assumptions (and questions as well)Some of the above may be dumb. :-) But trying to wrap my head around it.Your question is a bit messy and like a tough Question of a question paper :)(As teachers always try to ask simple questions making complex :D I hope you are not a teacher :) )Let see all of these one by one.\nAs you know\nThe Java Message Service . JMS is a part of the Java Platform, Enterprise Edition, and is defined by a specification developed under the Java Community Process as JSR 914. (From WIKI).\n \n And the most important thing\n(From WIKI).\nSome imp things you should know\n Keep in mind that AMQP is a Messaging technologies that do not implement the JMS API.\n JMS is API and AMQP is a protocol.So it doesn't make sense to say that what is default protocol of JMS, of course client applications use HTTP/S as the connection protocol when invoking a WebLogic Web Service.\n JMS is only a API spec. It doesn't use any protocol. A JMS provider (like ActiveMQ) could be using any underlying protocol to realize the JMS API. For ex: Apache ActiveMQ can use any of the following protocols: AMQP, MQTT, OpenWire, REST(HTTP), RSS and Atom, Stomp, WSIF, WS Notification, XMPPI suggest you to see  Good Luck :)Let's start from the basis.   (Message Oriented Middleware), developed with Erlang (a TLC-oriented programming language) and  (Advance Message Queuing Protocol). \nCurrently, many Client APIs (e.g., Java, C++, RESTful, etc.) are available to enable the usage of RabbitMQ messaging services. (Java Messaging Service) is a JCP standard defining a  to be implemented by a MOM. An example of MOM that implements (i.e. is compatible with) the JMS APIs is ActiveMQ; there's also HornetMQ, and others. Such middlewares get the JMS APIs and implement the exchange patterns accordingly.According to above, taken the skeleton of JMS APIs, an instance of RabbitMQ and its Java Client APIs, it is possible to develop a JMS implementation making use of RabbitMQ: the only thing that one has to do, at that point, is implementing the exchange pattern (over RabbitMQ) according to the JMS specification.The key is:  (in this case, RabbitMQ).JMS, when it was defined did not define a protocol between the JMS client and a messaging server. The JMS client, which implement the JMS API can use whatever protocol to communicate with messaging server. The client just need to be compliant with JMS api. Thats all. Ususally JMS clients use a custom protocol that their messaging server understands.AMQP on other hand is a protocol between a messaging client and messaging server. A JMS client can use AMQP as the protocol to communicate with the messaging server. And there are clients like that available. I had similar questions on JMS and AMQP. While the discussion here answer the questions. This link from spring.io also explains it nicely and worth taking a look, hence sharing...  JMS is an API, so some JMS API's are implemented over the AMQP protocol (like ) while most JMS APIs use other protocols. If the version of the AMQP protocol is the same, such a client should be able to communicate with another AMQP client.It depends on your configuration of that JMS API. For ActiveMQ, it could be  but by default it is 'openwire'I suspect you may be looking for  which says, in part:
Java

Is there a way to configure log4j so that it outputs different levels of logging to different appenders?  I'm trying to set up multiple log files.  The main log file would catch all INFO and above messages for all classes.  (In development, it would catch all DEBUG and above messages, and TRACE for specific classes.)  Then, I would like to have a separate log file.  That log file would catch all DEBUG messages for a specific subset of classes, and ignore all messages for any other class.  Is there a way to get what I'm after?Thanks,\nDanThis should get you started:Perhaps something like this?Thus, all info messages are written to server.log; by contrast, foo.log contains only com.example.foo messages, including debug-level messages.I had this question, but with a twist - I was trying to log different content to different files.  I had information for a LowLevel debug log, and a HighLevel user log.  I wanted the LowLevel to go to only one file, and the HighLevel to go to both a file, and a syslogd.My solution was to configure the 3 appenders, and then setup the logging like this:The part that was difficult for me to figure out was that the 'log4j.logger' could have multiple appenders listed. I was trying to do it one line at a time.Hope this helps someone at some point!For the main logfile/appender, set up a  to limit what is actually logged in the appender to INFO and above, regardless of whether or not the loggers have DEBUG, TRACE, etc, enabled.As for catching DEBUG and nothing above that... you'd probably have to write a custom appender.However I'd recommend not doing this, as it sounds like it would make troubleshooting and analysis pretty hard: 
Java

I am trying to set up a large-scale REST services server.  We're using Spring Boot 1.2.1 Spring 4.1.5, and Java 8.  Our controllers are implementing @RestController and the standard @RequestMapping annotations.My problem is that Spring Boot sets up a default redirect for controller exceptions to \"/error\".  From the docs:Coming from years writing REST applications with Node.js, this is, to me, anything but sensible.  Any exception a service endpoint generates should return in the response.  I can't understand why you'd send a redirect to what is most likely an Angular or JQuery SPA consumer which is only looking for an answer and can't or won't take any action on a redirect.What I want to do is set up a global error handler that can take any exception - either purposefully thrown from a request mapping method or auto generated by Spring (404 if no handler method is found for the request path signature), and return a standard formatted error response (400, 500, 503, 404) to the client without any MVC redirects.  Specifically, we are going to take the error, log it to NoSQL with a UUID, then return to the client the right HTTP error code with the UUID of the log entry in the JSON body.The docs have been vague on how to do this.  It seems to me that you have to either create your own  implementation or use  in some fashion, but all the examples I've see still include forwarding the response to some kind of error mapping, which doesn't help.  Other examples suggest that you'd have to list every Exception type you want to handle instead of just listing \"Throwable\" and getting everything.Can anyone tell me what I missed, or point me in the right direction on how to do this without suggesting up the chain that Node.js would be easier to deal with?  An annoymous user suggested an edit and got rejected, but his suggestion looks good and helpful so I'm adding it:Using Spring Boot 1.3.1.RELEASE It is easy and less intrusive to add the following properties to the application.properties:If working with a full RESTful Application, it is very important to disable the automatic mapping of static resources since if you are using Spring Boot's default configuration for handling static resources then the resource handler will be handling the request (it's ordered last and mapped to /** which means that it picks up any requests that haven't been handled by any other handler in the application) so the dispatcher servlet doesn't get a chance to throw an exception.Using Spring Boot 1.2.7.RELEASE I found a much less intrusive way of setting the \"throExceptionIfNoHandlerFound\" flag.  Replace the DispatcherServlet replacement code below (Step 1) with this in your application initialization class:In this case, we're setting the flag on the existing DispatcherServlet, which preserves any auto-configuration by the Spring Boot framework.  One more thing I've found - the @EnableWebMvc annotation is deadly to Spring Boot.  Yes, that annotation enables things like being able to catch all the controller exceptions as described below, but it also kills a LOT of the helpful auto-configuration that Spring Boot would normally provide.  Use that annotation with extreme caution when you use Spring Boot.After a lot more research and following up on the solutions posted here (thanks for the help!) and no small amount of runtime tracing into the Spring code, I finally found a configuration that will handle all Exceptions (not Errors, but read on) including 404s. tell SpringBoot to stop using MVC for \"handler not found\" situations.  We want Spring to throw an exception instead of returning to the client a view redirect to \"/error\".  To do this, you need to have an entry in one of your configuration classes:The downside of this is that it replaces the default dispatcher servlet. This hasn't been a problem for us yet, with no side effects or execution problems showing up.  If you're going to do anything else with the dispatcher servlet for other reasons, this is the place to do them. Now that spring boot will throw an exception when no handler is found, that exception can be handled with any others in a unified exception handler:Keep in mind that I think the \"@EnableWebMvc\" annotation is significant here.  It seems that none of this works without it.  And that's it - your Spring boot app will now catch all exceptions, including 404s, in the above handler class and you may do with them as you please.One last point - there doesn't seem to be a way to get this to catch thrown Errors.  I have a wacky idea of using aspects to catch errors and turn them into Exceptions that the above code can then deal with, but I have not yet had time to actually try implementing that.  Hope this helps someone.Any comments/corrections/enhancements will be appreciated.I think  meets your requirements. A sample piece of code for HTTP 400:You can check this With Spring Boot 1.4+ new cool classes for easier exception handling were added that helps in removing the boilerplate code.A new  is provided for exception handling, it is combination of  and . You can remove the  on the  method when use this new annotation.i.e.  For handling 404 errors adding  annotation and the following to application.properties was enough:\nYou can find and play with the sources here:\nWhat about this code ? I use a fallback request mapping to catch 404 errors.By default Spring Boot gives json with error details.It also works for all kind of request mapping errors. Check this article\nIf you want to create log it to NoSQL. You can create @ControllerAdvice where you would log it and then re-throw the exception. \nThere is example in documentation\nFor REST controllers, I would recommend to use .If Spring Boot aims to embed some auto-configuration, this library does more for exception handling. You just need to add the dependency:And then define one or more advice traits for your exceptions (or use those provided by default)Then you can defined the controller advice for exception handling as:Solution with \n and\n\nworked for me with Spring Boot 1.3.1, while was not working on 1.2.7
Java

I want to limit the maximum memory used by the JVM. Note, this is not just the heap, I want to limit the total memory used by this process.use the arguments  . Use  or  after the numbers for indicating Megs and Gigs of bytes respectively.  indicates the minimum and  the maximum.You shouldn't have to worry about the stack leaking memory (it is highly uncommon).  The only time you can have the stack get out of control is with infinite (or really deep) recursion.You need to run the JVM with the following command line argument.Example:That will allow a max of 1GB of memory for the JVM.The answer above is kind of correct, you can't gracefully control how much native memory a java process allocates. It depends on what your application is doing.That said, depending on platform, you may be able to do use some mechanism, ulimit for example, to limit the size of a java or any other process.Just don't expect it to fail gracefully if it hits that limit. Native memory allocation failures are much harder to handle than allocation failures on the java heap. There's a fairly good chance the application will crash but depending on how critical it is to the system to keep the process size down that might still suit you.If you want to limit memory for jvm (not the heap size ) \nulimit -v To get an idea of the difference between jvm and heap memory , take a look at this excellent article\nI've never used it.  Maybe you'll find it useful.  The spelling error is not mine.
Java

The title is in reference to Is this a branch prediction effect, too? Beware: here the processing for the sorted array is !!Consider the following code:This prints out a value of around 720 on my machine.Now if I activate the collections sort call, that value drops down to 142. Why?!?The results  conclusive, they don't change if I increase the number of iterations/time.Java version is 1.8.0_71 (Oracle VM, 64 bit), running under Windows 10, JUnit test in Eclipse Mars.Seems to be related to contiguous memory access (Double objects accessed in sequential order vs in random order). The effect starts vanish for me for array lengths of around 10k and less.Thanks to assylias for providing :It looks like caching / prefetching effect.The clue is that you compare Doubles (objects), not doubles (primitives). When you allocate objects in one thread, they are typically allocated sequentially in memory. So when  scans a list, it goes through sequential memory addresses. This is good for CPU cache prefetching heuristics.But after you sort the list, you still have to do the same number of memory lookups in average, but this time memory access will be in random order. to prove that the order of allocated objects matters.I think we are seeing the effect of memory cache misses:When you create the unsorted listall the double are most likely allocated in a contiguous memory area.\nIterating through this will produce few cache misses.On the other hand in the sorted list the references point to memory in a chaotic manner.Now if you create a sorted list with contiguous memory:this sorted list has the same performance than the original one (my timing).As a simple example that confirms the  and the  (+1!): The following does a simple comparison of both options:It is also not implemented as a JMH benchmark, but similar to the original code, with only slight modifications to observe the effect: The output on my machine isnicely showing that the timings are exactly the opposites of another: If random numbers are sorted, then the sorted version is slower. If sequential numbers are shuffled, then the shuffled version is slower.
Java

I have a problem deserializing a json string with Gson.\nI  receive an array of commands. The command can be start,  stop , some other type of command. Naturally I have polymorphism, and start/stop command inherit from command. How can I serialize it back to the correct command object using gson?Seems that I get only the base type, that is the declared type and never the runtime type.This is a bit late but I had to do exactly the same thing today. So, based on my research and when using gson-2.0 you really don't want to use the  method, but rather the more mundane . And you certainly don't need to do  or write adapters for the derived classes: just one adapter for the base class or interface, provided of course that you are happy with the default serialization of the derived classes. Anyway, here's the code (package and imports removed) (also available in ):The base class (interface in my case):The two derived classes, Cat:And Dog:The IAnimalAdapter:And the Test class:When you run the Test::main you get the following output:I've actually done the above using the  method too, but that seemed to require implementing custom DogAdapter and CatAdapter serializer/deserializer classes which are a pain to maintain any time you want to add another field to Dog or to Cat.Gson currently has a mechanism to  that reportedly can be configured for simple polymorphic deserialization, but I don't see how that's the case, as a Type Hierarchy Adapter appears to just be a combined serializer/deserializer/instance creator, leaving the details of instance creation up to the coder, without providing any actual polymorphic type registration.It looks like Gson will soon have the  for simpler polymorphic deserialization.  See  for more info.If use of the new  isn't possible, and you gotta use Gson, then I think you'll have to roll your own solution, registering a custom deserializer either as a Type Hierarchy Adapter or as Type Adapter.  Following is one such example.GSON has a pretty good test case here showing how to define and register a type hierarchy adapter. To use that do this:Serialize method of the adapter can be a cascading if-else check of what type it is serializing.Deserializing is a bit hacky. In the unit test example, it checks for existence of tell-tale attributes to decide which class to deserialized to. If you can change the source of the object you're serializing, you can add a 'classType' attribute to each instance which holds the FQN of the instance class's name. This is so very un-object-oriented though.Marcus Junius Brutus had a great answer (thanks!).  To extend his example, you can make his adapter class generic to work for all types of objects (Not just IAnimal) with the following changes:And in the Test Class:Long time has passed, but I couldn't find a really good solution online.. \nHere is small twist on @MarcusJuniusBrutus's solution, that avoids the infinite recursion.Keep the same deserializer, but remove the serializer - Then, in your original class, add a field with .\nThe trick is now to initialize this in the constructor , so make your interface into a an abstract class.The reason there is no infinite recursion here is that we pass the actual runtime class (i.e. Dog not IAnimal) to . This will not call our type adapter, as long as we use  and not If you want manage a TypeAdapter for a type and an other for his sub type, you can use a TypeAdapterFactory like this :This factory will send the most accurate TypeAdapter
Java

I have looked around quite a bit and haven't found the best solution to convert an existing IntelliJ project to Gradle. I work in a team environment and we currently share the .ipr file as we have a few build configurations that we track. We will be getting rid of those in favor of Gradle eventually but I can't screw things up too much until the Gradle conversion is done.Also, our Java source files are located in the root of the src directory instead of src/main/java as is standard.Is there a way I can add Gradle to my project that won't make me delete and recreate my IntelliJ project and won't screw everyone else up when they do a Git pull?Why don't you just add:in your root project folder, and use plugin for example:and with this fire from command line:and after that:After that everything should work Another way, simpler.Add your file to the root of your project. Close the project. Manually remove *.iml file. Then choose \"Import Project...\", navigate to your project directory, select the  file and click OK.There is no need to remove any  files. Follow this:I'm not able to add a comment due to reputation. I'm using Version 12I solved a similar problem by creating an entirely new project and \"Checking out from Version Control\"\nMerging the two projects later was fairly easy.Have you tried something similar ?Just as a future reference, if you already have a  project all you need to do is doing a  in your project directory which will generates  and other dependencies, then do a  in the same directory. 
Java

I use both ruby on rails and Java.  I really enjoy using migrations when I am working on a rails project.  so I am wondering is there a migrations like tool for Java? If there is no such tool is it a good idea to use migrations as a tool to control a database used by a Java project? I've used Hibernate's SchemaUpdate to perform the same function as migrations.  It's actually easier than migrations because every time you start up your app, it examines the database structure and syncs it up with your mappings so there's no extra rake:db:migrate step and your app can never be out of sync with the database it's running against.  Hibernate mapping files are no more complex than Rails migrations so even if you didn't use Hibernate in the app, you could take advantage of it.  The downside is that it's not as flexible as far as rolling back, migrating down, running DML statements. As pointed out in the comments, it also doesn't drop tables or columns. I run a separate method to do those manually as part of the Hibernate initialization process.I don't see why you couldn't use Rails migrations though - as long as you don't mind installing the stack (Ruby, Rake, Rails), you wouldn't have to touch your app.For a  between have a look at This should be a good start for you and anyone else to  is another project in this domain worth checking out. has a  utility that is patterned after the one from Rails.  Since it's implemented in Groovy, you should be able to use it from any of your Java projects.There are also two independent implementations of rails-like migrations for Java:1)  Maven-based migrations from 2)  Ant-based tasks from  (my personal favorite)Although these packages were written for Maven and Ant specifically, with some work you can adapt them to just about anything.I ran across this post while researching the same question. I haven't come to any conclusions about the best tool or approach yet, but one tool that I've come across which hasn't been mentioned in other answers so far is . I'd be interested to read any comparisons of these tools.Some other relevant resources: Martin Fowler and Pramod Sadalage's somewhat aged post on , and the book  by Sadalage and Scot Ambler. seems like a candidate, but the project doesn't look mature enough for production usage.There is also  which has been initially developed inside  but is now a dedicated project. We are currently using it and are very satisfied (which doesn't mean there aren't any good alternatives). I list more of them in my  bookmarks (with a focus on tools supporting Maven).
Java

Now that maven-3 did  for the <uniqueVersion>false</uniqueVersion> for snapshot artefacts it seems that you really need to use timestamped SNAPSHOTS. Especially m2eclipse, which does use maven 3 internally seems to be affected with it, update-snapshots does not work when the SNAPSHOTS are not unique.It seemed best  to set all snapshots to uniqueVersion=falseNow, it seems no big problem to switch to the timestamped version, after all they are managed by a central nexus repository, which is able to delete old snapshots in regular intervalls.The problem are the local developer workstations. Their local repository quickly does grow  large with unique snapshots.How to deal with this problem ?Right now i see the folowing possible solutions:What is the best way to keep your local repository from filling up your hard drive space ?Update:To verify the beaviour and to give more info i setup a small nexus server, build two projects (a and b) and try:a:b:Now, when i use maven and run \"deploy\" on \"a\", i'll havein the local repository. With a new timestamp version each time i run the deploy target. The same happens when i try to update Snapshots from the nexus server (close \"a\" Project, delete it from local repository, build \"b\")In an environment where lots of snapshots get build (think hudson server ...), the local reposioty fills up with old versions To test how and why this is failing i did some more tests. Each test is run against clean everything (de/glauche gets delete from both machines and nexus)local repository on machine A does contain snapshot.jar + snapshot-timestamp.jar BUT: only one timestamped jar in nexus, metadata reads:Ok, next try with maven 3.0.1 (after removing all traces of project a)So, to recap: The \"deploy\" goal in maven3 works better than in 2.2.1, the local repository on the creating machine looks fine.\nBut, the receiver always ends up with lots of timestamed versions ...What am i doing wrong ?I also did test various other configurations, first replace nexus with artifactory -> same behaviour. Then use linux maven 3 clients to download the snapshots from the repository manager -> local repository still has timestamped snapshots :(The  configuration applied to artifacts that were deployed (via mvn deploy) to a Maven repository such as Nexus.  To remove these from Nexus, you can easily create an automated job to purge the SNAPSHOT repository every day.  It can be configured to retain a certain number of shapshots or keep them for a certain period of time.  Its super easy and works great.Artifacts in the local repository on a developer machine get there from the \"install\" goal and do not use these timestamps...they just keep replacing the one and only SNAPSHOT version unless you are also incrementing the revision number (e.g. 1.0.0-SNAPSHOT to 1.0.1-SNAPSHOT).This plugin removes project's artifacts from local repository. Useful to keep only one copy of large local snapshot.Well I didn't like any of proposed solutions. Deleting maven cache often significantly increases network traffic and slows down build process. build-helper-maven-plugin helps only with one artifact, I wanted solution that can purge all outdated timestamped snapshot artifacts from local cache in one simple command. After few days of searching, I gave up and decided to write small program. The final program seems to be working quite well in our environment. So I decided to share it with others who may need such tool. Sources can be pulled from github: As far as the remote repository piece of this,  I think the previous answers that discuss a purging of SNAPSHOTs on a regular interval will work.  But no one has addressed the local-developer workstation synchronization part of your question.We have not started using Maven3 yet, so we've yet to see SNAPSHOTs starting to build up on local machines.But we have had different problems with m2eclipse.  When we have \"Workspace Resolution\" enabled and the project exists within our workspace, source updates usually keep us on the bleeding edge.  But we've found it's very difficult to get m2eclipse to update itself with recently published artifacts in Nexus.  We're experiencing similar problems within our team and it's particularly problematic because we have a very large project graph... there are a lot of dependencies that won't be in your workspace but will be getting SNAPSHOTs published frequently.I'm pretty sure this boils back to an issue in m2eclipse where it doesn't handle SNAPSHOTs exactly as it should.  You can see in the Maven console within eclipse where m2eclipse tells you it's skipping the update of a recently published SNAPSHOT because it's got a cached version.  If you do a -U from a run configuration or from the command line,  will pick up the metadata change.  But an \"Update Snapshots...\" selection should tell m2eclipse to have Maven expire this cache.  It doesn't appear to be getting passed along.  There appears to be a bug out there that is filed for this if you're interested in voting for it:\nYou made mention of this in a comment somewhere.The best workaround for this problem seems to be having developers purge their local workstations when things start to break down from within m2eclipse.  Similar solution to a different problem...  Others have reported problems with Maven 2.2.1 and 3 backing m2eclipse, and I've seen the same.I would hope if you're using Maven3 you can configure it to only pull the latest SNAPSHOT, and cache that for the amount of time the repository says (or until you expire it by hand).  Hopefully then you won't need to have a bunch of SNAPSHOTs sitting in your local repository.That is unless you're talking about a build server that is manually doing a  on them.  As far as how to prevent SNAPSHOTs from building up on an environment like a build server, we've kind of dodged that bullet by having each build use its own workspace and local repository (though, in Maven 2.2.1, certain things such as POMs seem to always come out of the ~/.m2/repository)  The extra SNAPSHOTs really only stick around for a single build and then they get dropped (and downloaded again from scratch).  So we've seen this approach does end up eating up more space to begin with, but it tends to remain more stable than having everything resolved out of a single repository.  This option (on Hudson) is called \"Use private Maven repository\" and is under the Advanced button of the Build section on project configurations when you've selected to build with Maven.  Here is the help description for that option:Hope this helps - if it doesn't address your problem please let me know where I missed., deleting timestamped files like  can be very simple:Install , save the script into a file and schedule the execution at each week, start, logon, whatever suits you.Or, you can even wire the execution into maven build, using . Notice, how is the repository location set by maven into the property  and then binded through configuration into variable :Add following parameter into your POM file 
Java

The library in question is .I want is to have the native library, JNI library, and all Java API classes in one JAR file to avoid redistribution headaches.There seems to be , butThe question is, can I bundle everything in one JAR and redistribute it? If yes, how?P.S.: Yes, I realize it may have portability implications.is great article, which solves my issue ..In my case I've got the following code for initialize the library:Take a look at . It will wrap your application up in a single jar file with a specialised class loader which handles \"jars within jars\" among other things.It  by unpacking them to a temporary working folder as required.(Disclaimer: I've never used One-JAR, haven't needed to as yet, just had it bookmarked for a rainy day.) is a class loader to load classes, native libraries and resources from a single monster JAR and from JARs inside the monster JAR.You will probably have to unjar the native library to the local file system.  As far as I know the bit of code that does the native loading looks at the file system.This code should help get you started (I haven't looked at it in a while, and it is for a different purpose but should do the trick, and I am pretty busy at the moment, but if you have questions just leave a comment and I'll answer as soon as I can).
Java

I am writing a Java utility which helps me to generate loads of data for performance testing.  It would be  cool to be able to specify a regex for Strings so that my generator spits out things which match this.  Is there something out there already baked which I can use to do this?  Or is there a library which gets me most of the way there?Thanks As mentioned in the comments, there is a library available at Google Code to acheive this:\nSee also  as suggested by Firstly, with a complex enough regexp, i believe this can be impossible. But you should be able to put something together for simple regexps.If you take a look at the source code of the class java.util.regex.Pattern, you'll see that it uses an internal representation of Node instances. Each of the different pattern components have their own implementation of a Node subclass. These Nodes are organised into a tree.By producing a visitor that traverses this tree, you should be able to call an overloaded generator method or some kind of Builder that cobbles something together. is capable of doing it as well:It's too late to help the original poster, but it could help a newcomer.  is a useful java library that provides many features for using regexes to generate strings (random generation, generating a string based on its index, generating all strings...).Example :Visual Studio Team System does include something like this. Not much help for Java though, so sorry.I've gone the root of rolling my  library for that (In c# but should be easy to understand for a Java developer).Rxrdg started as a solution to a problem of creating test data for a real life project. The basic idea is to leverage the existing (regular expression) validation patterns to create random data that conforms to such patterns. This way valid random data is created. It is not that difficult to write a parser for simple regex patterns. Using an abstract syntax tree to generate strings should be even easier.On stackoverflow podcast 11:This is probably not what you are looking for, but it might be a good starting off point, instead of creating your own.I can't seem to find anything in google, so I would suggest tackling the problem by parsing a given regular expression into the smallest units of work (\\w, [x-x], \\d, etc) and writing some basic methods to support those regular expression phrases.So for \\w you would have a method getRandomLetter() which returns any random letter, and you would also have getRandomLetter(char startLetter, char endLetter) which gives you a random letter between the two values.I know there's already an accepted answer, but I've been using  (the one mentioned in Craig's answer) and it works REALLY well for everything I've thrown at it. It's quick and that leaves me wanting to use the same regex to generate the real data for things like registration codes that this thing spits out.It takes a regex like:and it generates tons of unique codes like:Is this some big secret algorithm that RedGate figured out and we're all out of luck or is it something that us mere mortals actually could do?You'll have to write your own parser, like the author of String::Random (Perl) did. In fact, he doesn't use regexes anywhere in that module, it's just what perl-coders are used to.On the other hand, maybe you can have a look at , to get some pointers.EDIT: Damn, blair beat me to the punch by 15 seconds.It's far from supporting a full PCRE regexp, but I wrote the following Ruby method to take a regexp-like string and produce a variation on it. (For language-based CAPTCHA.)I am on flight and just saw the question: I have written easiest but inefficient and incomplete solution. I hope it may help you to start writing your own parser:Adding another tool I did not see listed here, that worked for me.\n(I tried the C# solution from Goran - Rxrdg - but with me the solution does not build).The link below is pretty simple and easy, and did the job for me:\nIf you want to generate \"critical\" strings, you may want to consider:EGRET \nthat generates \"evil\" strings covering your regular expressionsMUTREX \nthat generates fault-detecting strings by regex mutationBoth are academic tools (I am one of the authors of the latter) and work reasonably well.
Java

I'm baffled that I can't find a quick answer to this.  I'm essentially looking for a datastructure in Java which implements the  interface, but which stores its members in a sorted order.  I know that you can use a normal  and use  on it, but I have a scenario where I am occasionally adding and often retrieving members from my list and I don't want to have to sort it every time I retrieve a member in case a new one has been added.  Can anyone point me towards such a thing which exists in the JDK or even 3rd party libraries?:  The datastructure will need to preserve duplicates.:  I found all of this very interesting and learned a lot.  Aioobe in particular deserves mention for his perseverance in trying to achieve my requirements above (mainly a sorted java.util.List implementation which supports duplicates).  I have accepted his answer as the most accurate for what I asked and most thought provoking on the implications of what I was looking for even if what I asked wasn't exactly what I needed.  The problem with what I asked for lies in the List interface itself and the concept of optional methods in an interface.  To quote the javadoc:Inserting into a sorted list doesn't have precise control over insertion point.  Then, you have to think how you will handle some of the methods.  Take  for example:You are now left in the uncomfortable situation of either\n1) Breaking the contract and implementing a sorted version of add\n2) Letting  add an element to the end of the list, breaking your sorted order\n3) Leaving  out (as its optional) by throwing an  and implementing another method which adds items in a sorted order.Option 3 is probably the best, but I find it unsavory having an add method you can't use and another sortedAdd method which isn't in the interface.Other related solutions (in no particular order):Here is a \"minimal\" solution.The insert runs in linear time, but that would be what you would get using an ArrayList anyway (all elements to the right of the inserted element would have to be shifted one way or another).Inserting something non-comparable results in a ClassCastException. (This is the approach taken by  as well: )Note that overriding  (or  for that matter) to insert elements in a sorted fashion would be a . What you  do, is to override this method to throw an .From the docs of :Same reasoning applies for both versions of , both versions of  and . (All of which are optional operations according to the list interface.)....prints:Use .Have a look at   You can try  .Lists typically preserve the order in which items are added. Do you definitely need a , or would a sorted  (e.g. ) be okay for you? Basically, do you need to need to preserve duplicates?It might be a bit too heavyweight for you, but  has a  that is perfect to use as the model of a table or JListAioobe's approach is the way to go. I would like to suggest the following improvement over his solution though.aioobe's solution gets very slow when using large lists. Using the fact that the list is sorted allows us to find the insert point for new values using binary search.I would also use composition over inheritance, something along the lines of You could subclass ArrayList, and call Collections.sort(this) after any element is added - you would need to override two versions of add, and two of addAll, to do this.Performance would not be as good as a smarter implementation which inserted elements in the right place, but it would do the job. If addition to the list is rare, the cost amortised over all operations on the list should be low.I think the choice between SortedSets/Lists and 'normal' sortable collections depends, whether you need sorting only for presentation purposes or at almost every point during runtime. Using a sorted collection may be much more expensive because the sorting is done everytime you insert an element. If you can't opt for a collection in the JDK, you can take a look at the Since the currently proposed implementations which do implement a sorted list by breaking the Collection API, have an own implementation of a tree or something similar, I was curios how an implementation based on the TreeMap would perform. (Especialy since the TreeSet does base on TreeMap, too)If someone is interested in that, too, he or she can feel free to look into it:Its part of the , you can add it via Maven dependency of course. (Apache License)Currently the implementation seems to compare quite well on the same level than the guava SortedMultiSet and to the TreeList of the Apache Commons library.But I would be happy if more than only me would test the implementation to be sure I did not miss something important.Best regards!I had the same problem. So I took the source code of java.util.TreeMap and wrote . It implements my own :The implementation is based on updating node weights in the red-black tree when it is changed. Weight is the number of child nodes beneath a given node, plus one - self. For example when a tree is rotated to the left:updateWeight simply updates weights up to the root:And when we need to find the element by index here is the implementation that uses weights:Also comes in very handy finding the index of a key:You can find the result of this work at TreeSet/TreeMap (as well as their indexed counterparts from the indexed-tree-map project) do not allow duplicate keys , you can use 1 key for an array of values. If you need a SortedSet with duplicates use TreeMap with values as arrays. I would do that.
Java

Since I received no positives answers to my  question. I will try to write a Java FTP upload applet myself.My question is: \"Can you recommend a Java FTP client library for me to use?\"I want it to be:I found   of some libraries, but since this article is from 2003, maybe some new developments have happened :)Check out Apache , which contains FTP utilities. Off the top of my head I'm not sure if it meets all of your requirements, but it's certainly free!ftp4j is the best one, both for features and license:Yes, EnterpriseDT's  is stable (first released in 2000), has all the features you might need, and is open source as well. It's used in a bunch of open source projects (as well as in many commercial projects), and is acknowledged to be . As another poster noted, if you do wish to upgrade to SFTP and/or FTPS, it is a simple upgrade path with very few code changes required.I used cyaCommons-net surely. :) Most open source projects use it these days.ycI have successfully used the  library, which is free and open source. I can't compare it to other libraries (like the Apache Commons Net library) since I haven't used them. It does provide a simple upgrade path to SFTP (over SSH) and FTPS (over SSL), though that is a pay-for commercial product.Apache commons-nets get updates more frequently recently, while Enterprise DT library seems to update even more frequently.You have also this  which lists different options for FTP clients.commons-net is good, but  can give you some of the more advanced features you are looking for.I was downloading video files. Apache's FTPClient fumbled, it downloaded the video reasonably fast. but when I tried to play the video back, it lost chunks out of the middle of the video. ftp4j would download the whole video with no loss.ftp4j ftw
Java

How do you detect if  has been called on a socket on the remote side?The  method won't help, it will return  even if the remote side has closed the socket. Try this: Start the server, start the client. You'll see that it prints \"connected: true\" twice, even though the socket is closed the second time.The only way to really find out is by reading (you'll get -1 as return value) or writing (an  (broken pipe) will be thrown) on the associated Input/OutputStreams.Since the answers deviate I decided to test this and post the result - including the test example.The server here just writes data to a client and does not expect any input.The server:You can also check for socket output stream error while writing to client socket.The method Socket.Available will immediately throw a SocketException if the remote system has disconnected/closed the connection.
Java

I hear nowadays a lot about the Spring Framework. Why is there so much buzz around the Spring Framework in the industry?I already gave a partial answer in  but I'll add some links in this answer. Actually, I won't cover or discuss the technical qualities of Spring as they aren't new and don't explain the buzz in my opinion. Instead, consider the following events and acquisitions:As you can see, there have been lots of changes in the SpringSource sphere during the past year, with some pretty big moves during this summer. Don't you see the big picture now? Well, look at the resulting stack: with Java, Groovy, Grails as languages, Spring as container, tc Server as underlying application server, Hyperic for health and monitoring, VMware for virtualization, CloudFoundry as management and provisioning system, VMware/SpringSource has . And by complete, I mean really complete as this stack covers everything - except the JVM - to put Java on the Cloud: the software, the platform and the infrastructure i.e. all the different flavors of cloud computing.In other words, while others are still preparing themselves for it, VMware and SpringSource are already ready for the SaaS/PaaS/IaaS wave. This is exciting, this is where innovation goes, this creates (or at least feeds) the trend, this puts a lot of pressure on Java, the Application Server market, Java EE,... and this explains IMO the buzz around VMware/SpringSource. More than the upcoming arrival of Spring 3.0 :). Software as a Service\n Platform as a Service\n Infrastructure as a Service  Spring has been around for a while, it introduced important new design patterns, and it is indirectly responsible for reforming But I'm thinking you are hearing about it now because in August, VMware bought SpringSource for $420 million. That's rather high for an open source developer and consulting company...Let me try to explain you why spring, what is there in spring and what made spring so popular.The basic Idea of Spring Framework isI think you may want to read about , and .Spring is (among several other things) an inversion of control container.In the primordial days of crusty old J2EE, Spring Framework came along and made it possible to inject JNDI registered services into EJBs. Gee, you could actually begin to design an EJB to where it could be unit tested without having to fire up a J2EE app server - just mock the JNDI services that it collaborated with via Spring dependency injection.Well, for it's day, that was a not so minor miracle.These days, if you want to know why Spring continues to rock, check out this book and learn about this development stack, and how Spring is instrumental as the core bean factory mechanism to everything that surrounds it - from BlazeDS services to iBATIS or Hibernate to ActiveMQ messaging beans:And check out this article:Well it provides a great additional framework that lets you concentrate on writing less framework code and more application code.It provides things like:and a whole lot more.A lot of these concepts are fairly complex and because they provide the framework it means you can just plug in their components and leverage what has already been created for you.
Java

Let's say the bottleneck of my Java program really is some tight loops to compute a bunch of vector dot products. Yes I've profiled, yes it's the bottleneck, yes it's significant, yes that's just how the algorithm is, yes I've run Proguard to optimize the byte code, etc.The work is, essentially, dot products. As in, I have two  and I need to compute the sum of pairwise products. I know processor instruction sets exist to perform these kind of operations quickly and in bulk, like SSE or MMX.Yes I can probably access these by writing some native code in JNI. The JNI call turns out to  be pretty expensive.I know you can't guarantee what a JIT will compile or not compile. Has anyone  heard of a JIT generating code that uses these instructions? and if so, is there anything about the Java code that helps make it compilable this way?Probably a \"no\"; worth asking.So, basically, you want your code to run faster. JNI is the answer. I know you said it didn't work for you, but let me show you that you are wrong.Here's :and :We can compile and run that with  using commands line these:With an Intel Core i7-3632QM CPU @ 2.20GHz, Fedora 20, GCC 4.8.3, and OpenJDK 7 or 8, I get this kind of output:Or roughly 1.6 times faster. We need to use direct NIO buffers instead of arrays, but . On the other hand, manually unrolling the loop does not provide a measurable boost in performance, in this case.At least according to this  it is possible to aid the JIT compiler to identify your code as a vector operation. It does require some hinting, but it's at least possible. \"It is evident that most of the improvement comes as a result of persuading the JIT to recognise places where SIMD operations can be written as instructions accessing the SSE registers. By enabling this behaviour, the amount of floating-point arithmetic per cycle increases and as a consequence the rate at which the computation proceeds increases\"[Edit:15/10/2015] To address some of the scepticism expressed by others here I suggest anyone who wants to prove to themselves or other use the following method:Example:The result with and without the flag (on recent Haswell laptop, Oracle JDK 8u60):\n-XX:+UseSuperWord :  475.073 \u00b1 44.579  ns/op (nanoseconds per op)\n-XX:-UseSuperWord : 3376.364 \u00b1 233.211 ns/opThe assembly for the hot loop is a bit much to format and stick in here  but here's a snippet(hsdis.so is failing to format some of the AVX2 vector instructions so I ran with -XX:UseAVX=1): -XX:+UseSuperWord(with '-prof perfasm:intelSyntax=true')Have fun storming the castle!In HotSpot versions beginning with Java 7u40, the server compiler provides support for auto-vectorisation. According to However, this seems to be true only for \"simple loops\" - at least for the moment. For example, accumulating an array cannot be vectorised yet You could write OpenCl kernel to do the computing and run it from java . Code can be run on CPU and/or GPU and OpenCL language supports also vector types so you should be able to take explicitly advantage of e.g. SSE3/4 instructions.I'm guessing you wrote this question before you found out about netlib-java ;-) it provides exactly the native API you require, with machine optimised implementations, and does not have any cost at the native boundary due thanks to memory pinning.Have a look at . They show that Java HotSpot VM server compiler supports auto-vectorization using Super-word Level Parallelism, which is limited to simple cases of inside the loop parallelism. This article will also give you some guidance whether your data size is large enough to justify going JNI route.I dont believe most if any VMs are ever smart enough for this sort of optimisations. To be fair most optimisations are much simpler, such as shifting instead of multiplication whena power of two. The mono project introduced their own vector and other methods with native backings to help performance.
Java

Which one of the 2 options is better and faster to clear an ArrayList, and why?orIt happens that I have to, at random times, clear all entries from my ArrayList and I have no way to know how many new entries there will be in the future, there might be 0 or a 1000. Which method is faster and better, and why?It's hard to know without a benchmark, but if you have lots of items in your ArrayList and the average size is lower, it might be faster to make a new ArrayList.  would remove the elements without reducing the capacity of the list.Here mylist got cleared, the references to the elements held by it got nulled out, but it keeps the same backing array. Then mylist was reinitialized and got a new backing array, the old one got GCed. So one way holds onto memory, the other one throws out its memory and gets reallocated from scratch (with the default capacity). Which is better depends on whether you want to reduce garbage-collection churn or minimize the current amount of unused memory. Whether the list sticks around long enough to be moved out of Eden might be a factor in deciding which is faster (because that might make garbage-collecting it more expensive).I think that the answer is that it depends on a whole range of factors such as:These make it hard to predict which will be better.  But my intuition is that the difference will not be that great.Two bits of advice:The first one  will keep the same list just clear the list. The second one  creates a new  in memory.Suggestion: First one because that's what is is designed to do.If there is a good chance that the list will contain as much elements as it contains when clearing it, and if you're not in need for free memory, clearing the list is a better option. But my guess is that it probably doesn't matter. Don't try to optimize until you have detected a performance problem, and identified where it comes from.Tried the below program , With both the approach. \n1. With clearing the arraylist obj in for loop\n2. creating new New Arraylist in for loop. and to my surprise. the memory allocation didnt change much.  Before loop total free memory: 64,909 :: After loop total free memory: 64,775 ::  Before loop total free memory: 64,909 :: \nAfter loop total free memory: 64,765 ::So this says there is not much difference in using arraylist.clear from memory utilization perspective.   is going to keep the same ArrayList but the same memory allocation.  is going to allocate new memory for your ArrayList.The big difference is that ArrayLists will expand dynamically as you need more space.  Therefore, if you call  you will still, potentially, have a large amount of memory allocated for an ArrayList that might not be needed.That said  will be faster but if memory maters you might want to allocate a new ArrayList.I would suggest using list.clear() rather than allocating a new object. When you call the \"new\" keyword, you are creating more space in memory. In reality, it doesn't matter much. I suppose that if you know how large the list will be, it might be a good idea to create a new space but then specify how large the array will be.The truth is, it's not going to matter unless you're doing scientific programming. In that case, you need to go learn C++.
Java

3 questions:The connection timeout is the timeout in making the initial connection; i.e. completing the TCP connection handshake.  The read timeout is the timeout on waiting to read data. Specifically, if the server fails to send a byte <timeout> seconds after the last byte, a read timeout error will be raised.It means that the connection attempt can potentially block for ever.  There is no infinite loop, but the attempt to connect can be unblocked by another thread closing the socket.  (A  call may also do the trick ... not sure.)It means that a call to  on the socket stream may block for ever.  Once again there is no infinite loop, but the  can be unblocked by a  call, closing the socket, and (of course) the other end sending data or closing the connection.These are timeout values enforced by JVM for TCP connection establishment and waiting on reading data from socket.If the value is set to infinity, you will not wait forever. It simply means JVM doesn't have timeout  and OS will be responsible for all the timeouts. However, the timeouts on OS may be really long. On some slow network, I've seen timeouts as long as 6 minutes.Even if you set the timeout value for socket, it may not work if the timeout happens in the native code. We can reproduce the problem on Linux by connecting to a host blocked by firewall or unplugging the cable on switch.The only safe approach to handle TCP timeout is to run the connection code in a different thread and interrupt the thread when it takes too long.
Java

I have a function that uses Pattern.compile and a Matcher to search a list of strings for a pattern.  This function is used in multiple threads.  Each thread will have a unique pattern passed to the Pattern.compile when the thread is created.  The number of threads and patterns are dynamic, meaning that I can add more patterns and threads during configuration.Do I need to put a \"synchronize\" on this function if it uses regex?  Is regex in java thread safe?TIA, from the Java API documentation for the If you are looking at performance centric code, attempt to reset the Matcher instance using the reset() method, instead of creating new instances. This would reset the state of the Matcher instance, making it usable for the next regex operation. In fact, it is the state maintained in the Matcher instance that is responsible for it to be unsafe for concurrent access.While you need to remember that thread safety has to take into account the surrounding code as well, you appear to be in luck.  The fact that  are created using the Pattern's  factory method and lack public constructors is a positive sign.  Likewise, you use the  static method to create the encompassing .So, in short, if you do something like the example:you should be doing pretty well.Follow-up to the code example for clarity: note that this example strongly implies that the Matcher thus created is thread-local with the Pattern and the test.  I.e., you should not expose the Matcher thus created to any other threads.Frankly, that's the risk of any thread-safety question.  The reality is that  code can be made thread-unsafe if you try hard enough.  Fortunately, there are   that teach us a whole bunch of ways that we could ruin our code.  If we stay away from those mistakes, we greatly reduce our own probability of threading problems.A quick look at the code for  shows a bunch of member variables including the text that is being matched, arrays for groups, a few indexes for maintain location and a few s for other state.  This all points to a stateful  that would not behave well if accessed by multiple .  So does the :This is only an issue if, as @Bob Cross points out, you go out of your way to allow use of your  in separate s.  If you need to do this, and you think that synchronization will be an issue for your code, an option you have is to use a  storage object to maintain a  per working thread.To sum up, you can reuse (keep in static variables) the compiled Pattern(s) and tell them to give you new Matchers when needed to validate those regex pattens against some stringsee  (near the end) regarding the RegEx pattern used above for validating e-mails (in case it doesn't fit ones needs for e-mail validation as it is posted here)
Java

I have a java complied package to speak with the https server on net. Running the compilation gives the following exception:I think this is due to the connection established with the client machine is not secure.  Is there any way to configure the local machine or ports in order to connect to the remote https server?It is due to the fact that you are talking to an HTTP server, not an HTTPS server. Probably you didn't use the correct port number for HTTPS.You should have a local SMTP domain name that will contact the mail server and establishes a new connection as well you should change the SSL property in your programming below I got the same error message when I forgot to log in to the company firewall, before performing a POST request through a proxy.I got the same error. it was because I was accessing the https port using http.. The issue solved when I changed http to https. I face the same issue from Java application built in Jdevelopr 11.1.1.7 IDE. I solved the issue by unchecking the use of proxy form Project properties.You can find it in the following:\nProject Properties -> (from left panle )Run/Debug/Profile ->Click (edit) form the right panel -> Tool Setting from the left panel -> uncheck (Use Proxy) option.It worked for me now, I have change the setting of my google account as below:      Though I have enabled SSL and TSL while running program in this  of same post. I spend a lot of time but than I realized and found this link.\nAnd done 2 following steps and setting control in google. : Now I am able to send mail using above program.As EJP said, it's a message shown because of a call to a non-https protocol.\nIf you are sure it is HTTPS, check your bypass proxy settings, and in case add your webservice host url to the bypass proxy listAdding this as an answer as it might help someone later.I had to force jvm to use the IPv4 stack to resolve the error. My application used to work within company network, but while connecting from home it gave the same exception. No proxy involved. Added the jvm argument \n    and all the  requests were behaving normally.if connection is FTPS test:FTPSClient ftpClient = new FTPSClient(protocol, false);protocol = TLS,SSL\nand false = isImplicit.Another reason is maybe \"access denided\", maybe you can't access to the URI and received blocking response page for internal network access. If you are not sure your application zone need firewall rule, you try to connect from terminal,command line. \nFor GNU/Linux or Unix, you can try run like this command and see result is coming from blocking rule or really remote address: Maybe your default cerficate has expired. to renew it through admin console go \"Security >SSL certificate and key management > Key stores and certificates > NodeDefaultKeyStore > Personal certificates\"  select the \"default\" alias and click on \"renew\" after then restart WAS.If you're running the Java process from the command line on Java 6 or earlier, adding this switch solved the issue above for me:-Dhttps.protocols=\"TLSv1\"
Java

What exactly are the differences between  and ? When I run both of these commands, they both seem to do the same thing.  Well, both will clean.  That means they'll remove the target folder.   The real question is what's the difference between package and install?   will compile your code and also package it.  For example, if your pom says the project is a jar, it will create a jar for you when you package it and put it somewhere in the target directory (by default). will compile and package, but it will also put the package in your local repository.  This will make it so other projects can refer to it and grab it from your local repository.  Package & install are various phases in maven build lifecycle. package phase will execute all phases prior to that & it will stop with packaging the project as a jar. Similarly install phase will execute all prior phases & finally install the project locally for other dependent projects. For understanding maven build lifecycle please go through the following link 
Java

 has been out for a while now, but I cannot find any good resources on the configuration of the , specifically the new .\nMy questions:The G1 garbage collector is not the default in my installation of Java, version 1.7.0_01. You can see for yourself by using with some extra command line options:You don't need to enable experimental options to turn on the G1 collector any more, though:I don't know where you can find any good documentation.Oracle finally made G1 official in Java 7 U4:\nDescription:\nCommand line options:\nStill, I do not think it is the default collector in Java 7. For servers the default is the Parallel Collector as in Java 6.Yes, G1 is the new standard garbage collector in Java 1.7 JVM. you can find plenty of information on how to use and configre the new garbage collector:I have also found  article very helpful in understanding the inners of G1.Even more info .The rule on  is still applicable in Java 7 (and AFAIK, Java 8):But also consider: For example, if on Windows x64 you run...As of Java 7, simply . Perhaps also of interest is  you would want to:I've not used G1 myself, but  that it adheres to the same basic \"throughput / ergonomic\" flags used to tune the other parallel collectors. In my experience with the Parallel GC,  has been the pivotal one in providing the expected speed-memory tradeoff. YMMV.G1-specific options are listed Don't know,  It can be a pain to find, can't it? Probably the best \"hub\" page I've found is this one:Some deep reading required, but worth the time if you need to do some tuning. Particularly insightful is: G1 is not default collector in Java 7.  will enable G1GC There are many. Have a look at this  article for complete information..Here is a list of important options and their default values. This list applies to the latest Java HotSpot VM, build 24. You can adapt and tune the G1 GC  settings on the JVM command line.Sets the size of a G1 region. The value will be a power of two and can range from 1MB to 32MB. The goal is to have around 2048 regions based on the minimum Java heap size.Sets a target value for desired maximum pause time. The default value is 200 milliseconds. The specified value does not adapt to your heap size.Sets the percentage of the heap to use as the minimum for the young generation size. The default value is 5 percent of your Java heap. Sets the percentage of the heap size to use as the maximum for young generation size. The default value is 60 percent of your Java heap.Sets the value of the STW worker threads. Sets the value of n to the number of logical processors. The value of n is the same as the number of logical processors up to a value of 8.If there are more than eight logical processors, sets the value of n to approximately 5/8 of the logical processors. This works in most cases except for larger SPARC systems where the value of n can be approximately 5/16 of the logical processors.Sets the number of parallel marking threads. Sets n to approximately 1/4 of the number of parallel garbage collection threads (ParallelGCThreads).Sets the Java heap occupancy threshold that triggers a marking cycle. The default occupancy is 45 percent of the entire Java heap.Sets the occupancy threshold for an old region to be included in a mixed garbage collection cycle. The default occupancy is 65 percentSets the percentage of heap that you are willing to waste. The Java HotSpot VM does not initiate the mixed garbage collection cycle when the reclaimable percentage is less than the heap waste percentageSets the target number of mixed garbage collections after a marking cycle to collect old regions with at most G1MixedGCLIveThresholdPercent live data. The default is 8 mixed garbage collectionsSets an upper limit on the number of old regions to be collected during a mixed garbage collection cycle. The default is 10 percent of the Java heapSets the percentage of reserve memory to keep free so as to reduce the risk of to-space overflows. The default is 10 percent. When you increase or decrease the percentage, make sure to adjust the total Java heap by the same amount.You have re-configured many G1GC parameters, which are not required if you follow above documentation page. Please cross check with above recommendations especially on  and , which are to be based on your CPU cores. Remove re-configuration of un-necessary parameters.  from oracle:When you evaluate and fine-tune G1 GC, keep the following recommendations in mind:There are some changes with Java 7. Have a look at this Refer to oracle documentation page about  and related SE question:The documentation available at  (the link provided by Wojtek) seems to be the only official link with info but the info seems outdated as some of the flags mentioned there were only available in the test builds, they no longer exist in the production releases. Some one from Oracle should provide some updated documentation on the G1 GC.No G1 is not default garbage collector in jdk 1.7.0_02.\nThe default garbage collector depends upon the class of machine.\nIf the machine is of Server class then the default garbage collector is Throughput Collector.\nIf the machine is of Client class then the default garbage collector is Serial Collector.By default you don't really want to use G1 collector, as it is not really better than the others. It is only good for special purposes.In low latency application is is sligthly better than CMS, as it has a little bit shorter, and more predictable pause times. In exchange the throughput is much worse than CMS in exchange.So it is only good if the latency is important, but the throughput is not important at all. If both are important, then stay with CMS.
Java

In a simulation server environment where users are allowed to submit their own code to be run by the server, it would clearly be advantageous for any user-submitted code to be run in side a sandbox, not unlike Applets are within a browser.  I wanted to be able to leverage the JVM itself, rather than adding another VM layer to isolate these submitted components.This kind of limitation appears to be possible using the existing Java sandbox model, but is there a dynamic way to enable that for just the user-submitted parts of a running application? was designed to solve this, but unfortunately it doesn't have an implementation yet.This is a pretty detailed topic, and I'm mostly writing this all off the top of my head.But anyway, some imperfect, use-at-your-own-risk, probably buggy (pseudo) code:Obviously such a scheme raises all sorts of security concerns. Java has a rigorous security framework, but it isn't trivial. The possibility of screwing it up and letting an unprivileged user access vital system components shouldn't be overlooked.That warning aside, if you're taking user input in the form of source code, the first thing you need to do is compile it to Java bytecode. AFIAK, this cannot be done natively, so you'll need to make a system call to javac, and compile the source code to bytecode on disk.  a tutorial that can be used as a starting point for this.\n: as I learned in the comments, you actually can compile Java code from source natively using Once you have JVM bytecode, you can load it into the JVM using a   function. To set a security context for this loaded class you will need to specify a . The minimal constructor for a  requires both a CodeSource and a . The PermissionCollection is the object of primary use to you here- you can use it to specify the exact permissions the loaded class has. These permissions should be ultimately enforced by the JVM's .There's a lot of possible points of error here, and you should be extremely careful to completely understand everything before you implement anything.The  is a library for executing Java code with a limited set of permissions. \nIt can be used to allow access to only a set of white-listed classes and resources. It doesn't seem\nto be able to restrict access to individual methods. It uses a system with a custom class loader and\nsecurity manager to achieve this.I have not used it but it looks well designed and reasonably well documented.@waqas has given a very interesting answer explaining how this is possible to implement yourself. But it is much safer to leave such security critical and complex code to experts.Notice though that the project has not been updated since 2013 and the the creators describe it as \"experimental\". Its home page has disappeared but the Source Forge entry remains. Example code adapted from the project web site:To address the problem in the accepted answer whereby the custom  will apply to all threads in the JVM, rather than on a per-thread basis, you can create a custom  that can be enabled/disabled for specific threads as follows: is just a simple implementation of  to ensure that only authorised code can enable/disable the security manager. It looks like this:Well it's very late to give any suggestions or solutions, but still I was facing similar kind of issue, kind of more research oriented. Basically I was trying to provide a provision and automatic evaluations for programming assignments for Java course in e-learning platforms.I know this sounds a quite complex and lot of tasks, but Oracle Virtual Box already provides Java API to create or clone virtual machines dynamically.\n (Note, even VMware also provides API for doing same)And for the minimum size and configuration Linux distribution you can refer to this one here ,So now if students messes up or tries to do it, may be with memory or file system or networking, socket, maximum he can damage his own VM.Also internally into these VM's you can provide additional security like Sandbox (security manager ) for Java or creating user specific accounts on Linux and thus restricting access.Hope this helps !!Here's a thread-safe solution for the problem:Please comment!CUArnoYou will probably need to use a custom  and/or . For lots of detail, see  and  from Sun.
Java

Suppose i have a page that lists the objects on a table and i need to put a form to filter the table. The filter is sent as an Ajax GET to an URL like that: And instead of having lots of parameters on my Controller like:And supposing i have MyObject as:I wanna do something like:Is it possible? \nHow can i do that?You can absolutely do that, just remove the  annotation, Spring will cleanly bind your request parameters to your class instance:I will add some short example from me.The DTO class:Request mapping inside controller class:Query:Result:I hope it helps :)I have a very similar problem. Actually the problem is deeper as I thought. I am using jquery  which uses  as default. Unfortunately I based my system on that and when I needed a complex object as a  I couldn't just make it happen.In my case I am trying to send user preferences with something like;On client side the actual raw data sent to the server is; parsed as;and the server side is;I tried , added setter/getters, constructors with all possibilities to  but no chance as it recognized the sent data as 5 parameters but in fact the mapped method has only 2 parameters. I also tried Biju's solution however what happens is that, spring creates an UserPreferences object with default constructor and doesn't fill in the data.I solved the problem by sending JSon string of the preferences from the client side and handle it as if it is a String on the server side;client:server:to brief, I did the conversion manually inside the REST method. In my opinion the reason why spring doesn't recognize the sent data is the content-type.
Java

What are .jspf files in JSP? As I know the compiler will look for .jsp files to compile, then how are the .jspf files compiled?As others have noted, .jspf files are JSP fragments. They're designed to be statically included in another JSP file, not compiled on their own:You'll note that this example comes from the  directory. This means that it is not accessible outside of the web application; there's no way to construct a URL that can retrieve it. If you put them in the same directory as \"normal\" JSP files, you can construct such a URL; Tomcat, for example will retrieve the page as a text document. A front-end web-server, however, can block these URLS.I like JSPF files as a first step in . Since they're statically included, you can extract a small chunk of the file without making provision for scriptets or variables, leading to pages that are somewhat more maintainable (and I want to stress, it's a  step; dynamic includes and taglibs are usually a better long-term solution). When refactoring, I believe in keeping the fragments close to their parent files; this is when having a web-server to block URLs becomes useful.JSP Fragments can be compared to server side includes. These fragments are not compiled on their own, however there are compiled along side the page in which its included. If I've to display different pages base on a user preference, i will opt for jspf. .jspf files are generally files that are included in .jsp files via the include directive. The 'f' stands for 'fragment' as these files are not full JSPs in and of themselves.  Since .jspf is a fragment of a jsp hence it may not be complete and compilable source, so most of the time it can't be compiled independently of another, complete, source that references them. :  that .jspf is for JSP fragments. A fragment may not be complete and compilable source, so they likely can't be compiled independently of another, complete, source that references them.They're mentioned in  in the same context - a naming convention for JSP Fragments.In many web frameworks, it's possible to assemble views and pages from smaller, shared views and pages. Using JSP, these smaller pieces are called . As the name implies, they're not necessarily a complete representation without some larger context.Other languages and frameworks have their own term for the equivalent concept. In Ruby on Rails, for example, they're called .
Java

I have a crazy question about Java switches.Scenario 1 - When the  is two it successfully print the value as 2.\nScenario 2 - When I'm going to comment  in  it squawks saying the .Questions : \nScenario 1 : If the execution flow doesn't go to  (when the ), then how does it know the type of the value variable as ?\nScenario 2 : If the compiler knows the type of the value variable as , then it must have accessed to the  expression in .(Declaration and Initialization). Then why does it sqawrk When I'm going to comment  in , saying the .Switch statements are odd in terms of scoping, basically. From :In your case,  is in the same  as  and appears after it, even though  will never execute... so the local variable is in scope and available for  despite you logically never \"executing\" the declaration. (A declaration isn't really \"executable\" although initialization is.)If you comment out the  assignment, the compiler still knows which variable you're referring to, but you won't have gone through any execution path which assigns it a value, which is why you get an error as you would when you try to read any other not-definitely-assigned local variable.I would strongly recommend you  to use local variables declared in other cases - it leads to highly confusing code, as you've seen. When I introduce local variables in switch statements (which I try to do rarely - cases should be very short, ideally) I usually prefer to introduce a new scope:I believe this is clearer.The variable has been declared (as an int), but not initialized (assigned an initial value).  Think of the line:As:The  part tells the compiler at compile time that you have a variable called value which is an int. The  part initializes it, but that happens at run-time, and doesn't happen at all if that branch of the switch isn't entered.From  
Java

I'm having trouble with a brand new project in a brand new installation of Eclipse. Repro steps:Expected: Brand new project works fine.Actual: There are two errors:What am I doing wrong here? Perhaps I don't actually have the Java 7 JDK on my machine. How can I be sure? Looks like Java 7 is in fact not out yet. Sweet. 1) Find out where java is installed on your drive, open a cmd prompt, go to that location and run \".\\java -version\" to find out the exact version. Or, quite simply, check the add/remove module in the control panel.2) After you actually install jdk 7, you need to tell Eclipse about it. Window -> Preferences -> Java -> Installed JREs.To set JDK you can watch this video : \n. Then when you'll have JDK:1)Go to configure build path . \n2)Remove unbound JRE library .\n3)Add library --> JRE System library .Then project compile and done .. Have you actually downloaded and installed one of the milestone builds from  ?You can have a play with the features, though it's not stable so you shouldn't be releasing software against them.Most of the time after the installation of Eclipse eclipse.ini is changed.\nIf you change the jdk in eclipse.ini then eclipse will use this jdk by default.Let's say you install a new version of Eclipse and you have forgotten to change the eclipse.ini related to the jdk. Then Eclipse finds a jdk for you.\nLet's say it is java 1.6 that was automatically discovered (you did nothing).If you use maven (M2E) and you reference a 1.7 jdk then you will see the frustrating message.\nBut normally it is not displayed because you configure the correct jdk in eclipse.ini.That was my case. I made reference into the pom to a jdk that was not configured into Eclipse.In the screenshot you can see that 1.7 is configured and seen by Eclipse. In this case, you should make reference into the pom to a jre that is compatible with 1.7! If not -> frustrating message!Cause : This is common scenario when we import new project with different lib and JAR path. I faced this issue and got resolved using exact following steps:This will point your system's proper & valid JRE path, which did thing for me.\nUpdated  file with key-value property to because, that is my JAVA version. Also, selected  as my project libraryUpdated eclipse.ini file with key value property\n-Dosgi.requiredJavaVersion=1.7 (or) 1.8 whichever applicable. \n- it works for me. 
Java

in the case of using PreparedStatement with a single common connection without any pool, can I recreate an instance for every dml/sql operation mantaining the power of prepared statements? I mean:instead of:my question arises by the fact that I want to put this code into a multithreaded environment, can you give me some advice? thanksThe second way is a tad more efficient, but a much better way is to execute them in batches:You're however dependent on the JDBC driver implementation how many batches you could execute at once. You may for example want to execute them every 1000 batches:As to the multithreaded environments, you don't need to worry about this if you acquire and close the connection and the statement in the shortest possible scope  according the normal JDBC idiom using  statement as shown in above snippets.If those batches are transactional, then you'd like to turn off autocommit of the connection and only commit the transaction when all batches are finished. Otherwise it may result in a dirty database when the first bunch of batches succeeded and the later not.The loop in your code is only an over-simplified example, right?It would be better to create the PreparedStatement only once, and re-use it over and over again in the loop.In situations where that is not possible (because it complicated the program flow too much), it is still beneficial to use a PreparedStatement, even if you use it only once, because the server-side of the work (parsing the SQL and caching the execution plan), will still be reduced.To address the situation that you want to re-use the Java-side PreparedStatement, some JDBC drivers (such as Oracle) have a caching feature: If you create a PreparedStatement for the same SQL on the same connection, it will give you the same (cached) instance.About multi-threading: I do not think JDBC connections can be shared across multiple threads (i.e. used concurrently by multiple threads) anyway.Every thread should get his own connection from the pool, use it, and return it to the pool again.
Java

Suppose I have a method that returns a read-only view into a member list:Further suppose that all the client does is iterate over the list once, immediately. Maybe to put the players into a JList or something. The client does  store a reference to the list for later inspection!Given this common scenario, should I return a stream instead?Or is returning a stream non-idiomatic in Java? Were streams designed to always be \"terminated\" inside the same expression they were created in?The answer is, as always, \"it depends\".  It depends on how big the returned collection will be.  It depends on whether the result changes over time, and how important consistency of the returned result is.  And it depends very much on how the user is likely to use the answer.  First, note that you can always get a Collection from a Stream, and vice versa:So the question is, which is more useful to your callers.  If your result might be infinite, there's only one choice: Stream.If your result might be very large, you probably prefer Stream, since there may not be any value in materializing it all at once, and doing so could create significant heap pressure.If all the caller is going to do is iterate through it (search, filter, aggregate), you should prefer Stream, since Stream has these built-in already and there's no need to materialize a collection (especially if the user might not process the whole result.)  This is a very common case.  Even if you know that the user will iterate it multiple times or otherwise keep it around, you still may want to return a Stream instead, for the simple fact that whatever Collection you choose to put it in (e.g., ArrayList) may not be the form they want, and then the caller has to copy it anyway.  if you return a stream, they can do  and get it in exactly the form they want.The above \"prefer Stream\" cases mostly derive from the fact that Stream is more flexible; you can late-bind to how you use it without incurring the costs and constraints of materializing it to a Collection.  The one case where you must return a Collection is when there are strong consistency requirements, and you have to produce a consistent snapshot of a moving target.  Then, you will want put the elements into a collection that will not change.So I would say that most of the time, Stream is the right answer -- it is more flexible, it doesn't impose usually-unnecessary materialization costs, and can be easily turned into the Collection of your choice if needed.  But sometimes, you may have to return a Collection (say, due to strong consistency requirements), or you may want to return Collection because you know how the user will be using it and know this is the most convenient thing for them.  I have a few points to add to .It's quite common to return a Stream from a \"getter\" style method call. See the  in the Java 8 javadoc and look for \"methods... that return Stream\" for the packages other than . These methods are usually on classes that represent or can contain multiple values or aggregations of something. In such cases, APIs typically have returned collections or arrays of them. For all the reasons that Brian noted in his answer, it's very flexible to add Stream-returning methods here. Many of these classes have collections- or array-returning methods already, because the classes predate the Streams API. If you're designing a new API, and it makes sense to provide Stream-returning methods, it might not be necessary to add collection-returning methods as well.Brian mentioned the cost of \"materializing\" the values into a collection. To amplify this point, there are actually two costs here: the cost of storing values in the collection (memory allocation and copying) and also the cost of creating the values in the first place. The latter cost can often be reduced or avoided by taking advantage of a Stream's laziness-seeking behavior. A good example of this are the APIs in :Not only does  have to hold the entire file contents in memory in order to store it into the result list, it also has to read the file to the very end before it returns the list. The  method can return almost immediately after it has performed some setup, leaving file reading and line breaking until later when it's necessary -- or not at all. This is a huge benefit, if for example, the caller is interested only in the first ten lines:Of course considerable memory space can be saved if the caller filters the stream to return only lines matching a pattern, etc.An idiom that seems to be emerging is to name stream-returning methods after the plural of the name of the things that it represents or contains, without a  prefix. Also, while  is a reasonable name for a stream-returning method when there is only one possible set of values to be returned, sometimes there are classes that have aggregations of multiple types of values. For example, suppose you have some object that contains both attributes and elements. You might provide two stream-returning APIs:That is how they are used in most examples.  Note: returning a Stream is not that different to returning a Iterator (admitted with much more expressive power)IMHO the best solution is to encapsulate why you are doing this, and not return the collection.e.g.or if you intend to count themI think it depends on your scenario. May be, if you make your  implement , it is sufficient. or in the a functional style:But if you want a more complete and fluent api, a stream could be a good solution. I would probably have 2 methods, one to return a  and one to return the collection as a .This is the best of both worlds.  The client can choose if they want the List or the Stream and they don't have to do the extra object creation of making an immutable copy of the list just to get a Stream.This also only adds 1 more method to your API so you don't have too many methods
Java

We have a Java-application that needs to be brought to the foreground when a telecontrol mechanism activates something in the application.In order to get this we have realised in the called method of the Class which represents the Frame of our application (extension of a JFrame) following implementation:Under Windows XP this works the first time it is called, on the second time only the tab in the taskbar flashes, the frame doesn't come to the front anymore. Same goes for Win2k. On Vista it seems to work fine.Anyone ideas?A possible solution is:I had the same problem with bringing a  to the front under Ubuntu (Java 1.6.0_10). And the only way I could resolve it is by providing a . Specifically, I had to set my  to always stay on top whenever  is invoked, and provide  event handler to . So, here is the code that could be placed into a base , which is used to derive all application frames.Whenever your frame should be displayed or brought to front call .Since I moved to Ubuntu 9.04 there seems to be no need in having a  for invoking  -- as can be observed; this code was moved to the methods  and .Please note that method  should always be invoked on EDT.Windows has the facility to prevent windows from stealing focus; instead it flashes the taskbar icon.  In XP it's on by default (the only place I've seen to change it is using TweakUI, but there is a registry setting somewhere).  In Vista they may have changed the default and/or exposed it as a user accessible setting with the out-of-the-box UI.Preventing windows from forcing themselves to the front and taking focus is a feature since Windows 2K (and I, for one, am thankful for it).That said, I have a little Java app I use to remind me to record my activities while working, and it makes itself the active window every 30 minutes (configurable, of course).  It always works consistently under Windows XP and never flashes the title bar window.  It uses the following code, called in the UI thread as a result of a timer event firing:(the first line restores if minimized... actually it would restore it if maximized too, but I never have it so).While I usually have this app minimized, quite often it's simply behind my text editor.  And, like I said, it always works.I do have an idea on what your problem could be - perhaps you have a race condition with the setVisible() call.  toFront() may not be valid unless the window is actually displayed when it is called; I have had this problem with requestFocus() before.  You may need to put the toFront() call in a UI listener on a window activated event. At some point in time the above code stopped working, perhaps at Java 6 or 7. After some investigation and experimentation I had to update the code to override the window's  method do this (in conjunction with modified code from what is above):As of Java 8_20, this code seems to be working fine.Here's a method that REALLY works (tested on Windows Vista) :DThe fullscreen variable indicates if you want the app to run full screen or windowed.This does not flash the task bar, but bring the window to front reliably.Hj, all methods of yours are not working for me, in Fedora KDE 14. I have a dirty way to do bring a window to front, while we're waiting for Oracle to fix this issue.And, this works perfectly in my Fedora KDE 14  :-)This simple method worked for me perfectly in Windows 7:I tested your answers and only  worked for me. Although I couldn't manage to restore the window to its previous state (maximized/normal). I found this mutation better:That is  instead of .Simplest way I've found that doesn't have inconsistency across platforms:setVisible(false);\nsetVisible(true);The rules governing what happens when you .toFront() a JFrame are the same in windows and in linux :-> if a window of the existing application is currently the focused window, then focus swaps to the requested window\n-> if not, the window merely flashes in the taskbarBUT : -> new windows automatically get focusSo let's exploit this ! You want to bring a window to the front, how to do it ? Well :Or, in java code :There are numerous  in the javadoc for the toFront() method which may be causing your problem. But I'll take a guess anyway, when \"only the tab in the taskbar flashes\", has the application been minimized? If so the following line from the javadoc may apply:\"If this Window is visible, brings this Window to the front and may make it the focused Window.\" To avoid the window losing focus when its returning to visible after being hidden all that is needed is:Like so:
Java

I'm using google-api-client-java 1.2.1-alpha to execute a POST request, and am getting the following stacktrace when I execute() the HttpRequest.  It happens immediately after I catch and ignore a 403 error from a previous POST to the same URL, and re-used the transport for the subsequent request.  (It's in a loop inserting multiple entries to the same ATOM feed).Is there something I should be doing to 'clean up' after a 403?Why would the code below me be trying to acquire a  connection?You need to consume the response body before you can reuse the connection for another request. You should not only read the response status, but read the response  fully to the last byte whereby you just ignore the read bytes.I was facing a similar issue when using the HttpClient with Jetty to build a test framework. I had to create multiple requests to the Servelet from my client, but It was giving the same exception when executed.I found an alternative at You can also use this following method to instantiate your client. A similar exception message (since at least Apache Jarkata Commons HTTP Client 4.2) is:  This exception can happen when two or more threads interact with a single .How can you make a 4.2  instance threadsafe ( in the sense that two or more threads can interact with it without getting above error message)? Provide  with a connection-pooling  in the form of !This is an often-asked question.  BalusC's response is correct.  Please catch , and call HttpResponseException..().  If you need to read the error message, use response.() if you don't know the response content type, else if you do know the content type use response.(MyType.class).A simple code snippet from  in  (though usually you'll want to do something smarter in a real application):Full disclosure: I am an owner of the  project.I had the same issue with a jax-rs (resteasy)  object in my unit tests.\nI solved this with a call to \nThe releaseConnection()-Method is only on the resteasy  object, so I had to add a cast from  to .Ok, i have similar problem, all those solution not work, i tested on some device, problem was date in device, it was 2011 instead 2013, check also this can help. Try thisRead the InputStream like this:
Java

I often find when debugging a program it is convenient, (although arguably bad practice) to insert a return statement inside a block of code. I might try something like this in Java ....of course, this would yield the compiler error.I could understand why a warning might be justified as having unused code is bad practice. But I don't understand why this needs to generate an error. Is this just Java trying to be a Nanny, or is there a good reason to make this a complier error?Because unreachable code is meaningless to the compiler. Whilst making code meaningful to people is both paramount and harder than making it meaningful to a compiler, the compiler is the essential consumer of code. The designers of Java take the viewpoint that code that is not meaningful to the compiler is an error. Their stance is that if you have some unreachable code, you have made a mistake that needs to be fixed.There is a similar question here: , in which the author says \"Personally I strongly feel it should be an error: if the programmer writes a piece of code, it should always be with the intention of actually running it in some scenario.\" Obviously the language designers of Java agree.Whether unreachable code should prevent compilation is a question on which there will never be consensus. But this is why the Java designers did it.A number of people in comments point out that there are many classes of unreachable code Java doesn't prevent compiling. If I understand the consequences of G\u00f6del correctly, no compiler can possibly catch all classes of unreachable code.Unit tests cannot catch every single bug. We don't use this as an argument against their value. Likewise a compiler can't catch all problematic code, but it is still valuable for it to prevent compilation of bad code when it can.The Java language designers consider unreachable code an error. So preventing it compiling when possible is reasonable.(Before you downvote: the question is not whether or not Java should have an unreachable statement compiler error. The question is  Java has an unreachable statement compiler error. Don't downvote me just because you think Java made the wrong design decision.)There is no definitive reason why unreachable statements must be not be allowed; other languages allow them without problems. For your specific need, this is the usual trick:It looks nonsensical, anyone who reads the code will guess that it must have been done deliberately, not a careless mistake of leaving the rest of  statements unreachable.Java has a little bit support for \"conditional compilation\"It is Nanny. \nI feel .Net got this one right - it raises a warning for unreachable code, but not an error. It is good to be warned about it, but I see no reason to prevent compilation (especially during debugging sessions where it is nice to throw a return in to bypass some code). I only just noticed this question, and wanted to add my $.02 to this.In case of Java, this is not actually an option. The \"unreachable code\" error doesn't come from the fact that JVM developers thought to protect developers from anything, or be extra vigilant, but from the requirements of the JVM specification.Both Java compiler, and JVM, use what is called \"stack maps\" - a definite information about all of the items on the stack, as allocated for the current method. The type of each and every slot of the stack must be known, so that a JVM instruction doesn't mistreat item of one type for another type. This is mostly important for preventing having a numeric value ever being used as a pointer. It's possible, using Java assembly, to try to push/store a number, but then pop/load an object reference. However, JVM will reject this code during class validation,- that is when stack maps are being created and tested for consistency.To verify the stack maps, the VM has to walk through all the code paths that exist in a method, and make sure that no matter which code path will ever be executed, the stack data  for every instruction agrees with what any previous code has pushed/stored in the stack. So, in simple case of:at line 3, JVM will check that both branches of 'if' have only stored into a (which is just local var#0) something that is compatible with Object (since that's how code from line 3 and on will treat local var#0).When compiler gets to an unreachable code, it doesn't quite know what state the stack might be at that point, so it can't verify its state. It can't quite compile the code anymore at that point, as it can't keep track of local variables either, so instead of leaving this ambiguity in the class file, it produces a fatal error.Of course a simple condition like  will fool it, but it's not really fooling - it's giving it a potential branch that can lead to the code, and at least both the compiler and the VM can determine, how the stack items can be used from there on.P.S. I don't know what .NET does in this case, but I believe it will fail compilation as well. This normally will not be a problem for any machine code compilers (C, C++, Obj-C, etc.)One of the goals of compilers is to rule out classes of errors.  Some unreachable code is there by accident, it's nice that javac rules out that class of error at compile time.For every rule that catches erroneous code, someone will want the compiler to accept it because they know what they're doing.  That's the penalty of compiler checking, and getting the balance right is one of the tricker points of language design.  Even with the strictest checking there's still an infinite number of programs that can be written, so things can't be that bad.While I think this compiler error is a good thing, there is a way you can work around it.\nUse a condition you know will be true:The compiler is not smart enough to complain about that.It is certainly a good thing to complain the more stringent the compiler is the better, as far as it allows you to do what you need.\nUsually the small price to pay is to comment the code out, the gain is that when you compile your code works. A general example is Haskell about which people screams until they realize that their test/debugging is main test only and short one. I personally in Java do almost no debugging while being ( in fact on purpose) not attentive.If the reason for allowing  is to allow flags, then the fact that  does not generate a compile time error seems like inconsistency in the policy of generating CodeNotReachable exception, since the compiler 'knows' that  is not a flag (not a variable).Two other ways which might be interesting, but don't apply to switching off part of a method's code as well as :Now, instead of saying  you might want to say  and add  to the jvm arguments. The good point is that this allows for some granularity and requires adding an extra parameter to the jvm invocation so there is no need of setting a DEBUG flag in the code, but by added argument at runtime, which is useful when the target is not the developer machine and recompiling & transferring bytecode takes time.There is also the  way, but this might be an overkill, if you put it in Java in a JSP then it will terminate the server.Apart from that Java is by-design a 'nanny' language, I would rather use something native like C/C++ for more control.
Java

I'm relatively new to the Maven mantra, but I'm trying to build a command-line runnable jar with Maven. I've setup my dependencies, but when I run  and attempt to run the jar, two things happen. First, no main class is found, which is correctable. When I've corrected this, I get errors on run stating that classes cannot be found.Maven is not packaging my dependency libraries inside of the jar, so I am unable to run the jar as a stand-alone application. How do I correct this?The easiest way to do this would be to create an assembly using the  and the predefined  descriptor. You'll also need to generate a manifest with a main-class entry for this uber jar. The snippet below shows how to configure the assembly plugin to do so:Then, to generate the assembly, just run:If you want to generate the assembly as part of your build, simply bind the  mojo to the package phase:And simply run:Maven is not packaging your dependencies inside your jar file, because you don't usually do this with Java programs.Instead you deliver the dependencies together with your jar file and mention them in .To go this route, you'll need to enable the  property (documented ) for the .If you really want to include all your dependencies in your jar file, then you can use the Maven Assembly plugin to create a .This is what I would do for small projects. Most of the time you don't want one huge jar.\nmvn clean dependency:copy-dependencies package\njava -cp myjar.jar:./dependency/* com.something.MyClassI Agree with Joachim Sauer, Instead of using jar-with-dependency you should configure the jar plugin like that in your pom.xml:And use this assembly configuration to add the jar dependencies to you assembly:Just add the below code in pom.xml and Run as: maven:install . The jar will be created in target folder of eclipse which can be used as \"java -jar Hello.jar\" . but make sure that name of main class is given com.abc.HelloWorld.javaUse onejar plugin: It creates a runnable jar file that include all your dependencies.
Java

I have an ArrayList that I want to iterate over it. While iterating over it I have to remove elements at the same time. Obviously this throws a .What is the best practice to handle this problem? Should I clone the list first?I remove the elements not in the loop itself but another part of the code.My code looks like this:a.doSomething might call Test.removeA();Two options:As an example of the second option, removing any strings with a length greater than 5 from a list:From the JavaDocs of the ArrayListOne option is to modify the  method to this -But this would mean your  should be able to pass the  to the  method. Not a very good idea.Can you do this in two step approach : \n In the first loop when you iterate over the list , instead of removing the selected elements ,  them as . For this , you may simply copy these elements ( shallow copy ) into another .Then , once your iteration is done , simply do a  from the first list all elements in the second list.Here is an example where I use a different list to add the objects for removal, then afterwards I use stream.foreach to remove elements from original list :Do somehting simple like this:You should really just iterate back the array in the traditional wayEvery time you remove an element from the list, the elements after will be push forward. As long as you don't change elements other than the iterating one, the following code should work.You are trying to remove value from list in advanced \"for loop\", which is not possible, even if you apply any trick (which you did in you code).\nBetter way is to code iterator level as other advised here.I wonder how people have not suggested traditional for loop approach.This works as well.\"Should I clone the list first?\"That will be the easiest solution, remove from the clone, and copy the clone back after removal.An example from my rummikub game:In Java 8 you can use the Collection Interface and do this by calling the removeIf method:More information can be found 
Java

In Java, I'm dynamically creating a set of files and I'd like to change the file permissions on these files on a linux/unix file system.  I'd like to be able to execute the Java equivalent of . Is that possible Java 5? If so, how?I know in Java 6 the File object has setReadable()/setWritable() methods.   I also know I could make a system call to do this, but I'd like to avoid that if possible.  Full control over file attributes is available in Java 7, as part of the \"new\" New IO facility (). For example, POSIX permissions can be set with In earlier versions of Java, using native code of your own, or -ing command-line utilities are common approaches.In addition to erickson's suggestions, there's also , which allows you to call native libraries without using jni.  It's shockingly easy to use, and I've used it on a couple of projects with great success.  The only caveat is that it's slower than jni, so if you're doing this to a very large number of files that might be an issue for you.(Editing to add example)Here's a complete jna chmod example:for windows 7 with nio 2.0:Prior to Java 6, there is no support of file permission update at Java level. You have to implement your own native method or call  to execute OS level command such as .Starting from Java 6, you can use to set file permissions. But it doesn't simulate the POSIX file system which allows to set permission for different users. File.setXXX() only allows to set permission for owner and everyone else.Starting from Java 7, POSIX file permission is introduced. You can set file permissions like what you have done on *nix systems. The syntax is :This method can only be used on POSIX file system, this means you cannot call it on Windows system.For details on file permission management, recommend you to read .for Oralce Java 6:works under solaris/linux.You can use the methods of the File class: \nIn addition to erickson's answer here a helpful link with working code examples on using PosixFilePermissions:If you want to set 777 permission to your created file than you can use following method:Apache ant chmod (not very elegant, adding it for completeness) credit shared with @msorskyReference : There is an  which works very much similar to the UNIX chmod. It works with java se 7+ though.
Java

Is there any advantage of using instead of? As far as I can tell the following fragments are almost equivalent:Except that in case #2 the latch cannot be reused and more importantly you need to know in advance how many threads will be created (or wait until they are all started before creating the latch.)So in what situation might the latch be preferable?CountDown latch is frequently used for the exact opposite of your example. Generally, you would have many threads blocking on \"await()\" that would all start simultaneously when the countown reached zero.You could also use this as an MPI-style \"barrier\" that causes all threads to wait for other threads to catch up to a certain point before proceeding.That all said, the CountDown latch can safely be used in the manner you've shown in your example. is used to start a series of threads and then wait until all of them are complete (or until they call  a given number of times.Semaphore is used to control the number of concurrent threads that are using a resource. That resource can be something like a file, or could be the cpu by limiting the number of threads executing. The count on a Semaphore can go up and down as different threads call  and .In your example, you're essentially using Semaphore as a sort of CountLatch. Given that your intent is to wait on all threads finishing, using the  makes your intention clearer. definition from javadocs:However, no actual permit objects are used; the  just keeps a count of the number available and acts accordingly. Semaphores are used to control the number of concurrent threads that are using a resource.That resource can be something like a shared data, or a block of code () or any file. The count on a Semaphore can go up and down as different threads call () and (). But at any point of time, you can't have more number of threads greater than Semaphore count. Have a look at this  for semaphore uses. definition from javadocs: works by having a counter initialized with number of threads, which is decremented each time a thread complete its execution. When count reaches to zero, it means all threads have completed their execution, and thread waiting on latch resume the execution.Have a look at this  to understand CountDownLatch concepts clearly.Have a look at  at this  too. It has some similarities to .Say you walked in to golf pro shop, hoping to find a foursome,When you stand in line to get a tee time from one of the pro shop attendants, essentially you called , once you get a tee time, you called .Note: any of the free attendants can service you, i.e. shared resource.Now you walk up to starter, he starts a  and calls  to wait for others, for your part you called checked-in i.e. . and so does rest of the foursome. When all arrive, starter gives go ahead( call returns)Now, after nine holes when each of you take a break, hypothetically lets involve starter again, he uses a 'new'  to tee off Hole 10, same wait/sync as Hole 1.However, if the starter used a  to begin with, he could have reset the same instance in Hole 10 instead of a second latch, which use & throw.Looking at the freely available source, there is no magic in the implementation of the two classes, so their performance should be much the same. Choose the one that makes your intent more obvious.CountdownLatch makes threads wait on the await() method, until such a time as the count has reached zero.  So maybe you want all your threads to wait until 3 invocations of something, then all the threads can go.  A Latch generally can not be reset.A Semaphore allows threads to retrieve permits, which prevents too many threads from executing at once, blocking if it cannot get the permit(s) it requires to proceed.  Permits can be returned to a Semaphore allowing the other waiting threads to proceed.
Java

I'm rolling J2EE code that adheres to Servlet 2.5 and I'm wondering what are the major differences between 2.5 and 3. Pointers to official Sun docs and personal experiences are most appreciated.If I shouldn't be concerning myself with 3 for the time being, just say so. Thanks!UPDATEJust as an update and to be more explicit, these are the main differences between servlets 2.5 and 3 (I'm not trying to be exhaustive, I'm just mentioning the most interesting parts):In servlets 2.5, to declare a servlet with one init parameter you need to add this to :In servlets 3,  is optional and you can use annotations instead of XML. The same example:For filters, you need to add this in  in servlets 2.5:Equivalent using annotations in servlets 3:For a listener (in this case a ServletContextListener), in servlets 2.5:The same using annotations:In servlets 3, a  can add dynamically servlets, filters and listeners using the following methods added to : ,  and Example: say that some servlet container has five threads in its thread pool, and there is a time-consuming process to be executed per request (like a complex SQL query).An example of asynchronous support:Servlets 2.5:Servlets 3:The interface  also has methods to get the request object, response object and add listeners to notify them when a process has finished.In servlets 3, the interface  has been added two new methods:  and .For more details, have a look at the .Servlet 3.0 has not yet been released, but it looks like it's very close. The most important changes in 3.0 are: Pluggability, Ease of development, Async Servlet, Security. Whether or not these are important to you is impossible for me to say.The most significant of these is probably the support for asynchronous Servlets. Here's  that describes this in detail. The full specification can be downloaded .As Don mentioned, the main areas of improvements and additions are:Check out the Javaone 2008 presentation \"\" for details.Servlet 3 supports annotation to eliminate 
Java

I'm loading a text file from within a package in a compiled JAR of my Java project. The relevant directory structure is as follows:The code being used to load the file is:The print out will always print , no matter what I use. I'm not sure why the above wouldn't work, so I've also tried:Neither of these work.     so far on the topic, but none of them have been helpful - usually, they just say to load files using the root path, which I'm already doing. That, or just load the file from the current directory (just load ), which I've also tried. The file is being compiled into the JAR in the appropriate location with the appropriate name. How do I solve this? loads resources using system class loader, it obviously fails because it does not see your JARs loads resources using the same class loader that loaded Lifepaths class and it should have access to resources in your JARsThe rules are as follows:And try:instead of(not sure if it makes a difference, but the former will use the correct ClassLoader/ JAR, while I'm not sure with the latter)So there are several ways to get a resource from a jar and each has slightly different syntax where the path needs to be specified differently.The best explanation I have seen is this article from . I'll summarize here, but if you want to know more you should check out the article.Methods1) .  Format: \"/\"-separated names; no leading \"/\" (all names are absolute). Example: 2) Format: \"/\"-separated names; leading \"/\" indicates absolute names; all other names are relative to the class's packageExample: Don't use absolute paths, make them relative to the 'resources' directory in your project. Quick and dirty code that displays the contents of MyTest.txt from the directory 'resources'.You might want to try this to get the stream i.e first get the url and then open it as stream. I once had a similar question: There seems to be issue with the ClassLoader that you are using. Use the contextClassLoader to load class.  This is irrespective of whether it is in a static/non-static method......Don't know if of help, but in my case I had my resource in the /src/ folder and was getting this error.\nI then moved the picture to the bin folder and it fixed the issue.Make sure your resource directory (e.g. \"src\") is in your classpath (make sure it's a source directory in your build path in eclipse).Make sure clazz is loaded from the main classloader.Then, to load src/initialization/Lifepaths.txt, use Why:\n looks up foo from , . The leading \"/\" makes it load from the root of any directory in the classpath of clazz.Unless you're in a container of some kind, like Tomcat, or are doing something with ClassLoaders directly, you can just treat your eclipse/command line classpath as the only classloader classpath.What worked for me was to add the file under My Project/Java Resources/src and then use I didn't need to explicity add this file to the path (adding it to /src does that apparently)I found myself in a similar issue. Since I am using maven I needed to update my pom.xml to include something like this:Note the resource tag in there to specify where that folder is. If you have nested projects (like I do) then you might want to get resources from other areas instead of just in the module you are working in. This helps reduce keeping the same file in each repo if you are using similar config data @Emracool... I'd suggest you an alternative. Since you seem to be trying to load a *.txt file. Better to use  rather then this annoying  or . At least your code will execute properly.  
Java

I have How can i retrieve the session if am using entitymanager or how can i get the result from my detachedcriteria ?To be totally exhaustive, things are different if you're using a JPA 1.0 or a JPA 2.0 implementation.With JPA 1.0, you'd have to use . But keep in mind that   i.e. non portable from application server using Hibernate to the other. For example  you would do:But , you'd have to do:I agree, that's horrible, and the spec is to blame here (not clear enough).With JPA 2.0, there is a new (and much better)  method that is to be preferred over  for new applications.So with Hibernate as JPA 2.0 implementation (see ), you would do:See the section \"\" in the :This will explain better.
Java

I am looking at an algorithm that can map between characters with diacritics (, , , , ) and their \"simple\" character.For example:Etc.I have done this recently in Java:This will do as you specified:but it will fail on for example Bia\u0142ystok, because the  character is not diacritic.If you want to have a full-blown string simplifier, you will need a second cleanup round, for some more special characters that are not diacritics. Is this map, I have included the most common special characters that appear in our customer names. It is not a complete list, but it will give you the idea how to do extend it. The immutableMap is just a simple class from google-collections.The core java.text package was designed to address this use case (matching strings without caring about diacritics, case, etc.).Configure a  to sort on  differences in characters. With that, create a  for each string. If all of your code is in Java, you can use the  directly. If you need to store the keys in a database or other sort of index, you can .These classes use the  case folding data to determine which characters are equivalent, and support various  strategies.Note that collators are locale-specific. This is because \"alphabetical order\" is differs between locales (and even over time, as has been the case with Spanish). The  class relieves you from having to track all of these rules and keep them up to date.It's part of  as of ver. 3.1.returns You could use the  from :But there is still some work to do, since Java makes strange things with unconvertable Unicode characters (it does not ignore them, and it does not throw an exception). But I think you could use that as an starting point.There is a  on character folding on the unicode website which has a lot of relevant material. See specifically Section 4.1. \"Folding algorithm\".Here's a  of diacritic marker removal using Perl.These existing SO questions are related:Please note that not all of these marks are just \"marks\" on some \"normal\" character, that you can remove without changing the meaning.In Swedish, \u00e5 \u00e4 and \u00f6 are true and proper first-class characters, not some \"variant\" of some other character. They sound different from all other characters, they sort different, and they make words change meaning (\"m\u00e4tt\" and \"matt\" are two different words).Unicode has specific diatric characters (which are composite characters) and a string can be converted so that the character and the diatrics are separated. Then, you can just remove the diatricts from the string and you're basically done.For more information on normalization, decompositions and equivalence, see The Unicode Standard at the .However, how you can actually achieve this depends on the framework/OS/... you're working on. If you're using .NET, you can use the  method accepting the  enumeration.The easiest way (to me) would be to simply maintain a sparse mapping array which simply changes your Unicode code points into displayable strings.Such as:The use of a  array will allow you to efficiently represent replacements even when they in widely spaced sections of the Unicode table. String replacements will allow arbitrary sequences to replace your diacritics (such as the  grapheme becoming ).This is a language-agnostic answer so, if you have a specific language in mind, there will be better ways (although they'll all likely come down to this at the lowest levels anyway).Something to consider: if you go the route of trying to get a single \"translation\" of each word, you may miss out on some possible alternates.For instance, in German, when replacing the \"s-set\", some people might use \"B\", while others might use \"ss\".  Or, replacing an umlauted o with \"o\" or \"oe\".  Any solution you come up with, ideally, I would think should include both.In Windows and .NET, I just convert using string encoding. That way I avoid manual mapping and coding. Try to play with string encoding.In case of German it's not wanted to remove diacritics from Umlauts (\u00e4, \u00f6, \u00fc).\nInstead they are replaced by two letter combination (ae, oe, ue)\nFor instance, Bj\u00f6rn should be written as Bjoern (not Bjorn) to have correct pronounciation.For that I would have rather a hardcoded mapping, where you can define the replacement rule individually for each special character group.For future reference, here is a C# extension method that removes accents.
Java

Does maven require a connection to the internet at some point to be able to use it? Meaning specifically getting the internal maven plugins for compiling, cleaning, packaging, etc? You can run maven in offline mode . Of course any artifacts not available in your local repository will fail. Maven is not predicated on distributed repositories, but they certainly make things more seamless. Its for this reason that many shops use internal mirrors that are incrementally synced with the central repos. In addition, the  can be used to ensure you have all of your dependencies installed locally before you begin to work offline.If you have a PC with internet access in your LAN, you should install a local Maven repository.I recommend . This is what we use in our organization, it is really easy to setup.After setting up Artifactory you just need to change Maven's  in the development machines:We used this solution because we had problems with internet access in our development machines and some artifacts downloaded corrupted files or didn't download at all. We haven't had problems since.Maven needs the dependencies in your local repository. The easiest way to get them is with internet access (or harder using other solutions provided here).So assumed that you can get temporarily internet access you can prepare to go offline using the  with its  goal. This will download all your project dependencies to your local repository (of course changes in the dependencies / plugins will require new internet / central repository access).You have two options for this:1.) make changes in the  add this in first tag 2.) use the -o tag for offline command.Does this work for you?Don't forget to add it to your plugin repository and point the url to wherever your repository is.If not, you may need to run a local server, e.g. apache, on your machines.In preparation before working offline just run\nBefore going offline you have to make sure that everything is in your local repo, which is required while working offline. Running \"mvn dependency:go-offline\" for the project(s)/pom(s), you intend to work on, will reduce the efforts to achieve this. But it\u00b4s usually not the whole story, because dependency:go-offline will only download the \"bare build\" plugins (). So you have to find a way to download deploy / test / site plugins (and maybe others) and their dependencies into your repo.Furthermore dependency:go-offline does not download the pom\u00b4s artifact itself, so you have to dependency:copy it if required.Sometimes - as MaDa wrote - you do not know, what you will need, while being offline, which makes it pretty impossible to have a \"sufficient\" repo.Anyway having a properly filled repo you only have to add \"<offline>true</offline>\" to Maven\u00b4s settings.xml to go offline.Do not change the Maven profile (id) you used to fill your repo, while being offline. Maven recognizes the downloaded artifacts in its metadata with an \"identity\", which is bound to the profile id.The workaround has been to specify a , either within  file with  or by running  with  parameter. \nAfter initial project build, all necessary artifacts should be cached, and then you can reference repository location the same ways, while running Maven build in offline mode ().Answering your question directly: it does not require an internet connection, but access to a repository, on LAN or local disk (use hints from other people who posted here).If your project is not in a mature phase, that means when POMs are changed quite often, offline mode will be very impractical, as you'll have to update your repository quite often, too. Unless you can get a copy of a repository that has everything you need, but how would you know? Usually you start a repository from scratch and it gets cloned gradually during development (on a computer connected to another repository). A copy of the repo1.maven.org public repository weighs hundreds of gigabytes, so I wouldn't recommend brute force, either.orJust use Maven repository servers like Sonatype Nexus  or JFrog Artifactory .After one developer builds a project, build by next developers or Jenkins CI will not require Internet access.Maven repository server also can have proxies configured to access Maven Central (or more needed public repositories), and they can have cynch'ed list of artifacts in remote repositories.If you're using IntelliJ, you can simply go to  ->  ->  ->  and check/uncheck .My experience shows that the -o option doesn't work properly and that the go-offline goal is far from sufficient to allow a full offline build: The solution I could validate includes the use of the  maven option rather than the  (offline) one and\nthe use of the  in place of the In addition, I had to copy every  files of the local-repo into the  form expected by maven.See the solution I found .
Java

In case of the , What is the difference between  and third party dynamic code generation API s such as ? What is the difference between using both the approaches and when should one prefer one over another?JDK Dynamic proxy can only proxy by interface (so your target class needs to implement an interface, which will also be implemented by the proxy class).CGLIB (and javassist) can create a proxy by subclassing. In this scenario the proxy becomes a subclass of the target class. No need for interfaces.So Java Dynamic proxies can proxy:  where CGLIB can proxy: JDK proxies are implemented rather naively with only one interception dispatcher, the . This requires a virtual method dispatch to an implementation which cannot always be inlined. Cglib allows to create specialized byte code what can sometimes improve performance. Here are some comparisons for implementing an interface with 18 stub methods:The time is noted in nanoseconds with standard deviation in braces. You can find more details on the benchmark in , where Byte Buddy is a more modern alternative to cglib. Also, note that cglib is no longer under active development. Dynamic implementations of interfaces at runtime using . Spring uses dynamic proxies for transactions as follows:The generated proxy comes on top of bean. It adds transnational behavior to the bean. Here the proxy generates dynamically at runtime using JDK Reflection API.   When an application is stopped, the proxy will be destroyed and we will only have interface and bean on the file system.In the above example we have interface. But in most of implementation of interface is not best. So bean does not implement an interface, in that case we uses inheritance:In order to generate such proxies, Spring uses a third party library called .   CGLib (ode eneration rary) is built on top of , this is mainly used the generate proxy extending bean and adds bean behavior in the proxy methods.  
Java

I'm sending some parameters from a form in this way:I know I can get all the params in the controller method by adding a parameter likeI want to bind the parameters myParam[] (not the other ones) to a list or array (anything that keeps the index order), so I've tried with a syntax like:andbut none of them are binding the myParams. Even when I add a value to the map it is not able to bind the params:Is there any syntax to bind some params to a list or array without having to create an object as @ModelAttribute with a list attribute in it?ThanksArrays in  are used for binding several parameters of the same name:If you need to bind -style indexed parameters, I guess you need  anyway.Or you could just do it that way:That works for example for forms like this:This is the simplest solution :)One way you could accomplish this (in a hackish way) is to create a wrapper class for the List. Like this: Then your controller method signature would look like this:No need to use the @RequestParam or @ModelAttribute annotation if the collection name you pass in the request matches the collection field name of the wrapper class, in my example your request parameters should look like this:Just complementing what Donal Fellows said, you can use List with @RequestParamHope it helps!Subscribing what basil said in a comment to the question itself, if  then you can use @RequestParam List groupVal.Then calling the service with the list of params is as simple as:Change hidden field value with checkbox toggle like below...
Java

I am practicing for an exam, and found a sample problem that I don't understand. For the following code, find what the output is: The output of this code is , but I don't understand why. Can anyone help me?The first thing you should note is that   override 's , since the argument is  instead of , so the signatures don't match.Therefore the  method calls  exactly once - when executing  - since that's the only case in which both the static type of the instance  is executed for and the type of the argument are the  class.  is the 4th  statement (which comes after 4 increments of the static  variable), so 4 is printed.All the other  statements execute 's , and therefore print nothing.A more detailed explanation : calls 's  regardless of the type of the argument, since the static (compile time) type of  is , and the  class doesn't override that method. The  class doesn't have an  method with a single  argument, so  can't be called, regardless of the dynamic (runtime type) of . can execute either 's  or 's equals, since the compile time type of  is , and the  class has two  methods (one inherited from the  class and the other defined in the  class). The method being chosen depends on the compile time type of the argument :\n1. When the argument is  (as in  or ), 's  is called and nothing is printed.\n2. When the argument is , as in , both versions of  match that argument, but due to the rules of method overloading, the method with the most specific argument -  - is chosen and the  variable is printed.The equals method in Test takes an instance of Test.All the previous attempts have been made with an instance of Object, which take the inherrited method from the Object class:Since there is no print in there, it won't print any value.Your  will increment the value of count, so the moment when you actually call yourmethod, that does print that value, the value of count is 4. is the only line which has the right arguments that match the method signature  so it's the only line in the program which actually calls that print statement. This question is designed to teach you a few things.Essentially the trick here is that Test implicitly extends Object like all java classes do. Object contains an equals method that takes type Object. t1 and t2 are typed such that at run time the arguments never match the method signature of equals that is defined in Test. Instead it's always calling into the equals method in Object.java because either the base type Is Object in which case the only methods you have access to are the ones defined in Object.java or  the derived type is Object in which case Cannot be entered because in that case at runtime the argument is of type Object which is a Superclass of Test, not a subclass. So instead it looks at the equals method in the Test.java's implicitly typed superclass Object.java which also contains an equals method, which just happens to have a method signature of which in this case match our arguments at runtime so this equals method is the one that executes.Notice in the case of  both the base type and the derived type of t3 are Test.this means that at runtime you are calling the equals method in Test.java and the argument you are passing in is actually of type Test so the method signatures match and the code inside Test.java executes. At this point .Bonus bit of knowledge for you:annotation you may have seen in a few places explicitly instructs the compiler to fail if it does not find method with the exact same signature somewhere in a Superclass. This is useful to know if you definitely  to override a method and you want to be absolutely sure that you really are overriding the method and you haven't accidentally changed the method in either the superclass or subclass but not both and Introduced a runtime error where the wrong implementation of the method is being called causing unwanted behavior.There's two key things that you should know.
Java

Is there a way in Eclipse to select a Java class, and then bring up a list of all Java files where that class is used within a project?right-click on the class, and select references/ProjectFor searching the all workspace, ++Put the cursor on the class name (works for methods, constructors, fields, etc, too), press ++ and enjoy.
Java

I would like to have the javadoc comments contained in a jar file show in eclipse when I hover over a class.For example, after downloading JODA-2.0, three jars are obtained:In eclipse, [right click project -> Properties -> Java Build Path -> Libraries -> ADD JARs...] includes the binary in the project (can reference those classes) for joda-time-2.0.jar.But how can I link in the sources/javadoc comments contained in the other two jar files so that when I hover over those classes I see the javadocs?Adding the other two jars (joda-time-2.0-javadoc.jar and joda-time-2.0-sources.jar) to the build path does not link the javadocs or the source.You can try to CTRL + click on a class that has no source attached (do that in editor). When it shows you some info about the class you'll see the button that guides to attach source dialog. Click it and in dialog that pops up pick the source/javadoc location for your class.You can also do that from project build path settings you are mentioning: pick libraries tab, expand the library (jar) you want and you'll be offered to pick: source attachment, javadoc attachment, native library location, etc. You just pick whatever you want and edit its current settings.Or you can do as @JB Nizet said...You can also edit the classpathentry in the file \".classpath\" in your eclipse project. This can be helpful if you want to modify many entries at once or if you want to generate the path.\ne.g.:Right-click on the jar (the one with the class files), choose \"Properties\", the \"Javadoc location\", and choose the jar file with the javadoc. Do similarly for the source jar, using \"Java source attachment\".
Java

We normally create objects using the  keyword, like:Strings are objects, yet we do not use  to create them:Why is this? Can I make a String with ?In addition to what was already said, String  [ie, Strings like  but not like ] in Java are interned - this means that every time you refer to \"abcd\", you get a reference to a single  instance, rather than a new one each time.  So you will havebut if you hadthen its possible to have(and in case anyone needs reminding, always use  to compare Strings;  tests for physical equality)Interning String literals is good because they are often used more than once.  For example, consider the (contrived) code:If we didn't have interning of Strings, \"Next iteration\" would need to be instantiated 10 times, whereas now it will only be instantiated once.Strings are \"special\" objects in Java. The Java designers wisely decided that Strings are used so often that they needed their own syntax as well as a caching strategy. When you declare a string by saying:myString is a reference to String object with a value of \"something\". If you later declare:Java is smart enough to work out that myString and myOtherString are the same and will store them in a global String table as the same object. It relies on the fact that you can't modify Strings to do this. This lowers the amount of memory required and can make comparisons faster.If, instead, you writeJava will create a brand new object for you, distinct from the myString object.Hope this clears a few doubts. :)It's a shortcut. It wasn't originally like that, but Java changed it.This  talks about it briefly. The Java Specification guide talks about it also. But I can't find it online.String is subject to a couple of optimisations (for want of a better phrase). Note that String also has operator overloading (for the + operator) - unlike other objects. So it's very much a special case.In Java, Strings are a special case, with many rules that apply only to Strings.  The double quotes causes the compiler to create a String object.  Since String objects are immutable, this allows the compiler to intern multiple strings, and build a larger string pool.  Two identical String constants will always have the same object reference.  If you don't want this to be the case, then you can use new String(\"\"), and that will create a String object at runtime.  The intern() method used to be common, to cause dynamically created strings to be checked against the string lookup table.  Once a string in interned, the object reference will point to the canonical String instance.  When the classloader loads a class, all String constants are added to the String pool.Syntactic sugar. Thesyntax is still available.You can still use , but it would be harder to create new strings without string literals ... you would have to use character arrays or bytes :-) String literals have one additional property: all same string literals from any class point to same string instance (they are interned).There's almost no need to new a string as the literal (the characters in quotes) is already a String object created when the host class is loaded. It is perfectly legal to invoke methods on a literal and don, the main distinction is the convenience provided by literals. It would be a major pain and waste of tine if we had to create an array of chars and fill it char by char and them doing a new String(char array).The literal pool contains any Strings that were created without using the keyword .There is a difference : String without new reference is stored in String literal pool and String with new says that they are in heap memory.String with new are elsewhere in memory just like any other object.Output:I created two separate objects, both have a field(ref) 'Name'. So even in this case \"Jan Peter\" is shared, if I understand the way java deals..                 Feel free to create a new String with The usual notation  is more or less a convenient shortcut - which should be used for performance reasons except for those pretty rare cases, where you  need Strings that qualify for the equationIn response to the comment: this was  intended to be an advise but just an only a direct response to the questioners thesis, that  for Strings, which simply isn't true. Hope this edit (including the above) clarifies this a bit. BTW - there's a couple of good and much better answers to the above question on SO.Because String is an immutable class in java. Now why it is immutable?\nAs String is immutable so it can be shared between multiple threads and we dont need to synchronize String operation externally. \nAs String is also used in class loading mechanism. So if String was mutable then java.io.writer could have been changed to abc.xyz.mywriter
Java

I've got a question of some strange String pool behavior.\nI'm using  to compare equal Strings to find out whether they're in the pool or not.The output is:which is a big surprise for me. Could anyone explain this please?\nI think something about this is taking place at the compilation time. But why does adding  to a String makes any difference at all?is a , whereasisn't. Therefore the former compiles into just the string constant \"555\" and the latter compiles into the actual method invocation and concatenation, resulting in a fresh String instance.After decompiling this lineI got this bytecodewhich is equivalent tothat means expression  compiles to boolean . For  javac built this bytecodewhich is equivalent to which will always produce false since here we're comparing 2 disctinct objects.In the second case the compiler COULD have recognized that  is a no-op of sorts, since  is a compile-time value known to be zero length.  But the compiler is still required to check the result from  for null (since the null check would occur as a result of the  operation in the non-optimized case), so it's simplest to just not attempt the optimization.As a result, the compiler generates code to perform the concatenation, and a new string is created.\nString computed by constant expression are done at compile time and treated as constants or literals means the value of the string or expression is known or evaluated at compile time hence the compiler can check the same value in string pool and the return the same string object reference.\nString expressions whose values are known or can not be evaluated at compile but depends on the input or condition of run-time  then the compiler will not know the value of the string and hence always land up using StringBuilder to append the string and always returns a new string .\nI guess this example will clarify it better.
Java

So I need to remove a file from a jar / war file.\nI was hoping there was something like \"jar -d myjar.jar  file_I_donot_need.txt\"But right now the only way I can see of doing this from my Linux command line (without using WinRAR/Winzip or linux equivalent) is toPlease tell me there is a shorter way? jar is just a zip file after all. Definitely much faster than uncompressing/recompressing. In Java you can copy all the entries of a jar except the one you want to delete. i.e. you have to make a copy but don't need to create the individual files.You can do this byIn case you want to delete file in order to unsign signed jar, you can probably just make the .RSA file zero-sized. This can be accomplished with just . See  . (Worked for me, though I admit it's hack.)
Java

In practice can I assume that all int arrays in Java will start out filled with zeros? for all machines in which the JVM runs?Is this true for all types? char? boolean? enums?Where is this officially documented?The textbooks I have say that int arrays are set to zero but they also recommend that one should write a for-loop to set all values to zero just \"to be clearer\". is the right place to look for such information:  Default values themselves are given in .Yes. Primitive types in Java are always zero-initialized. References are also initialized to null.It should be Java Language Specification .  instead of \"For type byte, the default value is zero, that is, the value of (byte)0.\nFor type short, the default value is zero, that is, the value of (short)0.\nFor type int, the default value is zero, that is, 0.\nFor type long, the default value is zero, that is, 0L.\nFor type float, the default value is positive zero, that is, 0.0f.\nFor type double, the default value is positive zero, that is, 0.0d.\nFor type char, the default value is the null character, that is, '\\u0000'.\nFor type boolean, the default value is false.\nFor all reference types (\u00a74.3), the default value is null.\"Your textbook is wrong!  Writing such code is pointless, and a waste of your time typing it and the computers time running it.As others have said, the compiler guarantees that variables outside of methods (class/instance variables) are given a value of 0, false, or null.  As you probably know the compiler does not give variables inside of methods values, and instead forces you to give them a value before they are used.You will find, if you do things \"right\" that about 90%-95% of your \"variables\" never change after they are given a value.  However, new programmers tend to do things like this:this prevents you from being able to mark x as \"final\".  If you are able to mark x as \"final\" then it prevents accidental modification of the value, which prevents bugs.I would write the code like:This is called a blank final (a final variable that doesn't have a value when it is declared).If you remember that class/instance variables are initialized by the runtime then you will, hopefully, not write code to initialize them with throw away values, and then you can mark them as final.My personal practice is to always mark everything as final until I find that I need to modify it, and to never initialize a variable until I know the actual value I want it to have.  Doing this make the code faster (not noticeable since assignments are generally very quick) and safer since I rarely accidentally modify a value when I should not.
Java

I have the following piece of code:Upto this part the code is fine, but I am not able to instantiate 'in' within the main method like  as it is showing . What is the way I can do it? I do not want to make my Inner class static.You have to have a reference to the other outer class as well.If Inner was static then it would be A \"regular\" inner class has a hidden (implicit) pointer to a parent class instance. This allows the compiler to generate the code to chase the pointer for you without you having to type it. For instance, if there is a variable \"a\" in the parent class then the code in your inner class can just do \"a=0\", but the compiler will generate code for \"parentPointer.a=0\" maintaining the hidden pointer under the covers.This means when you create an instance of an inner class you have to have an instance of a parent class to link it to. If you do this creation inside a method of the parent class then the compiler knows to use \"this\" as the implicit pointer. If you want to link to some other parent instance then you use a special \"new\" syntax (see code snippet below). If you make your inner class \"static\" then there is no hidden pointer and your inner class cannot reference members of the parent class. A static inner class is identical to a regular class, but its name is scoped inside the parent.Here is a snippet of code that demonstrates the syntax for creating static and non-static inner classes:If you want to create  from within a method, do it from an instance method of the class :Alexei Kaigorodov's is the right answer.  His solution allows you to instantiate inner classes from within a static method, such as a main() of the same class.  Otherwise, you can't instantiate an inner class within a static method.  It does not compile.  Alexei's solution does compile and it does allow you to instantiate inner classes from a static method.  The other answers are interesting side-notes, but I don't find them responsive to the actual question.
Java

In some interfaces i wrote I'd like to name generic type parameter with more than one character to make the code more readable.Something like....Instead of this...But when it comes to methods, the type-parameters look like java-classes which is also confusing.This seems like Key and Value are classes. I found or thought of some notations, but nothing like a convention from sun or a general best-practice.Alternatives i guesed of or found...Oracle recommends the following in :I'd stick to it to avoid the confusion among the developers and possible maintainers.A good discussion can be found in the comments on the DZone page, .See the comment by Erwin Mueller. His suggestion makes perfect obvious sense to me: . Call an apple an apple, a car a car. The name in question is the name of a data type, right? (In , a class essentially defines a new data type.) So call it a \u201cType\u201d.Mueller\u2019s example, drawn from the original post\u2019s article:A duplicate Question provides  by Andy Thomas. Note the excerpt from Google\u2019s style guide that suggests a multi-character type name should end in a single uppercase .You can use javadoc to at least give users of your generic class a clue.  I still don't like it (I agree with @chaper29) but the docs help.  eg,The other thing I have been known to do is use my IDE to refactor a class breaking the convention.  Then work on the code and refactor back to single letters.  Makes it easier for me anyway if many type parameters are used.  Yes, you can use multi-character names for type variables, as long as they are clearly distinguished from class names.This differs from the convention suggested by Sun with the introduction of generics in 2004. However:Readability is good. Compare:to:or, with Google's multi-character convention: allows both single-letter names and multi-character class-like names ending in T. Single-character names are not the only way to distinguish type parameters from class names, as we've seen above.It's true that the @param JavaDoc elements can provide a longer description. But it's also true that the JavaDocs are not necessarily visible. (For example, there's a content assist in Eclipse that shows the type parameter names.)Many of Sun's original conventions are followed nearly universally in Java programming. However, this particular convention is not. The best choice among competing conventions is a matter of opinion. The consequences of choosing a convention other than Oracle's in this case are minor. You and your team can choose a convention that best meets your needs.The reason why the  reccommends using single letter is the following:I think with modern IDEs that reason is no longer valid as eg. IntelliJ Idea shows generic type parameters with different colors than regular classes.\nBecause of that distinction I use longer descriptive names for my generic types, with same convention as regular types. I avoid adding prefixes and suffixes such as T or Type as I consider them unnecessary noise and no longer needed to visually distinguish generic types.Note: As I am not a user of Eclipse or Netbeans, I do not know whether they offers a similliar feature.
Java

I want Eclipse to automatically suggest to me all possible options, while I'm writing some variable/class name or keyword, like in Flash Develop or Visual Studio.Is it possible?If not, with which Java IDE can I get this?I'm specifically asking about a way to  get the same thing I get using  + , while I'm typing.You can also set auto completion to open automatically while typing.Simply write  in  field, in Java/Editor/Content Assist (Window->Preferences).See this  for more details.Use the  shortcut for getting all possible autocomplete options available in a particular context in the editor.Auto Complete will also allow you to insert custom code templates into the editor, with placeholders for various inputs. For instance, attempting to auto complete the word \"test\" in a Java editor, in the context of a class body, will allow you to create a unit test that uses JUnit; you'll have to code the body of the method though. Some code templates like the former, come out of the box.+Yes. If the suggestion doesn't compare automatically, then press crtl + space button.Since you asked about other Java IDE, I suggest IntelliJ by JetBrains.\nJust look at it: not only does it support auto completion as you type, but also it support import package once you select the auto completion. Before someone said \"Eclipse is free\", note that IntelliJ has free community edition as well: See if your settings are correct also:Window -> Preferences -> Java -> Editor -> content assist. See if the \"completion inserts\" is checked off along with anything else there you want to help auto complete.Its simple\nthese are the steps:\n1. first go to the following settings\n   Window -> Preferences -> Java -> Editor -> content assist -> advanced\n2. there will be two boxes having checkboxes.\n3. check everthing in there and click apply.\n4. now ofcourse when you'll be coding there will be auto code completion feature automatically.Pressing + opens up the auto-completion dialog in Eclipse. In the Java Perspective it opens automatically after you typed a  (normally with a short delay).Now in eclipse Neon this feature is present. No need of any special settings or configuation .On + the code suggestion is available Steps:All the commands and variables which begin with that letter are now going to appear
Java

How does  annotation work in JPA?I found various answers whose extract is as follows:But I am still not sure how it works.Also as from the following lines:Does it mean that we should declare our version field as ?Let's say an entity  has an annotated  property:On update, the field annotated with  will be incremented and added to the  clause, something like this:If the  clause fails to match a record (because the same entity has already been updated by another thread), then the persistence provider will throw an .No but you could consider making the setter protected as you're not supposed to call it. Although @Pascal answer is perfectly valid, from my experience I find the code below helpful to accomplish optimistic locking:Why? Because:First point doesn't matter if application uses  JPA for inserting data into the database, as JPA vendor will enforce  for  field at creation time. But almost always plain SQL statements are also in use (at least during unit/ integration testing).Every time an entity is updated in the database the version field will be increased by one. Every operation that updates the entity in the database will have appended  to its query.In checking affected rows of your operation the jpa framework can make sure there was no concurrent modification between loading and persisting your entity because the query would not find your entity in the database when it's version number has been increased between load and persist.Version used to ensure that only one update in a time. JPA provider will check the version, if the expected version already increase then someone else already update the entity so an exception will be thrown.So updating entity value would be more secure, more optimist.If the value changes frequent, then you might consider not to use version field. For an example \"an entity that has counter field, that will increased everytime a web page accessed\"Just adding a little more info.JPA manages the version under the hood for you, however it doesn't do so when you update your record via , in such cases you need to manually add the version increment to the query.Pedro
Java

The Java Docs for the method\n\nincludes this in the returns description:How do I do a similar thing and initialize a String array (or any other array for that matter) to have a length 0?As others have said,will indeed create an empty array. However, there's one nice thing about arrays - their size can't change, so you can always use the same empty array reference. So in your code, you can use:and then just return  each time you need it - there's no need to create a new object each time.?Butwon't work as the type information is missing.Ok I actually found the answer but thought I would 'import' the question into SO anyway\nor\nMake a function which will not return null instead return an empty array you can go through below code to understand. 
Java

How to create Java Gradle project from command line?It should create  like on the picture below.UPDATE: .1. From \nI need to create file  with 2 lines.2. Add to  task below, than execute .3. Then run  (or corresponding string to other IDE plugin configured)So is there way to do it in one command?To create a Java project: create a new project directory, jump into it and executeSource folders and a Gradle build file (including a wrapper) will be build.The gradle guys are doing their best to solve all (y)our problems ;-). \nThey recently (since 1.9) added a new feature (incubating): the \"build init\" plugin\nSee: Unfortunately you cannot do it in one command. There is an open .Currently you'll have to do it by hand. If you need to do it often, you can create a , or just prepare your own project skeleton and copy it when needed.The JIRA issue mentioned above has been resolved, as of May 1, 2013, and fixed in 1.7-rc-1. The documentation on the  is available, although it indicates that this feature is still in the \"incubating\" lifecycle.Finally after comparing all solution, I think starting from  file can be convenient. Gradle distribution has  folder with a lot of examples, and there is  comand see . But they all needs some editing.You can use  below as well, then run The result is like below. That can be used without any Gradle plugin for Eclipse,\nor with  alternative to If you are using Eclipse, for an existing project (which has a  file) you can simply type  which will create all the Eclipse files and folders for this project.It takes care of all the dependencies for you and adds them to the project resource path in Eclipse as well.I could handle it using a groovy method in  to create all source folders for java, resources and test. Then I set it to run before  task.Now we can setup a new gradle Java EE project to eclipse with only one command. I put this example at I just tried with with Eclipse Neon.1 and Gradle:On windows 10 with Java Version:And it failed miserably as you can see in Eclipse.\nBut sailed like a soaring eagle in Intellij...I dont know Intellij, and a huge fan of eclipse, but common dudes, this means NO ONE teste Neon.1 for the simplest of use cases...to import a gradle project.\nThat is not good enough.\nI am switching to Intellij for gradle projects:
Java

I need to use mapview control in android and I can't seem to understand how to run .\nIs it installed with eclipse? I can't seem to find a download link.Thanks is part of the standard java distribution.In a windows 64-bit machine, you would normally find the jdk at It is used for managing keys and certificates you can sign things with, in your case, probably a jar file.If you provide more details of what you need to do, we could probably give you a more specific answer.keytool is a tool to manage key and certificates. It is provided with any standard JDK distribution and can be located in .For me it turned out to be in c/Program Files/Java/jdk1.7.0_25/bin (Windows 8). A more general answer to this question is that it will most likely be in the bin sub directory of wherever your jdk is installed. If you are working with a Mac... the keytool is part of the Java SDK and can be found in the following location /System/Library/Java/JavaVirtualMachines/[VERSION].jdk/Contents/Home/bin/keytoolhere: \nC:\\Program Files\\Java\\jre7\\bin\nit is an exe keytool.exeIf you have java installed of course keytool is in there. What you need to do is to add it on your PATH variable.It is in path/to/jdk/bin.\nMake sure that $JAVA_HOME is defined, and $JAVA_HOME/bin is added to $PATH, or else the 'keytool' command won't be recognized when called.
Java

I am trying to modify some legacy code from while back and getting the following kind of errors:Access restriction: The method create(JAXBRIContext, Object) from the type Headers is not accessible due to restriction on required library ..\\jre\\lib\\rt.jar for these import statements:Been searching what this might mean and how to fix it, however not been able to find a clear answer. Some posts seem to suggest that I have some JARs included that implement classes that are now available as part of the core java distribution, but as far as I can see none of the JARs I include contain different/older versions of the above classes.Anyone able to tell me what this error is all about and how I might go about fixing this? Thanks for your help already in advance,OlliI ran into something similar, I think that the cause of the warning is Eclipse trying to discourage you from using the internal  packages that are installed as part of your workspace JRE but which are not part of the public Java API.As Justin says in his answer, changing your compiler settings can hide the warning. A more fine-grained approach is to modify your build path to explicitly allow access to the package in question:After adding this access rule, your project should build without these warning.Excellent answer already provide onsite .See the summary below:Not a true solution, but everywhere I looked the solution suggested was to simply tell Eclipse that those aren't errors. You can change it by going to Properties --> Java Compiler --> Errors Warnings --> Deprecated and restrited APIs --> Forbidden reference (acess rule), Change it from Error to Warning or Ignore.i've solved this issue with these steps: expand your project, right click \"JRE System Library\" > Properties > choose 3rd option \"Workspace default JRE\" > OK . Hope it help you too\nRemove existing JRE System Library, then Error will be removed.I had the same problem when my plugin was depending on another project, which exported some packages in its manifest file. Instead of changing access rules, I have managed to solve the problem by adding the required packages into its Export-Package section. This makes the packages legally visible. Eclipse actually provides this fix on the \"Access restriction\" error marker.In the eclipse environment where you execute your java programs, take the following steps:I'm responding to this question because I had a different way of fixing this problem than the other answers had. I had this problem when I refactored the name of the plugins that I was exporting. Eventually I had to make sure to fix/change the following.This worked for me, but your mileage may vary.I just changed project facet to 1.7 and it worked.Go to BuildpathRemove Existing JRE and add new JRE library which contain Jdk1.6\nand finish \nNow clean all project and build again I think this way you can resolved your error
Java

How to split the string  to substrings of equal size in Java.\nEg.  of 4 equal size should give the output.Here's the regex one-liner version: is a zero-width assertion that matches the position where the previous match ended.  If there  no previous match, it matches the beginning of the input, the same as .  The enclosing lookbehind matches the position that's four characters along from the end of the last match.Both lookbehind and  are advanced regex features, not supported by all flavors.  Furthermore,  is not implemented consistently across the flavors that do support it.  This trick will work (for example) in , Perl, .NET and JGSoft, but not in  (PCRE), Ruby 1.9+ or TextMate (both Oniguruma).  JavaScript's  (sticky flag) isn't as flexible as , and couldn't be used this way even if JS did support lookbehind.I should mention that I don't necessarily  this solution if you have other options.  The non-regex solutions in the other answers may be longer, but they're also self-documenting; this one's just about the  of that. ;)Also, this doesn't work in Android, which doesn't support the use of  in lookbehinds.Well, it's fairly easy to do this by brute force:I don't think it's really worth using a regex for this.EDIT: My reasoning for not using a regex:This is very easy with :Output:Or if you need the result as an array, you can use this code:Reference:Note: Splitter construction is shown inline above, but since Splitters are immutable and reusable, it's a good practice to store them in constants:If you're using Google's  general-purpose libraries (and quite honestly, any new Java project probably  be), this is insanely trivial with the  class:and that's . Easy as!You can use  from  (handling exceptions) or from  (it handles exceptions for you)Put it inside a loop and you are good to go.I'd rather this simple solution:I asked @Alan Moore in a comment to the  how strings with newlines could be handled. He suggested using DOTALL.Using his suggestion I created a small sample of how that works:But I like @Jon Skeets solution in  also. For maintainability in larger projects where not everyone are equally experienced in Regular expressions I would probably use Jons solution.Another brute force solution could be, Where the code just steps through the string with substringsResult
Java

Is there any other way besides using  to get image height and width?Because I encounter an issue that locks up the thread.This error only occurs on a Sun app server and therefore I suspect that it is a Sun bug.Here is something very simple and handy.  I have found another way to read an image size (more generic). \nYou can use ImageIO class in cooperation with ImageReaders. \nHere is the sample code:Note that getFileSuffix is method that returns extension of path without \".\" so e.g.: png, jpg etc.\nExample implementation is:This solution is very quick as only image size is read from the file and not the whole image. I tested it and there is no comparison to ImageIO.read performance. I hope someone will find this useful.This is a rewrite of the great post by @Kay, which throws IOException and provides an early exit:I guess my rep is not high enough for my input to be considered worthy as a reply.I tried to test performance using some of the various approaches listed. It's hard to make a rigorous test as many factors affect the result. I prepared two folders, one with 330 jpg files and another one with 330 png files. The average file size was 4Mb in both cases. Then I called getDimension for each file. Each implementation of getDimension method and each image type was tested separately (separate run). Here is the execution times that I got (first number for jpg, second number for png): It's obvious that some methods load the whole file in order to get dimensions while others get by just reading some header information from the image. I think these numbers may be useful when application performance is critical.Thank you everyone for the contribution to this thread - very helpful.You can load jpeg binary data as a file and parse the jpeg headers yourself. The one you are looking for is the 0xFFC0 or Start of Frame header:For more info about the headers check out wikipedia's jpeg entry or I got the above info .I used a method similar to the code below which I got from  at the sun forums:}I found this free class, work perfectly:Simple way:Try using the ImageInfo freely available class, I've used it for the same purpose:You could use the Toolkit, no need for ImageIOIf you don't want to handle the loading of the image doTo get a Buffered Image with ImageIO.read is a very heavy method, as it's creating a complete uncompressed copy of the image in memory. For png's you may also use pngj and the code:You can get width and height of image with BufferedImage object using java.To get size of emf file without EMF Image Reader you can use code:
Java

What is the fastest way to strip all non-printable characters from a  in Java?So far I've tried and measured on 138-byte, 131-character String:My best try was the following:Any thoughts on how to make it even faster?Bonus points for answering a very strange question: why using \"utf-8\" charset name directly yields better performance than using pre-allocated static const ?I've tried my best to collected all the proposed solutions and its cross-mutations and published it as a . Currently it sports 17 algorithms. One of them is \"special\" -  algorithm () employs intricate reflection tricks thus achieving stellar speeds, but it messes up JVM strings' state, thus it's benchmarked separately.You're welcome to check it out and run it to determine results on your box. Here's a summary of results I've got on mine. It's specs:Different algorithms show ultimately different results given a different set of input data. I've ran a benchmark in 3 modes:This mode works on a same single string provided by  class as a constant. The showdown is:In charted form:\nSource string provider pre-generated lots of random strings using (0..127) character set - thus almost all strings contained at least one control character. Algorithms received strings from this pre-generated array in round-robin fashion.In charted form:\nSame as previous, but only 1% of strings was generated with control characters - other 99% was generated in using [32..127] character set, so they couldn't contain control characters at all. This synthetic load comes the closest to real world application of this algorithm at my place.In charted form:\nIt's very hard for me to decide on who provided the best answer, but given the real-world application best solution was given/inspired by Ed Staub, I guess it would be fair to mark his answer. Thanks for all who took part in this, your input was very helpful and invaluable. Feel free to run the test suite on your box and propose even better solutions (working JNI solution, anyone?).If it is reasonable to embed this method in a class which is not shared across threads, then you can reuse the buffer: etc...This is a big win - 20% or so, as I understand the current best case.If this is to be used on potentially large strings and the memory \"leak\" is a concern, a weak reference can be used.using 1 char array could work a bit betterand I avoided repeated calls to another micro-optimization that might work isWell I've beaten the current best method (freak's solution with the preallocated array) by about 30% according to my measures. How? By selling my soul.As I'm sure everyone that has followed the discussion so far knows this violates pretty much any basic programming principle, but oh well. Anyways the following only works if the used character array of the string isn't shared between other strings - if it does whoever has to debug this will have every right deciding to kill you (without calls to substring() and using this on literal strings this should work as I don't see why the JVM would intern unique strings read from an outside source). Though don't forget to make sure the benchmark code doesn't do it - that's extremely likely and would help the reflection solution obviously.Anyways here we go:For my teststring that gets  vs.  for the old variant. I'm quite sure the only way to beat that could be to write it in C (probably not though) or some completely different approach nobody has thought about so far. Though I'm absolutely not sure if the timing is stable across different platforms - produces reliable results on my box (Java7, Win7 x64) at least.You could split the task into a several parallel subtasks, depending of processor's quantity.IANA low-level java performance junkie, but have you tried ? It appears that it could allow some CPU's to perform checks in parallel.Also,  has some fun ideas for optimizations.I was so free and wrote a small benchmark for different algorithms. It's not perfect, but I take the minimum of 1000 runs of a given algorithm 10000 times over a random string (with about 32/200% non printables by default). That should take care of stuff like GC, initialization and so on - there's not so much overhead that any algorithm shouldn't have at least one run without much hindrance.Not especially well documented, but oh well.  - I included both of ratchet freak's algorithms and the basic version. At the moment I randomly initialize a 200 chars long string with uniformly distributed chars in the range [0, 200).If you mean  etc.: This shouldn't be faster - except for some better caching - since  is used internally, if the charset is not cached.One thing might be that you're using different charsets (or maybe some of your code does transparently) but the charset cached in  doesn't change.
Java

I would like to compile my Java program in Eclipse but not to run it. I can't understand how to do it.How can I compile a Java program to  files in Eclipse without running it?You can un-check the build automatically in Project menu and then build by hand by type Ctrl + B, or clicking an icon the appears to the right of the printer icon.You will need to go to ,then build your project. This will work, even when your source code does not contain any main method to run as an executable program. The .class files will appear in the bin folder of your project, in your workspace. In the case that you delete your .class file in Eclipse and then try to build it again from the .java file it will do nothing. If you try to run the .java file without the .class file you will get an error that it can not find the main class.You will either have to change and re-save the .java file then build it again, or else you have to run Clean on the project then build again.Go to the project explorer block ...\nright click on project name \nselect \"Build Path\"-----------> \"Configuration Build Path\"then the pop up window will get open.in this pop up window you will find 4 tabs. 1)source 2) project 3)Library 4)order and export Click on 1) Source select the project (under which that file is present which you want to compile)and then click on ok....Go to the workspace location of the project open a bin folder and search that class file ...you will get that java file compiled...just to cross verify check the changed timing.hope this will help.Thanks.Right click on It will compile all files in your project and updates your build folder, all without running.Try this in your console:If you also need any external library, try:
Java

This is not really a question, however, I would like to share some of my working code here for your reference when you need.As we know that  is deprecated from API22 and comletely removed since API23. At the moment, we cannot access  anymore (404).  So, the following is my working sample code for . It's working, tested with . Of course, the code perhaps is just a basic sample that posts two existed drawable files, also is not the best solution for all cases, and not good tuning.Any suggestions for better / more beautiful code will be appreciated.Hope this helps!For text part, please refer to @RacZo's answer below.I rewrite your code @RacZo and @BNK more modular and easy to use likeCheck full of code  at my .Nice answer @BNK!Just want to add to the answer... I was trying to figure how to append text fields to the body and created the following function to do it:It is working pretty well, so I hope it helps .for those one who is struggling like me to send utf-8 parameters and still no luck ...\nthe problem i had was in the dataOutputStream , and change the code of @RacZo to below codehope this work for some one like me
Java

Currently I have a Spring Boot application using Spring Data REST. I have a domain entity  which has the  relationship to another domain entity, . These classes are structured as follows:Post.java:Comment.java:Their Spring Data REST JPA repositories are basic implementations of :PostRepository.java:CommentRepository.java:The application entry point is a standard, simple Spring Boot application. Everything is configured stock.Application.javaEverything appears to work correctly. When I run the application, everything appears to work correctly. I can POST a new Post object to  like so:Body: \nResult at :However, when I perform a GET at  I get an empty object  returned,  and if I try to POST a comment to the same URI, I get an HTTP 405 Method Not Allowed.What is the correct way to create a  resource and associate it with this ? I'd like to avoid POSTing directly to  if possible.Assuming you already have discovered the post URI and thus the URI of the association resource (considered to be  in the following), it generally takes these steps:Note, that in the last step, according to the specification of , you can submit multiple URIs identifying comments separated by a line break to assign multiple comments at once.A few more notes on the general design decisions. A post/comments example is usually a great example for an aggregate, which means I'd avoid the back-reference from the  to the  and also avoid the  completely. If the comments don't have a lifecycle on their own (which they usually don't in an composition-style relationship) you rather get the comments rendered inline directly and the entire process of adding and removing comments can rather be dealt with by using . Spring Data REST has added  in the latest release candidate for the upcoming version 2.2.You have to post the comment first and while posting the comment you can create an association posts entity.It should look something like below :and it will work perfectly fine.I faced the same scenario and I had to remove the repository class for the sub entity as I have used one to many mapping and pull data thru the main entity itself. Now I am getting the entire response with data.
Java

I'm currently looking for ways to create automated tests for a  (Java API for RESTful Web Services) based web service. I basically need a way to send it certain inputs and verify that I get the expected responses. I'd prefer to do this via JUnit, but I'm not sure how that can be achieved.What approach do you use to test your web-services? As entzik pointed out, decoupling the web service from the business logic allows me to unit test the business logic. However, I also want to test for the correct HTTP status codes etc. comes with a great RESTful client API that makes writing unit tests really easy. See the unit tests in the examples that ship with Jersey. We use this approach to test the REST support in , if you are interested the You can try out  which makes it  simple to test REST services and validating the response in Java (using JUnit or TestNG).As James said; There is built-in  for Jersey. A simple hello world example can be like this:pom.xml for maven integration. When you run . Frameworks start a grizzly container. You can use jetty or tomcat via changing dependencies.ExampleApp.javaHelloWorld.javaHelloWorldTest.javaYou can check  sample application.Though its too late from the date of posting the question, thought this might be useful for others who have a similar question. \nJersey comes with a test framework called the  which allows you to test your RESTful Web Service, including the response status codes. You can use it to run your tests on lightweight containers like Grizzly, HTTPServer and/or EmbeddedGlassFish. Also, the framework could be used to run your tests on a regular web container like GlassFish or Tomcat. You probably wrote some java code that implements your business logic and then you have generated the web services end point for it.An important thing to do is to independently test your business logic. Since it's pure java code you can do that with regular JUnit tests. Now, since the web services part is just an end point, what you want to make sure is that the generated plumbing (stubs, etc) are in sync with your java code. you can do that by writing JUnit tests that invoke the generated web service java clients. This will let you know when you change your java signatures without updating the web services stuff.If your web services plumbing is automatically generated by your build system at every build, then it may not be necessary to test the end points (assuming it's all properly generated). Depends on your level of paranoia.I use Apache's  to call Restful Services. The HTTP Client library allows you to easily perform get, post or whatever other operation you need. If your service uses JAXB for xml binding, you can create a JAXBContext to serialize and deserialize inputs and outputs from the HTTP request.Take a look at . This can  generate a proxy implementation for your JAX-RS webservice class using jersey client behind the scene. Effectively you will call you webservice methods as simple java methods from your unit tests. Handles http authentication as well.There is no code generation involved if you need to simply run tests so it is convenient.  Dislclaimer: I am the author of this library.I certainly would not assume that the person who wrote the JAX-RS code and is looking to unit test the interface is somehow, for some bizarre, inexplicable reason, oblivious to the notion that he or she can unit testing other parts of the program, including business logic classes. It's hardly helpful to state the obvious and the point was repeatedly made that the responses need to be tested, too. Both Jersey and RESTEasy have client applications and in the case of RESTEasy you can use the same annoations (even factor out annotated interface and use on the client and server side of your tests). REST not what this service can do for you; REST what you can do for this service. Keep it simple. Have a look at  which can be imported from Maven Central.Usage example:As I understand the main purpose of the auther of this issue is to decouple JAX RS layer from business one. And unit test only the first one. Two basic problems here we have to resolve:The first one is solved with Arquillian.\nThe second one is perfectly described in Here is an example of the code, it may differ if you use another application server, but I hope you'll get the basic idea and advantages.A couple of notes:Hope, it'll help.
Java

Can one develop an entire application using JavaFX and run it on iOS, Android or Windows Phone 8, without writing platform-specific code? is a good resource for how everything was started and what was the state of JavaFX on embedded and mobile in beginning of 2014. But,  has changed since then and the users who stumble on this thread do not get the updated information.Most of my points are related to Invariant's answer, so I would suggest to go through it first.Some bad news first:Now, some good news:If you are not the DIY kind, I would suggest to install the IDE plugin on your favourite IDE and get started.Most of the documentation on how to get started can be found  and some of the samples can be found .Yes you can run JavaFX application on iOS, android, desktop, RaspberryPI (no windows8 mobile yet).   If you are going to develop serious  applications here is some more info At present for JavaFX Oracle priority list is Desktop (Mac,windows,linux)  .For iOS/android oracle done most of the hardwork and opnesourced javafxports of these platforms as part of OpenJFX ,but there is no JVM from oracle for ios/android.Community is putting all together by filling missing piece(JVM) for ios/android,Community made good progress in running JavaFX  on ios ( / android(). If you want you can also contribute to the community by sponsoring () or start developing apps and report issues. Johan Vos created a website for javafx ports ,check this for updated info ..Oracle JavaFX from  supports only . On these platforms, JavaFX applications are typically run on JVM from Java SE or OpenJDK.There is also a  project, which is an open-source project sponsored by a . It aims to port JavaFX  to Android and iOS.On Android, this library can be used like any other Java library; the . It's what people mean by saying that \"Android runs Java\".On iOS, situation is a bit more complex, as neither Java SE nor OpenJDK supports Apple mobile devices. Till recently, the only sensible option was to use  ahead-of-time Java compiler for iOS. Unfortunately, on 15 April 2015, .One possible alternative is Intel's . Till recently, it was a proprietary technology, but on 11 August 2016 it was . Although it can be possible to compile an iOS JavaFX app using  JavaFXPorts' JavaFX implementation, there is no evidence for that so far. As you can see, the situation is dynamically changing, and this answer will be hopefully updated when new information is available.With Windows Phone it's simple: there is no JavaFX support of any kind.Possible. You can get commercial sport also. 
Java

 is declared as .But you can call  to reassign it.Huh? How is this possible if it's ?(same point applies to  and )And more importantly, if you can mutate the public static final fields, what does this mean as far as the guarantees (if any) that  gives you? (I never realized nor expected System.in/out/err behaved as  variables):By the way, actually you can mutate  fields via reflection by calling  on them (or by using  methods). Such techniques are used during deserialization, by Hibernate and other frameworks, etc, but they have one limitation: code that have seen value of final field before modification is not guaranteed to see the new value after modification. What's special about the fields in question is that they are free of this limitation since they are treated in special way by the compiler.Java uses a native method to implement ,  and .On my JDK1.6.0_20,  looks like this:You still can't \"normally\" reassign  variables, and even in this case, you aren't directly reassigning the field (i.e. you still can't compile \"\"). Native methods allow some things that you simply can't do in regular Java, which explains why there are restrictions with native methods such as the requirement that an applet be signed in order to use native libraries.To extend on what Adam said, here is the impl:and setOut0 is defined as:Depends on the implementation.  The final one may never change but it could be a proxy/adapter/decorator for the actual output stream, setOut could for example set a member that the out member actually writes to.  In practice however it is set natively.the  which is declared as final in System class is a class level variable.\nwhere as out which is in the below method is a local variable.\nwe are no where passing the class level out which is actually a final one into this method usage of the above method is as below:now the data will be diverted to the file.\nhope this explanation makes the sense.So no role of native methods or reflections here in changing  purpose of the final keyword.As far as how, we can take a look at the source code to :In other words, JNI can \"cheat\". ; )
Java

What would be a use case for a use of a Mockito spy?It seems to me that every spy  use case can be handled with a mock, using callRealMethod.One difference I can see is if you want most method calls to be real, it saves some lines of code to use a mock vs. a spy. Is that it or am I missing the bigger picture?The answer is in : was introduced after , but spy() was left there of course, to ensure backward compatibility.Otherwise, you're right: all the methods of a spy are real unless stubbed. All the methods of a mock are stubbed unless  is called. In general, I would prefer using , because it doesn't force me to use the  idiom instead of the traditional If there is an object with 8 methods and you have a test where you want to call 7 real methods and stub one method you have two options:The  on  recommends using a spy for partial mocks.When Mockito creates a mock \u2013 it does so from the Class of a Type, not from an actual instance. The mock simply creates a bare-bones shell instance of the Class, entirely instrumented to track interactions with it. On the other hand, the spy will wrap an existing instance. It will still behave in the same way as the normal instance \u2013 the only difference is that it will also be instrumented to track all the interactions with it.In the following example \u2013 we create a mock of the ArrayList class:As you can see \u2013 adding an element into the mocked list doesn\u2019t actually add anything \u2013 it just calls the method with no other side-effect. A spy on the other hand will behave differently \u2013 it will actually call the real implementation of the add method and add the element to the underlying list:Here we can surely say that the real internal method of the object was called because when you call the size() method you get the size as 1, but this size() method isn\u2019t been mocked!  The internal real size() method is called as size() isn\u2019t mocked (or stubbed) and hence we can say that the entry was added to the real object.Source:   + self notes.
Java

I have found lots of books in java saying switch statement is faster than if else statement. But I didnot find antwhere saying .I have a situation i have to choose any one item out of two i can use either of the following wayor using if statement like the followingIn the above example which Because there are special bytecodes that allow efficient switch statement evaluation when there are a lot of cases.If implemented with IF-statements you would have a check, a jump to the next clause, a check, a jump to the next clause and so on. With switch the JVM loads the value to compare and iterates through the value table to find a match, which is faster in most cases.A  statement is not always faster than an  statement.  It scales better than a long list of  statements as  can perform a lookup based on all the values.  However, for a short condition it won't be any faster and could be slower.At the bytecode level, subject variable is loaded only once into processor register from a memory address in the structured .class file loaded by Runtime,and this is in a switch statement; whereas in an if-statement, a different jvm instruction is produced by your code-compiling DE, and this requires that each variable be loaded in to registers although same variable is used as in next preceeding if-statement. If you know of coding in assembly language then this would be commonplace; although java compiled coxes are not bytecode, or direct machine code, the conditional concept hereof is still consistent.\nWell, I tried to avoid deeper technicality upon explaining. I hope I had made the concept clear and demystified. Thank you.If you are performing an insane amount of checks like 100+ you may want to consider some abstraction.You have incoming packets that range from ids 0 through 255. You use maybe 150 of them. You may want to consider something like the below instead of a switch of 150 ids.I should also point out that index list isn't really needed and would probably slow the code down anyways. It was merely a suggestion so you don't have empty locations. Also not to mention is this situation you're only losing out of 106 indexes. I'm not 100% sure, but I believe each of these are pointing to null anyways so no real memory issues would be present.
Java

I am trying to understand more about java, especially about memory management and threads.\nFor this reason I have recently found interest in looking at thread dumps.Here are few lines taken from a web app using VisualVM, a built-in tool for java:First I have questions about some variable names: Then for the stack trace itself:I thought that the word locked was related in someway to a wait condition, however, I was wrong.  In fact, I am wondering why locked is repeated three times, but the thread is in runnable state as seen in the same dump:Then last of all, this was the worst of them:This thread is in runnable state, but it's waiting on condition. What condition and what is 0x00000?Why the stack trace is so short without any evidence of the thread class?If you could answer to all my questions I would be very grateful.ThanksThe TID is thead id and NID is: Native thread ID. This ID is highly platform dependent. It's the NID in jstack thread dumps.  On Windows, it's simply the OS-level thread ID within a process.  On Linux and Solaris, it's the PID of the thread (which in turn is a light-weight process).  On Mac OS X, it is said to be the native pthread_t value.Go to this link: : for a definition and a further explanation of these two terms. On IBM's site I found this link: . that covers this in greater detail:It explains what that waiting on means:\nA lock prevents more than one entity from accessing a shared resource. Each object in Java\u2122 has an associated lock (gained by using a synchronized block or method). In the case of the JVM, threads compete for various resources in the JVM and locks on Java objects.Then it describes the monitor as a special kind of locking mechanism that is used in the JVM to allow flexible synchronization between threads. For the purpose of this section, read the terms monitor and lock interchangeably.Then it goes further:Here is a more in-depth explanation of what you are seeing on the lines from the thread dump. A Java thread is implemented by a native thread of the operating system. Each thread is represented by a line in bold such as:*The following 6 items explains this as I've matched them from the example, values in the brackets[]:  Definition of the ReferenceQueue is:\nReference queues, to which registered reference objects are appended by the garbage collector after the appropriate reachability changes are detected. The finalizer thread runs so the garbage collection operates to clean up resources associated with an object.  If I'm seeing it corectly, the finalizer can't get the lock to this object: java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:118) because the java object is running a method, so the finalizer thread is locked until that object is finished with it's current task.  Also, the finalizer isn't just looking to reclaim memory, it's more involved than that for cleaning up resources.  I need to do more study on it, but if you have files open, sockets, etc... related to an objects methods, then the finalizer is going to work on freeing those items up as well.It is a pointer in memory to the thread.  Here is a more detailed description:C.4.1 Thread InformationThe first part of the thread section shows the thread that provoked the fatal error, as follows:The thread pointer is the pointer to the Java VM internal thread structure. It is generally of no interest unless you are debugging a live Java VM or core file.This last description came from: Here are a few more links on thread dumps: Further to @James Drinkard's excellent answer:Note that, depending on the underlying implementation, the  of a thread that is blocked in a native method may be reported as , where   It turns out that this description also encompasses being blocked in an OS call such as a poll or read operation - presumably because there is no guarantee that the JVM can know when a native method call has blocked at the OS level.Many discussions of JVM thread dumps that I've seen either ignore this possibility completely, or blithely skim over it without considering the implications - not least of which is that monitoring tools may confusingly report that several such threads are 'running', and furthermore that they are all running at 100%.Try  This is probally enough for many cases.
Java

I was reading the JavaDoc for Threadlocal hereand it says\n\"ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID). \"But my question is why did they choose to make it static (typically) - it makes things a bit confusing to have \"per thread\" state but the fields are static?Because if it were an instance level field, then it would actually be \"Per Thread - Per Instance\", not just a guaranteed \"Per Thread.\"  That isn't normally the semantic you're looking for.  Usually it's holding something like objects that are scoped to a User Conversation, Web Request, etc.  You don't want them also sub-scoped to the instance of the class.\nOne web request => one Persistence session.\nNot one web request => one persistence session per object.Either make it static or if you are trying to avoid any static fields in your class - make the class itself a singleton and then you can safely use the an instance level ThreadLocal as long as you have that singleton available globally.It doesn't have to be. The important thing is that it should be a singleton.The reason is that the variables are accessed via a pointer associated with the thread.  They act like global variables with thread scope, hence static is the closest fit.  This is the way that you get thread local state in things like pthreads so this might just be an accident of history and implementation.A use for an threadlocal on a per instance per thread is if you want something to be visible in all methods of an object and have it thread safe without synchronizing access to it like you would so for an ordinary field. 
Java

I just saw code similar to this:When ran, this block of code will print out:I understand why the first is : because the two objects are separate objects, so the  compares the references. But I can't figure out, why is the second statement returning ? Is there some strange autoboxing rule that kicks in when an Integer's value is in a certain range? What's going on here?The  line is actually guaranteed by the language specification. From :The discussion goes on, suggesting that although your second line of output is guaranteed, the first isn't (see the last paragraph quoted below):Yep the first output is produced for comparing reference; 'a' and 'b' - these are two different reference. In point 1, actually two references are created which is similar as - The second output is produced because the JVM tries to save memory, when the  falls in a range (from -128 to 127). At point 2 no new reference of type Integer is created for 'd'. Instead of creating new object for the Integer type reference variable 'd', it only assigned with previously created object referenced by 'c'. All of these are done by JVM. These memory saving rules are not only for Integer. for memory saving purpose, two instances of the following wrapper objects (while created through boxing), will always be == where their primitive values are the same - Integer objects in some range (I think maybe -128 through 127) get cached and re-used.  Integers outside that range get a new object each time.My guess is that Java keeps a cache of small integers that are already 'boxed' because they are so very common and it saves a heck of a lot of time to re-use an existing object than to create a new one.Yes, there is a strange autoboxing rule that kicks in when the values are in a certain range. When you assign a constant to an Object variable, nothing in the language definition says a new object  be created. It may reuse an existing object from cache.In fact, the JVM will usually store a cache of small Integers for this purpose, as well as values such as Boolean.TRUE and Boolean.FALSE.In Java the boxing works in the range between -128 and 127 for an Integer. When you are using numbers in this range you can compare it with the == operator. For Integer objects outside the range you have to use equals.That is an interesting point. \nIn the book  suggests always to override equals for your own classes. Also that, to check equality for two object instances of a java class always use the equals method. returns:In Java 5, a new feature was introduced to save the memory and improve performance for Integer type objects handlings. Integer objects are cached internally and reused via the same referenced objects.For more detail pls go through below Link:If we check the source code of  obeject, we will find the source of  method just like this:  which can explain why  objects, which in the range from -128 () to 127 (), are the same referenced objects during the autoboxing. And we can see there is a class  takes care of the  cache array, which is a private static inner class of  class.There is another interesting example may help us understand this weird situation:
Java

I have a JSON file like this:Before when files had a root element I would use:code but I can't think how to code the  class as the root element is an array.I have tried using:with: But haven't had any luck. How else can I read this using this method?P.S I have got this to work using: But I would prefer to know how to do it (if possible) with both methods.Problem is caused by comma after last element of your array (after each ). If you remove it and change your data to \nwill work fine.Seems to work fine. But there is an extra  Comma in your string.sample call:
Java

Please help me understand where to use a regular JOIN and where a JOIN FETCH.For example, if we have these two queriesandIs there any difference between them? If yes, which one to use when?In this two queries, you are using JOIN to query all employees that have at least one department associated.But, the difference is: in the first query you are returning only the Employes for the Hibernate. In the second query, you are returning the Employes  all Departments associated. So, if you use the second query, you will not need to do a new query to hit the database again to see the Departments of each Employee.You can use the second query when you are sure that you will need the Department of each Employee. If you not need the Department, use the first query.I recomend read this link if you need to apply some WHERE condition (what you probably will need): If you don't use  and the Departments continue to be returned, is because your mapping between Employee and Department (a ) are setted with . In this case, any HQL (with  or not) query with  will bring all Departments. Remember that all mapping *ToOne ( and ) are EAGER by default.in  i mentioned before on the comment, read this part :this \"JOIN FETCH\" will have it's effect if you have (fetch = FetchType.LAZY) property for a collection inside entity(example bellow).And it is only effect the method of \"when the query should happen\". And you must also know :  when is the association fetched --> your \"FETCH\" typehow is it fetched --> Join/select/Subselect/BatchIn your case, FETCH will only have it's effect if you have department as a set inside Employee, something like this in the entity:when you use you will get  and . when you didnt use fetch you can still get  but hibernate will processing another select to the database to get that set of department.so its just a matter of performance tuning, about you want to get all result(you need it or not) in a single query(eager fetching), or you want to query it latter when you need it(lazy fetching).Use eager fetching when you need to get small data with one select(one big query). Or use lazy fetching to query what you need latter(many smaller query).use fetch when :Dherik : I'm not sure about what you say, when you don't use fetch the result will be of type :  which means a list of Object tables and not a list of Employee. When you use fetch, there is just one select and the result is the list of Employee  containing the list of departements. It overrides the lazy declaration of the entity. If you have @oneToOne mapping set to FetchType.LAZY and you use second query(because you need Department objects to be loaded as part of Employee objects) what Hibernate will do is, it will issue queries to fetch Department objects for every individual Employee object it fetches from DB. Later in the code you might access Department objects via Employee to Department single-valued association and Hibernate will not issue any query to fetch Department object for the given Employee. Remember Hibernate still issues queries equal to the number of Employees it has fetched. Hibernate will issue same number of queries in both above queries if you wish to access Department objects of all Employee objects
Java

Should logger be declared static or not? Usually I've seen two types of declaration for a logger :orWhich one should be used? what are the pro's and con's of both?The advantage of the non-static form is that you can declare it in an (abstract) base class like follows without worrying that the right classname will be used:However its disadvantage is obviously that a whole new logger instance will be created for every instance of the class. This may not per se be expensive, but it adds a significant overhead. If you'd like to avoid this, you'd like to use the  form instead. But its disadvantage is in turn that you have to declare it in every individual class and take care in every class that the right classname is been used during logger's construction because  cannot be used in static context. However, in the average IDE you can create an autocomplete template for this. E.g.  + .On the other hand, if you obtain the logger by a factory which in turn may cache the already-instantiated loggers, then using the non-static form won't add that much overhead. Log4j for example has a  for this purpose.I used to think that all loggers should be static; however,  brings up some important memory concerns, regarding classloader leaks. Declaring a logger as static prevents the declaring class (and associated classloaders) from being garbage collected in J2EE containers that use a shared classloader. This will result in PermGen errors if you redeploy your application enough times.I don't really see any way to work around this classloader leak issue, other than declaring loggers as non-static.The most important difference is how it affects your log files: in which category do logs go?I would strongly recommend that last option. It has these advantages, compared to the other solutions:It also has disadvantages:Use inversion of control and pass the logger into the constructor. If you create the logger inside the class you are going to have a devil of a time with your unit tests. You are writing unit tests aren't you?
Java

There are two types of  statements in java - classic:  and shorthand: . Is one faster than the other or are they the same?statement:ternary operator:There's only one type of \"if\" statement there. The other is a conditional expression. As to which will perform better: they could compile to the same bytecode, and I would expect them to behave identically - or so close that you definitely wouldn't want to choose one over the other in terms of performance.Sometimes an  statement will be more readable, sometimes the conditional operator will be more readable. In particular, I would recommend using the conditional operator when the two operands are simple and side-effect-free, whereas if the main purpose of the two branches  their side-effects, I'd probably use an  statement.Here's a sample program and bytecode:Bytecode decompiled with :As you can see, there is a  difference in bytecode here - whether the  occurs within the brance or not (unlike my previous hugely-flawed attempt :) but I would be very surprised if the JITter ended up with different native code.Both of your examples will probably compile to identical or nearly identical bytecode, so there should be no difference in performance.Had there been a difference in execution speed, you should still use the most idiomatic version (which would be the second one for assigning a single variable based on a simple condition and two simple sub-expressions, and the first one for doing more complex operations or operations that do not fit on a single line). These are the same.  Both of them are fairly fast, typically around 10-30 nano-seconds. (depending on usage pattern)  Is this time frame important to you?You should do what you believe is clearest.neither - they will be compiled to the same.Just to add to all the other answers:The second expression is often called tertiary/ternary operator/statement. It can be very useful because it returns an expression. Sometimes it makes the code more clearer for typical short statements.
Java

This is my jTable I will call this method to retrieve the data from database and put it into table modelCurrently I was using this method to refresh the table after updating the table data. I will first clear the table and then restructure the table model again so it will refresh the jTable. But I was thinking is there any best practices or better way to do that? If you want to notify your  about changes of your data, use\nFrom the :The faster way for your case is:The optimized way when one or few cell change:try thisWould it not be better to use  and  that will cause the table to update?I did it like this in my Jtable its autorefreshing after 300 ms;I doubt it will do good with large number of objects like over 500, only other way is to implement TableModelListener in your class, but i did not understand how to use it well. look at 
Java

I want to deploy sources and javadocs with my snapshots. This means that I want to automize the following command:Just to execute:I don't want to have javadoc/sources generation executed during the  phase (i.e. local builds).I know that source/javadoc plugins can be synchronized with the execution of the  plugin but I can't figure out how to wire it to the snapshots releases.See  for a complete example.Just to add an alternative that doesn't require you to muck with plugin configuration:Credit goes to mcbeelen from The article referred to by Dan also mentions another approach that works without modifying poms AND won't go away anytime soon:Which works fine with Maven 3+, along with...Which I have tested from Jenkins deploying to Nexus.This approach was nice because I only had to modify some Jenkins jobs and didn't need to mess with my poms.
Java

I'm working on a Java Selenium-WebDriver. I added andbecause my Applications takes few seconds to load the User Interface. So I set 2 seconds implicitwait. but I got Then I add Now it works fine. Which one is a better way? Well, there are two types of wait: explicit and implicit wait. \nThe idea of explicit wait isThe concept of implicit wait isYou can get difference in details .In such situations I'd prefer using explicit wait ( in particular): function returns your found web element.\nFrom the documentation on :\n\nDetails you can get Usage of  in your case be the following:This approach IMHO better as you do not know exactly how much time to wait and in  polling interval you can set arbitrary timevalue which element presence will be verified through .\nRegards.If using webdriverJs (node.js),The code above makes browser wait for 5 seconds after clicking the button.This thread is a bit older, but thought I'd post what I currently do (work in progress).Though I'm still hitting situations where the system is under heavy load and when I click a submit button (e.g., login.jsp), all three conditions (see below) return  but the next page (e.g., home.jsp) hasn't started loading yet.This is a generic wait method that takes a list of ExpectedConditions.  I have defined various reusable ExpectedConditions (three are below).  In this example, the three expected conditions include document.readyState = 'complete', no \"wait_dialog\" present, and no 'spinners' (elements indicating async data is being requested).Only the first one can be generically applied to all web pages.Depending on the page, I may use one or all of them:There are also predefined ExpectedConditions in the following class:  Using  is an unconditional wait. If your test loads faster you will still have to wait. So in principle using  is the better solution.However, I don't see why  does not work in your case. Did you measure if the  actually takes two seconds before throwing an exception. If so, can you try to use WebDriver's conditional wait as described in  answer?I like to use custom conditions. Here's some code in Python:Whenever you need to wait, you can do it explicitly by checking existance of a certain element (such element may vary from page to page).  returns list - empty or not, you have just to check.click appears to be blocking? - here's another way to wait if you're using WebDriverJS:The code above waits after the button is clicked for the next page to load and then grabs the source of the next page.Sometimes implicit wait seems to get overridden and wait time is cut short.  [@eugene.polschikov] had good documentation on the whys.  I have found in my testing and coding with Selenium 2 that implicit waits are good but occasionally you have to wait explicitly.  It is better to avoid directly calling for a thread to sleep, but sometimes there isn't a good way around it.  However, there are other Selenium provided wait options that help.  and  have proved especially useful.   Implicitly wait and Thread.sleep Both are used for synchronization only..but the difference is we can use Implicitly wait for entire program but Thread.sleep will works for that single code only..Here my suggestion is use Implicitly wait once in the program when every time your Webpage will get refreshed means use Thread.sleep at that time..it will much Better :)Here is My Code :Implicit Wait: During Implicit wait if the Web Driver cannot find it immediately because of its availability, the WebDriver will wait for mentioned time and it will not try to find the element again during the specified time period. Once the specified time is over, it will try to search the element once again the last time before throwing exception. The default setting is zero. Once we set a time, the Web Driver waits for the period of the WebDriver object instance.Explicit Wait: There can be instance when a particular element takes more than a minute to load. In that case you definitely not like to set a huge time to Implicit wait, as if you do this your browser will going to wait for the same time for every element.\nTo avoid that situation you can simply put a separate time on the required element only. By following this your browser implicit wait time would be short for every element and it would be large for specific element.I prefer the following code to wait for 2 seconds.Use this code incase if the page refreshes when you change the control from one input field to another input field within the same page. Pass the corresponding driver reference to this method to find the element. Line1 is used to click outside that makes the refresh. If you have any queries post your comment.
Java

I have an app that makes extensive use of a WebView. When the user of this app does not have Internet connection, a page saying \"web page not available\" and various other text appears. Is there a way to not show this generic text in my WebView? I would like to provide my own error handling. I found out  doesn't actually clear the view.First create your own error page in HTML and put it in your assets folder, Let's call it myerrorpage.html\nThen with onReceivedError:The best solution I have found is to load an empty page in the OnReceivedError event like this:Finally, I solved this. (It works till now..)My solution is like this...Here is my full source. Check this out.Addition:Here is layout....Check out the discussion at . It's quite long, but the consensus seems to be that a) you can't stop the \"web page not available\" page appearing, but b) you could always load an empty page after you get an onReceivedErrorWhen webview is embedded in some custom view such that user almost believes that he is seeing a native view and not a webview. In such scenario showing the \"page could not be loaded\" error is preposterous, what I usually do in such situation is I load blank page and show a toast message as belowYou could use a  request to get the page content and then display that data using the  , this way you are not using multiple server calls. Alternative you can use  to check the  object for validity.Perhaps I misunderstand the question, but it sounds like you're saying you get the error received callback, and you just are asking what is the best way to not show the error? Why don't you just either remove the web view from the screen and/or show another view on top of it?I suppose that if you insist on doing this, you could just check if the resource is there before calling the loadURL function. \nJust simply override the functions and do the check before calling the super()REMARK (maybe off-topic): In http, there is a method called HEAD which is described as follow:This method might be handy.\nAnyway how ever you implement it ... check this code:You could try this check using I would just change the webpage to whatever you are using for error handling:  this can all be found on I've been working on this problem of ditching those irritable Google error pages today. It is possible with the Android example code seen above and in plenty of other forums (ask how I know):IF you put it in shouldOverrideUrlLoading() as one more webclient. At least, this is working for me on my 2.3.6 device.  We'll see where else it works later. That would only depress me now, I'm sure.  The goBack bit is mine. You may not want it.Try thisWe can set the visibility of webView to 0(view.INVISIBLE) and show some message.\nThis code works for my app running on lolipop.try this  , before redirect to another url check for internet conncetion based on that page should be loaded or not.override your WebViewClient method has side-effects, as it cancels the original URL loading.
Java

How much is read from  variable slower than from regular field?More concretely is simple object creation faster or slower than access to  variable?I assume that it is fast enough so that having  instance is much faster then creating instance of  every time. But does that also apply for byte[10] or byte[1000] for example?Edit: Question is what is really going on when calling 's get? If that is just a field, like any other, then answer would be \"it's always fastest\", right?Running unpublished benchmarks,  takes around 35 cycle per iteration on my machine. Not a great deal. In Sun's implementation a custom linear probing hash map in  maps s to values. Because it is only ever accessed by a single thread, it can be very fast.Allocation of small objects take a similar number of cycles, although because of cache exhaustion you may get somewhat lower figures in a tight loop.Construction of  is likely to be relatively expensive. It has a fair amount of state and construction goes through the  SPI mechanism. You may be able to optimise by, for instance, cloning or providing the .Just because it may be faster to cache in a  rather than create does not necessarily mean that the system performance will increase. You will have additional overheads related to GC which slows everything down.Unless your application very heavily uses  you might want to consider using a conventional thread-safe cache instead.In 2009, some JVMs implemented ThreadLocal using an unsynchronised HashMap in the Thread.currentThread() object. This made it extremely fast (though not nearly as fast as using a regular field access, of course), as well as ensuring that the ThreadLocal object got tidied up when the Thread died. Updating this answer in 2016, it seems most (all?) newer JVMs use a ThreadLocalMap with linear probing. I am uncertain about the performance of those \u2013 but I cannot imagine it is significantly worse than the earlier implementation.Of course, new Object() is also very fast these days, and the Garbage Collectors are also very good at reclaiming short-lived objects.Unless you are certain that object creation is going to be expensive, or you need to persist some state on a thread by thread basis, you are better off going for the simpler allocate when needed solution, and only switching over to a ThreadLocal implementation when a profiler tells you that you need to.Good question, I've been asking myself that recently. To give you definite numbers, the benchmarks below (in Scala, compiled to virtually the same bytecodes as the equivalent Java code):available , were performed on an AMD 4x 2.8 GHz dual-cores and a quad-core i7 with hyperthreading (2.67 GHz).These are the numbers:Thread num.: 1\nTotal tests: 200Run times:  (showing last 5)\n 9.0069       9.0036       9.0017       9.0084       9.0074      (avg = 9.1034       min = 8.9986       max = 21.0306     )Thread num.: 2\nTotal tests: 200Run times:  (showing last 5)\n 4.5563       4.7128       4.5663       4.5617       4.5724      (avg = 4.6337       min = 4.5509       max = 13.9476     )Thread num.: 4\nTotal tests: 200Run times:  (showing last 5)\n 2.3946       2.3979       2.3934       2.3937       2.3964      (avg = 2.5113       min = 2.3884       max = 13.5496     )Thread num.: 8\nTotal tests: 200Run times:  (showing last 5)\n 2.4479       2.4362       2.4323       2.4472       2.4383      (avg = 2.5562       min = 2.4166       max = 10.3726     )Thread num.: 1\nTotal tests: 200Run times:  (showing last 5)\n 91.1741      90.8978      90.6181      90.6200      90.6113     (avg = 91.0291      min = 90.6000      max = 129.7501    )Thread num.: 2\nTotal tests: 200Run times:  (showing last 5)\n 45.3838      45.3858      45.6676      45.3772      45.3839     (avg = 46.0555      min = 45.3726      max = 90.7108     )Thread num.: 4\nTotal tests: 200Run times:  (showing last 5)\n 22.8118      22.8135      59.1753      22.8229      22.8172     (avg = 23.9752      min = 22.7951      max = 59.1753     )Thread num.: 8\nTotal tests: 200Run times:  (showing last 5)\n 22.2965      22.2415      22.3438      22.3109      22.4460     (avg = 23.2676      min = 22.2346      max = 50.3583     )Total work:  20000000\nThread num.: 1\nTotal tests: 200Run times:  (showing last 5)\n 12.625       12.631       12.634       12.632       12.628      (avg = 12.7333      min = 12.619       max = 26.698      )Test name:   loop_heap_read\nTotal work:  20000000Run times:  (showing last 5)\n 6.412        6.424        6.408        6.397        6.43        (avg = 6.5367       min = 6.393        max = 19.716      )Thread num.: 4\nTotal tests: 200Run times:  (showing last 5)\n 3.385        4.298        9.7          6.535        3.385       (avg = 5.6079       min = 3.354        max = 21.603      )Thread num.: 8\nTotal tests: 200Run times:  (showing last 5)\n 5.389        5.795        10.818       3.823        3.824       (avg = 5.5810       min = 2.405        max = 19.755      )Thread num.: 1\nTotal tests: 200Run times:  (showing last 5)\n 200.217      207.335      200.241      207.342      200.23      (avg = 202.2424     min = 200.184      max = 245.369     )Thread num.: 2\nTotal tests: 200Run times:  (showing last 5)\n 100.208      100.199      100.211      103.781      100.215     (avg = 102.2238     min = 100.192      max = 129.505     )Thread num.: 4\nTotal tests: 200Run times:  (showing last 5)\n 62.101       67.629       62.087       52.021       55.766      (avg = 65.6361      min = 50.282       max = 167.433     )Thread num.: 8\nTotal tests: 200Run times:  (showing last 5)\n 40.672       74.301       34.434       41.549       28.119      (avg = 54.7701      min = 28.119       max = 94.424      )A thread local is around 10-20x that of the heap read. It also seems to scale well on this JVM implementation and these architectures with the number of processors.@Pete is correct test before you optimise.I would be very surprised if constructing a MessageDigest has any serious overhead when compared to actaully using it.Miss using ThreadLocal can be a source of leaks and dangling references, that don't have a clear life cycle, generally I don't ever use ThreadLocal without a very clear plan of when a particular resource will be removed.Build it and measure it.Also, you only need one threadlocal if you encapsulate your message digesting behaviour into an object. If you need a local MessageDigest and a local byte[1000] for some purpose, create an object with a messageDigest and a byte[] field and put that object into the ThreadLocal rather than both individually.
Java

I am developing on Eclipse on Windows and Code gets deployed on Unix. I am fething the system property values using System.getProperty(\"key\") ... how do I pass this in Eclipse so that I do not have to modify the code and it works on Eclipse for debugging?Any suggestions?Run -> Run configurations, select project, second tab: \u201cArguments\u201d. Top box is for your program, bottom box is for VM arguments, e.g. .You can use java , for using them from eclipse you could:You can add command line arguments to your run configuration. Just edit the run configuration and add -Dmyprop=value (or whatever) to the VM Arguments Box.run configuration -> arguments -> vm arguments(can also be placed in the debug configuration under Debug Configuration->Arguments->VM Arguments)
Java

The contract of  with regards to , is as follows:This is rather peculiar, because if  and , then we have:The fact that  is a good thing, because it alerts us of programmer error. And yet, that error would not be catched if for various reasons we just switched it around to , which would just \"silently fail\" instead.So the questions are:In contrast, this is what the  says:If  is appropriate for , why isn't it for ?These are the actual words in the  documentation:And what is an object?My argument from this angle is really simple.To the question of whether this asymmetry is inconsistent, I think not, and I refer you to this ancient Zen k\u014dan:At that moment, the compiler reached enlightenment.An exception really should be an  situation.   A null pointer might not be a programmer error.  You quoted the existing contract.  If you decide to go against convention, after all this time, when every Java developer expects equals to return false, you'll be doing something unexpected and unwelcome that will make your class a pariah.I could't disagree more.  I would not rewrite equals to throw an exception all the time.  I'd replace any class that did that if I were its client.Think of how .equals is related to == and .compareTo is related to the comparison operators >, <, >=, <=.If you're going to argue that using .equals to compare an object to null should throw a NPE, then you'd have to say that this code should throw one as well:The difference between o1.equals(o2) and o2.equals(o1) is that in the first case you're comparing something to null, similar to o1 == o2, while in the second case,  so there's no comparison happening at all.Regarding the .compareTo contract, comparing a non-null object with a null object is like trying do this:Obviously this won't compile.  You can use auto-unboxing to make it compile, but you get a NPE when you do the comparison, which is consistent with the .compareTo contract:Not that this is neccessarily an answer to your question, it is just an example of when I find it useful that the behaviour is how it is now.As it stands I can do.And I have no chance of getting a NullPointerException.  If it were changed as you suggested, I would be back to having to do:Is this a good enough reason for the behaviour to be as it is?? I don't know, but it is a useful side-effect.If you take object oriented concepts into account, and consider the whole sender and receiver roles, I'd say that behaviour is convenient. See in the first case you're asking an object if he is equal to nobody. He SHOULD say \"NO, I'm not\".In the second case though, you don't have a reference to anyone So you aren't really asking anyone. THIS should throw an exception, the first case shouldn't.I think it's only asymmetric if you kind of forget about object orientation and treat the expression as a mathematical equality. However, in this paradigm both ends play different roles, so it is to be expected that order matters.As one final point. A null pointer exception should be raised when there's an error in your code. However, Asking an object if he is nobody, shouldn't be considered a programming flaw. I think it's perfectly ok to ask an object if he isn't null. What if you don't control the source that provides you with the object? and this source sends you null. Would you check if the object is null and only afterwards see if they are equals? Wouldn't it be more intuitive to just compare the two and whatever the second object is the comparison will be carried out without exceptions? In all honesty, I would be pissed if an equals method within its body returns a null pointer exception on purpose. Equals is meant to be used against any sort of object, so it shouldn't be so picky on what it receives. If an equals method returned npe, the last thing on my mind would be that it did that on purpose. Specially considering it's an unchecked exception. IF you did raise an npe a guy would have to remember to always check for null before calling your method, or even worse, surround the call to equals in a try/catch block (God I hate try/catch blocks) But oh well...Personally, I'd rather it perform as it does.The  identifies that the problem is in the object against which the equals operation is being performed.If the  was used as you suggest and you tried the (sort of pointless) operation of... where o1= null...\nIs the  thrown because your comparison function is screwed or because o1 is null but you didn't realise?\nAn extreme example, I know, but with current behaviour I feel you can tell easily where the problem lies. In the first case  returns false because  is not equal to , which is perfectly fine. In the second case, it throws  because  is . One cannot call any method on a . It may be a limitation of programming languages in general, but we have to live with it.It is also not a good idea to throw  you are violating the contract for the  method and making things more complex than it has to be.There are many common situations where  is not in any way exceptional, e.g. it may simply represent the (non-exceptional) case where a key has no value, or otherwise stand for \u201cnothing\u201d. Hence, doing  with an unknown  is also quite common, and having to always check for  first would be just wasted effort.As for why  is different, it  a programming error to call  instance method on a null reference , and therefore worthy of an exception. The ordering of  and  in  should be chosen such that  is known to not be . I would argue that in almost all cases this reordering can be done based on what is known about the objects beforehand (e.g., from their origin, or by checking against  for other method calls).Meanwhile if both objects are of unknown \u201cnullness\u201d, then other code almost certainly requires checking at least one of them, or not much can be done with the object without risking the .And since this is the way it is specified, it is a programming error to break the contract and raise an exception for a  argument to . And if you consider the alternative of requiring an exception to be thrown, then every implementation of  would have to make a special case of it, and every call to  with any potentially  object would have to check before calling.It  have been specified differently (i.e., the precondition of  would require the argument to be non-), so this is not to say that your argumentation is invalid, but the current specification makes for a simpler and more practical programming language.Note that the contract is \"for any non-null reference x\". So the implementation will look like: need not be  to be deemed equal to  because the following definition of  is possible:I think it's about convenience and more importantly consistency - allowing nulls to be part of the comparison avoids having to do a  check and implement the semantics of that each time  is called.  references are legal in many collection types, so it makes sense they can appear as the right side of the comparison. Using instance methods for equality, comparison etc., necessarily makes the arrangement asymmetric - a little hassle for the huge gain of polymorphism. When I don't need polymorphism, I sometimes create a symmetric static method with two arguments, . This method then checks whether one or both arguments are null references. If I specifically want to exclude null references, then I create an additional method e.g.  or similar, that does a null check before delegating to the other method.This is a tricky question. For backward compatability you can't do so.Imagine the following scenarioNow with equals returning false else clause will get executed, but not when throwing an exception.Also null is not really equal to say \"2\" so it makes perfect sense to return false. Then it is probably better to insist null.equals(\"b\") to return also false :))But this requirement does make a strange and non symmetric equals relation.
Java

Consider the following code:The program's output is:When I run from the shell, of course, it works as expected:The internets tell me that, due to the fact that pipe behavior isn't cross-platform, the brilliant minds who work in the Java factory producing Java can't guarantee that pipes work.How can I do this?I am not going to do all of my parsing using Java constructs rather than  and , because if I want to change the language, I'll be forced to re-write my parsing code in that language, which is totally a no-go.How can I make Java do piping and redirection when calling shell commands?Write a script, and execute the script instead of separate commands.Pipe is a part of the shell, so you can also do something like this:I ran into a similar problem in Linux, except it was \"ps -ef | grep someprocess\".\nAt least with \"ls\" you have a language-independent (albeit slower) Java replacement.  Eg.:With \"ps\", it's a bit harder, because Java doesn't seem to have an API for it.I've heard that Sigar might be able to help us:\nThe simplest solution, however, (as pointed out by Kaj) is to execute the piped command as a string array.  Here is the full code:As to why the String array works with pipe, while a single string does not... it's one of the mysteries of the universe (especially if you haven't read the source code).  I suspect that it's because when exec is given a single string, it parses it first (in a way that we don't like).  In contrast, when exec is given a string array, it simply passes it on to the operating system without parsing it.Actually, if we take time out of busy day and look at the source code\n(at ), we find that is exactly what is happening:Create a Runtime to run each of the process. Get the OutputStream from the first Runtime and copy it into the InputStream from the second one.
Java

My questions is: Is there a good solution to use regular expression in GWT?I'm not satisfied with the use of String.split(regex) for example. GWT translates the Code to JS and then uses the regex as a JS regex. But I cannot use something like the Java Matcher or Java Pattern. But I would need these for group matching.Is there any possibility or library?I tried Jakarta Regexp, but I had other problems because GWT doesn't emulate all methods of the Java SDK this library uses. I want to be able to use something like this on the client side:The same code using RegExp could be:GWT 2.1 now has a  class that might solve your problem:This answer covers ALL pattern matches, not only one, as in other answers here:Function:...and sample use:If you want a pure GWT solution, I'm not sure it can be done. But if you're willing to use JSNI, you can use JavaScript's RegExp object to get the matched groups and all. You'll need to learn JSNI for GWT and JavaScript RegExp object.The  seems to provide an emulation of java.util.regex.Pattern and friends.\nIt doesn't look complete (Matcher in particular), but might be a good start.The technique they use to plug their own implementations of Java classes for the client side is the  declaration in module XML. It's mentioned in GWT docs, module XML format description under \"Overriding one package implementation with another\". Standard JRE translatable classes in GWT are emulated the same way.
Java

How do I lock compiled Java classes to prevent decompilation?I know this must be very well discussed topic on the Internet, but I could not come to any conclusion after referring them.Many people do suggest obfuscator, but they just do renaming of classes, methods, and fields with tough-to-remember character sequences but what about sensitive constant values?For example, you have developed the encryption and decryption component based on a password based encryption technique. Now in this case, any average Java person can use  to decompile the class file and easily retrieve the password value (defined as constant) as well as  and in turn can decrypt the data by writing small independent program!Or should such sensitive components be built in native code (for example, VC++) and call them via ?Some of the more advanced Java bytecode obfuscators do much more than just class name mangling. , for example, can also scramble your code flow in a way that makes it really hard to follow and works as an excellent code optimizer...Also many of the obfuscators are also able to scramble your string constants and remove unused code.Another possible solution (not necessarily excluding the obfuscation) is to use  and a custom classloader that does the decryption (preferably using native runtime library).Third (and possibly offering the strongest protection) is to use native ahead of time compilers like  or , for example, that compile your Java code directly to a platform specific native binary.In any case You've got to remember that as the saying goes in Estonian \"Locks are for animals\". Meaning that every bit of code is available (loaded into memory) during the runtime and given enough skill, determination and motivation, people can and will decompile, unscramble and hack your code... Your job is simply to make the process as uncomfortable as you can and still keep the thing working...As long as they have access to both the encrypted data and the software that decrypts it, there is basically no way you can make this completely secure. Ways this has been solved before is to use some form of external black box to handle encryption/decryption, like dongles, remote authentication servers, etc. But even then, given that the user has full access to their own system, this only makes things difficult, not impossible -unless you can tie your product directly to the functionality stored in the \"black box\", as, say, online gaming servers.Disclaimer: I am not a security expert.This sounds like a bad idea: You are letting someone encrypt stuff with a 'hidden' key that you give him. I don't think this can be made secure.Maybe asymmetrical keys could work:I'm not sure, but I believe the client can actually encrypt the license key with the public key you gave him. You can then decrypt it with your private key and re-encrypt as well.You could keep a separate public/private key pair per customer to make sure you actually are getting stuff from the right customer - now  are responsible for the keys...No matter what you do, it can be 'decompiled'. Heck, you can just disassemble it. Or look at a memory dump to find your constants. You see, the computer needs to know them, so your code will need to too.What to do about this?Try not to ship the key as a hardcoded constant in your code: Keep it as a per-user setting. Make the user responsible for looking after that key.Take a look at the  article  by Vladimir Roubtsov. It explains why encryption of class files is mostly pointless.@jatanp: or better yet, they can decompile, remove the licensing code, and recompile.  With Java, I don't really think there is a proper, hack-proof solution to this problem.  Not even an evil little dongle could prevent this with Java.My own biz managers worry about this, and I think too much.  But then again, we sell our application into large corporates who tend to abide by licensing conditions--generally a safe environment thanks to the bean counters and lawyers.  The act of decompiling itself can be illegal if your license is written correctly. So, I have to ask, do you  need hardened protection like you are seeking for your application?  What does your customer base look like?  (Corporates?  Or the teenage gamer masses, where this would be more of an issue?)I don't think there exists any effective offline antipiracy method. The videogame industry has tried to find that many times and their programs has always been cracked. The only solution is that the program must be run online connected with your servers, so that you can verify the lincense key, and that there is only one active connecion by the licensee at a time. This is how  or  works. Even tough there are private servers developed for them to bypass the security. Having said that, I don't believe that mid/large corporations use illegal copied software, because the cost of the license for them is minimal (perhaps, I don't know how much you are goig to charge for your program) compared to the cost of a trial version.If you're looking for a licensing solution, you can check out the . It's based on the use of asymmetrical keys. However, it doesn't mean your application cannot be cracked. Every application can be cracked with enough effort. What really important is, as , figuring out how strong protection you need. You can use byte-code encryption with no fear. The fact is that the cited above paper \u201cCracking Java byte-code encryption\u201d contains a logic fallacy. The main claim of the paper is . But this is not true. The assumption missed here is . Nothing can oblige the protected java app not only to launch these classes but even decrypt and pass them to . In other words, if you are in standard JRE you can't intercept  method because the standard java has no API for this purpose, and if you use modified JRE with patched  or any other \u201chacker trick\u201d you can't do it because protected java app will not work at all, and therefore you will have nothing to intercept. And absolutely doesn't matter which \u201cpatch finder\u201d is used or which trick is used by hackers. These technical details are a quite different story. Q: If I encrypt my .class files and use a custom classloader to load and decrypt them on the fly, will this prevent decompilation?A: The problem of preventing Java byte-code decompilation is almost as old the language itself. Despite a range of obfuscation tools available on the market, novice Java programmers continue to think of new and clever ways to protect their intellectual property. In this Java Q&A installment, I dispel some myths around an idea frequently rehashed in discussion forums.The extreme ease with which Java .class files can be reconstructed into Java sources that closely resemble the originals has a lot to do with Java byte-code design goals and trade-offs. Among other things, Java byte code was designed for compactness, platform independence, network mobility, and ease of analysis by byte-code interpreters and JIT (just-in-time)/HotSpot dynamic compilers. Arguably, the compiled .class files express the programmer's intent so clearly they could be easier to analyze than the original source code.Several things can be done, if not to prevent decompilation completely, at least to make it more difficult. For example, as a post-compilation step you could massage the .class data to make the byte code either harder to read when decompiled or harder to decompile into valid Java code (or both). Techniques like performing extreme method name overloading work well for the former, and manipulating control flow to create control structures not possible to represent through Java syntax work well for the latter. The more successful commercial obfuscators use a mix of these and other techniques.Unfortunately, both approaches must actually change the code the JVM will run, and many users are afraid (rightfully so) that this transformation may add new bugs to their applications. Furthermore, method and field renaming can cause reflection calls to stop working. Changing actual class and package names can break several other Java APIs (JNDI (Java Naming and Directory Interface), URL providers, etc.). In addition to altered names, if the association between class byte-code offsets and source line numbers is altered, recovering the original exception stack traces could become difficult.Then there is the option of obfuscating the original Java source code. But fundamentally this causes a similar set of problems.\nEncrypt, not obfuscate?Perhaps the above has made you think, \"Well, what if instead of manipulating byte code I encrypt all my classes after compilation and decrypt them on the fly inside the JVM (which can be done with a custom classloader)? Then the JVM executes my original byte code and yet there is nothing to decompile or reverse engineer, right?\"Unfortunately, you would be wrong, both in thinking that you were the first to come up with this idea and in thinking that it actually works. And the reason has nothing to do with the strength of your encryption scheme.
Java

I noticed some unexpected behavior (unexpected relative to my personal expectations), and I'm wondering if something if there is a bug in the JVM or if perhaps this is a fringe case where I don't understand some of the details of what exactly is supposed to happen.  Suppose we had the following code in a main method by itself:A naive expectation would be that this would print , the largest even representable .  However, I believe integer arithmetic is supposed to \"rollover\" in Java, so adding 1 to  should result in .  Since  is still less than , the loop would keep iterating through the negative even ints.  Eventually it would get back to 0, and this process should repeat as an infinite loop.When I actually run this code, I get non-deterministic results.  The result that gets printed tends to be on the order of half a million, but the exact value varies.  So not only is the loop terminating when I believe it should be an infinite loop, but it seems to terminate randomly.  What's going on?My guess is that this is either a bug in the JVM, or there is a lot of funky optimization going on that makes this expected behavior.  Which is it?Known bug. Related toand others.I think they're considered low-priority to fix because they don't come up in the real world.This is bizarre. It certainly looks like a bug somewhere. I get the same results every time with the same code, but trivial changes to the code change the result. For example:... always prints 2147483640 and truewhereas this:always prints -2147483648 and true.Very, very weird.(That's running an OpenJDK 1.6 VM on Linux.)EDIT: Running OpenJDK 1.7 on Windows 7, I don't see the problem:Try adding I wonder if there is optimization occurring because count is never read from. - another answer gave the link to bugs in Oracle's bug tracker. Drawing from that:However, this is unlikely to occur in practice, because:This seems to be a loop optimizations as I observe the same result but IF I also print out  then the result changes.I.e.Produces 2147483638 while the original code produces 457158 (or similar)
Java

When  is a , is  guaranteed to be , or might it sometimes be  (depending on the sign of )? can be  or . There are no other values it can take in IEEE 754 arithmetics in round-to-nearest (and in Java, the rounding mode is ). The subtraction of two identical finite values is  as producing  in this rounding mode. , in comments below, cites the IEEE 754 standard as saying, section 6.3:This  shows that in particular  and  are both .Infinities and NaN both produce NaN when subtracted from themselves.The SMT solver Z3 supports IEEE floating point arithmetic. Let's ask Z3 to find a case where . It immediately finds  as well as . Excluding those, there is no  that satisfies that equation.Z3 implements IEEE floating point arithmetic by converting all operations to boolean circuits and using the standard SAT solver to find a model. Barring any bugs in that translation or the SAT solver the result is perfectly precise.Proof for...Note the counterexample for the rounding mode : . For a certain  the result of  is negative zero. Such a case can hardly be found by humans. Yet, with an SMT solver it is easy to find. We can change  to  so that Z3 uses IEEE equality comparison semantics instead of exact equality. After that change, there is again no counter-example because  according to IEEE.I tried making the rounding mode a variable. That would work in theory but Z3 has a bug here. For now we have to manually specify a hard-coded rounding mode. If we could make it a variable we could ask Z3 to prove this statement for  rounding modes in one query.
Java

What does \"\" do in Eclipse?  It syncs the Eclipse project settings with that of the pom. If you for example change important plugin settings, such as the output java version, you will find that Eclipse will ask you to update the project and afterwards the configured Java runtime in the project will have changed to reflect what your Maven pom indicates.That is an important thing to keep in mind: the Maven pom is the lead in this kind of project setup. If you want settings to change, try to do that through the pom and not through Eclipse project settings directly or doing a project update might revert what you have changed. There are usually some things I have to correct myself anyway though, such as build path exclusions that m2eclipse likes to put in and strange deployment assembly configurations.To add on to what @Gimby said - Update Project also provides more options such as  which is extremely helpful when you have dependencies that are looking for the latest. (e.g.:   will find 1.0.* - whatever's the latest.)Updating project is synonymous with Ivy's Resolve.  It will make sure that all referenced dependencies are there, as well as clean the project to make sure that they are included correctly.
Java

How deep do I need to go into the call stack before I get a StackOverflowError? Is the answer platform dependent?It depends on the amount of virtual memory allocated to the stack.  You can tune this with the  VM parameter or with the  constructor.The stack size can be set with the  command line switch but as a rule of thumb, it is deep enough, hundreds if not thousands of calls deep. (The default is platform dependent, but at least 256k in most platforms.)If you get a stack overflow, 99% of the time it's caused by an error in the code.I tested on my system and didn't find any constant value, sometimes stack overflow occurs after 8900 calls, sometimes only after 7700, random numbers.Compare these two calls:\n(1) Static method:(2) Non-static method using a different class:Test recursion class has  as the only method.
Java

A new feature coming in JDK 8 allows you to add to an existing interface while preserving binary compatibility.The syntax is likeThis way for all existing implementations of  when they upgrade to this new version they don't all suddenly have compiles errors around .While this is neat, what happens when you are implementing two interfaces which both have added a new defaulted method which you did not implement?  Let me explain with an example.Has this been defined as part of JDK 8 yet?I found the Java gods talking about something similar here , but its part of private mailing list and I cannot ask them directly.See this for more details on how defaults are going to be used in JDK 8 and extending the Collection interface to support lambdas:\nThe video session to watch is here  This is the designer talking about the feature called Virtual Extensions. He also talks about how this doesn't break backward compatibility.The answer to the duplicate operation is:My answer to your question is: Yes, it is a form of multiple inheritance, because you can inherit behavior from different parents. What's missing is to inherit states, i. e., attributes.I know this is a old post, but as i'm working with this stuff...You will have an error from the compiler, telling you that:Yes, but you can add getters and setters to your interface that the implementing classes then must implement. Nevertheless, the implementing classes don't inherit attributes. So, AFAICS, it's more like a trait-style solution rather than a multiple inheritance style solution. If anyone's still looking for an answer, in case a class implements two interfaces with the same default method then the class needs to resolve the disambiguity by providing an implementation of its own. Look at  tutorial for more details on how inheritance in default methods work.In short: it's a compile time error, must over the method by hand in the implementation.The major purpose to introduce default method in Java 8, is to make interface extendable, without breaking existing implementations (there are so many 3rd party Java libraries).And  like in C++ is actually intended to be avoided, that's definitely not the purpose of default method in Java.2 options:Tips:There are  scenarios:1) First, that was mentioned, where there is 2) Second, when there As far as I see it, it is no multiple inheritance because they are stateless.\nSo virtual extension methods don't support full object or class functionality. 
Java

I have a class that takes objects from a  and processes them by calling  in a continuous loop.  At some point I know that no more objects will be added to the queue.  How do I interrupt the  method so that it stops blocking?Here's the class that processes the objects:And here's the method that uses this class to process objects:If interrupting the thread is not an option, another is to place a \"marker\" or \"command\" object on the queue that would be recognized as such by MyObjHandler and break out of the loop.However, if you do this, the thread might be interrupted while there are still items in the queue, waiting to be processed. You might want to consider using  instead of , which will allow the processing thread to timeout and terminate when it has waited for a while with no new input. I faced the similar problem and used the  approach suggested by  with some minor changes,  Interrupt the thread:Or don't interrupt, its nasty.
Java

I want to access messages in GMail from a Java application using JavaMail and IMAP. Why am I getting a  ?Here is my code:I set the timeout values so that it wouldn't take \"forever\" to timeout. Also,  also has the username and password, which seems redundant with the URL. Is there another way to specify the protocol? (I didn't see it in the JavaDoc for IMAP.)Using imaps was a great suggestion. Neither of the answers provided just worked for me, so I googled some more and found something that worked. Here's how my code looks now.This is nice because it takes the redundant Authenticator out of the picture. I'm glad this worked because the SSLNOTES.txt make my head spin.In JavaMail, you can use  as the URL scheme to use IMAP over SSL. (See  in your JavaMail distribution for more details.) For example, .Similarly, use  to send emails via Gmail. e.g., . Again, read  for more details. Hope it helps!You need to use the following properties for imaps:Notices it's \"imaps\", not \"imap\", since the protocol you're using is imaps (IMAP + SSL)You have to connect to GMail using SSL only. Setting the following properties will force that for you. If you'd like more sample code on using JavaMail with Gmail (e.g. converting Gmail labels to IMAP folder names, or using IMAP IDLE), do check out my program  on .Check . There is a minimal gmail client built using this API.I used following properties to get the store and It works well.Here is what worked for my team and I, given a classic account nickname@gmail.com and a business account employee@business.com :with USERNAME = \"nickname\" in the classic case, and USERNAME = \"employee@business.com\" in the business account case.In the classic case, and if you use an old JavaMail dependency, don't forget to lower the account security here : In both cases check in GMail  if IMAP is enabled for the account.Hope it helps!To go further :You need to have JSSE installed to use SSL with Java
Java

This is the code I have:And the tests I have, which I run .When I run test  I will see:But when I run the test  all I see is:Quoting from  page..So my understanding is, in test bar, Stupid class is loaded, otherwise I would have seen a null I guess? So Class object is created because class itself is loaded..And now quoting from  page  So I am expecting to see the \"Stupid class loaded!\" text in test bar as well, but I am not.Also quoting from which is not very accurate it seems..What am I missing?The above quote is plain wrong, but it is just one instance of a very widespread misconception. initializes the class by default, but you have the choice of calling an overload that takes a  and supplying . You'll get the class loaded without initializing.In the first case you are loading and initializing a class when you use , that's why the static initializers are run and hence you see  as output . In the second case, you are just assigning a reference of the class,  (use java -verbose:class to see what classes are loaded) but you aren't really initializing it (or to be more precise, not doing anything that forces the initializers to run). Thus you don't see the output as . Try doing something like calling  on the class, it should force the  initialization of the class and you should see My code : ^ - This shows that the class is loaded but not initialized.
Java

Is it correct practice to add Javadoc comments in Interface and add non Javadoc comments in the implementation?Most IDEs generate non JavaDoc comments for implementations when you auto generate comments. Shouldn't the concrete method have the description?For methods that are implementation only (not overrides), sure, why not, especially if they are public.If you have an overriding situation and you are going to replicate any text, then definitely not. Replication is a surefire way of causing discrepancies. As a result, users would have a different understanding of your method based on whether they examine the method in the supertype or the subtype. Use  or don't provide a documentation - The IDEs will take the lowest available text to use in their Javadoc view. As an aside, if your overriding version adds stuff to the documentation of the supertype, you could be in a world of trouble. I studied this problem during my PhD and found that in general folks will never be aware of the extra information in the overriding version if they are invoking through a supertype. Addressing this problem was one of the major feature of the prototype tool that I built - Whenever you invoked a method, you got an indication if its target or any potential overriding targets contained important information (e.g., a conflicting behavior). For instance, when invoking put on a map, you were reminded that if your implementation is a TreeMap, your elements need to be comparable.Both the implementation and the interface should have javadoc. With some tools, you can inherit the documentation of the interface with the @inheritDoc keyword.Somewhat good practice is to putas implementation's javadoc (unless there's something extra to be explained about the implementation's details).@see generates a link to the description in the interface. But i think it is good to add some details about the implementation too.Sjoerd correctly says that both interface and implementation should have JavaDoc. The interface JavaDoc should define the contract of the method - what the method should do, what inputs it takes, what values it should return, and what it should do in cases of error.The implementation documentation should note extensions or restrictions on the contract, and also appropriate details of the implementation, especially performance. Generally, when you override a method, you adhere to the contract defined in the base class/interface, so you don't want to change the original javadoc anyhow. Therefore the usage of  or  tag mentioned in other answers is not needed and actually only serves as a noise in the code. All sensible tools inherit method javadoc from the superclass or interface as specified :The fact that some tools (I'm looking at you, Eclipse!) generate these by default when overriding a method is only a sad state of things, but doesn't justify cluttering your code with useless noise.There can of course be the opposite case, when you actually want to add a comment to the overriding method (usually some additional implementation details or making the contract a bit stricter). But in this case, you almost never want to do something like this:Why? Because the inherited comment can possibly be very long. In such case, who will notice the extra sentence at the end of the 3 long paragraphs?? Instead, just write down the piece of your own comment and that's all. All the javadoc tools always show some kind of  link which you can click to read the base class comment. There is no point in mixing them.For the sake of generated javadoc yes it does matter. If you declare references to a concrete implementation using only the interface then it doesn't since interface's methods will be retrieved by the IDE.
Java

I have a program like this:If I try to execute it, i am getting compiler error as :  based on java default values i should get the below output right??Will final variables have dafault values?if I change my code like this,I am getting output as:Can anyone please explain this behavior.., chapter \"Initializing Instance Members\":That is to say:behaves exactly like:As you can thus see, once an instance has been created, the final field has not been , while (from ):While it does not seem to be stated explitely in the docs (at least I have not been able to find it), a final field must temporary take its default value before the end of the constructor, so that it has a  if you read it before its assignment.Default values: On your second snippet, x is initialized on instance creation, so the compiler does not complain:Also note that the following approach doesn't work. Using default value of final variable is only allowed through a method. is  that you  assign the default value to blank final instance variable in constructor (or in  which is pretty the same). That is why you get the error in the first case. However it doesn't say that you can not access it in constructor before. Looks weird a little bit, but you can access it before assignment and see default value for int - 0.    As mentioned by @I4mpi,   the rule that each value should be  before any access:However, it also has an  in regards to constructors and fields:So in second case the value  is  at the beginning of the constructor, because it contains the assignment at the end of it. If you don't initialize  you'll get a compile-time error since  is never initialized. Declaring  as final means that it can be initialized only in the constructor or in  (since this block will be copied by the compiler into every constructor). The reason that you get  printed out before the variable is initialized is due to the behavior  defined in the  (see: \"Default Values\" section):The first error is the compiler complaining that you have a final field, but no code to initialize it - simple enough.In the second example, you have code to assign it a value, but the sequence of execution means you reference the field both before and after assigning it.The pre-assigned value of any field is the default value.All non-final fields of a class initialize to a default value ( for nummeric data types,  for boolean and  for reference types, sometimes called complex objects). These fields initialize before a constructor (or instance initialization block) executes independent of whether or not the fields was declared before or after the constructor. fields of a class has  and must be explicitly initialized just once before a class constructor has finished his job.Local variables on the inside of an execution block (for example, a method) has no default value. These fields must be explicitly initialized before their first use and it doesn't matter whether or not the local variable is marked as final.Let me put it in the simplest words I can. variables need to be initialized, this is mandated by the Language Specification.\nHaving said that, please note that it is not necessary to initialize it at the time of declaration. It is required to initialize that before the object is initialized.We can use initializer blocks to initialize the final variables. Now, initializer blocks are of two types\n and The block you used is a non-static initializer block. So, when you create an object, Runtime will invoke constructor and which in turn will invoke the constructor of the parent class.After that, it will invoke all the initializers (in your case the non-static initializer). In your question, : Even after the completion of initializer block the final variable remains un-initialized, which is an error compiler will detect.In : The initializer will initialize the final variable, hence the compiler knows that before the object is initialized, the final is already initialized. Hence, it will not complain.Now the question is, why does  takes a zero. The reason here is that compiler already knows that there is no error and so upon invocation of init method all the finals will be initialized to defaults, and a flag set that they can change upon actual assignment statement similar to .\nSee the init invocation below:As far as I'm aware, the compiler will always initialize class variables to default values (even final variables). For example, if you were to initialize an int to itself, the int would be set to its default of 0. See below:The above would print the following:No. You are not seeing that output because you are getting a compile-time error in the first place. Final variables do get a default value, but the Java Language Specification (JLS) requires you to initialize them by the end of the constructor (LE: I'm including initialization blocks here), otherwise you'll get a compile-time error which will prevent your code to be compiled and executed. Your second example respects the requirement, that's why (1) your code compiles and (2) you get the expected behaviour. In the future try to familiarize yourself with the JLS. There's no better source of information about the Java language.
Java

Looking at the last JUnit test case I wrote, I called log4j's BasicConfigurator.configure() method inside the class constructor.  That worked fine for running just that single class from Eclipse's \"run as JUnit test case\" command.  But I realize it's incorrect: I'm pretty sure our main test suite runs all of these classes from one process, and therefore log4j configuration should be happening higher up somewhere.But I still need to run a test case by itself some times, in which case I want log4j configured.  Where should I put the configuration call so that it gets run when the test case runs standalone, but not when the test case is run as part of a larger suite?The  class determines which log4j config to use in a  which runs when the class is loaded.  There are three options intended for end-users:See also the .I generally just put a log4j.xml file into src/test/resources and let log4j find it by itself: no code required, the default log4j initialisation will pick it up. (I typically want to set my own loggers to 'DEBUG' anyway)You may want to look into to . It is a facade that wraps around Log4j that doesn't require an initial setup call like Log4j. It is also fairly easy to switch out Log4j for Slf4j as the API differences are minimal.I use system properties in log4j.xml:and start tests with:
Java

I noticed in the Java 6 source code for String that hashCode only caches values other than 0. The difference in performance is exhibited by the following snippet: gives the following output:So my questions are:For your amusement, each line here is a string that hash to 0:You're worrying about nothing.  Here's a way to think about this issue.Suppose you have an application that does nothing but sit around hashing Strings all year long.  Let's say it takes a thousand strings, all in memory, calls hashCode() on them repeatedly in round-robin fashion, a million times through, then gets another thousand new strings and does it again.And suppose that the likelihood of a string's hash code being zero were, in fact, much greater than 1/2^32.  I'm sure it is  greater than 1/2^32, but let's say it's a lot worse than that, like 1/2^16 (the square root! now that's a lot worse!).In this situation, you have more to benefit from Oracle's engineers improving how these strings' hash codes are cached than anyone else alive. So you write to them and ask them to fix it. And they work their magic so that whenever s.hashCode() is zero, it returns  (even the first time! a 100% improvement!). And let's say that they do this without degrading the performance at all for any other case.Hooray!  Now your app is... let's see... 0.0015% faster!What used to take an entire day now takes only 23 hours, 57 minutes and 48 seconds!And remember, we set up the scenario to give every possible benefit of the doubt, often to a ludicrous degree.Does this seem worth it to you? since posting this a couple hours ago, I've let one of my processors run wild looking for two-word phrases with zero hash codes. So far it's come up with: bequirtle zorillo, chronogrammic schtoff, contusive cloisterlike, creashaks organzine, drumwood boulderhead, electroanalytic exercisable, and favosely nonconstruable. This is out of about 2^35 possibilities, so with perfect distribution we'd expect to see only 8. Clearly by the time it's done we'll have a few times that many, but not outlandishly more. What's more significant is that I've now come up with a few interesting band names/album names!  No fair stealing!It uses 0 to indicate \"I haven't worked out the hashcode yet\". The alternative would be to use a separate Boolean flag, which would take more memory. (Or to not cache the hashcode at all, of course.)I don't expect  strings hash to 0; arguably it would make sense for the hashing routine to deliberately avoid 0 (e.g. translate a hash of 0 to 1, and cache that). That would increase collisions but avoid rehashing. It's too late to do that now though, as the String hashCode algorithm is explicitly documented.As for whether this is a good idea in general: it's an certainly efficient caching mechanism, and  (see edit) be even better with a change to avoid rehashing values which end up with a hash of 0. Personally I would be interested to see the data which led Sun to believe this was worth doing in the first place - it's taking up an extra 4 bytes for every string ever created, however often or rarely it's hashed, and the only benefit is for strings which are hashed .EDIT: As KevinB points out in a comment elsewhere, the \"avoid 0\" suggestion above may well have a net  because it helps a  case, but requires an extra comparison for  hash calculation.I think there's something important that the other answers so far are missing: the zero value exists so that the hashCode-caching mechanism works robustly in a multi-threaded environment.If you had two variables, like cachedHashCode itself and an isHashCodeCalculated boolean to indicate whether cachedHashCode had been calculated, you'd need thread synchronization for things to work in a multithreaded environment.  And synchronization would be bad for performance, especially since Strings are very commonly reused in multiple threads.My understanding of the Java memory model is a little sketchy, but here's roughly what's going on:The hashCode caching mechanism in java.lang.String is set up to rely on point 5 above.  You might understand it better by looking at the source of java.lang.String.hashCode().  Basically, with multiple threads calling hashCode at once, hashCode might end up being calculated multiple times (either if the calculated value is zero or if multiple threads call hashCode at once and both see a zero cached value), but you can be sure that hashCode() will always return the same value.  So it's robust, and it's performant too (because there's no synchronization to act as a bottleneck in multi-threaded environments).Like I said, my understanding of the Java memory model is a little sketchy, but I'm pretty sure I've got the gist of the above right.  Ultimately it's a very clever idiom for caching the hashCode without the overhead of synchronization.0 isn't cached as the implementation interprets a cached value of 0 as \"cached value not yet initialised\".  The alternative would have been to use a , whereby null implied that the value was not yet cached.  However, this would have meant an additional storage overhead.Regarding the probability of a String's hash code being computed as 0 I would say the probability is quite low and can happen in the following cases:From :This turns out to be a good question, related to a .The value zero is reserved as meaning \"the hash code is not cached\".According to the Javadoc, the formula for a String's hashcode is:using  arithmetic, where  is the ith character of the string and  is the length of the string.  (The hash of the empty String is defined to be zero as a special case.)My intuition is that the hashcode function as above gives a uniform spread of String hash values across the range of  values.  A uniform spread that would mean that the probability of a randomly generated String hashing to zero was 1 in 2^32.The best strategy is to ignore the issue.  If you are repeatedly hashing the same String value, there is something rather strange about your algorithm.This is a space versus time trade-off.  AFAIK, the alternatives are:I think that the Java designers have made the right call for Strings, and I'm sure that they have done extensive profiling that confirms the soundness of their decision.  However, it  follow that this would  be the best way to deal with caching.(Note that there are two \"common\" String values which hash to zero; the empty String, and the String consisting of just a NUL character.  However, the cost of calculating the hashcodes for these values is small compared with the cost of calculating the hashcode for a typical String value.)Well folks, it keeps 0 because if it is zero length, it will end up as zero anyways.And it doesn't take long to figure out that the len is zero and so must the hashcode be.So, for your code-reviewz! Here it is in all it's Java 8 glory:As you can see, this will always return a quick zero if the string is empty:The \"avoid 0\" suggestion seems appropriate to recommend as best practice as it helps a genuine problem (seriously unexpected performance degradation in constructible cases that can be attacker supplied) for the meager cost of a branch operation prior to a write. There is some remaining 'unexpected performance degradation' that can be exercised if the only things going into a set hash to the special adjusted value. But this is at worst a 2x degradation rather than unbounded.Of course, String's implementation can't be changed but there is no need to perpetuate the problem.
Java

Given a stream such as , how can I most elegantly transform it into given form: (assuming, of course, I've defined class Pair)? This isn't strictly about ints or primitive streams. The answer should be general for a stream of any type.My  library which extends standard streams provides a  method for all stream types. For primitive streams it does not change the stream type, but can be used to make some calculations. Most common usage is to calculate differences:For object stream you can create any other object type. My library does not provide any new user-visible data structures like  (that's the part of library concept). However if you have your own  class and want to use it, you can do the following:Or if you already have some :This functionality is implemented using . It has quite low overhead and can parallelize nicely. Of course it works with any stream source, not just random access list/array like many other solutions. In many tests it performs really well.  a JMH benchmark where we find all input values preceding a larger value using different approaches (see  question).The Java 8 streams library is primarily geared toward splitting streams into smaller chunks for parallel processing, so stateful pipeline stages are quite limited, and doing things like getting the index of the current stream element and accessing adjacent stream elements are not supported.A typical way to solve these problems, with some limitations, of course, is to drive the stream by indexes and rely on having the values being processed in some random-access data structure like an ArrayList from which the elements can be retrieved. If the values were in , one could generate the pairs as requested by doing something like this:Of course the limitation is that the input cannot be an infinite stream. This pipeline can be run in parallel, though.There is not elegant, it's a hackish solution, but works for infinite streamsNow you can limit your stream as long as you want I hope there is better solution, something like clojure I've implemented a spliterator wrapper which takes every  elements  from the original spliterator and produces :Following method may be used to create a consecutive stream:Sample usage:You can do this in  (I contribute to this library), using the sliding operator.Or Assuming the Pair constructor can accept a Collection with 2 elements. If you wanted to group by 4, and increment by 2 that is also supported.Equivalant static methods for creating a sliding view over java.util.stream.Stream are also provided in cyclops-streams  class.Note :- for single-threaded operation ReactiveSeq would be more appropriate. LazyFutureStream extends ReactiveSeq but is primarily geared for concurrent / parallel use (it is a Stream of Futures).LazyFutureStream extends ReactiveSeq which extends Seq from the awesome jOO\u03bb (which extends java.util.stream.Stream), so the solutions Lukas' presents would also work with either Stream type. For anyone interested the primary differences between the window / sliding operators are the obvious  relative power / complexity trade off and suitability for use with infinite streams (sliding doesn't consume the stream, but buffers as it flows). The  provides the windowed functionnality. Given a Pair class and a Stream, you can do it like this:Now the  stream contains:If you're willing to use a third party library and don't need parallelism, then  offers SQL-style window functions as followsYieldingThe  function accesses the next value in traversal order from the window.A question in the comments was asking for a more general solution, where not pairs but n-tuples (or possibly lists) should be collected. Here's thus an alternative approach:Yielding a list of listsWithout the , the result would beDisclaimer: I work for the company behind jOO\u03bbWe can use  (very powerful  library)You can do this with the Stream.reduce() method (I haven't seen any other answers using this technique).In your case, I would write my custom IntFunction which keeps track of the last int passed and use that to map the original IntStream.The operation is essentially stateful so not really what streams are meant to solve - see the \"Stateless Behaviors\" section in the :One solution here is to introduce state in your stream through an external counter, although it will only work with a sequential stream.An elegant solution would be to use . Something like:This is pretty concise and elegant, however it uses a list as an input. An infinite stream source cannot be processed this way.Another (lot more troublesome) issue is that zip together with the entire Streams class has been lately removed from the API. The above code only works with  or older releases. So with the latest JDK I would say there is no elegant FP style solution and right now we can just hope that in some way zip will be reintroduced to the API.This is an interesting problem. Is my  attempt below any good?I believe it does not lend itself to parallel processing, and hence may be disqualified. As others have observed, there is, due to the nature of the problem, some statefulness required.I was faced with a similar problem, in which I wanted what was essentially the Oracle SQL function LEAD. My attempt to implement that is below.You can achieve that by using a bounded queue to store elements which flows through the stream (which is basing on the idea which I described in detail here: )Belows example first defines instance of BoundedQueue class which will store elements going through the stream (if you don't like idea of extending the LinkedList, refer to link mentioned above for alternative and more generic approach). Later you just combine two subsequent elements into instance of Pair:I agree with @aepurniet\nbut instead map you have to use mapToObjRun a  loop that runs from 0 to  of your stream
Java

I have read \"\" but I'm still confused. How do I know when I should mark a variable volatile? What if I get it wrong, either omitting a volatile on something that needs it or putting volatile on something that doesn't? What are the rules of thumb when figuring out what variables should be volatile in multithreaded code?You basically use it when you want to let a member variable be accessed by multiple threads but do not need compound atomicity (not sure if this is the right terminology).the above is a bad example, because you  compound atomicity.Now to a valid example:Now, why can't you just use ? In fact you can (in the sense that that your program won't blow up or something), but the change to  by the other thread may or may not be \"visible\" to the main thread.  Basically this means that it is even possible that your app. keeps writing  forever if you  use  (in practice, the value tends to become eventually visible. However, you should not risk not using volatile when necessary, since it can lead to nasty bugs (caused by in-completely constructed objects etc.).If you put  keyword on something that doesn't need , it won't affect your code's correctness (i.e. the behaviour will not change). In terms of performance, it will depend on the JVM implementation. In theory you might get a tiny performance degradation because the compiler can't do reordering optimisations, have to invalidate CPU cache etc., but then again the compiler could prove that your field cannot ever be accessed by multiple threads and remove the effect of  keyword completely and compile it to identical instructions.  \nResponse to this comment:  You can and it will behave correctly. Anything that you can with  can be done with , but not vice versa. There are two reasons you might prefer  if you can:  Volatile is most useful in lock-free algorithms. You mark the variable holding shared data as volatile when you are not using locking to access that variable and you want changes made by one thread to be visible in another, or you want to create a \"happens-after\" relation to ensure that computation is not re-ordered, again, to ensure changes become visible at the appropriate time.The  describes which operations can be re-ordered and which cannot.The  can also be used to safely publish immutable objects in a multi-threaded Environment.Declaring a field like  secures that all threads always see the currently available instance reference.See  for more on that topic.Actually disagree with the example given in the top voted answer, to my knowledge it does  properly illustrate volatile semantics as per the Java memory model. Volatile has way more complex semantics. In the example provided, the main thread could continue to print \"Today's temperature is 0\" forever even if there is another thread running that is supposed to update the temperature if that other thread never gets scheduled.A better way to illustrate volatile semantics is with 2 variables.   For simplicity's sake, we will assume that the only way to update the two variables is through the method .For simplicity's sake, we will assume that only 2 threads are running, main thread and thread 2.the last two assignment instructions can  be reordered for optimization purposes by either the compiler, runtime or the hardware.Once the main thread reads the volatile variable temperature (in the process of printing it),1) There is a guarantee that it will see the  value of this volatile variable regardless of how many threads are writing to it, regardless of which method they are updating it in, synchronized or not.2) If the system.out statement in the main thread runs,  the time instant at which thread 2 has run the statement temperature = temp,  both yesterday's temperature and todays temperature will be guaranteed to print the values set in them by thread 2 when it ran the statement temperature=temp.This situation gets a  more complex if a) Multiple threads are running and b) There are other methods than just the setTemperatures method that can update the variable yesterday's temperature and todays temperature that are actively being called by these other threads. I think it would take a decent size article to analyze the implications based on how the Java Memory Model describes the volatile semantics. In short, attempting to just use volatile for synchronization is extremely risky, and you would be better off sticking to synchronizing your methods. From java concurrency  :This means that changes to a volatile variable are always visible to other threads. It also means that when a thread reads a volatile variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change.Regarding your query:If you feel that all reader threads always get latest value of a variable, you have to mark variable as , volatile modifier guarantees memory consistency. If you have multiple threads to write and read variables,  modifier alone does not guaranty memory consistency.  You have to  the code or use high level  constructs like , ,  etc. Related SE questions/articles: article\"The volatile keyword is used on variables that may be modified simultaneously by other threads.\"\"Since other threads cannot see local variables, there is never any need to mark local variables volatile. You need synchronized to co-ordinate changes to variables from different threads, but often volatile will do just to look at them.\"
Java

I am new to Maven, I have a Java based web project with maven configured in my MyEclipse.\nNow if I modified any java files then do I need to do  or ?from So the answer to your question is, it depends on whether you want it in installed into your local repo. Install will also run package because it's higher up in the goal phase stack. is the option that is most often used.\n is seldom used, only if you're debugging some issue with the maven build process.    See:   Note that  will only create a jar file.\n will do that  install the jar (and class etc.) files in the proper places if other code depends on those jars.  I usually do a ; this deletes the  directory and recreates all jars in that location.\nThe clean helps with unneeded or removed stuff that can sometimes get in the way.\nRather then debug (some of the time) just start fresh all of the time.  From the ,  will run the project's integration tests,  won't.If you really need to not install the generated artifacts, use at least .package - takes the compiled code and package it in its distributable format, such as a JAR or WAR file.\ninstall - install the package into the local repository, for use as a dependency in other projects locallyIf you're  using a  repository (like artifactory), use plain old:\n   Pretty old topic but AFAIK, if you run your own repository (eg: with  artifactory) to share jar among your team(s), you might want to use instead. This way, your continuous integration server can be sure that all dependencies are correctly pushed into your remote repository. If you missed one, mvn will not be able to find it into your CI local m2 repository.Also you should note that if your project is consist of several modules which are dependent on each other, you should use \"install\" instead of \"package\", otherwise your build will fail, cause when you use install command, module A will be packaged and deployed to local repository and then if module B needs module A as a dependency, it can access it from local repository.The  way is  if you did things correctly for the core part of your build then there should be no need to install your packages in the local repository.In addition if you use Travis you can \"cache\" your dependencies because it will not touch your  if you use package for your own project.In practicality if you even attempt to do a  you usually need to do a  before.  There's just too many bugs with either  or it's numerous poorly maintained plugins.It depends on what you're trying to achieve after changing the Java file. Until you want to test the maven process, you never need to do anything. Eclipse/MyEclipse will build what is necessary and put the output in the appropriate place within your project. You can also run or deploy it (if it's a web project, for example), without your needing to explicitly do anything with maven. In the end, to install your project in the maven repository, you will need to do a maven install. You may also have other maven goals that you wish to execute, which MyEclipse won't do automatically.As I say, it depends on what you want to do.
Java

I need a  datastructure for my use case. I should be able to push items into the datastructure and I only want to retrieve the last item from the Stack . The  says :I definitely do not want synchronized behavior here as I will be using this datastructure local to a method . Apart from this why should I prefer  over  here ?P.S: The javadoc from Deque says :For one thing, it's more sensible in terms of inheritance. The fact that  extends  is really strange, in my view. Early in Java, inheritance was overused IMO -  being another example.For me, the crucial word in the docs you quoted is .  exposes a set of operations which is all about being able to fetch/add/remove items from the start or end of a collection, iterate etc - and that's it. There's deliberately no way to access an element by position, which  exposes  it's a subclass of .Oh, and also  has no interface, so if you know you need  operations you end up committing to a specific concrete class, which isn't usually a good idea.Here is my interpretation of inconsistency mentioned in the description of Stack class.If you look at General-purpose Implementations  - you'll see there is a consistent approach to implementation of set, map and list. But Stack class: 1) don't have its own interface; 2) is a subclass of Vector class - which is based on resizable array; so where is linked list implementation of stack?In Deque interface we don't have such problems including two implementations (resizable array - ArrayDeque; linked list - LinkedList).Deque is used is situation where you want to retrieve elements from both head and tail. If you want a simple stack there is no need to go for a deque.  
Java

The official Redis homepage lists JDBC-Redis and JRedis. What are the advantages / disadvantages of each ? Are there any other options ? You can use also , which is also in the . It is compatible with the latest version of Redis.As of June 2012, Jedis is the Java client library recommended by the Redis official page.I've tried JDBC-Redis, Jredis and Jedis.\nJDBC-Redis is not good at performance. JRedis and Jedis are both fast, I use Jredis for times but now I prefer Jedis because it's simple, and I can handle network connection errors as I want.Both  and  are being actively developed. I personally use Jedis since it seems to be more actively developed.Spring provides a wrapper around both implementations and they're providing serialization/deserialization, amongst other things: Spring Data now added support for a 3rd library called  (Redis Java Client) -- I don't know what the pros/cons for it are, though.An easier solution is to not worry about working at the lowest level but use an Object Hash Mapper (OHM) like JOhm instead. JOhm lets users decorate their existing objects with familiar annotations to allow persistence to Redis without any invasive code changes. It does not even need any external configuration. You can think of the OHM as a NoSQL counterpart to the ORM of RDBMS. JOhm is hosted just an update: it seems jredis is not that active anymore, jedis however is going strong and had some great features implemented recently, it s also the same developer of JOhm.extract from their readme on github: Ok.. so what can I do with Jedis?\n[...]TransactionsPipeliningPublish/SubscribePersistencecontrol commandsRemote server control commandsConnection poolingSharding (MD5, MurmureHash)Key-tags for shardingSharding with pipeliningI was using jredis until recently on half a dozen of projects, moved them all to jedis in no time, without surprises.Jedis is a very good client. I have used jedis to make some performance test against redis. 50 clients, 1m requests completed in 20 seconds(on a old intel 2core 2.6g machine, 100m network). I believe the performance can be much higher if I can use 1000m network to do the test. JDBC-Redis is just a JDBC wrapper for JRedis database.\nIf you plan on using your code with different back-ends then JDBC is a good way to go. NOTE: It is not a complete JDBC implementation and the NOSQL will bleed through.\nIf you are going to stay with Redis then I would suggest using the API, which will give you more flexibility. Use a DAO layer pattern to encapsulate your DB Access and down the road that is all you will need to change.
Java

There are at the moment, two ways to mark code as depreacted in java.Via JavaDocOr as an annotation:This is my problem - I find it a bit too much to declare both, when marking a method as deprecated when using Eclipse. I really just want to use one of them.However does using the annotation give the compiler actual useful additional information?But only using the annotation, I cannot state why the method is deprecated - I can only do that with JavaDoc, and deprecating a method without specying why is bad.So, can I only use one of them? Or should I really just learn to specify both?You should use both. The Annotation allows the compiler to display a warning whenever a deprecated method is used, and the javadoc explains why. Both are important.As per Oracle's Java Annotations :From the :So basically, if you want a guarantee that there will be compiler warnings, you need to use the annotation. And because of some API designer's breathtaking incompetence, you need to specify the javadoc tag as well to give an explanation.Personally, I'd say the annotation is useless and should be omitted until it's fixed, since any good compiler or IDE will display warnings with the javadoc tag as well.You should specify both.The annotation lets the compiler know about it and trigger warnings when the method is used.\nThe JavaDoc attribute lets developers know about before they start using it.These are two very different things!You should write both.\nThe @Deprecated Anotation is for the Compiler and the @deprecated JavaDoc tag is for the Person who wants to now why this is deprecated.An example can look like this:This can be easily dealt with a good IDE.Eclipse Neon, for eg. automatically adds @Deprecated annotation, when I create a javadoc @deprecated on a method or field.So I simply write the javadoc with the appropriate explanation and let the IDE take care of adding the @Deprecated annotation, the minute I save the file.
Java

While browsing the code for the Java 8 version of ForkJoinPool(which has a few interesting changes from Java 7) I ran across this construct ():I'm struggling with why you would write it like this instead of justIs it just a semantics/readability choice, since you could read the first construct as ? Or is there some additional benefit I'm missing?If you read the comments at top of the file, just below the class declaration, there is a section which explains the use of this construct: makes extensive use of  from  and most of the occurrences of  in  can \u2014 as mentioned by other answers \u2014 be explained by this comment under the heading Style notes:The choice to use write a -loop with an empty body as  seems however to be a mostly stylistic choice. This is perhaps clearer in , which happened to be updated in Java 8.In the Java 7  you can find this:While much of the code around it has also changed, it is clear that the replacement in Java 8 is this:The first version has the weakness that if the lone semicolon happened to be deleted it would change the meaning of the program depending on the following line.As seen below, bytecode generated by  and  is slightly different, but not in any way that should affect anything when run.Java code:Generated code:Leaving aside any potential performance benefits, there is a clear readability benefit.With  the trailing semicolon is not always obvious at first glance, you may be confused into thinking that the following statement or statements are inside the loop. For example:It would be very easy to misread the above as having the if statement inside the loop, and even if you did read it correctly it would be easy to think that it was a programming mistake and the if should be inside the loop.With  though it is immediately at a glance clear that there is no body to the loop.If you will read comment above the code, It is mentioned that...If the caller is not a , this method is behaviorally equivalent toSo it is just another form to implement above code in else part...!!In  it is mentioned that, And if you will see implementation of , It is updating the lock and returns  if blocking is unnecessary.Blank while loops are used to provide an interrupt until some condition reset to true/false.Here,  is a blocker/interrupt until  will be  when  is . Loop will continue execution while  is not releasable () and  is not blocked !! Execution will be out of loop as soon as  will set to true.Note that,  does not update CAS variable, but it guarantee that program will wait until variable gets updated (force to wait until variable gets updated).  You can easily make something like this with:
Java

Can someone explain this to me. As long as there is only a single implementation of the interface and that implementation is annotated with  with Spring's component scan enabled, Spring framework can find out the (interface, implementation) pair. If component scan is not enabled, then you have to define the bean explicitly in your application-config.xml (or equivalent spring configuration file).Once you have more than one implementation, then you need to qualify each of them and during auto-wiring, you would need to use the  annotation to inject the right implementation, along with  annotation. If you are using @Resource (J2EE semantics), then you should specify the bean name using the  attribute of this annotation.Firstly, it is always a good practice to code to interfaces in general. Secondly, in case of spring, you can inject any implementation at runtime. A typical use case is to inject mock implementation during testing stage.Your bean configuration should look like this:Alternatively, if you enabled component scan on the package where these are present, then you should qualify each class with  as follows:Then  in  will be injected with an instance of type .Also it may cause some warnigs in logs like a . And many other reasons for this are described here 
Java

I am a newbie in java and wanted to use curl in java. What is my question is curl built-in in java or I have to install it from any 3rd party source to use with Java. If so, how to install curl in java. I have been googling for a long time but didnt find any help. Hope anyone can help me out there. Thanks in advance.You can make use of  and/or . Also see the  on the subject. It's however a bit verbose. To end up with less verbose code, you may want to consider  instead.By the way: if your next question is \"How to process HTML result?\", then the answer is \". .\".The  object allows you to execute external command line applications from Java and would therefore allow you to use cURL however as the other answers indicate there is probably a better way to do what you are trying to do. If all you want to do is download a file the URL object will work great.Some people have already mentioned ,  and . If you need all the control and extra features that the curl library provides you (and more), I'd recommend .Using standard java libs, I suggest looking at the HttpUrlConnection class\nIt can handle most of what curl can do with setting up the connection.\nWhat you do with the stream is up to you.Curl is a non-java program and must be provided outside your Java program.You can easily get much of the functionality using , unless there is some specific functionality like \"resume transfer\" you need (which is tedious to code on your own)
Java

I want to use the JRE 1.7 that I downloaded .So I correctly install the .pkg file, and when I try  in the terminal I get this :But in Eclipse I can't use anything else than JRE 1.6. When I go in Properties > Java Build Path > Add Library > JRE System Library, I can't find the 1.7 (there is only option for it :  with this issue : What should I do ? ThanksThe download from  which installs in  is only the JRE, for development you probably want to download the JDK from  and install that instead.  This will install the JDK at  which you can then add to Eclipse via Preferences -> Java -> Installed JREs.Try editing your eclipse.ini file and add the following at the topOf course the path may be slightly different, looks like I have an older version...I'm not sure if it will add itself automatically. If not go intoPreferences --> Java --> Installed JREsClick Add and follow the instructions there to add itYou need to tell Eclipse which JDK/JRE's you have installed and where they are located.This is somewhat burried in the Eclipse preferences: In the Window-Menu select \"Preferences\". In the Preferences Tree, open the Node \"Java\" and select \"Installed JRE's\". Then click on the \"Add\"-Button in the Panel and select \"Standard VM\", \"Next\" and for \"JRE Home\" click on the \"Directory\"-Button and select the top level folder of the JDK you want to add.Its easier than the description may make it look.
Java

I'm working on a high-performance Android application (a game), and though I try to code for readability first, I like to keep in the back of my mind a picture of what is happening under the hood. With C++, I've developed a fairly good intuition about what the compiler will and won't do for me. I'm trying to do the same for Java/Android.Hence this question. I could find very little about this topic on the web. Will the Java compiler, Dalvik converter (dx) and/or JITter (on Android 2.2+) perform optimizations like the following?Etcetera...This is Ben, one of the engineers working on the JIT @ Google. When Bill and I started on this project, the goal was to deliver a working JIT as soon as possible with minimal impact to resource contention (eg memory footprint, CPU hijacked by the compiler thread) so that it can run on low-end devices as well. Therefore we used a very primitive trace based model. That is, the compilation entity passed to the JIT compiler is a basic block, sometimes as short as a single instruction. Such traces will be stitched together at runtime through a technique called chaining so that the interpreter and code cache lookup won't be invoked often. To some degree the major source of speedup comes from eliminating the repeated interpreter parsing overhead on frequently executed code paths.That said, we do have quite a few local optimizations implemented with the Froyo JIT:In Gingerbread we added simple inlining for getters/setters. Since the underlying JIT frontend is still simple trace based, if the callee has branches in there it won't be inlined. But the inline cache mechanism is implemented so that virtual getters/setters can be inlined without problems.We are currently working on enlarging the compilation scope beyond a simple trace so that the compiler has a larger window for code analysis and optimization. Stay tuned.I'm sure that my answer will not answer all of your questions but I guess it is a win if it answers even one.You seem to have a profound knowledge on the subject and know what you want so you might want to do the following. Build an example application containing the aspects you want to investigate on.Take the APK you get and run it through the . Reverse engineering your own code to do just what you are intending is perfectly fine as we know.The APK Tool will extract and decode your resources and will reverse engineer  files to  files. You might want to look up the  project too to get more information about how to read the  files and about its limitations.Again I'm pretty sure that this is not going to answer all of your questions but it might be a good start.First, let me preface this by saying that I'm not an expert on dalvik, and some of my responses may be wrong. But I have dug into the JIT code in dalvik, and I'm quite familiar with the bytecode that dalvik runs.Also, I'd like to mention another avenue of approach to you - dx and dalvik are both open source, so you can dig into them all you like. Although, they're obviously not small codebases, so would take a fair bit of effort to dig into them at that level
Java

How can an anonymous class extend a superclass or implement an interface?Anonymous classes  extend or implement something, like any other Java class, even if it's just .For example:Here,  is an object of an anonymous class which implements .An anonymous class can extend another class using the same syntax:What you can't do is implement more than one interface. You need a named class to do that. Neither an anonymous inner class, nor a named class, however, can extend more than one class.An anonymous class usually implements an interface:If you mean whether you can implement  or more interfaces, than I think that's not possible. You can then make a private interface which combines the two. Though I cannot easily imagine why you would want an anonymous class to have that:Anonymous classes  extend superclass or implements interfaces. for example:Moreover, although anonymous class cannot implement multiple interfaces, you can create an interface that extends other interface and let your anonymous class to implement it.An anonymous class is extending or implementing while creating its object\nFor example : Here anonymous class is implementing Interface.here anonymous Class is extending a abstract Class.
Java

How can I  + (which normally would kill the process)\nin a CLI (command line interface) Java application?Does a multi-platform solution exist (Linux, Solaris, Windows)?I'm using 's , but if necessary, I could use some other method\nto read characters from standard input.This should be able to intercept the signal, but only as an intermediate step before the JVM completely shutdowns itself, so it may not be what you are looking after.You need to use a  () to intercept the  signal triggered by a + (on Unix as well as on Windows).\nSee  (pdf, page 8 and 9).I am assuming you want to shutdown gracefully, and not do short circuit the shutdown process.  If my assumption is correct, then you should look at .In order to be able to handle + without shutting down for some reason, you'll need to use some form of signal handling (since the + input isn't actually passed directly to your application, but instead is handled by the OS which generates a SIGINT that is then passed to Java.See  for details on signal handling.(If you're just wanting to gracefully shutdown, akf's answer will suffice.)Some links about how to handle SIGTERM - that is the signal the program is getting on the OS side:That should work on POSIX operating systems - that is, Mac and Unix should work, on windows I'm not sure, I remember hearing it is also POSIX compatible to some extent, but might varty a lot with different versions.
Java

I have a problem importing an external project. I go File -> Import... -> Existing Projects into Workspace, choose the folder where the project is located and everything is imported - but the package names of the project don't seem to be what Eclipse expects. The package names all have a prefix:etc.But Eclipse expectsetc. because the directory is src/prefix1/prefix/package1I don't really want to mess around with external code. How do I tell Eclipse to ignore the directory \"src/prefix1\"? Or what else can I do?Just go into the build path and the source path to be  instead of .It may be easiest to right-click on the  directory and select \"Build Path / Remove from build path\", then find the  directory, right click and select \"Build Path / Use as source folder\".I just ran into this problem, and since Mr. Skeet's solution did not work for me, I'll share how I solved this problem.It turns out that I opened the java file under the 'src' before declaring it a source directory.After right clicking on the 'src' directory in eclipse, selecting 'build path', and then 'Use as Source Folder' the already  (F5 refreshing it did not work).Provided the path to the java file from \"prefix1\" onwards lines up with the package in the file (example from the requester's question prefix1.prefix.packagename2). This should workEclipse should no longer complain about 'src.'Move your problem *.java files to other folder.Click 'src' item and press \"F5\".Red crosses will dissaperar.Return your *.java files to \"package path\", click 'src' item and press \"F5\".All should be ok.If you have imported an existing project, then just remove your source folders and then add them again to build path, and restart eclipse. Most of the times eclipse will keep showing the error till you restart.I get this problem in Eclipse sometimes when importing an Android project that does not have a .classpath file.   The one that Eclipse creates is not exactly the same one that Android expects.  But, the Android .classpath files are usually all relative, so I just copy a correct .classpath file from another project over the incorrect .classpath.  I've created a video that shows how I do this:  Suppose your project has a package like\n  (declared package)Your package explorer shows\npackage top level named name1.name2\nsub packages named name3.name4You will have errors because Eclipse extracts the package name from the file directory structure on disk starting at the point you import from.My case was a bit more involved, perhaps because I was using a symbolic link to a folder outside my workspace.  I first tried Build Path.Java Build Path.Source Tab.Link Source Button.Browse to the folder before name1 in your package.Folder-name as you like (i think). But had issues.Then I removed the folder from the build path and tried File > Import... > General > File System > click Next > From Directory > Browse... to folder above name1 > click Advanced button > check Create links in workspace > click Finish button.Go to src folder of the project and copy all the code from it to some temporary location and build the project. And now copy the actual code from temporary location to project src. And run the build again. Problem will be resolved.None these answers worked in my case.  All of my projects (several modules) suddenly had this issue.  Without knowing how or why this happened, I was able to quickly resolve this by deleting all the projects from Spring Tool Suite (without checking the delete from disk box), then re-importing them.
Java

Is it possible to have a different set of dependencies in a maven pom.xml file for different profiles?e.g.I'd like to pick up a different dependency jar file in one profile that has the same class names and different implementations of the same interfaces.To quote the :(Emphasis is mine)Just put the dependency for the  profile inside the profile declaration itself and do the same for .Your groupId, artifactId should be tokenized in your profiles as properties and you can move your dependencies to the generic section.
Java

I'm not really sure what is causing it as it is correctly listed in the manifest:I also added \"Android Private Libraries\" to build path, and moved it to the top of \"Order and Export\", but it still gave me the same error.EDIT: I rebuilt the project completely, and was unable to reproduce the error.  Not sure what was causing it.I had the same issue for my project.It happened due to the conflict in android support library version between my project and the library project that i added in my project. ... Everything will work...This following method worked for me. \nRight click on your  and select . The \"Properties for \" panel will open. From the menu on the left go to  ->  .\nFrom the list below uncheck th box next to . \nFinally  and run.Hope it worksIf you are using Eclipse try Project -> CleanThis happens if we change Build Path of the APP, this can be in any case of Adding or Removing or Changing Libraries or .jar file. The Best solution is to 1) Create libs folder under project root \n2) Copy and paste the jar file into it\n3) Configure the build path (Add jar)\n4) Clean and run\n\ncheers :-)If you get this error while using the new Instant Run feature in Android Studio 2.0 and above then this is some kind of bug on their side. \n\nTo fix this you will have to stop your app manually on Device/Emulator if it's not stopped then from Android Studio select .\n\nThen click the  button or I had same issue, this worked for me 1) Full path of activity in mainfest in place of relative path.2) Delete 'build' folder and clean project.I met the same problem .\nand I found the sample code was \nput in directory \"JAVA\" \ninstead of directory \"src\".\nAfter move code to src ,\nthe problem was solved.Hope it works~Believe me or not... I tried out almost each answer I had found here on stackoverflow. Nothing would help, until I just restarted the machine. My Android Studio works on Ubuntu 16.04 LTS.For any one who is having multidex enable write thisinside write a class  like belowand in  write this  inside Application tagI had this issue recently and I am using Android Studio 0.8.4The problem was the fact that I decided to rename an XML menu layout file that was called main.xml.Right click on it and chose . Before renaming it, be sure uncheck  and pressed . Because my file was originally named , it renamed critical paths in the app.iml and build.gradle, mainly the java.srcDirs in the build.gradle, since the path is defined as .I hope this helps anyone that may be experiencing this issue.I faced this error once when I defined a class that extended a view but referred to this custom view in the layout file with the wrong name. Instead of , I had included  in the XML layout file.I ran into the same issue. I solved it by first deleting the build folder in your android project folder and the build folder in your app folder.\nthen clean your project and build.I had this issue, raised by several causes, but i see this in your stacktrace \"\",  I found a diference in my  before it stop working.I've ADDED the line: this is the final version:Now it works! =)I had the same exact issue. As @weiweia suggested, move the code from the java directory to src worked for me. I also removed the Android Dependencies from Project --> Properties --> Java Build Path --> Order and Export, and made sure only to include Library Projects in the Android screen. I had this problem for quite a while, and like everybody else the answers above didn't apply to my project. In my project I had linked up a project to my project and it was throwing ClassDefNotFoundError every time some code for the other project was executed. So this was my solution. I went to project properties of my project and Java Build Path. Pressed the \"Source\"-tab and \"link source\" from src-folder of the other project to my own project and named a new folder \"core-src\". Hopes this solution helps someoneI had the same issue. I am using Xamarin.Android.The problem in my case was that I changed the versionCode and versionName.I had no problem when I had them set like this:The issue appeared when I changed it to this (versionCode 2 and versionName 0.0.1):I fixed the issue by changing to versionCode 2 and versionName 1.0.0.1, like so:I am unsure why this was a problem, maybe Android doesn't like a lower versionName with a higher versionCode?I found the following on Just in case anybody faces the same problem as me and no suggest\nanswer here helps.For me the cause was, that the Android studio refactor is buggy.\nI moved an innerclass outside of a class, which was a View and therefore\nalso had a xml, where the direct path was set. This path will not get\nrefactored by studio! And no error will be thrown. Hope this helps anybody. Cheers.I had this problem after upgrading from version 18.\nAfter the upgrade I had the following:\nProject Build Target was 5.01, targetSDKVersion=21\nBuild Tools were still from Android 4.3.1 (18) \nWhat I noticed was that those apps that were deriving their activities from ActionBarActivity crashed with the above error those that did not still ran.So the simple fix was to use the latest \ninstead of only those of Android SDK Build Tools 18, which seems somehow the default.So the culprit seems the Appcompat library, which I use for Actionbar backward compability.And a : using the appcompat library I had to set/fix: \n (which was recommended in some other useful post and which has a value of 19 by default))In our case we wanted to compile Vagrant version and had same error. We fixed it by  and  in Build menuI just restarted the device and ran the app. It worked without any issues. Hope this helps someone :)I found this error in  when i tried do debug in a device with , so i checked the Android Studio and i noticed that . After install, i solved the problem.I had this problem several times and often I didn't do something obviously wrong with dependencies. It's always a good idea to check if this 'not found' class is present in the final apk. If it is, like it happened in my cases, the problem usually is: Check if class that you extend is available and then try to fix your build script or dependencies accordingly.I also faced the same problem,\nwe can solve this by doing some thing like1- Uninstall the app.2- Rebuild the project.3- Clean the project.4- Invalidate and restart the project from file -> invalidate and restart.I had the same issue on Windows. I had renamed the path to the project to something containing a space. Make sure the path to your project does not contain a space.For those of you who are having this issue on Android Studio, I had the same problem after a merge and for some reason it even persisted after  and  operations which was driving me crazy.Turns out, it can be fixed by running gradle build once from command line. Simply run the following n the project directory:I hope it'd save someone the time waste and frustration I had to go through.I had this issue in IntelliJ IDEA. This is how I solved it:Project Properties > Facets > Click the Android Facet created from the external library you are adding > Check the box 'Library Module'.
Java

In the spirit of type safety associated with the  JPA 2.0 also has an API to support  representation of entities. Is anyone aware of a fully functional implementation of this API (to generate the Metamodel as opposed to creating the metamodel classes manually)? It would be awesome if someone also knows the steps for setting this up in Eclipse (I assume it's as simple as setting up an annotation processor, but you never know).EDIT:\nJust stumbled across . But the issue remains since I can't find any download links for the jar.EDIT 2:\nAwhile has passed since I asked this question, but I thought I'd come back and add a link to the Yes it is. Here are the implementations and instructions for the various JPA 2.0 implementations:For Hibernate, the implementation is provided by Please take a look at Using Hibernate is most recommended.()OpenJPA seems require additional element .EclipseLink requires .For Apache Maven users,Following simple configuration seems work. ()you can run it with \"mvn compiler:compile\"Note that this method works only with those old maven-compiler-plugin. Check the version in code.Eclipse's JPA 2.0 support through Dali (which is included in \"Eclipse IDE for JEE Developers\") has its own metamodel generator integrated with Eclipse.This should work on any JPA provider as the generated classes are standard.Also see .For eclipselink, only the following dependency is sufficient to generate metamodel. Nothing else is needed. For Hibernate as provider which is most common IMHO:In case of build tools like Gradle, Maven you need to have Hibernate JPA 2 Metamodel Generator jar in the classpath and compiler level>=1.6 that is all you need build the project and metamodel will be generated automatically.In case of IDE Eclipse \n1. goto Project->Properties->Java Compiler->Annotation Processing and enable it. \n2. Expand Annotation Processing->Factory Path-> Add External Jar add Hibernate JPA 2 Metamodel Generator jar check the newly added jar and say OK. Clean and Build done!Link Hibernate JPA 2 Metamodel Generator jar link from maven repo\n
Java

Eclipse is unable to open, have used eclipse before and has open before without a problem. Now I keep getting the following error message:Have gotten eclipse to open and work on projects before and won't open.Here is a screen shot of what I keep getting:. Open  and add the following lines to the top of the file:: I just nailed down the root cause on my own Windows machine. The GlassFish installer complained with exactly the same error message and after digging in GlassFish forums, the cause was clear: a corrupt JRE install on a Windows machine. My JRE came along with the JDK and the Java 6 JDK installer didn't install the JRE properly somehow. A DLL file was missing in JDK's JRE installation. After I reinstalled the standalone JRE from , overwriting the old one, the GlassFish installer continued and also Eclipse was able to start flawlessly without those two lines in .It usually is because:More details on the wiki page \"\"As mentioned in \"\":So I would check your $PATH, starting by n new shell sesion (whatever your OS is), typing '' to see if it still returns anything.Here is how I fixed mine:when you download eclipse, you get a .zip package containing eclipse.exe and all the other files needed to run eclipse but it is missing the jre files. so all you need to do is to find where jre folder is located on your hard drive and add it to the rest of the eclipse package.I had the same problem and the issue was that I had a 32 bit version of Eclipse running on my 64 bit machine and it wanted the 32 bit version of JRE. I changed  to  in the  file like so:and that solved the problem.You may want to just install the 64 bit Eclipse, but this will take care of the error.Did you install Java via the java.com web browser auto install?  If so, then that's your problem! You need to to the \"manual\" install: It's just a matter of having the correct match of 32-bit Eclipse/32-bit Java or 64-bit Eclipse/64-bit Java.  Many 64-bit Windows have 32-bit browsers and the latter is the version of Java that the auto-installer will provide - not what the 64-bit Eclipse wants.I also had same problem when developing android applications using eclipse IDE.\nI solved it by removing all the java installations (I had java 6 and 7 both) and re-install only jdk 7.Make sure the install path of JDK is in your Path variable in Windows.adding   to the .ini file helped me.I had this problem too on a win7 machine.\nI wanted to update the jre with a jdk. So i deleted the jre folder and downloaded and unzipped the new jdk.\nThe issue was i manually deleted the jre folder, when instead i should've uninstalled it. This leaves a bunch of registry entries that still point to the old jre. Somehow eclipse still wants to use the old jre.\nI couldn't uninstall the old java vm, i kept getting this error:Error 1723. There is a problem with this Windows Installer package. A DLL required for this install to complete could not be run. Contact your support personnel or package vendorSo i had to use this MS utility to fix the uninstall:Then i had to install again the vm. I installed to the same location the original one was at, to avoid losing another hour! After that eclipse started correctly.JulioI just had this problem and fixed it this way. I noticed the error message has jre in it not jre6 or jre7, so i copied jre6 from program files to eclipse folder then renamed it from jre6 to jre, then it worked :pNewb move on my part, but I had . Installed JDK and my problem went immediately away.I had this problem and it was due to my windows machine playing up. I went into control panel -> system -> advanced - environment variables.I edited the PATH variable (which was already correctly set up), changed NOTHING, clicked OK to come back out of the screens. Then eclipse worked. No idea why, except because windows. Hopefully this may help someone.I got this fixed by doing the below steps,1) Please find the screenshot for the same.I had this issue;  I fixed it by going to Computer-->Properties-->Advanced Settings-->Environmental VariablesIn the System Variables find the variable named PATH.\n-->Select Edit\n-->At the very end of the Path Variable, put a \";\" then add your path of your JDK and put \\bin\\ at the endShould be fixed. C:\\Program Files (x86)\\Common Files.......HP\\LeanFT\\bin C:\\Programs Files\\Java\\jre1.8.0_121C:\\Program Files (x86)\\Common Files.......HP\\LeanFT\\bin;C:\\Programs Files\\Java\\jre1.8.0_121\\bin\\Sources:\nCopy javaw.exe from and paste it inside Eclipse folder\nwhere eclipse.exe is there. That's all.Is so simple,only add your java path for example:in  system variable 
Java

I see gain in performance when using  and  operator over  operator.Is there any guideline, which one to use  or ?Given a scenario: I know exact classes to be matched, that is ,  (these are final classes), etc.Is using  operator bad practise ?The reason that the performance of  and  is different is that they are doing different things.So the recommendation is to ignore the performance issue and use the alternative that gives you the answer that you need.And yes, overuse of either of them is \"design smell\".  If you are not careful, you end up with a design where the addition of new subclasses results in a significant amount of code reworking.  In most situations, the preferred approach is to use polymorphism.  Do you want to match a class , e.g. only matching  instead of any subclass of ? If so, use  and . I would typically do this in an , so that an instance of X isn't deemed equal to an instance of a subclass of X - otherwise you can get into tricky symmetry problems. On the other hand, that's more usually useful for comparing that two objects are of the  class than of one specific class.Otherwise, use . Note that with  you will need to ensure you have a non-null reference to start with, or you'll get a , whereas  will just return  if the first operand is null.Personally I'd say  is more idiomatic - but using  of them extensively is a design smell in most cases.I know it has been a while since this was asked, but I learned an alternative yesterdayWe all know you can do:but what if you dont know exactly what type of class it needs to be?\nyou cannot generically do:as it gives a compile error.\nInstead, here is an alternative - isAssignableFrom()For example:getClass() has the restriction that objects are only equal to other objects of the same class, the same run time type, as illustrated in the output of below code: Outputs:SubClass extends ParentClass. subClassInstance is instanceof ParentClass. Different getClass() return results with subClassInstance and parentClassInstance. 
Java

I have string like \" I am a boy\". I want to print like this way\n\" I (\\n new line) am (\\n new line) a (\\n new line) boy\".Can anybody help me?You can also use :Try:It can be done several ways. I am mentioning 2 simple ways.To make the code portable to any system, I would use: This is important because different OSs use different notations for newline: Windows uses \"\\r\\n\", Classic Mac uses \"\\r\", and Mac and Linux both use \"\\n\".Commentors - please correct me if I'm wrong on this... It's better to use  as an OS independent new-line character instead of  and it's easier than using Why to use , because on each OS, new line refers to a different set of character(s); is the acronym of  and  is the acronym of . The escape characters are written inside the parenthesis. So on each OS, new line stands for something specific to the system.  is OS agnostic, it is portable. It stands for  on Unix systems or  on Windows systems and so on. Thus, Do not use , instead use .If you want to have your code os-unspecific you should use println for each wordbecause Windows uses \"\\r\\n\" as newline and unixoid systems use just \"\\n\"println always uses the correct one is used for making separate line; If you simply want to print a newline in the console you can use \u00b4\\n\u00b4 for newlines.If you want to break text in swing components you can use html:Full program example, with a fun twist:Open a new blank document and save it as .  \"iAmABoy\" is the class name.Paste the following code in and read through it.  Remember, I'm a beginner, so I appreciate all feedback!Now, in terminal/cmd, browse to  and type:You can replace the args  with anything!What about  using a formatter like ?:As  says, its available from java 1.5 and is another way to  or  and, like this two, is .you can use  tag in your string for show in html pagesSystem.out.println(\"I\\nam\\na\\nboy\");This works\nIt will give one space character also along before enter character
Java

Very similar to , except for Java.What is the recommended way of encoding strings for an XML output in Java. The strings might contain characters like \"&\", \"<\", etc.Very simply: use an XML library. That way it will actually be  instead of requiring detailed knowledge of bits of the XML spec.As others have mentioned, using an XML library is the easiest way. If you do want to escape yourself, you could look into  from the  library.Just use.This will allow any characters except the ending So you can include characters that would be illegal such as & and >. For example.However, attributes will need to be escaped as CDATA blocks can not be used for them.This has worked well for me to provide an escaped version of a text string:Try this:While idealism says use an XML library, IMHO if you have a basic idea of XML then common sense and performance says template it all the way. It's arguably more readable too. Though using the escaping routines of a library is probably a good idea.Consider this: XML  meant to be written by humans.Use libraries for generating XML when having your XML as an \"object\" better models your problem. For example, if pluggable modules participate in the process of building this XML.Edit: as for how to actually escape XML in templates, use of CDATA or  from JSTL are two good solutions,  can be used like this:The behavior of StringEscapeUtils.escapeXml() has changed from Commons Lang 2.5 to 3.0.\nIt now no longer escapes Unicode characters greater than 0x7f.This is a good thing, the old method was to be a bit to eager to escape entities that could just be inserted into a utf8 document.The new escapers to be included in Google Guava 11.0 also seem promising:\nNote: Your question is about , not . Escaping is using <, etc. to allow the parser to distinguish between \"this is an XML command\" and \"this is some text\". Encoding is the stuff you specify in the XML header (UTF-8, ISO-8859-1, etc).First of all, like everyone else said, use an XML library. XML looks simple but the encoding+escaping stuff is dark voodoo (which you'll notice as soon as you encounter umlauts and Japanese and other weird stuff like \"\" (&#FF11; is 1)). Keeping XML human readable is a Sisyphus' task.I suggest never to try to be clever about text encoding and escaping in XML. But don't let that stop you from trying; just remember when it bites you (and it will).That said, if you use only UTF-8, to make things more readable you can consider this strategy:I'm using this in an SQL editor and it allows the developers to cut&paste SQL from a third party SQL tool into the XML without worrying about escaping. This works because the SQL can't contain umlauts in our case, so I'm safe. does not escape control characters (< 0x20).  XML 1.1 allows control characters; XML 1.0 does not.  For example,  will happily serialize a Java object's control characters into XML, which an XML 1.0 parser will reject.To escape control characters with Apache commons-lang, useTo escape XML characters, the easiest way is to use the Apache Commons Lang project, JAR downloadable from: The class is this: org.apache.commons.lang3.StringEscapeUtils;It has a method named \"escapeXml\", that will return an appropriately escaped String. While I agree with Jon Skeet in principle, sometimes I don't have the option to use an external XML library. And I find it peculiar the two functions to escape/unescape a simple value (attribute or tag, not full document) are not available in the standard XML libraries included with Java.As a result and based on the different answers I have seen posted here and elsewhere, here is the solution I've ended up creating (nothing worked as a simple copy/paste):The above accommodates several different things:At some point, I will write the inversion of this function, toUnescaped(). I just don't have time to do that today. When I do, I will come update this answer with the code. :)Here's an easy solution and it's great for encoding accented characters too!OutputsFor those looking for the quickest-to-write solution: use methods from :Remember to include dependency:Use  and forget about text handling it will be done for you automatically.Try to encode the XML using Apache XML serializer 
Java

How can one quickly turn off all Log4J output using a log4j.properties file?Set level to OFF\n(instead of DEBUG, INFO, ....)If you want to turn off logging programmatically then useYou can change the level to OFF which should get rid of all logging. According to the log4j website, valid levels in order of importance are TRACE, DEBUG, INFO, WARN, ERROR, FATAL. There is  called OFF which is a higher level than FATAL, and turns off all logging.You can also create an extra root logger to log nothing (level OFF), so that you can switch root loggers easily.  to get you started on that.You might also want to read the  because I think turning off all logging may not help. It will certainly not speed up your app that much, because logging code is executed anyway, up to the point where log4j decides that it doesn't need to log this entry.Change level to what you want. (I am using Log4j2, version 2.6.2). This is simplest way, change to For example: File \n
Java

This is the code:This is the test:Works fine, the class is tested. But Cobertura says that there is zero code coverage of the private constructor of the class. How can we add test coverage to such a private constructor?Well, there are ways you could potentially use reflection etc - but is it really worth it? This is a constructor which should , right?If there's an annotation or anything similar that you can add to the class to make Cobertura understand that it won't be called, do that: I don't think it's worth going through hoops to add coverage artificially.EDIT: If there's no way of doing it, just live with the slightly reduced coverage. Remember that coverage is meant to be something which is useful to  - you should be in charge of the tool, not the other way round.I don't entirely agree with Jon Skeet. I think that if you can get an easy win to give you coverage and eliminate the noise in your coverage report, then you should do it. Either tell your coverage tool to ignore the constructor, or put the idealism aside and write the following test and be done with it:Although it's not necessarily for coverage, I created this method to verify that the utility class is well defined and do a bit of coverage as well.I have placed the full code and examples in I had made private the constructor of my class of static utility functions, to satisfy CheckStyle. But like the original poster, I had Cobertura complaining about the test. At first I tried this approach, but this doesn't affect the coverage report because the constructor is never actually executed. So really all this tests is if the constructor is remaining private - and this is made redundant by the accessibility check in the subsequent test.I went with Javid Jamae's suggestion and used reflection, but added assertions to catch anybody messing with the class being tested (and named the test to indicate High Levels Of Evil).This is so overkill, but I gotta admit I like the warm fuzzy feeling of 100% method coverage.The reasoning behind testing code that doesn't do anything is to achieve 100% code coverage and to notice when the code\ncoverage drops. Otherwise one could always think, hey I don't have 100% code coverage anymore but it's PROBABLY because\nof my private constructors. This makes it easy to spot untested methods without having to check that it just was a private constructor. As your codebase grows you'll actually feel a nice warm feeling looking at 100% instead of 99%.IMO it's best to use reflection here since otherwise you would have to either get a better code coverage tool that ignores these constructors or somehow tell the code coverage tool to ignore the method (perhaps an Annotation or a configuration file) because then you would be stuck with a specific code coverage tool.In a perfect world all code coverage tools would ignore private constructors that belong to a final class because the constructor is there as a \"security\" measure nothing else:)\nI would use this code:\nWith , it is possible to find other solution.I assume that you simply want to create utility class with few public static methods. If you can use Java 8, then you can use  instead.There is no constructor and no complain from Cobertura. Now you need to test only the lines you really care about.Newer versions of Cobertura have built-in support for ignoring trivial getters/setters/constructors:Ignore trivial allows the ability to exclude constructors/methods that contain one line of code. Some examples include a call to a super constrctor only, getter/setter methods, etc. To include the ignore trivial argument add the following:or in a Gradle build:Finally, there is solution!Don't.\nWhat's the point in testing an empty constructor?\nSince cobertura 2.0 there is an option to ignore such trivial cases (together with setters/getters), you can enable it in maven by adding configuration section to cobertura maven plugin:Alternatively you can use : .I don't know about Cobertura but I use Clover and it has a means of adding pattern-matching exclusions. For example, I have patterns that exclude apache-commons-logging lines so they are not counted in the coverage.Another option is to create a static initializer similar to the following code This way the private constructor is considered tested, and the runtime overhead is basically not measurable. I do this to get 100% coverage using EclEmma, but likely it works out for every coverage tool. \nThe drawback with this solution, of course, is that you write production code (the static initializer) just for testing purposes. Sometimes Cobertura marks code not intended to be executed as 'not covered', there's nothing wrong with that. Why are you concerned with having  coverage instead of ?Technically, though, you can still invoke that constructor with reflection, but it sounds very wrong to me (in this case).If I were to guess the intent of your question I'd say:For 1, it is obvious that you want all initialisation to be done via factory methods. In such cases, your tests should be able to test the side effects of the constructor. This should fall under the category of normal private method testing. Make the methods smaller so that they only do a limited number of determinate things (ideally, just one thing and one thing well) and then test the methods that rely on them.For example, if my [private] constructor sets up my class's instance fields  to . Then I can (or rather must) test it:For 2, you can configure clover to exclude Util constructors if you have a set naming pattern for Util classes. E.g., in my own project I use something like this (because we follow the convention that names for all Util classes should end with Util):I have deliberately left out a  following  because such constructors are not meant to throw exceptions (they are not meant to do anything).There of course can be a third case where you may want to have an empty constructor for a non-utility class. In such cases, I would recommend that you put a  with the exact signature of the constructor.If you have many such exceptional classes then you can choose to modify the generalized private constructor reg-ex I suggested and remove  from it. In this case, you will have to manually make sure that your constructor's side effects are still tested and covered by other methods in your class/project.Test.java is your source file,which is having your private constructorYou can't.You're apparently creating the private constructor to prevent instantiation of a class that is intended to contain only static methods. Rather than trying to get coverage of this constructor (which would require that the class be instantiated), you should get rid of it and trust your developers not to add instance methods to the class.
Java

I want to trim a string if the length exceeds 10 characters.Suppose if the string length is 12 (), then the new trimmed string will contain .How can I achieve this?Using  like this avoids an exception in the case where the string is already shorter than .Notes: from  library could be your friend:There is a  function which does this. Courtesy:Steeve McCauleyAs usual nobody cares about UTF-16 surrogate pairs. See about them:  Even authors of org.apache.commons/commons-lang3You can see difference between correct code and usual code in this sample:Or you can just use this method in case you don't have StringUtils on hand:Just in case you are looking for a way to trim and keep the LAST 10 characters of a string.s = s.substring(Math.max(s.length(),10) - 10);
Java

I'm working on a business project that done in java and needs huge computation power to computer business markets. Simple math but with huge amount of data.We ordered some cuda gpu's to try it with and since Java not supported by cuda, Im wondering where to start with. Should i build a JNI interface? should i use JQUDA or is there other ways to go with this?I dont have experience in this fields and i would like if someone direct me to something so then i can start researching and learning.First of all, you should be aware of the fact that CUDA will not automagically make computations faster. On the one hand, because GPU programming is an art, and it can be very, very challenging to get it . On the other hand, because GPUs are well-suited only for certain  of computations.This may sound confusing, because you can basically compute  on the GPU. The key point is, of course, whether you will achieve a good speedup or not. The most important classification here is whether a problem is  or . The first one refers, roughly speaking, to problems where several threads are working on their own tasks, more or less independently. The second one refers to problems where  threads are  - but on different parts of the data. The latter is the kind of problem that GPUs are good at: They have  cores, and all the cores do the same, but operate on different parts of the input data. You mentioned that you have \"simple math but with huge amount of data\". Although this may sound like a perfectly data-parallel problem and thus like it was well-suited for a GPU, there is another aspect to consider: GPUs are ridiculously fast in terms of theoretical computational power (FLOPS, Floating Point Operations Per Second). But they are often throttled down by the memory bandwidth.This leads to another classification of problems. Namely whether problems are  or . The first one refers to problems where the number of instructions that are done for each data element is low. For example, consider a parallel vector addition: You'll have to  two data elements, then perform a single addition, and then  the sum into the result vector. You will not see a speedup when doing this on the GPU, because the single addition does not compensate for the efforts of reading/writing the memory. The second term, \"compute bound\", refers to problems where the number of instructions is high compared to the number of memory reads/writes. For example, consider a matrix multiplication: The number of instructions will be O(n^3) when n is the size of the matrix. In this case, one can expect that the GPU will outperform a CPU at a certain matrix size. Another example could be when many complex trigonometric computations (sine/cosine etc) are performed on \"few\" data elements. As a rule of thumb: You can assume that reading/writing one data element from the \"main\" GPU memory has a latency of about 500 instructions....Therefore, another key point for the performance of GPUs is : If you have to read or write data (and in most cases, you will have to ;-)), then you should make sure that the data is kept as close as possible to the GPU cores. GPUs thus have certain memory areas (referred to as \"local memory\" or \"shared memory\") that usually is only a few KB in size, but particularly efficient for data that is about to be involved in a computation.So to emphasize this again: GPU programming is an art, that is only remotely related to parallel programming on the CPU. Things like Threads in Java, with all the concurrency infrastructure like ,  etc. might give the impression that you just have to split your work somehow and distribute it among several processors. On the GPU, you may encounter challenges on a much lower level: Occupancy, register pressure, shared memory pressure, memory coalescing ... just to name a few.  However, when you have a data-parallel, compute-bound problem to solve, the GPU is the way to go. A general remark: Your specifically asked for CUDA. But I'd strongly recommend you to also have a look at OpenCL. It has several advantages. First of all, it's an vendor-independent, open industry standard, and there are implementations of OpenCL by AMD, Apple, Intel and NVIDIA. Additionally, there is a much broader support for OpenCL in the Java world. The only case where I'd rather settle for CUDA is when you want to use the CUDA runtime libraries, like CUFFT for FFT or CUBLAS for BLAS (Matrix/Vector operations). Although there are approaches for providing similar libraries for OpenCL, they can not directly be used from Java side, unless you create your own JNI bindings for these libraries. You might also find it interesting to hear that in October 2012, the OpenJDK HotSpot group started the project \"Sumatra\":  . The goal of this project is to provide GPU support  in the JVM, with support from the JIT. The current status and first results can be seen in their mailing list at  However, a while ago, I collected some resources related to \"Java on the GPU\" in general. I'll summarize these again here, in no particular order.(: I'm the author of  and  ) : An open-source library that is created and actively maintained by AMD. In a special \"Kernel\" class, one can override a specific method which should be executed in parallel. The byte code of this method is loaded at runtime using an own bytecode reader. The code is translated into OpenCL code, which is then compiled using the OpenCL compiler. The result can then be executed on the OpenCL device, which may be a GPU or a CPU. If the compilation into OpenCL is not possible (or no OpenCL is available), the code will still be executed in parallel, using a Thread Pool. : An open-source library for converting parts of Java into CUDA programs. It offers dedicated interfaces that may be implemented to indicate that a certain class should be executed on the GPU. In contrast to Aparapi, it tries to automatically serialize the \"relevant\" data (that is, the complete relevant part of the object graph!) into a representation that is suitable for the GPU.  : A library for translating annotated Java code (with some limitations) into CUDA code, which is then compiled into a library that executes the code on the GPU. The Library was developed in the context of a PhD thesis, which contains profound background information about the translation process. : Scala bindings for OpenCL. Allows special Scala collections to be processed in parallel with OpenCL. The functions that are called on the elements of the collections can be usual Scala functions (with some limitations) which are then translated into OpenCL kernels. : A language extension for Java that allows parallel constructs (e.g. parallel for loops, OpenMP style) which are then executed on the GPU with OpenCL. Unfortunately, this very promising project is no longer maintained.  (JCUDA) : A library that can translate special Java Code (called JCUDA code) into Java- and CUDA-C code, which can then be compiled and executed on the GPU. However, the library does not seem to be publicly available. : Java language extension for for OpenMP constructs, with a CUDA backend : Java bindings for OpenCL: An object-oriented OpenCL library, based on auto-generated low-level bindings : Java bindings for OpenCL: An object-oriented OpenCL library, based on auto-generated low-level bindings : Java bindings for OpenCL: Auto-generated low-level bindings and object-oriented convenience classes : Java bindings for OpenCL: Low-level bindings that are a 1:1 mapping of the original OpenCL API : Java bindings for CUDA: Low-level bindings that are a 1:1 mapping of the original CUDA API : Java bindings for OpenCL. Seem to be no longer maintained since 2010 : Java bindings for CUDA. Seem to be no longer maintainedI'd start by using one of the projects out there for Java and CUDA: 
Java

I have been checking the upcoming , namely: . Yes, I am impatient, there's a lot of new stuff, but, there is something I don't understand, some simple code:the javadocs areI would appreciate if somebody created some simple real-life examples about , how you could code it in previous java versions  and how you can code the same routines using .It doesn't make sense to  a  that's already flat, like the  you've shown in your question.  However, if you had a  then it would make sense and you could do this:Which would print:To do this pre-Java 8 you just need a loops:Imagine that you want to create the following sequence: 1, 2, 2, 3, 3, 3, 4, 4, 4, 4 etc. (in other words: 1x1, 2x2, 3x3 etc.)With  it could look like:where:With Java < 8 you would need two nested loops:Let's say I have a  where each  is essentially a . I want to get a list of all dates for which at least one of the time series has a value.  to the rescue:Not only is it readable, but if you suddenly need to process 100k elements, simply adding  will improve performance without you writing any concurrent code.Extract unique words sorted ASC from a list of phrases:... and the output: Am I the only one who finds unwinding lists boring? ;-)Let's try with objects. Real world example by the way. Given: Object representing repetitive task. About important task fields: reminders are starting to ring at  and repeat every  (e.g. 5 HOURS) and there will be  reminders in total(including starting one).Goal: achieve a list of task copies, one for each task reminder invocation.P.S.: I would appreciate if someone suggested a simpler solution, I'm not a pro after all.\n@RBz asked for detailed explanation so here it is.\nBasically flatMap puts all elements from streams inside another stream into output stream. A lot of streams here :). So, for each Task in initial stream lambda expression  creates a stream of long values that represent task start moments. This stream is limited to  instances. It's values start from  and each next value is calculated using lambda .  returns the stream with each long value as a Long wrapper instance. Then each Long in that stream is mapped to new Task instance that is not repetitive anymore and contains exact execution time. This sample contains only one Task in input list. But imagine that you have a thousand. You will have then a stream of 1000 streams of Task objects. And what  does here is putting all Tasks from all streams onto the same output stream. That's all as I understand it. Thank you for your question!Given this:and this:We can then do this:This method takes one Function as an argument, this function accepts one parameter T as an input argument and return one stream of parameter R as a return value. When this function is applied on each element of this stream, it produces a stream of new values. All the elements of these new streams generated by each element are then copied to a new stream, which will be a return value of this method. 
Java

I'd like to scroll to the bottom of the RecyclerView list after loading the activity. throws an exception about being not supported in RecyclerView, and  doesn't seem to do anything.After the above block of code, I addedwhich doesn't work. There are 30 elements in .Just set  or  so that LLM will layout items from end.The difference between these two is that  will set the view to show the last element, the layout direction will remain the same. (So, in an left-to-right horizontal Recycler View, the last element will be shown and scrolling to the left will show the earlier elements)Whereas  will change the order of the elements added by the Adapter. The layout will start from the last element, which will be the left-most in an LTR Recycler View and then, scrolling to the right will show the earlier elements.Sample:See  for details.I was looking at this post to find the answer but... I think everyone on this post was facing the same scenario as me: scrollToPosition() was fully ignored, for an evident reason.What I was using?... what ?I know its late to answer here, still if anybody want to know solution is belowWhen you call , that does not immediately lay out and position items on the screen (that takes a single layout pass) hence your  call has no actual elements to scroll to when you call it.Instead, you should register a  (via  from a  created by ) which delays your  until after the first layout pass:To scrolldown from any position in the recyclerview to bottomandabove code works, but it's not smooth and not cool.Only Ian's answer was able to make my  scroll to a specified position. However, The  was not able to scroll afterwards when I used .  worked but the initial animation made it too slow when the list was long. \nThe reason was the listener was not removed. I used the code below to remove the current  and it worked as a charm.IF you have adapter attached with recyclerView then just do this.
Java

Java is nearing version 7. It occurs to me that there must be plenty of textbooks and training manuals kicking around that teach methods based on older versions of Java, where the methods taught, would have far better solutions now.What are some boilerplate code situations, especially ones that you see people implement through force of habit, that you find yourself refactoring to utilize the latest versions of Java?Enums. Replacing withGenerics and no longer needing to create an iterator to go through all elements in a collection. The new version is much better, easier to use, and easier to understand.EDIT:Before:AfterUsing local variables of type  to perform string concatenation. Unless synchronization is required, it is now recommended to use  instead, because this class offers better performance (presumably because it is unsynchronized).reading a string from standard input::::Here is one that I see: versus . is not recommended for new code, but I still see people use it.As for compatibility, Sun makes a huge effort to have Java be backwards and forwards compatible. That partially accounts for why generics are so complex. Deprecation is also supposed to help ease transitions from old to new code.Older code using Thread instead of the many other alternatives to Thread... these days, very little of the code I run across still needs to use a raw thread. They would be better served by a level of abstraction, particular //.See:VARARGS can be useful too.For example, you can use:instead of:orUsing local variables of type Vector to hold a list of objects. Unless synchronization is required, it is now recommended to use a List implementation such as ArrayList instead, because this class offers better performance (because it is unsynchronized).Formatted printing was introduced as late as in JDK 1.5. So instead of using:or the equivalent using a StringBuilder,one can use The latter is much more readable, both from the string concatenation and the string builder versions. Still I find that people adopt this style very slowly. Log4j framework for example, doesn't use this, although I believe it would be greatly benefited to do so. Explicit conversion between primitive and wrapper types (e.g. Integer to int or vice versa) which is taken care of automatically by autoboxing/unboxing since Java 1.5.An example isCan simply be written asBut watch out for NullPointerExceptions :)Q1: Well, the most obvious situations are in the generics / type specific collections.  The other one that immediately springs to mind is the improved for loop, which I feel is a lot cleaner looking and easier to understand.Q2: In general, I have been bundling the JVM along side of my application for customer-facing apps.  This allows us to use new language features without having to worry about JVM incompatibility.  If I were not bundling the JRE, I would probably stick to 1.4 for compatibility reasons.A simple change in since 1.5 but makes a small difference - in the Swing API accessing the contentPane of a JFrame:becomesAnd of course the introduction of Enums has changed the way many applications that used constants in the past behave.String.format() has greatly improved String manipulation and the ternary if statement is quite helpful in making code easier to read.Generic collections make coding much more bug-resistant.\nOLD:NEW:Using Iterator:Or an alternate form sometimes seen:Is now all replaced with:Although I admit that static imports can easily be overused, I like to usein classes that use a lot of Math functions.  It can really decrease the verbosity of your code.  I wouldn't recommend it for lesser-known libraries, though, since that can lead to confusion.Converting a number to a String:In this case I think there has always been a better way of doing this:copying an existing array to a new array:::formerly, I had to explicitly create a new array and then copy the source elements to the new array (calling a method with a lot of parameters). now, the syntax is cleaner and the new array is returned from a method, I don't have to create it. by the way, the method  has a variation called , which copies a specific region of the source array (pretty much like ).The new -each construct to iterate over arrays and collection are the biggest for me.These days, when ever I see the boilerplate  loop to iterate over an array one-by-one using an index variable, it makes me want to scream:Replacing the above with the :Clean, concise, and best of all, it gives  to the code rather than showing  to do something. Clearly, the code has meaning to iterate over the collection, rather than the old  loop saying how to iterate over an array.Furthermore, as each element is processed independent of other elements, it may allow for future optimizations for parallel processing without having to make changes to the code. (Just speculation, of course.)Related to ; the utility method   which, starting from Java 5, takes varargs parameters is immensely useful.I often find myself simplifying something likeby usingAnnotationsI wonder no one mentioned it so far, but many frameworks rely on annotations, for example  and  It is common today to deprecate xml configuration files are in favor of annotations in code (though this means losing flexibility in moving from configuration to meta-code, but is often the right choice).The best example is EJB 2 (and older) compared to  and how programming EJB has been simplified thanks to annotations.  I find annotations also very useful in combination with some AOP tools like AspectJ or Spring AOP. Such combination can be very powerful. Changing JUnit 3-style tests:to JUnit 4-style tests:Improved singleton patterns.  Technically these are covered under the popular answer enums, but it's a significant subcategory.is cleaner and safer thanConverting classes to use generics, thereby avoiding situations with unnecessary casts.Okay, now it's my turn to get yelled at.I don't recommend 90% of these changes.It's not that it's not a good idea to use them with new code, but breaking into existing code to change a for loop to a for(:) loop is simply a waste of time and a chance to break something. (IIWDFWI) If it works, don't fix it!If you are at a real development company, that change now becomes something to code-review, test and possibly debug.If someone doing this kind of a refactor for no reason caused a problem of ANY sort, I'd give them no end of shit.On the other hand, if you're in the code and changing stuff on that line anyway, feel free to clean it up.Also, all the suggestions in the name of \"Performance\" really need to learn about the laws of optimization.  In two words, Don't!  Ever!  (Google the \"Rules of optimization if you don't believe me).I'm a little wary to refactor along these lines if that is all you are doing to your source tree.  The examples so far do not seem like reasons alone to change any working code base, but maybe if you are adding new functionality you should take advantage of all the new stuff. , they are just using the more manageable constructs of newer JDKs to .Most ways to make your code elegant are not in the JDK.Using Swing's new  to sort tables versus rolling your own from scratch.New version of Java rarely break existing code, so just leave old code alone and focus on how the new feature makes your life easier.If you just leave old code alone, then writing new code using new features isn't as scary.String comparisons, really old school Java programmers I've met would do:(Supposedly for performance reasons)Whereas these days most people just do:Using Vector instead of the new Collections.Using classes instead of enumsUsing Thread instead of the new java.util.concurrency package.It is worth noting that Java 5.0 has been out for five years now and there have only been minor changes since then.  You would have to be working on very old code to be still refactoring it.
Java

I have been battling the ; the  method is excessively slow to detect printers in our application with the initial run-in. Clients with more than 100 network printers have reported that behaviour that executes this code is poorly performing the first time it is run.After seeing that the look-up results are being cached, I have initially deployed a dummy look-up within a separate thread (executed at start-up). However, for a particular client this solution is not working. I do not currently have their environment and cannot see what is causing the exact performance problem.I am trying to see if a  supports a given   performing a look-up of  and . So I pull all available s and the default :And then, obtain the  and the  from the client request. Finally, I ask the  if the  is supported by:The  declares that when  is called with null  and  and has behaved correctly up until now. However, I am not entirely sure if this is the way to perform if a printer supports a selected page size. I would appreciate your feedback and experience on this issue. Around the time I implemented my approach, my workstation decided to have serious network issues, which took me awhile to figure out. Finally, my implementation has been tested with the networking tool  (to simulate network load) and the results have not improved significantly.I will continue testing and update this question. Hopefully I can find a solution and share it with people here. I am guessing that the initial lookup:is still causing issues.The beta build is finally tested on the client environment and performance of the printing dialog is about 5 times improved (the initial pull of printer now takes about 1 minute under the same environment compared to about 5 minutes). Still the initial wait time is not an acceptable amount of time, however, is the best I could do for now. We have also heard from the client that a print server is being used and following the suggestions in the comments (@Wardy), I will be moving on in this direction. Hopefully, we can leverage the advantages of the print server.More aggressive caching. Have the client perform the look-up once and persist the cache between restarts. Better yet, save the cache to a central data store which is accessible by all clients.I'm assuming that network printers and their capabilities don't change that often but you have to update the cache eventually, but the \"who\" and \"when\" is dependent on your environment. Updates to the cache can be made by a client that runs your current discovery in the background and if changes are detected updates the cache. If you have a central component that runs continuously anyway, that would be a good place where you can check in fixed intervals.If you have some kind of directory service you can compare its list of printers with you cache before contacting each printer to get its capabilities to lessen network and cpu load.If list of printers is stored in LDAP, you may try to lookup printers using .
Java

I have an issue with the following code, which I isolated to the most closed form, I am using Java 8, which is almost ready for launch (18 March 2014), so I expect no serious issues in the implementation itself, so it may/must be my own code:The code in itself may not make most sense, but that is because I have stripped a load of other irrelevant methods.However, when you observe the output, you see something strange, at a certain point, for me personally after 30 seconds, I see the following:The time when it switches from  to , seems to depend on the number of calls the method, as with longer sleeps in between, it takes longer to switch.I am running this, for full information on Windows 8 64-bit, with as :Can anyone explain to me what is going on?\nI'd also appreciate if others with Java 8 -any build-, could run and see if they have the same issue.Some more information after using this code:Output:I have also checked the  VM option, when this has been used, it returns  as expected.So the conclusion seems to be that in my particular use case, the interpreted and JIT compiled/inlined variants of the code are not the same and hence it is a possibility that after the interpreted code is compiled it switches from interpreted to compiled and thus clarifying the switch in output.Adding the  option to the actual program in which the bug occured, has also fixed the issue there.This is a known bug in Java8.See this Jira: ....I have reproduced this issue with:Claims that this issue is resolved in b127 are confusing since I see it clearly in b129 (unless I am confused about the JVM version conventions...)Adding System.out.println(System.getProperties());
Java

Sometimes you want to filter a  with more than one condition:or you could do the same with a complex condition and a  :My guess is that the second approach has better performance characteristics, but I don't  it.The first approach wins in readability, but what is better for the performance?The code that has to be executed for both alternatives is so similar that you can\u2019t predict a result reliably. The underlying object structure might differ but that\u2019s no challenge to the hotspot optimizer. So it depends on other surrounding conditions which will yield to a faster execution, if there is any difference.Combining two filter instances creates more objects and hence more delegating code but this can change if you use method references rather than lambda expressions, e.g. replace  by . That way you have eliminated the synthetic delegating method created for your lambda expression. So combining two filters using two method references might create the same or lesser delegation code than a single  invocation using a lambda expression with .But, as said, this kind of overhead will be eliminated by the HotSpot optimizer and is negligible.In theory, two filters could be easier parallelized than a single filter but that\u2019s only relevant for rather computational intense tasks.So there is no simple answer.The bottom line is, don\u2019t think about such performance differences below the odor detection threshold. Use what is more readable.In a Set, i have 10 thousand references to a distinct objects. Then i did the \"speed test\":After 10 executions the average time was 45,5 milliseconds. Next, i use multi filter():The average time was 44,7 milliseconds.Of course this is a test with simple operations, but i believe there is no difference, because, Stream uses internal iteration, unlike \"for\" loopings that uses external iteration, in other words, the looping happens only once and after completed the result is returned. It's likely that there is a difference in time that the compiler will take to read the filters, which is insignificant.This test shows that your second option can perform significantly better.  Findings first, then the code:now the code:
Java

I am using Java NIO for my socket connections, and my protocol is text based, so I need to be able to convert Strings to ByteBuffers before writing them to the SocketChannel, and convert the incoming ByteBuffers back to Strings.  Currently, I am using this code:This works most of the time, but I question if this is the preferred (or simplest) way to do each direction of this conversion, or if there is another way to try.  Occasionally, and seemingly at random, calls to  and  will throw a \n exception, or similar, even if I am using a new ByteBuffer object each time a conversion is done.  Do I need to synchronize these methods?  Any better way to convert between Strings and ByteBuffers?  Thanks!Check out the  and  API descriptions - You should follow a  to avoid this problem.  For example, for :By the way, this is the same approach I am using for NIO although some of my colleagues are converting each char directly to a byte in the knowledge they are only using ASCII, which I can imagine is probably faster.Unless things have changed, you're better off with Usually buffer.hasArray() will be either always true or always false depending on your use case. In practice, unless you really want it to work under any circumstances, it's safe to optimize away the branch you don't need.Answer by Adamski is a good one and describes the steps in an encoding operation when using the general encode method (that takes a byte buffer as one of the inputs)However, the method in question (in this discussion) is a variant of encode - . This is a . (Please see java docs reference in P.S.)As per the docs,  (which is what is happening in ZenBlender's code -- using static encoder/decoder in a multi threaded environment).Personally, I like to use  methods (over the more general encode/decode methods) as they take away the burden by performing all the steps under the covers. ZenBlender and Adamski have already suggested multiple ways options to safely do this in their comments. Listing them all here:P.S.java docs references:
Java

I've just replaced  in the following lambda expression by :Eclipse compiler says:I haven't found any explanation in the  Lexical Structure / Keywords.The place to look is So the Eclipse message is misleading, especially as the same message is used for both cases, when an error is generated for a lambda parameter or when a warning is generated for any other  identifier.
Java

What does the term  mean? I couldn't find anything explanatory enough. says that POJO is an ordinary Java Object and not a special object. Now, what makes or what doesn't make and object special in Java?The above page also says that a POJO should not have to extend prespecified classes, implement prespecified Interfaces or contain prespecified Annotations. Does that also mean that POJOs are not allowed to implement interfaces like ,  or classes like Applets or any other user-written Class/Interfaces? Also, does the above policy (no extending, no implementing) means that we are not allowed to use any external libraries?Where exactly are POJOs used? To be more specific, am I allowed to extend/implement classes/interfaces that are part of the Java or any external libraries? The name is used to emphasize that a given object is an ordinary Java Object, not a special object such as those defined by the EJB 2 framework.class A {} \nclass B extends/implements C {}Note: B is non POJO when C is kind of distributed framework class or ifc. \ne.g. javax.servlet.http.HttpServlet,  javax.ejb.EntityBean or J2EE extn\nand not serializable/comparable. Since serializable/comparable are valid for POJO.  Here A is simple object which is independent. \nB is a Special obj since B is extending/implementing C. So B object gets some more meaning from C and B is restrictive to follow the rules from C. and B is with distributed framework. Hence B object is not POJO from its definition.Code using class A object reference does not have to know anything about the type of it, and It can be used with many frameworks.So a POJO should not have to 1) extend prespecified classes and 2) Implement prespecified interfaces.JavaBean is a example of POJO that is serializable, has a no-argument constructor, and allows access to properties using getter and setter methods that follow a simple naming convention. POJO purely focuses on business logic and has no dependencies on (enterprise) frameworks.\nIt means it has the code for business logic but how this instance is created, Which service(EJB..) this object belongs to and what are its special characteristics( Stateful/Stateless) it has will be decided by the frameworks by using external xml file. Example 1: JAXB is the service to represent java object as XML;  These java objects are simple and come up with default constructor getters and setters.\n Example 2: Hibernate where simple java class will be used to represent a Table. columns will be its instances.\nExample 3: REST services. In REST services we will have Service Layer and Dao Layer to perform some operations over DB. So Dao will have vendor specific queries and operations. Service Layer will be responsible to call Which DAO layer to perform DB operations. Create or Update API(methods) of DAO will be take POJOs as arguments, and update that POJOs and insert/update in to DB. These POJOs (Java class) will have only states(instance variables) of each column and its getters and setters.In practice, some people find annotations elegant, while they see XML as verbose, ugly and hard to maintain, yet others find annotations pollute the POJO model.\nThus, as an alternative to XML, many frameworks (e.g. Spring, EJB and JPA) allow annotations to be used instead or in addition to XML:\nDecoupling the application code from the infrastructure frameworks is one of the many benefits of using POJOs. Using POJOs future proofs your application's business logic by decoupling it from volatile, constantly evolving infrastructure frameworks. Upgrading to a new version or switching to a different framework becomes easier and less risky. POJOs also make testing easier, which simplifies and accelerates development. Your business logic will be clearer and simpler because it won't be tangled with the infrastructure code References :  , he and some others came up with it as a way to describe something which was a standard class as opposed to an EJB etc.Usage of the term implies what it's supposed to tell you. If, for example, a dependency injection framework tells you that you can inject a POJO into any other POJO they want to say that you do not have to do anything special: there is no need to obey any contracts with your object, implement any interfaces or extend special classes. You can just use whatever you've already got. To give another example: while Hibernate can map any POJO (any object you created) to SQL tables, in Core Data (Objective C on the iPhone) your objects have to extend NSManagedObject in order for the system to be able to persist them to a database. In that sense, Core Data cannot work with any POJO (or rather POOCO=PlainOldObjectiveCObject) while Hibernate can. (I might not by 100% correct re Core Data since I just started picking it up. Any hints / corrections are welcome :-) ).Plain Old Java Object :)Well, you make it sound like those are all terrible restrictions.In the usual context where POJO is/are used, it's more like a benefit:It means that whatever library/API you're working with is perfectly willing to work with Java objects that haven't been doctored or manhandled in any way, i.e. you don't have to do anything special to get them to work.For example, the XStream XML processor will (I think) happily serialize Java classes that don't implement the  interface. That's a plus! Many products that work with data objects used to force you to implement  or even extend an  class. Many libraries will expect bean behavior, i.e. getters and setters.Usually, whatever works with POJOs will also work with not-so-PO-JO's. So XStream will of course also serialize Serializable classes.POJO is a Plain Old Java Object - as compared to something needing Enterprise Edition's (J2EE) stuff (beans etc...).POJO is not really a hard-and-fast definition, and more of a hand-wavy way of describing \"normal\" non-enterprise Java Objects. Whether using an external library or framework makes an object POJO or not is kind of in the eye of the beholder, largely depending on WHAT library/framework, although I'd venture to guess that a framework would make something less of a POJOThe whole point of a POJO is simplicity and you appear to be assuming its something more complicated than it appears. If a library supports a POJO, it implies an object of any class is acceptible.  It doesn't mean the POJO cannot have annotations/interface or that they won't be used if they are there, but it is not a requirement. IMHO The wiki-page is fairly clear. It doesn't say a POJO cannot have annotations/interfaces.A Plain Old Java Object (POJO) that contains all of the business logic for your extension.Exp. Pojo which contains a single method was coined by Martin Fowler, Rebecca Parsons and Josh Mackenzie when they were preparing for a talk at a conference in September 2000. Martin Fowler in  explains how to implement a  pattern in Java. After enumerating some of disadvantages of using :As an alternative, he proposed to use  for Domain Model implementation:
Java

I realize that to become a better programmer, you need to program!\nSo obviously the more practice, the better you become. My problem is this. I am currently in university, and I find my course load is a bit daunting, and I don't have a lot of free time. I don't think I could really take on a big project, particularly I don't think I would have to motivation to see it through, it would be easier just for me to keep putting it off in favour of work that is due is school.But I still want to practice. \nSo I am looking for any resources which have programming challenges which can be completed in a fairly small amount of time. Ideally something i could get done in under 10 hours of work (so just over an hour of work each day), if not smaller. I have heard of Google Code Jam, but I am not sure the length of the programs it specifies, nor the skill level. Does anyone have suggestions? Even perhaps a compendium of tutorials for different functions might be useful. For example, a tutorial on file IO would be worthwhile (if I didn't already know it), even though it can be a fairly small topic.You should look into , they do exactly what you are talking about.  Short exercises that are designed to perfect your coding/thining abilities.Other references: has some math/number related problems that are very interesting and ranged from easy to very challenging. You can pick your language of choice and submit only the solution (a large integer number). After you submitted the correct solution, you have access to a forum/comment page where others posted their comments and solutions.From experience I recommend finding a task that you do repetitively and turning it into a program. I also recommend, seriously, re-invent the wheel in order to get practice with programming. Don't let people tell you to not do something just because it exists already. If you don't know how it works, try to write it yourself. I don't exactly know what programming level you are on, but don't try to do anything too crazy off the bat, that is just a demotivator (such as trying to write a game for the PS3).If you already can navigate your way around with IO, then you should try to really learn how to use Collections effectively. I think one of the best practice assignments I have ever done was rewriting the Java TreeMap Class. It was a huge challenge and I learned a lot by doing it.Here are some suggestions for practice assignments:Take a text file that has a fair amount of information in it, grab anything, you can get something from here if you'd like:  and make a program that will do the following:One of my favorite things to do is mess with web data, go to a polling website, find a page that has poll data in a tabular form and do the following:Or just look for any site and extract data from it, just make sure the site is robot friendly , you don't want any one site to feel like it is under attack. Most of the time though this isn't normally a problem because if you read the site's terms of use it clearly states you are allowed to download 1 copy of whatever it is you are viewing so long as you don't intend to sell it. Of course this changes for every site.Go to a website and get all of the links off of the page programmatically.Here is a fun one, the Susan Program (I don't remember why it is named Susan) which I initially wrote using a C program and two Bourne shell scripts in a Unix environment. The idea in this program is to fork 4 child processes and give them each a task like so:Child 1: Reads in a file, creates a dictionary of each word and its position in the file, this is outputted to a file.Child 2: Takes Child 1's output and reconstructs the document, this is outputted to a file.Child 3: Takes Child 2's output and does what child 1 did againChild 4: Takes Child 3's output and does what child 2 did againThe goal here is to have an exact replica of the original file once Child 4 outputs it. This is challenging and somewhat pointless, but the point of this exercise is to get the practice.In your case, don't feel that you need to use different threads for this, you can just use a single program with two different functions and just call them in order.Again, not sure if you are at this level yet, but try to replace any \"for\" or \"foreach\" loop you have in your program with recursion, just as practice. Recursion is a pain in the butt, but it is valuable to know and understand.These are some suggestions which I think will really help you sharpen your skills.EnjoyI like  and  to take quick programming challenges and exercises.Code Jam is a good programming contest, although, as you mentioned, most of the problems there aren't for beginners.There's a good selection of problems from past topcoder algorithm competitions. (They are held ~2 times a month for almost 10 years already, so there're quite a lot.)\nDifficulty range from  (but still interesting) problems in the 2nd division to very hard.\nAdditionally, there're  with solutions and live environment where you can submit and test your code. You can also learn from submissions by other people.Check .\nAnother advantage of topcoder is the regular online contests they hold. I find that competing against other people in realtime is a great boost for motivation.There're many more problem archives, like ,  and , although they rarely provide solutions or even hints. might have some programming challenges to your liking.  A lot of the answers on that site are golfed (they implement the program in the least number of characters) but there are definitely some interesting examples to learn from.Try enrolling on any IT course on the following websites:These websites offer free educational IT programs from prestigious schools wherein there are lot of challenging exercises to sharpen your programming skills. I've learned to program percolation, pattern recognition, bouncing ball and so many more interesting things because of this. You will upload your program upon completion of the exercises and you will be graded accordingly (basically your progam will be checked).At the end of each course, you will even receive a certificate of completion. Cool Right?It depends of the language, but in the past  and  did great for me, also you can join to an open source initiative because usually helps to give you better code review chances.I've always thought that practicing with sample interview questions was a great way to sharpen one's skills and get exposed to types of problems that you normally wouldn't solve. Plus, if you're going to be looking for a job it helps you even more.Here's a pretty simple one that I did for fun the other day:Glassdoor.com has a lot of good interview question submitted by people who actually got them in an interview.Since you are in University and looking to improve your coding skills the hard-copy book  might be a good fit for you.  It's got great general programming questions and tidbits about interviewing with some of the best companies in tech.   Not only are there great questions, but there are decent problem breakdowns as well.[Disclosure: I own the book but otherwise have no association to it.]If you like programming and want to improve your programmer skills, you must try . It's a social young site, similar to StackOverflow but based on posting and solving programming challenges, instead of asking and answering questions. From very easy challenges to very hard ones.You can try to solve ACM problems. There are thousands of problems there and you can find the difficulty level so you can choose which problems to do first. The offcial site for this is: .  You can learn more there.regards\narefinIt may seem a little obvious, but I've noticed a real boost in my regular-expressions skills lately just from answering regex questions on Stack Overflow. Teaching forces you to break down problems into easily explainable pieces, and will also guide your research on those occasions where you know most, but not quite all, of a solution.I suggest finding a topic you're already somewhat proficient in, since this type of thing isn't so good as a beginners' tutorial. Search SO for questions tagged with that topic and try to figure out the answers. Don't just code them in your head; go ahead and write them out, test them, and explain them. If you're not sure your answer is correct, just write it without posting it.
Java

I have a java class that does a binary sum, I am still trying to figure out how to do unit tests but I don't know how to do it. I've googled around and the best explanation I had was the page from Wikipedia: but I'm still unsure how to do my test for this program. What the program does is basically take 2 byte[] and add them and return the new binary array. Written in Java. How can I test it?For making unit test for your project, please follow these steps (I am using Eclipse in order to write this test):1- Click on New -> Java Project.2- Write down your project name and click on finish.3- Write click on your project. Then, click on New -> Class.4- Write down your class name and click on finish.Then, complete the class like this: 5- Click on File -> New -> JUnit Test Case.6- Check setUp() and click on finish. SetUp() will be the place that you initialize your test.7- Click on OK.8- Here, I simply add 7 and 10. So, I expect the answer to be 17. Complete your test class like this:9- Write click on your test class in package explorer and click on Run as -> JUnit Test.10- This is the result of the test.I hope it helps.This is a very generic question and there is a lot of ways it can be answered.If you want to use JUnit to create the tests, you need to create your testcase class, then create individual test methods that test specific functionality of your class/module under tests (single testcase classes are usually associated with a single \"production\" class that is being tested) and inside these methods execute various operations and compare the results with what would be correct. It is especially important to try and cover as many corner cases as possible.In your specific example, you could for example test the following:To verify the results, you can use various assertXXX methods from the org.junit.Assert class (for convenience, you can do 'import static org.junit.Assert.*'). These methods test a particular condition and fail the test if it does not validate (with a specific message, optionally).Example testcase class in your case (without the methods contents defined):If you are not used to writing unit tests but instead test your code by writing ad-hoc tests that you then validate \"visually\" (for example, you write a simple main method that accepts arguments entered using the keyboard and then prints out the results - and then you keep entering values and validating yourself if the results are correct), then you can start by writing such tests in the format above and validating the results with the correct assertXXX method instead of doing it manually. This way, you can re-run the test much easier then if you had to do manual tests.Like @CoolBeans mentioned, take a look at . Here is a short  to get you started as well with jUnit 4.xFinally, if you really want to learn more about testing and test-driven development (TDD) I recommend you take a look at the following book by Kent Beck: .Create a Class in Java to add 2 numbers and then you can create jUnit to create Test Cases for that class. You have to assert the expected vs actual output from the tests. It's really that simple.
Java

I've been working with the new , and I've come across what seems like a common operation that isn't supported functionally: an \"orElseOptional\"Consider the following pattern:There are many forms of this pattern, but it boils down to wanting an \"orElse\" on an optional that takes a function producing a new optional, called only if the current one does not exist.It's implementation would look like this:I'm curious if there's a reason such a method doesn't exist, if I'm just using Optional in an unintended way, and what other ways people have come up with to deal with this case.I should say that I think that solutions involving custom utility classes/methods aren't elegant because people working with my code won't necessarily know they exist.Also, if anyone knows, will such a method be included in JDK 9, and where might I propose such a method? This seems like a pretty glaring omission to the API to me.This is part of JDK 9 in the form of , which takes a . Your example would then be:For details see  or  I wrote.The cleanest \u201ctry services\u201d approach given the current API would be:The important aspect is not the (constant) chain of operations you have to write once but how easy it is to add another service (or modify the list of services is general). Here, adding or removing a single  is enough.Due to the lazy evaluation of streams, no service will be invoked if a preceding service returned a non-empty .It's not pretty, but this will work: is a fairly handy pattern for use with .  It means \"If this  contains value , give me , otherwise give me \".  In this case, we call  and get an .  If that  contains value , we want to get , but if it is empty, we want to get . Rinse-repeat with more alternatives.Other uses of this pattern are Perhaps this is what you're after: Otherwise, you may want to have a look at . Here's an example of what I  that you're after:This is looks like a good fit for pattern matching and a more traditional Option interface with Some and None implementations (such as those in , ) or a lazy  implementation in .I'm the author of this library. With  you can also use structural  on JDK types. For Optional you can match on the present and absent cases via the .  it would look something like this -
Java

I am testing our server-application (written Java) on different operating systems and thought that OpenSolaris (2008.11) would be the least troublesome due to the nice Java integration. Turns out I was wrong, as I end up with a UnknownHostExceptionThe output is:However,  returns the correct IP address, and  returns  as expected. Also, the same code works perfectly on FreeBSD. Is there anything special to OpenSolaris that I am not aware of?Any hints appreciated, thanks.In good tradition I can answer my own question once again:It seems that  ignores the /etc/resolv.conf but only looks at the /etc/hosts file (where I hadn't specified anything besides localhost). Adding the IP and hostname to this file solves the problem and the exception is gone.Above answer is almost correct and I got hint from above and my problem get resolved...Thanks.But to improve this, I am adding steps-by-steps changes, so that it will be helpfull for even naive users.Steps:Now, overall file may look like this:Host lookups on Solaris uses  so depending on what the 'hosts:' line says it determines if , NIS, DNS and/or LDAP should be consulted.If you only use hosts and DNS you should have this in :The reason  works is because the  command directly consults . If you want to do a better command line test, use the command:Checkout  then put your hostname to hosts file.I use  as a fall back for when  throws an .  Here's the code (without exception handling for clarity).This errors shows up when I changed the workstation name and tried start Glassfish 2. You also must rename the entry at /etc/hosts, something like this:If you see this message than you need set hostname   ! After this, check which  file contain string like this .Also, check that command  returns something like this:Another option is in this post (in fact, what is in your /etc/sysconfig/network file for your hostname...by changing it to an FQDN name fixes this issue).I am having issues around this as well.  I need to do further testing, but it looks like\n can be more reliable.  I think that this does not do the lookup, but just grabs the IP.I am using it as the 'next best' when the  fails.
Java

What is the difference between these 2? I found few results on google nothing conclusive. Here is a follow up question: Say I create spring mvc web app annotate couple of classes with @Controller annotation and create something that will successfully transfer some information from front end -> back end and vice versa and perhaps some database might be involved on the back end side. What would you call that? Rest web service or servlet or something else ?A  is a service that provides service methods to its clients using either the REST programming paradigm or the SOAP protocol for communication. There are several ways to implement a web service. The most simple way to write a web service would be to write a class and annotate it with the  and  annotations from , and then launch it from a -method with:The result is that you can view the  at the registered URL and if you have SoapUI or any other SOAP client you can also test and use your web service.A  on the other hand is used to transport  requests and resonses. It can be used to write a web application with JSPs and HTML, or to serve XML and JSON responses (as in a RESTful service) and of course also to receive and return SOAP messages. You can think of it as . Servlets have their own standard which is currently the A more comprehensive and practical approach is to write a web service with a framework and to publish it on an application server or servlet container such as Tomcat or JBoss. In this case you would use a Servlet to handle the transport of the HTTP requests which transmit your SOAP or REST messages.To write a web service with servlet technology you can for example use JAX-WS (e.g. for SOAP). In order to write RESTful services, you can either use JAX-RS (with the reference implementation being ), or alternatively you can use , but afaik that is not the main purpose of this framework and Jersey is considerably easier to use.Regarding the second question:\nThe  annotation is a  specific stereotype annotation that tells Spring something about what your bean is supposed to do. What exactly a method of a controller will return depends on the actual implementation of your methods, you can configure Spring to return plain text, HTML, JSON, XML, binary data or what ever you want.A note on the side, a class that is annotated with  is not yet a servlet, it is simply a bean. How you use servlets depends mainly on the Framework that you use. For example, when you use Spring, the servlet job is done by Springs  which in turn forwards requests to the correct beans. If you use Tomcat, then you can directly write your own servlets by simply subclassing the  class and overwriting the necessary methods such as  which responds to HTTP GET requests from your browser.What you're describing is a , where a human uses a browser to interact with a software system. A  is a way for software systems to communicate with each other using HTTP and XML or JSON, without any humans involved.A  is a Java-specific way of writing software that responds to HTTP requests. Spring MVC abstracts away a lot of the implementation detail to make writing web applications easier, but uses servlets under the covers.My take on it would be that Web Service defines higher level abstraction such as some business specific functionality. While Servlet is just a software implementation component responsible for transport of data.Web Service implementation would typically rely on servlet for receiving data. However, it can as well use it's custom layer of dealing with protocol data.@Controller is probably more related to Web Service than servlet which is,again, a way to implement transport.A servlet is an HTTP query handler. You can do what you want with your incoming queries. A servlet run on the JVM.A web service is tied to a more or less rigid protocol: An interface (API) is defined with available methods and their arguments and return values for the service.This interface is exposed using the protocol mechanisms. These protocols are agnostic about the host that will run the service: you can define the same web service using PHP, Java, C# or your own language. You only need to have a piece of code able to understand queries for the protocol and able to produce answers readable by the client.For example  is a web service protocol:\nWikipedia definition:Web services operate on a higher level than servlets. Servlets are API which is simple and provides capabilities to write server side components.For example RESTfull is a Web Service which contains many other \"functionality\" along with servlet.\nTo deploy, we may define the web.xml as -which is none but a servletThe most obvious difference between Servlet and Web Service is: \nYou access servlet via HTTP while access Web Service via SOAP (Simple Object \nAccess Protocol). \nBut, in fact, you can not directly invoke a servlet, you can only open URL \nconnection and put some parameter to the servlet if the caller is out of \nyour application. And you can not restrict what parameters the caller can \nput. The caller does not know what parameters your servlet can receive \neither. \nSo, You'd better use web service to provide API to other applications, the \nWSDL file of your web service can give the caller enough information to \ninvoke your web service.Web Service uses ServletContainer class which is again a Servlet class, which handles the request in clean and structured way. \nThe REST stands for REpresentational STateless Protocol. Here the request won't store any data.The REST Web Service supports HTTP methods We can map any number of URLs to Web Service class which can have any type of HTTP methods.On other hand, there can be only 1 URL mapping can be done for each servlet.\nThough the end requirement can be achieved with the help of request parameter conditions, but using servlet nowadays won't provide clean way.In webservice we can define URL path at  as well as , which allows us to code in more structured way.
Java

there is a rule which says:that works fine for primitive types like int or strings:But what's about non primitive types? In most cases I've seen the following:or in singletons, where instance variable is not in upper case.The question is what is the right way to declare those types of variables (like log and instance)?That's still a . See the  for more information regarding the naming convention for constants. But in reality, it's all a matter of preference.The dialog on this seems to be the antithesis of the conversation on naming  and  classes. I find this alarming, and think that the decision runs much deeper than simply choosing one naming convention and using it always with .When naming interfaces and abstract classes, the accepted convention has evolved into not prefixing or suffixing your  or  with any identifying information that would indicate it is anything other than a class.The developer is said not to need to know that the above classes are  or an .My personal preference and belief is that we should follow similar logic when referring to  variables. Instead, we evaluate its usage when determining how to name it. It seems the all uppercase argument is something that has been somewhat blindly adopted from the C and C++ languages. In my estimation, that is not justification to continue the tradition in Java.We should ask ourselves what is the function of  in our own context. Here are three examples of how  may be used in :Could you use all uppercase in all three scenarios? Absolutely, but I think it can be argued that it would detract from the purpose of each. So, let's examine each case individually.In the case of the  example above, the logger is declared as private, and will only be used within the class, or possibly an inner class. Even if it were declared at  , its usage is the same:Here, we don't  that  is a  member variable. It could simply be a  instance variable. We don't know. We don't need to know. All we need to know is that we are logging the message to the logger that the class instance has provided.You wouldn't name it  in this scenario, so why should you name it all uppercase if it was ? Now you might say, why are you using  integers as an ? That is a   and I'd even say semi-controversial, so I'll try not to derail this discussion for long by venturing into it. However, it would be suggested that you could implement the following accepted enum pattern:There are variations of the above that achieve the same purpose of allowing explicit conversion of an  and . In the scope of streaming this information over a network, native Java serialization is simply too verbose. A simple , , or  could save tremendous bandwidth. I could delve into a long winded compare and contrast about the  of  vs  involving type safety, readability, maintainability, etc.; fortunately, that lies outside the scope of this discussion.If you can bring yourself to accept that the above statement is , we can follow that up with a discussion of style. When declaring an , the accepted style says that we don't do the following:Instead, we do the following:If your  block of integers serves as a loose , then why should you use a different naming convention for it? This usage case is perhaps the most cloudy and debatable of all. The static constant  usage example is where this is most often encountered. Java , but there are times when it is important to know how many bytes a data structure will occupy. For example, consider you are writing or reading a list of data structures to a binary file, and the format of that binary file requires that the total size of the data chunk be inserted before the actual data. This is common so that a reader knows when the data stops in the scenario that there is more, unrelated, data that follows. Consider the following made up file format:This file contains a list of  objects serialized into a byte stream and written to this file. This file has 325 bytes of  objects, but without knowing the size of each  you have no way of knowing which bytes belong to each . So, you define the size of  on :The  data structure will occupy 13 bytes when written to the file as defined above. Knowing this, when reading our binary file, we can figure out dynamically how many  objects follow in the file:This seems to be the typical usage case and argument for all uppercase  constants, and I agree that in this context, all uppercase makes sense. Here's why:Java doesn't have a  class like the C language, but a  is simply a class with all public members and no constructor. It's simply a data ure. So, you can declare a  in  like fashion:Let me preface this example by stating I personally wouldn't parse in this manner. I'd suggest an immutable class instead that handles the parsing internally by accepting a  or all 4 variables as constructor arguments. That said, accessing (setting in this case) this s members would look something like:These aren't  or , yet they are publicly exposed members that can be directly set. For this reason, I think that when a  member is exposed publicly, it makes sense to uppercase it entirely. This is the one time when it  important to distinguish it from public, non-static variables.In conclusion, the convention you choose for  variables is going to be your preference, but I strongly believe that the context of use should heavily weigh on your design decision. My personal recommendation would be to follow one of the two methodologies:Methodology 2 basically condenses its context into visibility, and leaves no room for interpretation.This is how I view the naming convention of  variables. I don't think it is something that can or should be boxed into a single catch all. I believe that you should evaluate its intent before deciding how to name it.(I do expect to be met with resistance, but also hope to gather some support from the community on this approach. Whatever your stance, please keep it civil when rebuking, critiquing, or acclaiming this style choice.)Well that's a very interesting question. I would divide the two constants in your question according to their type.  is a constant of primitive type while  is a non-primitive type.When we are making use of a constant of a primitive types, we are mutating the constant only once in our code  and we are just accessing the value of the constant elsewhere . This is the reason we are comfortable with using this convention.While in the case of non-primitive types, although, we initialize the constant in only one place , we are expected to mutate or call a method on this constant elsewhere . We guys don't like to put a dot operator after the capital characters. After all we have to put a function name after the dot operator which is surely going to be a camel-case name. That's why  would look awkward.Same is the case with  types. We are usually not mutating or calling a method on a  constant in our code and that's why we use the capital naming convention for a  type object.The language doesn't care. What's important is to follow the established styles and conventions of the project you're working on, such that other maintainers (or you five months from now) have the best possible chance of not being confused.I think an all-uppercase name for a mutable object would certainly confuse me, even if the reference to that object happened to be stored in a  variable.There is no \"right\" way -- there are only conventions. You've stated the most common convention, and the one that I follow in my own code:  static finals should be in all caps. I imagine other teams follow other conventions.A constant reference to an object is not a constant, it's just a constant reference to an object. is not what defines something to be a constant or not. It's just the Java way to define a constant, but it doesn't mean that every  declaration was put there to define a constant.When I write  I'm not trying to define a constant, I'm just trying to define a reference to an object that is  (that it is not accessible from other classes),  (that it is a class level variable, no instance needed) and  (that can only be assigned once). If it happens to coincide with the way Java expects you to declare a constant, well, bad luck, but it doesn't make it a constant. I don't care what the compiler, sonar, or any Java guru says. A constant value, like  is one thing, and a constant reference to an object is another. Gold is known to shine, but not everything that shines is gold.These variables are constants, i.e.  whether they're named in all caps or not.  The all-caps convention simply makes it more obvious that these variables are meant to be constants, but it isn't required.  I've seen in lowercase before, and I'm fine with it because I know to only use the logger to log messages, but it does violate the convention.  You could argue that naming it  is a sub-convention, I suppose.  But in general, naming constants in uppercase isn't the One Right Way, but it is The Best Way.In my opinion a variable being \"constant\" is often an implementation detail and doesn't necessarily justify different naming conventions. It may help readability, but it may as well hurt it in some cases.Don't live fanatically with the conventions that SUN have med up, do whats feel right to you and your team.Update: There were special cases that was excluded didn't know that. I however withholds to do what you and your team seems fit.
Java

I have a method that returns void in a class that is a dependency of the class I want to test.This class is huge and I'm only using this single method from it.\nI need to replace the implementation of this method for the test as I want it to do something different and I need to be able to access the parameters this method receives.I cannot find a way of doing this in . I think I know how to do it with  by using  but I don't want to add another library unless absolutely necessary. If I understand what you want to do correctly, you should be able to use :The  explains:If you just call the void method for each time you're expecting it to be invoked and then invoke  prior to calling , Easymock will \u201cremember\u201d each invocation.So I don\u2019t think you need to explicitly call  (other than ) since you\u2019re not expecting anything from a void method, except its invocation.Thanks Chris! by fellow StackOverflow user  is a good blog post that provides more detail. Notable excerpt:If you only want access to the parameters for later, you might also appreciate the  class which is new to EasyMock 2.4.You can use an instance of the \"Capture\" class in place of a matcher. When your mocked method is invoked, the Capture instance will store the parameter it was invoked with.You might want to check out PowerMock. EasyMock is based on the proxy reflection API meaning everything is a proxy and you can only test interfaces, and thus only non-final methods and classes. This might work for some, but if you're testing the world as built, you'll need more power.With PowerMock the Java 5 instrumentation API removes the limitations. No need to write mock object implementations of the object to be tested (just ugly IMO). Couple PowerMock with Mockito (or JMockit) and you'll really be off to the races.Of course, there is the other direction of rewriting your code to be more easily tested, which is generally a good idea too, if possible.In situations like these I've found that making a nested class in my unit test class and overriding the methods with special requirements in that way is the best route. So if you're testing  which has that method with the parameters you need to access, you'd do something like:In my unit testing code, I then just use this instance instead. Just treat it as if it was any other mock object. Much easier than mixing libraries, which I agree is probably not a good idea.
Java

I have a parsing function that parses an encoded length from a byte buffer, it returns the parsed length as an int, and takes an index into the buffer as an integer arg.  I want the function to update the index according to what it's parsed, i.e. want to pass that index by reference.  In C I'd just pass an .\nWhat's the cleanest way to do this in Java?\nI'm currently looking at passing the index arg. as an , but it's a bit ugly.You can try using  from Apache Commons library.  There is no direct way of doing this in the language itself.This isn't possible in Java. As you've suggested one way is to pass an . Another would be do have a little class e.g.  that wrapped an .Wrap the byte buffer and index into a  object. A ByteBuffer encapsulates the concept of a buffer+position and allows you to read and write from the indexed position, which it updates as you go along.You cannot pass arguments by reference in Java.What you can do is wrap your integer value in a mutable object. Using Apache Commons'  is a good option. Another, slightly more obfuscated way, is to use an  like you suggested. I wouldn't use it as it is unclear as to why you are wrapping an  in a single-celled array.Note that  is immutable.You can design new class like this:later you can create object of this class :then you can pass  as argument where you want to pass an integer variable:so for update the integer value:for getting value:You can use .You can create a Reference class to wrap primitives:Then you can create functions that take a Reference as a parameters:Usage:Hope this helps.
Java

I want to encrypt a string using AES with my own key. But I'm having trouble with the bit length of the key. Can you review my code and see what I need to fix/change.Right now I get an exception \"\". Do I need to pad my key? How should I do it?Also do I need to set anything for ECB or CBC?ThanksYou should use SHA-1 to generate a hash from your key and trim the result to 128 bit (16 bytes).Additionally don't generate byte arrays from Strings through  it uses the platform default Charset. So the password \"bla\u00f6\u00e4\" results in different byte array on different platforms.Edit:\nIf you need 256 bit as key sizes you need to download the \"Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files\" , use SHA-256 as hash and remove the  line.\n\"ECB\" is the default Cipher Mode and \"PKCS5Padding\" the default padding.\nYou could use different Cipher Modes and Padding Modes through the  string using following format: \"Cipher/Mode/Padding\"For AES using CTS and PKCS5Padding the string is: \"AES/CTS/PKCS5Padding\"You should use a KeyGenerator to generate the Key, AES key lengths are 128, 192, and 256 bit depending on the cipher you want to use.Take a look at the tutorial  Here is the code for Password Based Encryption, this has the password being entered through System.in you can change that to use a stored password if you want. This wll work.
Java

How can I check to make sure my variable is an int, array, double, etc...? Edit: For example, how can I check that a variable is an array? Is there some function to do this?Java is a statically typed language, so the compiler does most of this checking for you.  Once you declare a variable to be a certain type, the compiler will ensure that it is only ever assigned values of that type (or values that are sub-types of that type).The examples you gave (int, array, double) these are all primitives, and there are no sub-types of them.  Thus, if you declare a variable to be an :You can be sure it will only ever hold  values.If you declared a variable to be a , however, it is possible that the variable will hold sub-types of .  Examples of these include , , etc.If you did have a  variable, and you needed to know if it was an , you could do the following:However, if you find yourself thinking you need to do that, you may want to re-think your approach.  In most cases, if you follow object-oriented principals, you will not need to do this.  There are, of course, exceptions to every rule, though.Actually quite easy to roll your own tester, by abusing Java's method overload ability. Though I'm still curious if there is an official method in the sdk.Example:then:You may work with Integer instead of int, Double instead of double, etc. (such classes exists for all primitive types).\nThen you may use the operator instanceof, like a.getClass().getName() - will give you the datatype of the actual object referred to by a, but not the datatype that the variable, a, was originally declared as or subsequently cast to.boolean b = a instanceof String - will give you whether or not the actual object referred to by a is an instance of a specific class.\nAgain, the datatype that the variable, a, was originally declared as or subsequently cast to has no bearing on the result of the instanceof operator.I took this information from:\nThis can happen. I'm trying to parse a String into an int and I'd like to know if my Integer.parseInt(s.substring(a, b) is kicking out an int or garbage before I try to sum it up.By the way, this is known as reflection. Here's some more information on the subject: The first part of your question is meaningless. There is no circumstance in which you don't know the type of a primitive variable at compile time.Re the second part, the only circumstance that you don't already know whether a variable is an array is if it is an Object. In which case  will tell you.I did it using: Well, I think checking the type of variable can be done this way. public  void checkType(T object) {This way you need not have multiple overloaded methods. I think it is good practice to use collections over arrays due to the added benefits. Having said that, I do not know how to check for an array type. Maybe someone can improve this solution. Hope this helps! P.S Yes, I know that this doesn't check for primitives as well. public class Demo1\n{}
Java

So I'm drawing this triangle in android maps using the code below in my draw method:The pointX_returned are the coordinates which I'm getting from the fields. They are basically latitudes and longitudes.\nThe result is a nice triangle but the insider is empty and therefore I can see the map. Is there a way to fill it up somehow? You probably need to do something like :And use this color for your path, instead of your ARGB. Make sure the last point of your path ends on the first one, it makes sense also.Tell me if it works please !Ok I've done it. I'm sharing this code in case someone else will need it:Thanks for the hint Nicolas!you can also use vertice : this function shows how to create a triangle from bitmap. That is, create triangular shaped cropped image. Try the code below or The function above returns an triangular image drawn on canvas. You need remove path.moveTo after first initial.Using @Pavel's answer as guide, here's a helper method if you don't have the points but have start x,y and height and width. Also can draw inverted/upside down - which is useful for me as it was used as end of vertical barchart. 
Java

An Enum in Java implements the Comparable interface.  It would have been nice to override Comparable's compareTo method, but here it's marked as final.  The default natural order on Enum's compareTo is the listed order.  Does anyone know why a Java Enum has this restriction?For consistency I guess... when you see an  type, you know  that its natural ordering is the order in which the constants are declared.To workaround this, you can easily create your own  and use it whenever you need a different ordering:You can use the  directly:or use it in collections or arrays:Further information:Providing a default implementation of compareTo that uses the source-code ordering is fine; making it final was a misstep on Sun's part.  The ordinal already accounts for declaration order.  I agree that in most situations a developer can just logically order their elements, but sometimes one wants the source code organized in a way that makes readability and maintenance to be paramount.  For example:The above ordering looks good in source code, but is not how the author believes the compareTo should work.  The desired compareTo behavior is to have ordering be by number of bytes.  The source-code ordering that would make that happen degrades the organization of the code.  As a client of an enumeration i could not care less how the author organized their source code.  I do want their comparison algorithm to make some kind of sense, though.  Sun has unnecessarily put source code writers in a bind.Enumeration values are precisely ordered logically according to the order they are declared. This is part of the Java language specification. Therefore it follows that enumeration values can only be compared if they are members of the same Enum. The specification wants to further guarantee that the comparable order as returned by compareTo() is the same as the order in which the values were declared. This is the very definition of an enumeration.One possible explanation is that  should be consistent with .And  for enums should be consistent with identity equality ().If  where to be non-final it would be possible to override it with a behaviour which was not consistent with , which would be very counter-intuitive.If you want to change the natural order of your enum\u2019s elements, change their order in the source code.
Java

I would like to have a bidirectional JSON to Java serializationI'm using  the Java to JSON to JQuery path... ()\ne.g. and In JQuery I use this works  (e.g. annotations work already, thanks to all the answerers)However, how do I do the  path: have JSON be serialized to a Java Object back using RequestBody? no matter what I try, I can't get something like this to work:I have Jackson configured correctly (it serializes on the way out) and I have MVC set as annotations driven of courseHow do I make it work? is it possible at all? or is Spring / JSON / JQuery is oneway (out)? I changed this Jackson settingTo the (almost similiar one) suggested And it seems to work! I don't know what exactly did the trick, but it works...I'm pretty sure you only have to register  (the easiest way to do that )Here's a working example:You can test this setup by executing  on the command line, and then sending a POST request:I used the  to do this.Here's what the response looks like:In Addition you also need to be sure that you have in your SPring configuration xml.I also would recommend you to read this blog post. It helped me alot.\njust checked my working code where I have @RequestBody working correctly.\nI also have this bean in my config:May be it would be nice to see what Log4j is saying. it usually gives more information and from my experience the @RequestBody will fail if your request's content type is not Application/JSON. You can run Fiddler 2 to test it, or even Mozilla Live HTTP headers plugin can help.In addition to the answers here...if you are using jquery on the client side, this worked for me:Java:Jquery (you need to include Douglas Crockford's json2.js to have the JSON.stringify function):If you do not want to configure the message converters yourself, you can use either \n, add Jackson to the classpath and Spring will give you both JSON, XML (and a few other converters) by default. Additionally, you will get some other commonly used features for conversion, formatting and validation.In case you are willing to use Curl for the calls with JSON 2 and Spring 3.2.0 in hand checkout the FAQ . As AnnotationMethodHandlerAdapter is deprecated and replaced by  RequestMappingHandlerAdapter. 
Java

I'd like to use Hibernate's criteria api to formulate a particular query that joins two entities. Let's say I have two entities, Pet and Owner with a owner having many pets, but crucially that association is not mapped in the Java annotations or xml.With hql, I could select owners that have a pet called 'fido' by specifying the join in the query (rather than adding a set of pets to the owner class).Can the same be done using hibernate criteria? If so how?Thanks,\nJMy understanding is that if you do this using HQL, you are creating a Cartesian join with a filter, rather than an inner join. Criteria queries do not support doing this.This is indeed possible with criteria::  This actually performs a sub-query instead of a join but it allows you to use Criteria on two entities that do not have a hibernate relationship defined.In NHibernate you can use subqueries which are defined as DetachedCriteria. Not sure if it works the same in Java, most probably it is the same:Assumed that it is joined using the name of the owner.There's a , which you can give arbitrary , and add to your .  In the  string, the token {alias} \"will be replaced by the alias of the root entity.\"
Java

We use GSLB for geo-distribution and load-balancing. Each service is assigned a fixed domain name. Through some DNS magic, the domain name is resolved into an IP that's closest to the server with least load. For the load-balancing to work, the application server needs to honor the TTL from DNS response and to resolve the domain name again when cache times out. However, I couldn't figure out a way to do this in Java.The application is in Java 5, running on Linux (Centos 5).Java has some seriously weird dns caching behavior. Your best bet is to turn off dns caching or set it to some low number like 5 seconds.Per Byron's answer, you can't set  or  as System Properties by using the  flag or calling  because these are not System properties - they are  properties.If you want to use a System property to trigger this behavior (so you can use the  flag or call ), you will want to set the following  property:This system property will enable the desired effect.  But be aware: if you don't use the  flag when starting the JVM process and elect to call this from code instead:This code  execute before any other code in the JVM attempts to perform networking operations.  This is important because, for example, if you called  in a .war file and deployed that .war to Tomcat, this wouldn't work: Tomcat uses the Java networking stack to initialize itself much earlier than your .war's code is executed.  Because of this 'race condition', it is usually more convenient to use the  flag when starting the JVM process. If you don't use  or call , you will need to edit  and set those security properties in that file, e.g.But pay attention to the security warnings in the comments surrounding those properties.  Only do this if you are reasonably confident that you are not susceptible to .To expand on Byron's answer, I believe you need to edit the file  in the  directory to effect this change.Here is the relevant section:Documentation on the  file .This has obviously been fixed in newer releases (SE 6 and 7). I experience a 30 second caching time max when running the following code snippet while watching port 53 activity using tcpdump.To summarize the other answers, in  you can set the value of the property  to adjust how DNS lookups are cached.  Note that this is  a system property but a security property.  I was able to set this using:This can also be set by the system property  though this will not override a security property if it is set elsewhere.I would also like to add that if you are seeing this issue with web services in WebSphere, as I was, setting  will not be enough.  You need to set to the system property  to .  Unlike the time-to-live property, this can be set as a JVM argument or via ).IBM has a pretty detailed post on how WebSphere handles DNS caching .  The relevant piece to the above is:
Java

Take the  for example Can anyone give me an example of a  where the  and  methods are different?According to the  doc, the  method will often seek to ensure that an element exists within the  rather than adding duplicates. So my question is, what is the difference between the  and  methods?Is it that the  method will add duplicates regardless? (I doubt that it is because if a  should only have distinct elements this would circumvent that).EDIT:\nIn a  the  and  methods are the same method (see my answer below). Can anyone give me an example of a class where the  and  methods are different?I guess the difference is in the contract, that when element can not be added to collection the  method throws an exception and  doesn't.From: From: There is no difference for the implementation of :For  there actually is a difference:The difference between  and  is explained by these two excerpts from the javadocs:From the  interface:From the  interface is a  implementation that does not impose any insertion restrictions.  Therefore the  and  methods have the same semantics.By contrast,  is an implementation in which  and  behave differently, depending on how the queue was instantiated.from the source code in jdk 7 as follow:we can easily know that the add function will return true when successfully add a new element into the queue, but throw a exception when failed .The  interface specifies that  will throw an  if no space is currently available (and otherwise return ) while  will return  if the element couldn't be inserted due to capacity restrictions.The reason they are the same in a  is that this queue is specified to be unbounded, i.e. there are no capacity restrictions.  In the case of no capacity restrictions, the contracts of  and  display the same behaviour.Source: The offer method inserts an element if possible, otherwise returning false. This differs from the Collection.add method, which can fail to add an element only by throwing an unchecked exception. The offer method is designed for use when failure is a normal, rather than exceptional occurrence, for example, in fixed-capacity (or \"bounded\") queues.
Java

Is anything like this possible in Java? Can one assign custom numeric values to enum elements in Java?, and then some, example from documentation:Assuming that EXIT_CODE is referring to  ( exit_code ) then you could doThen you can put the following at appropriate spots in your code
Java

How would I go about doing calculations with extremely large numbers in Java? I have tried  but that maxes out at 9223372036854775807, and when using an integer it does not save enough digits and therefore is not accurate enough for what I need. Is there anyway around this?You can use the  class for integers and  for numbers with decimal digits. Both classes are defined in  package.Example:Use the  class that is a part of the Java library.Checkout BigDecimal and BigInteger.Here is an example which gets big numbers very quickly.Depending on what you're doing you might like to take a look at GMP (gmplib.org) which is a high-performance multi-precision library. To use it in Java you need JNI wrappers around the binary library.See some of the Alioth Shootout code for an example of using it instead of BigInteger to calculate Pi to an arbitrary number of digits.
Java

I am using javadoc doclets with gradle, so I need to use the package tools.jar, which is in the lib folder from the jdk (1.6.0_26 in my case).The point is that gradle does not take it automatically, so I was adding that tools package to my libs folder, and then adding it to dependencies.gradle . Now I want to take it directly from my JDK home into my dependencies.gradle. Is there a way to do that? I have tried the next in my dependencies.gradle:But it does not find it while compiling.Found it.  JAVA_HOME points to the JDK, while java.home points to the JRE. See  for more info.Soo... My problem was that my startpoint was the jre folder (C:\\jdk1.6.0_26\\jre) and not the jdk folder (C:\\jdk1.6.0_26) as I thought(tools.jar is on the C:\\jdk1.6.0_26\\lib folder ). The compile line in dependencies.gradle should be:I had this problem when I was trying to run commands through CLI. It was a problem with system looking at the JRE folder i.e. \n. If we look in there, there is no , hence the error. You need to find where the  is, in my case: , and if you look in the  directory, you will see .What I did I created a new environment variable :\nAnd then you need to edit your PATH variable to include JAVA_HOME, i.e.  \nRe-open command prompt and should run. I got the same error using Eclipse trying to execute a Gradle Task. Every time I run a command (i.e. war) the process threw an exception like: I tried the solution listed in this post but none of them solved this issue. Here my solution :Run again, Enjoy! It may be two years too late, but I ran into the same problem recently and this is the solution I ended up with after finding :It should work if java.home points to a directory that's not under the JDK directory and even on Mac OS where you'd have classes.jar instead of tools.jar.I just added a  file with the following content:I was struggling as well for this Solution. Found a better way to it with Gradle as described .\nWe can get the JVM/JDK information from Gradle itself.So simple.Add this to :Did you make sure that tools.jar made it on the compile class path? Maybe the path is incorrect.Like other answers I set  property in  file. But path with \\ separators did not work (building on windows 10): So instead of i had to usethen the build was successfulProblem is that project is build with JRE instead of JDK and since I was building it from eclipse this also worked:In my case (Windows 10) after Java update I lost my Enviroment Variables, so I fixed added the variables again, based in the following steps 
Java

I need web access from Gradle through a proxy server to use the Gradle/Artifactory integration for Jenkins. To reduce possible causes for issues, I manually add the Artifactory plugin in build.gradle and run it from command line:Following  description I specified the following in .gradle/gradle.properties in my home directory:With the above proxy configuration (that is otherwise known to work), it fails:I have two proxy servers to choose from, and one always responds with  (), the other with  (), so obviously, the proxyHost and proxyPort options are used.As the user name (based on an Active Directory user) contains a backslash, I tried both  and , but neither worked. The user specified is different from the user that is logged in to the machine and Active Directory. This user's credentials aren't valid for the proxy, so I need to be able to specify a different user.Setting the same options in Jenkins' or Artifactory's GUI worked.Refinement over Daniel's response: worked for me (with grade.properties in either homedir or projet dir, build was still failing). Thanks for pointing the issue at gradle that gave this workaround.Using a  simple \"Request a URL\" Java program, I was able to replicate the issue. and  seem to be non-standard, albeit popular, options, as they're not described in ; even though the Gradle manual mentions them.It seems Java programs that wish to support proxy authentication  (and I was able to do this using the code on the linked page).I submitted this issue (and a fix) to . Raised issue GRADLE-1556 was resolved in 1.0-milestone-8 (Feb 2012)Try the following:This is my gradle.properties, please note those HTTPS portionIn my  I have the following task, which uses the usual linux proxy settings,  and , from the shell env:For me, works adding this configuration in the gradle.properties file of the project, where the build.gradle file is:Where : \nproxyUrl is the url of the proxy server (.)proxyPort is the port (usually 8080)USER is my domain userPASSWORD, my passwordIn this case, the proxy for http and https is the sameIf you are behind proxy and using eclipse, go to . Select the Active Providers as 'Manual'.Under Proxy entries section, click on HTTPS, click Edit and add proxy host & port. If username and password are required, give that as well. It worked for me!
Java

Why should I write (as my collegue says):instead of:?I know that the use of constants is recommended but I think the value of  will never change! So I write .You should not. The  name is no more meaningful than 1. If however this value has some other meaning (for example, month in the year), then using a constant (like ) will make your code clearer.I can guess that this constant in Commons Math library was created in Java 1.4 when there were no Integer cache and autoboxing, so it had sense in terms that you may reuse the same  object (not primitive ) in different places to save memory. So it was added for performance reasons, not for code clarity. Now it's obsolete: even if you need an  object, you can use  or implicit autoboxing and get the cached one.You should  write ! Neither should you write  (see exception below)!Why? A literal like  is called a . Magic numbers are \"unique values with unexplained meaning or multiple occurrences which could (preferably) be replaced with named constants\" (explanation from the same Wikipedia page).So what usually should be done is making those magic numbers to constants whose name represents or explains the meaning of that number. The constant  does not explain the meaning.So what you actually have to do is to find the meaning of the value in this context and create a constant with exactly that name. If the  represents the maximum number of allowed threads for example, you should have a constant like:EDIT as per Tagir's commentIf the literal itself has a meaning in the domain for which you are writing the code, then it should not be replaced by a named constant. Tagir's example for calculating the inverse element is a good one:Here the literal  has a meaning in this context inside the math domain. So it can be used as is.I happen to have just written style guidelines for my company and I'd suggest the following: it gives you a  object rather than primitive  1, and as it is  it acts as a constant and can be used in comparison of  objects because will always return same instance.So in the above scenario it might not look  but somewhere if you are using it while comparison, it for sure has impact.Moreover, as much as we can, should prefer the use of constants over hardcoded beacuse:You may know whether it will never change, but I won't if I start editing your code...Basically it's a way of documenting your code . The reason to use constants and examples like this is to avoid This being said, you can use it to a point where it is not advantageous anymore and clutter inducing. I tend to do it for things that are used more than once or have the concept of being changed by me or someone else... or in simpler terms  values.From  you'll see it's defined as:So, you'll see that INTEGER_ONE is not the same as 1. It's an object that's already been constructed for you. So, if we're needing an instance of , rather than create your own, you can reuse the one from the library saving time and memory.It really depends on your application, if you indeed what the  version of 1, then, you'd probably be better of using that instead of this  class.Imagine that you have this But a few thousand times...And suddenly in needs to be a 2.What it easier for you to change?EDIT: Before downvoting, im answering from the perspective of the advantages of not using magic numbers, im not in any way (i thought this was inferable, come on people) advising to change the library constant.
Java

I'm trying to use ant to compile using this command :I don't know if the problem comes from my windows 64bit, or by something else. Because I have java Installed in the 64 & 32 prog files. I downloaded  and putted it in C:\\Program Files\\apache-ant-1.8.2I tried to put ant everywhere, I switched also the ENV PATH between java 64 and 32 but everytime I get this error message :I searched for tools.jar in the ant lib folder, in the java 64 and 32, but no trace of it in the system.What do you think ? A JRE doesn't have a tools.jar, you need a JDK. Set your JAVA_HOME and PATH variables so that they point to a JDK, not a JRE.I had similar issue and got solved by doing following , 1) set JAVA_HOME as C:\\Program Files (x86)\\Java\\jdk1.7.0\\ 2) ANT_HOME as F:\\ant\\apache-ant-1.8.4-bin\\apache-ant-1.8.43) add both to 'path ' in system variablesI had to copy C:\\Program Files\\Java\\jdk1.6.0_26\\lib\\tools.jar to C:\\Program Files\\Java\\jre6\\lib\\extThanks anyway.Please make sure that you are pointing to JDK and not a JRE. For example, you should set JAVA_HOME as \"C:\\Program Files\\java\\jdk1.6.0_26\" and have %JAVA_HOME%\\bin in your system path.tools.jar comes with JDK, but what happens in your case it looks for it within /Java/jre6. Change JAVA_HOME env var to one of your JDK home.
Java

What is the most efficient way to remove the first 3 characters of a string?For example:Just use substring:  will return Use substring method of String class :\n       Use the  method of the  class :
Java

I have an array of numbers from 1 to 100 (both inclusive). The size of the array is 100. The numbers are randomly added to the array, but there is one random empty slot in the array. \nWhat is the quickest way to find that slot as well as the number that should be put in the slot? A Java solution is preferable.You can do this in O(n). Iterate through the array and compute the sum of all numbers. Now, sum of natural numbers from 1 to N, can be expressed as . In your case N=100.Subtract the sum of the array from , where N=100.That is the missing number. The empty slot can be detected during the iteration in which the sum is computed.We can use XOR operation which is safer than summation because in programming languages if the given input is large it may overflow and may give wrong answer.Before going to the solution, know that . So if we XOR two identical numbers the value is 0. Now, XORing [1..n] with the elements present in the array cancels the identical numbers. So at the end we will get the missing number.This was an Amazon interview question and was originally answered here: It was answered, as below:It was also blogged here: Here is a simple program to find the missing numbers in an integer array5050 - (sum of all values in the array) = missing numberThis is c# but it should be pretty close to what you need:Well, use a bloom filter.On a similar scenario, , it does not include duplicates and only one number is missing, , using binary search.The solution that doesn't involve repetitive additions or maybe the n(n+1)/2 formula doesn't get to you at an interview time for instance.You have to use an array of 4 ints (32 bits) or 2 ints (64 bits). Initialize the last int with (-1 & ~(1 << 31)) >> 3. (the bits that are above 100 are set to 1) Or you may set the bits above 100 using a for loop.Example: (32 bit version) lets say that the missing number is 58. That means that the 26th bit (left to right) of the second integer is set to 0.The first int is -1 (all bits are set) so, we go ahead for the second one and add to \"no\" the number 32. The second int is different from -1 (a bit is not set) so, by applying the NOT (~) operator to the number we get 64. The possible numbers are 2 at the power x and we may compute x by using log on base 2; in this case we get log2(64) = 6 => 32 + 32 - 6 = 58.Hope this helps.This is not a search problem. The employer is wondering if you have a grasp of a checksum. You might need a binary or for loop or whatever if you were looking for multiple unique integers, but the question stipulates \"one random empty slot.\" In this case we can use the stream sum. The condition: \"The numbers are randomly added to the array\" is meaningless without more detail. The question does not assume the array must start with the integer 1 and so tolerate with the offset start integer. Success time: 0.18 memory: 320576 signal:0I found this beautiful solution here: ========Simplest Solution for sorted Array===========Finding the missing number from a series of numbers. IMP points to remember.I think the easiest and possibly the most efficient solution would be to  loop over all entries and use a bitset to remember which numbers are set, and then test for 0 bit. The entry with the 0 bit is the missing number.This Program finds missing numbersOne thing you could do is sort the numbers using quick sort for instance. Then use a for loop to iterate through the sorted array from 1 to 100. In each iteration, you compare the number in the array with your for loop increment, if you find that the index increment is not the same  as the array value, you have found your missing number as well as the missing index. Below is the solution for finding all the missing numbers from a given array:Lets say you have n as 8, and our numbers range from 0-8 for this example\nwe can represent the binary representation of all 9 numbers as follows\n0000\n0001\n0010\n0011\n0100\n0101\n0110\n0111\n1000in the above sequence there is no missing numbers and in each column the number of zeros and ones match, however as soon as you remove 1 value lets say 3 we get a in balance in the number of 0's and 1's across the columns. If the number of 0's in a column is <= the number of 1's our missing number will have a 0 at this bit position, otherwise if the number of 0's > the number of 1's at this bit position then this bit position will be a 1. We test the bits left to right and at each iteration we throw away half of the array for the testing of the next bit, either the odd array values or the even array values are thrown away at each iteration depending on which bit we are deficient on. The below solution is in C++At each iteration we reduce our input space by 2, i.e N, N/2,N/4 ... = O(log N), with space O(N)Solution With PHP ;and  will give the index of missing numberHere program take time complexity is O(logn) and space complexity O(logn)If the array is randomly filled, then at the best you can do a linear search in O(n) complexity. However, we could have improved the complexity to O(log n) by divide and conquer approach similar to quick sort as pointed by giri given that the numbers were in ascending/descending order. Now I'm now too sharp with the Big O notations but couldn't you also do something like (in Java)where numbers is the array with your numbers from 1-100.\nFrom my reading of the question it did not say when to write out the missing number.Alternatively if you COULD throw the value of i+1 into another array and print that out after the iteration.Of course it might not abide by the time and space rules. As I said. I have to strongly brush up on Big O.Another homework question. A sequential search is the best that you can do. As for a Java solution, consider that an exercise for the reader. :PQuick sort is the best choice with maximum efficiency....
Java

I have a loop over a bunch of URLs, for each one I'm doing the following:The first query is fine, the second throws this exception:This is just a simple single-threaded app. How can I release this connection?The recommended way, by Httpcomponents 4.1, is to close connection and release any underlying resources:where  passed is a response entity.This seems to work great :And don't forget to consume the entity even if you didn't open its content. For instance, you expect a HTTP_OK status from the response and don't get it, you still have to consume the entity !To answer my own question: to release the connection (and any other resources associated with the request) you must close the InputStream returned by the HttpEntity:From the Since version 4.2, they introduced a much more convenience method that simplifies connection release: I'm chiming in with a detailed answer that specifically addresses Apache HttpClient 4.0.1.  I'm using this HttpClient version, since it's provided by WAS v8.0, and I need to use that provided HttpClient within Apache Wink v1.1.1, also provided by WAS v8.0, to make some NTLM-authenticated REST calls to Sharepoint.To quote Oleg Kalnichevski on the Apache HttpClient mailing list:If the response is not to be consumed, then the request can be aborted using the code below:Apache HttpClient Version: 4.1.3I've got this problem when I use HttpClient in Multithread envirnoment (Servlets). \nOne servlet still holds connection and another one want to get connection.  version 4.0 use version 4.2 use and set this two setters: HTTP HEAD requests must be treated slightly differently because response.getEntity() is null.\nInstead, you must capture the HttpContext passed into HttpClient.execute() and retrieve the connection parameter to close it (in HttpComponents 4.1.X anyway).HttpComponents 4.2.X added a releaseConnection() to HttpRequestBase to make this easier.I had the same issue and solved it by closing the response at the end of the method:I'm using HttpClient 4.5.3, using  worked for me.
Java

I am trying to trouble shoot a JUnit. In the source code, I have set break point in two places: 1) in a line where a static member is initialized 2) the first line of one of the test cases.The debugger stops in the static field initializing line. But it doesn't stop in the test case. No matter where I set the break point in the test case, the debugger doesn't stop there. I know for sure that the test case is executed as I can see the log messages that I have added appear in the log.Any help would be greatly appreciated.I am using Eclipse Galileo and JUnit4 launcher.This could be related to one of the bugs in .If this indeed turns out to be the issue, you should move to a higher version of the JDK (that's no guarantee though, since ). The best bet is to use -XX:+UseParallelGC flag. Increasing the size of the minimum and maximum heap size, to delay the first GC, bring temporary relief.By the way, use  to track how others have been faring.Fix could be as simple as clicking run/skip all breakpoints. Worked for me.Make sure, under Run > Debug Configurations, that 'Stop in main' is selected, if applicable to your situation.Usually when this happens to me (rare but it does) means that the code being executed is different than the code in the editor.   It will happen from time to time for Eclipse that the built classes and the code in editor are out of sync.  When that happens I get all sort of weird debugger behavior (debugging empty lines, skipping lines of codes etc).Restarting Eclipse, clean all projects and rebuild everything usually clears things up.   I had also the Maven plugins (older versions... had not had it for a while now) that had a tendency to do that too.Otherwise it might be a bug, maybe the one Vineet stated,Hope this helpsYou might have accidentally skipped all break points in Eclipse toolbar. To fix this go to Eclipse -> Run -> Skip All Breakpoints. For JDK7, run->Debug Configurations, check \"Keep JUnit running after a test run when debugging\".Make sure you declare the package at the top.\nIn my groovy code this stops at breakpoints:This does not stop at breakpoints:Project -> Clean seemed to work for me on on JRE 8In order to debugger work with remote, the java .class files must be complied along with debugging information. If \"\" option was passed to compiler then the class file will not have necessary information and hence debugger will not be able to match breakpoints on source code with that class in remote. Meanwhile, if jars/class files were , then they also will not have any debug info. According to your responses, most probably this is not your case, but this info could be useful for others who face the same issue.Happened to me once, when I had unchecked \"Run > Build automatically\" and forgot to re-check it.:One additional comment regarding Vineet Reynolds answer.I found out that I had to set -XX:+UseParallelGC in eclipse.iniI setup the vm arguments as followthat solved the issue.Also verify if breakpoints on other lines DO work, it may be a bug in the debugger. I have had a problem with the Eclipse debugger where putting a breakpoint on a boolean assignment whose code was on the next line didn't work , but putting it on the previous or next line did.If nothing works- Another possible problem is that the debugger port may be blocked by the firewall. For example, I was using mule anypoint studio (v 5.4.3). The default debugger port is 6666. When a flow is executed, it would not stop at breakpoint. when I changed the port to another (e.g. 8099), it worked fine.Go to  and check if too many debug instances are created.\nMy issue was resolved when i deleted multiple debug instances from configuration and freshly started debugging.If you are on Eclipse,Right click on your project folder under \"Package Explorer\".Goto Source -> Clean up and choose your project.This will cleanup any mess and your break-point should work now.Creating a new workspace worked for me.In my case I had multiple projects in same workspace. The java file I was trying to debug was present in more than one projects with same package.I didn't need the other project, so simply closed unrelated projects (or remove the file from unrelated project).In my case the problem was that I hadn't Debug view open in Debug perspective, so:1 - Be sure you have debug perspective opened:2 - Be sure you have debug view opened:This is what works for me:I had to put my local server address in the  configuration like this:: that address, is the one I configure in my Apache  file.: the only breakpoint that was working was the 'Break at first line', after that, the breakpoints didn't work.: check your  properties in your  file, and remove any you think is not required.
Java

How to write a byte array to a file in Java?You can use  from .As  points out the most straight forward now . Details for this can be found in the . Old answer:\n  would be the most straight forward. What is the data you want to write?The  may be of some use to you.As of Java 1.7, there's a new way: Java 1.7 also resolves the embarrassment that Kevin describes: reading a file is now:A commenter asked \"why use a third-party library for this?\" The answer is that it's way too much of a pain to do it yourself.  Here's an example of how to  do the inverse operation of reading a byte array from a file (sorry, this is just the code I had readily available, and it's not like I want the asker to actually paste and use this code anyway):Everyone ought to be thoroughly appalled by what a pain that is.  I, unsurprisingly, recommend Guava's .To write a byte array to a file use the method from BufferedOutputStream class. implements a buffered output stream. By setting up such an output stream, an application can write bytes to the underlying output stream without necessarily causing a call to the underlying system for each byte written. For your example you need something like: has a  method. Note that if you're doing any file/IO work then the Apache Commons IO library will do a lot of work for you.No need for external libs to bloat things - especially when working with Android. Here is a native solution that does the trick. This is a pice of code from an app that stores a byte array as an image file.
Java

I have a  named  with the following content:I know I can get the array  with:And now I want to parse that  into a ...What is the easiest way to do this?Definitely the easiest way to do that is using Gson's default parsing function .  There is an implementation of this function suitable for when you need to deserialize into any  (e.g., any ), which is .In your case, you just need to get the  of a  and then parse the JSON array into that , like this:You may want to take a look at .Below code is using .\nI have printed the number of element in list as well as the elements in ListCheck this out, I believe this is what you need. 
Java

I know that Android 6.0 has new permissions and I know I can call them with something like this Today I saw a Google app which needs 3 permissions: contacts, sms and camera. It's making a page 1-3 and calls them all together at the same time to activate.Can anybody tell me how I can call 4 permissions to activate at the same time like sms, camera, contacts and storage?Example (forgot the name of the google app :( )\nThe app needs sms,contacts and camera the app asked me (and made a dialog page1-3) activate sms, activate contacts and then camera. \nSo this google app was calling all 3 required permissions together and my question is how can i achive the same ?Just include all 4 permissions in the  call and Android will automatically page them together like you mentioned.I have a helper method to check multiple permissions and see if any of them are not granted.Then just send it all of the permissions.  Android will ask only for the ones it needs.The app needs 2 permissions at startup . SEND_SMS and ACCESS_FINE_LOCATION (both are mentioned in manifest.xml).I am using  which is  prepared to handle Android pre-Marshmallow and so no need to check build versions.As soon as the app starts up, it asks for multiple permissions together. If both permissions are granted the normal flow goes. In case one or more permissions are not granted, ActivityCompat.requestPermissions() will request permissions and the  control goes to onRequestPermissionsResult() callback method.You should check the value of shouldShowRequestPermissionRationale() flag in onRequestPermissionsResult() callback method. -Any time user clicks Deny permissions (including the very first time), it will return true.  So when the user denies, we can show more explanation and keep asking again-Only if user select \u201cnever asks again\u201d it will return false. In this case, we can continue with limited functionality and guide user to activate the permissions from settings for more functionalities, or we can finish the setup, if the permissions are trivial for the app.Small code :}In your onCreateThen check resultThe following methodology is about I found this is in the runtime permissions example from Google's github.Check the \"Asking for multiple permissions at a time\" section in this article:It's very well explained, and may also touch other related topics you haven't think about.I have successfully implemented simple code for Multiple permission at Once.\nFollow the below steps\n1:Make Utility.java class like below2: Now call in your Activity onCreate() or according to your logic.3:Now check permission before performing operation for particular task4: Now implement onRequestPermissionsResult() method in your Activity as belowShort and sweet :). what I believe in.
Java

In Java you can mark method as final to make it  to override.In C# you have to mark method as virtual to make it  to override.Does it mean that in C# you should mark all methods virtual (except a few ones that you don't want to be overridden), since most likely you don't know in what way your class can be inherited?No. If the language designers thought that virtual should have been the default then .Overridablility is a , and like all features it has . The costs of an overrideable method are considerable: there are big design, implementation and testing costs, particularly if there is any \"sensitivity\" to the class; virtual methods are ways of introducing untested third-party code into a system and that has a security impact.If you don't know how you intend your class to be inherited then  because  Your extensibility model is definitely something you should know ahead of time; it should deeply influence your design and testing strategy. I advocate that all classes be  and all methods be  until you have a real-world customer-focussed reason to unseal or to make a method virtual. Basically your question is \"I am ignorant of how my customers intend to consume my class; should I therefore make it arbitrarily extensible?\"  No; you should ! You wouldn't ask \"I don't know how my customers are going to use my class, so should I make all my properties read-write?  And should I make all my methods read-write properties of delegate type so that my users can replace any method with their own implementation?\"  No, don't do any of those things until you have  that a user actually needs that capability!  Spend your valuable time designing, testing and implementing features that users actually want and need, and do so from a position of knowledge.No! Because you don't know how your class will be inherited, you should  mark a method as  if you  that you want it to be overridden.In my opinion the currently accepted  is unnecessarily dogmatic.Fact is that when you don't mark a method as , others cannot override its behaviour and when you mark a class as  others cannot inherit from the class. This can cause substantial pain. I don't know how many times I cursed an API for marking classes  or not marking methods  simply because they did not anticipate my use case.Theoretically it might be the correct approach to only allow overriding methods and inheriting classes which are meant to be overridden and inherited but in practice it's impossible to foresee every possible scenario and there really isn't a good reason to be so closed in.One way to make the call is to look at the name of the method or property. A  method on a List does exactly what the name implies and it doesn't allow for much of . Changing its implementation would likely be not very transparent so marking it as  is probably unnecessary. Marking the  method as virtual is far more useful as someone could create a special List which only accepts some objects via the Add method etc. Another example are custom controls. You would want to make the main drawing method  so others can use the bulk of the behaviour and just change the look but you probably wouldn't override the X and Y properties.In the end you often don't have to make that decision right away. In an internal project where you can easily change the code anyway I wouldn't worry about these things. If a method needs to be overridden you can always make it virtual when this happens.\nOn the contrary, if the project is an API or library which is consumed by others and slow to update, it certainly pays off to think about which classes and methods might be useful. In this case I think it's better to be open rather than strictly closed.No. Only methods that you want derived classes to specify should be virtual. Virtual is not related to final.To prevent overriding of a virtual method in c# you use We can conjure up reasons for/again either camp, but that's entirely useless.In Java there are millions of unintended non-final public methods, but we hear very few horror stories.In C# there are millions of sealed public methods, and we hear very few horror stories.So it is not a big deal - the need to override a public method is rare, so it's moot either way.This reminds me of another argument - whether a local variable should be final by default. It is a pretty good idea, but we cannot exaggerate how valuable it is. There are billions of local variables that could be, but are not, final, but it has been shown to be an actual problem. Making a method virtual will generally slow down any code that needs to call it.  This slowdown will be insignificant but may in some cases be quite large (among other things, because non-virtual method calls may be in-lined, which may in turn allow the optimizer to eliminate unnecessary operations).  It's not always possible to predict the extent to which virtual calls may affect execution speed, and one should generally void doing things which will make code slower except when there's a discernible benefit for doing so.The performance benefit of making methods non-virtual is probably sufficient in many cases to justify having methods be non-virtual by default, but when classes are designed to be inherited most methods should be virtual and unsealed; the primary usage for non-virtual or sealed methods should be as wrappers for other (possibly protected) virtual methods (code that wants to change the underlying behavior should override the appropriate virtual rather than the wrapper).There are frequently non-performance-related reasons for marking classes as  or limiting inheritance to other classes within the assembly.  Among other things, if a class is externally inheritable, all members with  scope are effectively added to its public API, and any changes to their behavior  may break any derived classes that rely upon that behavior.  On the other hand, if a class is inheritable, making its methods  doesn't really increase its exposure.  If anything, it may reduce derived class's reliance upon the base class internals by allowing them to completely \"bury\" aspects of the base class implementation that are no longer relevant in the derived class [e.g. if the members of  were virtual, a derived class which overrode them all could use an array of arrays to hold things (avoiding large-object-heap issues), and wouldn't have to try to keep the private array used by  consistent with the array-of-arrays.
Java

I am using the Google Maps Android API v2, and I need a way to chance the position of the \"My Location\" button. I get the \"My Location\" button like this: Just use GoogleMap.setPadding(left, top, right, bottom), which allows you to indicate parts of the map that may be obscured by other views. Setting padding re-positions the standard map controls, and camera updates will use the padded region.You can get the \"My Location\" button and move it, like :This may not be the best solution, but you could place your own button over the map and handle it yourself. It would take the following:-1) Put the map in a frameLayout and add your button on top. E.g.2) Edit the maps UI settings so the button doesn't appear when you call setMyLocationEnabled(true). You can do this via map.getUiSettings(). setMyLocationButtonEnabled(false);3) Handle the click of your new button to emulate what the supplied button does. E.g. call mMap.setMyLocationEnabled(...); and pan the map to the current location.Hope that helps, or hope someone comes a long with a simpler solution for you ;-)It's already been explained above.Just a small addition to fabLouis's answer.\nYou may also get your map view from the SupportMapFragment.See the method below. It lives inside a class that extends SupportMapFragment. It gets the container view for the button and displays it at the bottom, centered horizontally.    First, obtain Google Map View:Then find MyLocation button (id's from Android Studio debugger):Finally, just set new RelativeLayout params for MyLocation button (align parent right + center vertically in this case):Boom! Now you can move it as you want ;)I solved this problem in my map fragment by re positioning my location button to the right bottom corner of view using code below, here is my Maps Activity.java :-add this lines of code in onCreate() method,and here is onMapReady() code :-I hope, this will solve your problem. Thanks.If you just want to have location indication enabled (the blue dot) but don't need default My Location button:This way you can also draw your own button where you want without strange stuff like this .I don't fancy seeing these magic view IDs others are using, I suggest using tags to find s children.Here is my solution for placing the  button above the  controls.I had the same problem. I ended up using the Hierarchy Viewer to identify the view used to display the button and manipulated it. Very hacky, I know, but could not figure out a different way.It was a bit of a struggle to get this working. But I got it done, and in the process also started to move the zoom buttons around. Here my complete code:One way to deal with this problem. Delete default button and create your own.\nIn OnCreate statement add the next:try this codeYou can use following approach:
Java

I have the following (maybe common) problem and it absolutely puzzles me at the moment:There are a couple of generated event objects which extends the abstract class  and I want to divide them to Session Beans, likeBut there could be more than two event types in future, so the if-else will be long and maybe unreadable. Additionally I think  is not really \"best practice\" in this case.I could add an abstract method to the  type and have them divide itself but then I have to inject the specific Session Beans within each entity.Is there any hint to achieve a \"pretty\" solution for this problem?Thanks for any help!The simplest approach is to have the Event provide a method you can call so the Event knows what to do.Polymorphism is your friend.Then justA number of people have raised the objection that you \"have to know the kinds of event at compile time.\"  And, yes, you clearly have to know what events you're interpreting at compile time of the generator part, when else would you be able to write the generating part?  These competing examples use Command pattern, which is fine, but means Events have to know the details not just of their representation but of how to  their representation.  That means each class may have two kinds of requirements changes to which their sensitive: changes in what events represent, and changes in the way the events are represented in print.  Now, consider, for example, needing to internationalize this.  In the Command-pattern case, you have to go to  classes for  different Event types and write new  methods.  In the polymorphism case, the changes are localized to one class.  Naturally if you need to internationalize once, you may need many languages, which drive you to adding something like a Strategy  in the Command-pattern case, requiring now  classes \u00d7  languages; again, you need only have one strategy and one class in the polymorphism case.There are reasons to choose either approach, but to claim the polymorphism approach is  is just incorrect.Each event has a function, say do.\nEach subclass overrides do, to do (:P) the appropriate action.\nDynamic dispatch does everything else afterwards.\nAll you need to do, is call event.do()I have no commenting rights and i dont know the exact answer. But is it just me or some ppl here suggest using overloading (which happens at compile time and therefore just generate compile error) to solve  this problem?Just an example. As you see, it will not compile.What's the problem with exploiting the method resolution order?Let Java do the work of matching the correct argument type, then just dispatch the event properly.This is a typical use case for , also known as tagged unions. Unfortunately, Java does not support them directly, so they have to be implemented using some variation of the visitor pattern.Here we have defined our , now to provide a dispatch mechanism:Here I used maximum possible separation of concerns so that responsibility of each class and interface is one and only one. In real life projects ,  implementation and  interface declaration are usually merged into a single class , but that introduces circular dependencies and forces some dependencies between concrete classes (and as we know, one should prefer to depend on interfaces).Additionally,  should usually be replaced with a type parameter to represent the result type, like this:This allows one to use stateless visitors, which are very nice to deal with.This technique allows to (almost?) always eliminate  mechanically rather than having to figure out a problem-specific solution.You could register each of your handler classes against each event type, and perform dispatch when event happens like this.And then get your specific handlers to implement the interface, and register those handlers with the EventRegister.You could have a  interface, defined likewith implementations like , , etc.Then define a , with entries like . Then your dispatch method could be reduced to:Here's a unit test:
Java

In Java when we declare it will give compile time error but  compiles fine. Why does this happen? The compiler will, in this case, evaluate the calculation (because it contains only constants) and try to assign the result to the variable. This calculation is done with type  and only converted to  on assignment, if at all possible.In your case, the first calculation is too large to fit into a  (). The second one will overflow the  and end up in a range that  supports (). So the assignment works in that case.Mind you, you probably don't ever want to rely on these things in code.You are facing the problem as your number is .In the first case it does not wrap around and hence it overflows the range of short. But in the second case it wraps around after the calculationa and hence it comes in the range of short and so you dont have the compile time error.A loss of precision means that you are losing information of the given value.() In your first case the range of short is crossed(1073741824) and hence you are loosing the information.From (very correctly mentioned in  similar question)
Java

Does assigning an unused object to null in Java improve the garbage collection process in any measurable way?My experience with Java (and C#) has taught me that is often counter intuitive to try and outsmart the virtual machine or JIT compiler, but I've seen co-workers use this method and I am curious if this is a good practice to pick up or one of those voodoo programming superstitions?Typically, no.But like all things: it depends. The GC in Java these days is VERY good and everything should be cleaned up very shortly after it is no longer reachable. This is just after leaving a method for local variables, and when a class instance is no longer referenced for fields.You only need to explicitly null if you know it would remain referenced otherwise. For example an array which is kept around. You may want to null the individual elements of the array when they are no longer needed.For example, this code from ArrayList:Also, explicitly nulling an object will not cause an object to be collected any sooner than if it just went out of scope naturally as long as no references remain.Both:and:Are functionally equivalent.In my experience, more often than not, people null out references out of paranoia not out of necessity. Here is a quick guideline:I would say that the vast majority of the time you will not need to null out references. Trying to outsmart the garbage collector is useless. You will just end up with inefficient, unreadable code.Explicitly setting a reference to null instead of just letting the variable go out of scope, does not help the garbage collector, unless the object held is very large, where setting it to null as soon as you are done with is a good idea.Generally setting references to null, mean to the READER of the code that this object is completely done with and should not be concerned about any more.A similar effect can be achieved with by putting in an extra set of bracesthis allows the bigThing to be garbage collected right after leaving the nested braces.At least in java, it's not voodoo programming at all.  When you create an object in java using something likeyou do two things: first, you create a reference to an object, and second, you create the Foo object itself.   So long as that reference or another exists, the specific object can't be gc'd.  however, when you assign null to that reference...and assuming nothing else has a reference to the object, it's freed and available for gc the next time the garbage collector passes by.  It depends.Generally speaking shorter you keep references to your objects, faster they'll get collected.If your method takes say 2 seconds to execute and you don't need an object anymore after one second of method execution, it makes sense to clear any references to it. If GC sees that after one second, your object is still referenced, next time it might check it in a minute or so.Yes. From \"The Pragmatic Programmer\" p.292:By setting a reference to NULL you reduce the number of pointers to the object by one ... (which will allow the garbage collector to remove it)Above program throws . If you uncomment , the  is solved. It is always good practice to set the unused variable to nullGood article is today's .The way GC's work is by looking for objects that do not have any pointers to them, the area of their search is heap/stack and any other spaces they have.  So if you set a variable to null, the actual object is now not pointed by anyone, and hence could be GC'd.But since the GC might not run at that exact instant, you might not actually be buying yourself anything.  But if your method is fairly long (in terms of execution time) it might be worth it since you will be increasing your chances of GC collecting that object. The problem can also be complicated with code optimizations, if you never use the variable after you set it to null, it would be a safe optimization to remove the line that sets the value to null (one less instruction to execute).  So you might not actually be getting any improvement.So in summary, .I was working on a video conferencing application one time and noticed a huge huge huge difference in performance when I took the time to null references as soon as I didn't need the object anymore. This was in 2003-2004 and I can only imagine the GC has gotten even smarter since. In my case I had hundreds of objects coming and going out of scope every second, so I noticed the GC when it kicked in periodically. However after I made it a point to null objects the GC stopped pausing my application. So it depends on what your doing...I assume the OP is referring to things like this:In this case, wouldn't the VM mark them for GC as soon as they leave scope anyway?Or, from another perspective, would explicitly setting the items to null cause them to get GC'd before they would if they just went out of scope? If so, the VM may spend time GC'ing the object when the memory isn't needed anyway, which would actually cause worse performance CPU usage wise because it would be GC'ing more earlier.\"\"I do not know about Java but in .net (C#, VB.net...) it is usually not required to assign a null when you no longer require a object. However note that it is \"usually not required\". By analyzing your code the .net compiler makes a good valuation of the life time of the variable...to accurately tell when the object is not being used anymore. So if you write obj=null it might actually look as if the obj is still being used...in this case it is counter productive to assign a null.There are a few cases where it might actually help to assign a null. One example is you have a huge code that runs for long time or a method that is running in a different thread, or some loop. In such cases it might help to assign null so that it is easy for the GC to know its not being used anymore.There is no hard & fast rule for this. Going by the above place null-assigns in your code and do run a profiler to see if it helps in any way. Most probably you might not see a benefit.If it is .net code you are trying to optimize, then my experience has been that taking good care with Dispose and Finalize methods is actually more beneficial than bothering about nulls.Some references on the topic: Even if nullifying the reference were marginally more efficient, would it be worth the ugliness of having to pepper your code with these ugly nullifications? They would only be clutter and obscure the intent code that contains them. Its a rare codebase that has no better candidate for optimisation than trying to outsmart the Garbage collector (rarer still are developers who succeed in outsmarting it). Your efforts will most likely be better spent elsewhere instead, ditching that crufty Xml parser or finding some opportunity to cache computation. These optimisations will be easier to quantify and don't require you dirty up your codebase with noise. 
Java

I use visualVM connect a multi thread Java application, thread has 4 status, namely running, sleeping, wait, Monitor. What does this Monitoring status mean? What's the difference between wait and Monitor?These states are the same as mentioned in the  enum. \"Wait\" means, as the documentation says:\"Monitor\" is the  state, in which the thread is waiting to obtain a lock on an object (because it's trying to enter a  block or method while another thread already holds the associated lock).That's not a \"monitoring\" status... It indicates that the thread is in the  state. I see there is another good answer, i'll just point you to  for deeper explanationMonitor will mean the thread is waiting to attain a lock on an object.  For example when one thread is running a synchronized method and another one tries to invoke it on the same object, it will not be able to until the first invocation of the method is finished.  This is because the first thread has a monitor or lock on that object, so the second one must wait until it is released. From :
Java

By looking at the file  of my , I see that the keystore type to use by default is set to . , there is a list of the keystore types that can be used.Is there a recommended keystore type? What are the pros/cons of the different keystore types?There are a few more types than what's listed in the standard name list you've linked to. You can find more in the . The most common are certainly  (the default) and  (for PKCS#12 files, often with extension  or sometimes ).JKS is the most common if you stay within the Java world. PKCS#12 isn't Java-specific, it's particularly convenient to use certificates (with private keys) backed up from a browser or coming from OpenSSL-based tools ( wasn't able to convert a keystore and import its private keys before Java 6, so you had to use other tools).If you already have a PKCS#12 file, it's often easier to use the  type directly. It's possible to convert formats, but it's rarely necessary if you can choose the keystore type directly.In Java 7,  was mainly useful as a  but less for a  (see the ), because you couldn't store certificate entries without a private key. In contrast,  doesn't require each entry to be a private key entry, so you can have entries that contain only certificates, which is useful for trust stores, where you store the list of certificates you trust (but you don't have the private key for them).This has changed in Java 8, so you can now have certificate-only entries in  stores too. (More details about these changes and further plans can be found in .)There are a few other keystore types, perhaps less frequently used (depending on the context), those include:Here is a post which introduces different types of keystore in Java and the differences among different types of keystore. Below are the descriptions of different keystores from the post:
Java

I am writing a serializer to serialize POJO to JSON but stuck in circular reference problem. In  hibernate bidirectional one-to-many relation, parent references child and child references back to parent and here my serializer dies. (see example code below)\nHow to break this cycle? Can we get owner tree of an object to see whether object itself exists somewhere in its own owner hierarchy? Any other way to find if the reference is going to be circular? or any other idea to resolve this problem?Can a bi-directional relationship even be represented in JSON? Some data formats are not good fits for some types of data modelling. One method for dealing with cycles when dealing with traversing object graphs is to keep track of which objects you've seen so far (using identity comparisons), to prevent yourself from traversing down an infinite cycle.I rely on  To handle this kind of issue by using The featureSuppose a bi-directional relationship between A and B class as followsAnd BNow use GsonBuilder To get a custom Gson object as follows (Notice  method)Now our circular referenceTake a look at  class  1.6 (released september 2010) has specific annotation-based support for handling such parent/child linkage, see . ()You can of course already exclude serialization of parent link already using most JSON processing packages (jackson, gson and flex-json at least support it), but the real trick is in how to deserialize it back (re-create parent link), not just handle serialization side. Although sounds like for now just exclusion might work for you.EDIT (April 2012):  now supports true  (), so you can solve it this way also.In addressing this problem, I took the following approach (standardizing the process across my application, making the code clear and reusable):Here's the code:1)2)3)4)5) In the first case, null is supplied to the constructor, you can specify another class to be excluded - both options are added below6)or, to exclude the Date objectIf you are using Javascript, there's a very easy solution to that using the  parameter of  method where you can pass a function to modify the default serialization behavior. Here's how you can use it. Consider the below example with 4 nodes in a cyclic graph.Later, you can easily recreate the actual object with the cyclic references by parsing the serialized data and modifying the  property to point to the actual object if it's using a named reference with a  like in this example.Used a solution similar to Arthur's but instead of  I used and used  gson annotation for fields which I need in the json, other fields are excluded. on parent property in child class could solve itThis error can appened when you have two objects :With using GSon for serialization, i have got this error :To solved this, just add key word transient :As you can see here : This is how i finally solved it in my case. This works at least with Gson & Jackson.If you are using Jackon to serialize, just apply  to your bi-directinal mapping\nIt will solve the circular reference problem.the answer number 8 is the better, i think so if you know what field is throwing a error the  you only set the fild in null and solved. To make the code readable a big comment is moved from the comment  to below.The answer is very simple.For example \nProductBean has got serialBean.The mapping would be bi-directional relationship.now if we try to use gson.toJson(), it will end up with circular reference.To avoid the problem.now the problem is over.Thank U...
Java

I'm trying to execute external command from java code, but there's a difference I've noticed.\nwhen running the code:the exitValue is 0 and the command terminated ok.but when I use:Thanks, but the second code wasn't correct.  I use ProcessBuilder this way and it still doesn't work:the exit value is 1001 and the command terminates in the middle although waitFor returns.What should I do to fix the problem with ?The various overloads of  take either an array of strings or a single string.  The single-string overloads of  will tokenise the string into an array of arguments, before passing the string array onto one of the  overloads that takes a string array.  The  constructors, on the other hand, only take a varargs array of strings or a  of strings, where each string in the array or list is assumed to be an individual argument.  Either way, the arguments obtained are then joined up into a string that is passed to the OS to execute.So, for example, on Windows,will run a  program with the two given arguments.  In this case, the command-line gets tokenised and put back together.  However,will fail, unless there happens to be a program whose name is  in .  This is because there's no tokenisation: the command to run is assumed to have already been tokenised.  Instead, you should useor alternativelyLook at how  passes the String command to the . It uses a tokenizer and explodes the command into individual tokens, then invokes  which constructs a .If you construct the  with an array of strings instead of a single one, you'll get to the same result.The  constructor takes a  vararg, so passing the whole command as a single String has the same effect as invoking that command in quotes in a terminal:Yes there is a difference.  So what you are telling ProcessBuilder to do is to execute a \"command\" whose name has spaces and other junk in it.  Of course, the operating system can't find a command with that name, and the command execution fails.
Java

Is there (not NotImplementedException, not supported).Or, if you use Apache Commons Lang and the operation should be supported, but has not been implemented (yet?):You can use either UnsupportedOperationException or NoSuchMethodException or extend the Exception class and create your own custom exception called NotImplementedException or whatever
Java

What is the best method of performing an scp transfer via the Java programming language? It seems I may be able to perform this via JSSE, JSch or the bouncy castle java libraries. None of these solutions seem to have an easy answer.I ended up using - it was pretty straightforward, and seemed to scale up pretty well (I was grabbing a few thousand files every few minutes).Take a lookThat is the source code for Ants' SCP task.  The code in the \"execute\" method is where the nuts and bolts of it are.  This should give you a fair idea of what is required. It uses JSch i believe.Alternatively you could also directly execute this Ant task from your java code.plug: sshj is the only sane choice! See these examples to get started: , .I wrapped Jsch with some utility methods to make it a bit friendlier and called itAvailable here: SCP utility to tar a folder, zip it, and scp it somewhere, then unzip it.Usage:Also includes useful classes - Scp and Exec, and a TarAndGzip, which work in pretty much the same way.The  lists several Java alternatives,  seems to fit what you're asking for.I use this SFTP API which has SCP called Zehon, it's great, so easy to use with a lot of sample code. Here is the site This is , no need to reinvent. Quick and dirty! First, go to  and download latest Apache Ant binary. (nowadays, apache-ant-1.9.4-bin.zip). Extract the downloaded file and find the JAR  (\"apache-ant-1.9.4/lib/ant-jsch.jar\"). . Also ant-launcher.jar and ant.jar. Go to  and download the jar. Nowadays, . Also .Now, can you easyly use into java code the Ant Classes  for copy files over network or  for commands in SSH servers.   Code Example Scp:I looked at a lot of these solutions and didn't like many of them.  Mostly because the annoying step of having to identify your known hosts.  That and JSCH is at a ridiculously low level relative to the scp command.  I found a library that doesn't require this but it's bundled up and used as a command line tool.  I looked through the source code and discovered how to use it without the command line.  Here's an example of uploading:The biggest downside is that it's not in a maven repo (that I could find).  But, the ease of use is worth it to me.jsCH has worked great for me. Below is an example of a method that will connect to sftp server and download files to specified directory. It is recommended to stay away from disabling StrictHostKeyChecking. Although a little bit more difficult to set up, for security reasons specifying the known hosts should be the norm.  recommended - not recommended Like some here, I ended up writing a wrapper around the JSch library.It's called way-secshell and it is hosted on GitHub: JSch is a nice library to work with. It has quite an easy answer for your question.You can find complete code at supports SCP transfers (as well as SFTP, FTP and FTPS).I wrote an scp server which is much easier than others. I use Apache MINA project (Apache SSHD) to develop it. You can take a look here: \nAlso you can download the jar file from  directory.\nHow to use? Take a look on: 
Java

I have a question about the primitive type  in Java. I am using JDK 1.6. If I have the following: the compiler does not want to compile - it says that it \"cannot convert from int to short\" and suggests that I make a cast to , so this:really works. But my question is why do I need to cast? The values of a and b are in the range of  - the range of short values is {-32,768, 32767}.\nI also need to cast when I want to perform the operations -, *, / (I haven't checked for others).If I do the same for primitive type , I do not need to cast aa+bb to . The following works fine:I discovered this while designing a class where I needed to add two variables of type short, and the compiler wanted me to make a cast. If I do this with two variables of type , I don't need to cast. Thank you very much in advance.A small remark: the same thing also happens with the primitive type . So, this works:but this not:For , , , and , there is no need to cast. Only for  and  values. As explained in  (but also for other language compilers as well, like Java)There is a predefined implicit conversion from short to int, long, float, double, or decimal.You cannot implicitly convert nonliteral numeric types of larger storage size to short (see Integral Types Table for the storage sizes of integral types). Consider, for example, the following two short variables x and y:The following assignment statement will produce a compilation error, To fix this problem, use a cast:It is possible though to use the following statements, where the destination variable has the same storage size or a larger storage size:A good follow-up question is:\"why arithmetic expression on the right-hand side of the assignment operator evaluates to int by default\" ?A first answer can be found in:[From Electronic Notes in Theoretical Computer Science 82 No. 2 (2003)\nBlesner-Blech-COCV 2003: , Jan Olaf BLECH,\nFakult\u00e4t f\u00fcr Informatik,\nUniversit\u00e4t Karlsruhe\nKarlsruhe, Germany]In C# and Java, the arithmatic expression on the right hand side of the assignment evaluates to int by default. That's why you need to cast back to a short, because there is no implicit conversion form int to short, for obvious reasons.EDIT: Okay, now we know it's Java... states:In other words, it's like C# - the addition operator (when applied to integral types) only ever results in  or , which is why you need to cast to assign to a  variable.In C# (you haven't specified the language, so I'm guessing), the only addition operators on primitive types are:These are in the C# 3.0 spec, section 7.7.4. In addition, decimal addition is defined:(Enumeration addition, string concatenation and delegate combination are also defined there.)As you can see, there's no  operator - so both operands are implicitly converted to int, and the int form is used. That means the result is an expression of type \"int\", hence the need to cast.Given that the \"why int by default\" question hasn't been answered ...First, \"default\" is not really the right term (although close enough). As noted by VonC, an expression composed of ints and longs will have a long result. And an operation consisting of ints/logs and doubles will have a double result. The compiler promotes the terms of an expression to whatever type provides a greater range and/or precision in the result (floating point types are presumed to have greater range and precision than integral, although you do lose precision converting large longs to double).One caveat is that this promotion happens only for the terms that need it. So in the following example, the subexpression 5/4 uses only integral values and is performed using integer math, even though the overall expression involves a double. The result isn't what you might expect...OK, so why are byte and short promoted to int? Without any references to back me up, it's due to practicality: there are a limited number of bytecodes. \"Bytecode,\" as its name implies, uses a single byte to specify an operation. For example , which adds  two ints. Currently, , and integer math takes  for each type (ie, 36 total between integer and long), not counting conversion operators.If short, and byte each got their own set of opcodes, you'd be at 241, limiting the ability of the JVM to expand. As I said, no references to back me up on this, but I suspect that Gosling et al said \"how often do people actually use shorts?\" On the other hand, promoting byte to int leads to this not-so-wonderful effect (the expected answer is 96, the actual is -16):What language are you using?Many C based languages have a rule that any mathematical expression is performed in size int or larger.  Because of this, once you add two shorts the result is of type int.  This causes the need for a cast.In java, every numeric expression like:x will always result to be at least an int, or a long if one of the addition elements was a long.But there's are some quirks toughJava always uses at least 32 bit values for calculations. This is due to the 32-bit architecture which was common 1995 when java was introduced. The register size in the CPU was 32 bit and the arithmetic logic unit accepted 2 numbers of the length of a cpu register. So the cpus were optimized for such values.This is the reason why all datatypes which support arithmetic opperations and have less than 32-bits are converted to int (32 bit) as soon as you use them for calculations.So to sum up it mainly was due to performance issues and is kept nowadays for compatibility.AFAIS, nobody mentions of  usage for that. If you modify your last example and define variables a and b as \nvariables, then the compiler is  that their sum, value 5 , can be assigned to a\nvariable of type , without any loss of precision. In this case, the compiler is good\nto assign the sum of a and b to c . Here\u2019s the modified code:I'd like to add something that hasn't been pointed out. Java doesn't take into account the values you have given the variables (2 and 3) in...short a = 2;\nshort b = 3;\nshort c = a + b;So as far as Java knows, you could done this...short a = 32767;\nshort b = 32767;\nshort c = a + b;Which would be outside the range of short, it autoboxes the result to an int becuase it's \"possible\" that the result will be more than a short but not more than an int. Int was chosen as a \"default\" because basically most people wont be hard coding values above 2,147,483,647 or below -2,147,483,648Any data type witch is lower than \"int\" (except Boolean) is implicitly converts to \"int\".In Your case:result of (a+b) is implicitly converted to int. And now you are assigning it to \"short\".So that you are getting the error.short,byte,char --for all these we will get same error.
Java

I was using  to make my code cleaner, and it pointed out that I'm using  instead of . Because it seems that  does not instantiate a new object so is more memory-friendly. How can  not instantiate a new object? How does it work? Is this true for all integers?Integer.valueOf implements a cache for the values -128 to +127.  See the last paragraph of the Java Language Specification, section 5.1.7, which explains the requirements for boxing (usually implemented in terms of the .valueOf methods).From the : is generaly used for autoboxing and therefore (when used for autoboxing) caches at least values from -128 to 127 to follow the autoboxing specification.Here is the  implementation for Sun JVM 1.5.? Have a look at the whole class to see how the cache is initialized.they are pushing you to use  instead of  so the method  does it for you, and caches the value in case you want to get the same number again in future. In that case, method won't instatiate new Integer, but will give you the cached one, what will make 'creation' of new Integer a lot quicker and memory friendly process..This way you may cause yourself alot of problems if you are unexperienced java programmer since you will conclude that  , because you may (or may not) have the same pointer for two Integers, and probably you will practise it in a way, let's say, you learned in C#, so that will show you bugs from time to time, and you won't know how & where those came from... From the java.lang.Integer Source Code. Integer cache is configurable. To configure the Integer cache size other than Sun we need to use the System property  as per the source code.From java.lang.Short,java.lang.Byte and java.lang.Long creates a cache of 127 to -128
Java

I'm having troubles of getting my current position coordinates using the NETWORK provider of android location system. Already read a lot of tutorials and implemented 4 or 5 existing classes to my project and all of them are giving me the last coordinates but not the current ones.I'm pretty sure that the problem is something fundamental that I am missing but I am not able to understand what exactly it is.  Acctualy GPS possitioning works fine, but NETWORK positioning dosn't.\nWhen Ive turned devices GPS on cordinates keep changing while im moving, but dosnt happence same when I have turn it off and relay on the NETWORK_PROVIDERFirst you need to define a  to handle location changes.Then get the  and ask for location updatesAnd finally make sure that you have added the permission on the Manifest, For using only network based location use this oneFor GPS based location, this oneYou need to write code in the  method, because . I.e. you need to save the new location to return it if getLocation is called.If you don't use the  it always will be the old location.I'm using  and it works nicely for my application.In my activity I put this code:also check if your emulator runs with Google API
Java

What are some guidelines for when it is  necessary to check for a null?A lot of the inherited code I've been working on as of late has null-checks ad nauseam. Null checks on trivial functions, null checks on API calls that state non-null returns, etc. In some cases, the null-checks are reasonable, but in many places a null is not a reasonable expectation.I've heard a number of arguments ranging from \"You can't trust other code\" to \"ALWAYS program defensively\" to \"Until the language guarantees me a non-null value, I'm always gonna check.\" I certainly agree with many of those principles up to a point, but I've found excessive null-checking causes other problems that usually violate those tenets. Is the tenacious null checking really worth it?Frequently, I've observed codes with excess null checking to actually be of poorer quality, not of higher quality. Much of the code seems to be so focused on null-checks that the developer has lost sight of other important qualities, such as readability, correctness, or exception handling. In particular, I see a lot of code ignore the std::bad_alloc exception, but do a null-check on a .In C++, I understand this to some extent due to the unpredictable behavior of dereferencing a null pointer; null dereference is handled more gracefully in Java, C#, Python, etc. Have I just seen poor-examples of vigilant null-checking or is there really something to this?This question is intended to be language agnostic, though I am mainly interested in C++, Java, and C#.Some examples of null-checking that I've seen that seem to be  include the following:This example seems to be accounting for non-standard compilers as C++ spec says a failed new throws an exception. Unless you are explicitly supporting non-compliant compilers, does this make sense? Does this make  sense in a managed language like Java or C# (or even C++/CLR)?Another example is when working on internal code. Particularly, if it's a small team who can define their own development practices, this seems unnecessary. On some projects or legacy code, trusting documentation may not be reasonable... but for new code that you or your team controls, is this really necessary?If a method, which you can see and can update (or can yell at the developer who is responsible) has a contract, is it still necessary to check for nulls?When developing a private or otherwise internal function, is it really necessary to explicitly handle a null when the contract calls for non-null values only? Why would a null-check be preferable to an assert?(obviously, on your public API, null-checks are vital as it's considered impolite to yell at your users for incorrectly using the API)Compared to:First note that this a special case of contract-checking: you're writing code that does nothing other than validate at runtime that a documented contract is met. Failure means that some code somewhere is faulty.I'm always slightly dubious about implementing special cases of a more generally useful concept. Contract checking is useful because it catches programming errors the first time they cross an API boundary. What's so special about nulls that means they're the only part of the contract you care to check? Still,On the subject of input validation:null is special in Java: a lot of Java APIs are written such that null is the only invalid value that it's even possible to pass into a given method call. In such cases a null check \"fully validates\" the input, so the full argument in favour of contract checking applies.In C++, on the other hand, NULL is only one of nearly 2^32 (2^64 on newer architectures) invalid values that a pointer parameter could take, since almost all addresses are not of objects of the correct type. You can't \"fully validate\" your input unless you have a list somewhere of all objects of that type.The question then becomes, is NULL a sufficiently common invalid input to get special treatment that  doesn't get?Unlike Java, fields don't get auto-initialized to NULL, so a garbage uninitialized value is just as plausible as NULL. But sometimes C++ objects have pointer members which are explicitly NULL-inited, meaning \"I don't have one yet\". If your caller does this, then there is a significant class of programming errors which can be diagnosed by a NULL check. An exception may be easier for them to debug than a page fault in a library they don't have the source for. So if you don't mind the code bloat, it might be helpful. But it's your caller you should be thinking of, not yourself - this isn't defensive coding, because it only 'defends' against NULL, not against (foo *)(-1).If NULL isn't a valid input, you could consider taking the parameter by reference rather than pointer, but a lot of coding styles disapprove of non-const reference parameters. And if the caller passes you *fooptr, where fooptr is NULL, then it has done nobody any good anyway. What you're trying to do is squeeze a bit more documentation into the function signature, in the hope that your caller is more likely to think \"hmm, might fooptr be null here?\" when they have to explicitly dereference it, than if they just pass it to you as a pointer. It only goes so far, but as far as it goes it might help.I don't know C#, but I understand that it's like Java in that references are guaranteed to have valid values (in safe code, at least), but unlike Java in that not all types have a NULL value. So I'd guess that null checks there are rarely worth it: if you're in safe code then don't use a nullable type unless null is a valid input, and if you're in unsafe code then the same reasoning applies as in C++.On the subject of output validation:A similar issue arises: in Java you can \"fully validate\" the output by knowing its type, and that the value isn't null. In C++, you can't \"fully validate\" the output with a NULL check - for all you know the function returned a pointer to an object on its own stack which has just been unwound. But if NULL is a common invalid return due to the constructs typically used by the author of the callee code, then checking it will help.In all cases:Use assertions rather than \"real code\" to check contracts where possible - once your app is working, you probably don't want the code bloat of every callee checking all its inputs, and every caller checking its return values.In the case of writing code which is portable to non-standard C++ implementations, then instead of the code in the question which checks for null and also catches the exception, I'd probably have a function like this:Then as one of the list of things you do when porting to a new system, you define PLATFORM_TRAITS_NEW_RETURNS_NULL (and maybe some other PLATFORM_TRAITS) correctly. Obviously you can write a header which does this for all the compilers you know about. If someone takes your code and compiles it on a non-standard C++ implementation that you know nothing about, they're fundamentally on their own for bigger reasons than this, so they'll have to do it themselves.One thing to remember that your code that you write today while it may be a small team and you can have good documentation, will turn into legacy code that someone else will have to maintain. I use the following rules:If you write the code and its contract, you are responsible for using it in terms of its contract and ensuring the contract is correct.  If you say \"returns a non-null\" x, then the caller should not check for null.  If a null pointer exception then occurs with that reference/pointer, it is your contract that is incorrect.Null checking should only go to the extreme when using a library that is untrusted, or does not have a proper contract.  If it is your development team's code, stress that the contracts must not be broken, and track down the person who uses the contract incorrectly when bugs occur.Part of this depends on how the code is used -- if it is a method available only within a project vs. a public API, for example. API error checking requires something stronger than an assertion.So while this is fine within a project where it's supported with unit tests and stuff like that:in a method where you don't have control over who calls it, something like this may be better:It depends on the situation.  The rest of my answer assumes C++.NULL checking in general is evil as it's add a small negative token to the code testability. With NULL checks everywhere you can't use \"pass null\" technique and it will hit you when unit testing. It's better to have unit test for the method than null check.Check out decent presentation on that issue and unit testing in general by Misko Hevery at  Older versions of Microsoft C++ (and probably others) did not throw an exception for failed allocations via new, but returned NULL. Code that had to run in both standard-conforming and older versions would have the redundant checking that you point out in your first example.It would be cleaner to make all failed allocations follow the same code path:It's widely known that there are procedure-oriented people (focus on doing things the right way) and results-oriented people (get the right answer). Most of us lie somewhere in the middle. Looks like you've found an outlier for procedure-oriented. These people would say \"anything's possible unless you understand things perfectly; so prepare for anything.\" For them, what you see is done properly. For them if you change it, they'll worry because the ducks aren't all lined up.When working on someone else's code, I try to make sure I know two things.\n1. What the programmer intended\n2. Why they wrote the code the way they did  For following up on Type A programmers, maybe this helps.So \"How much is enough\" ends up being a social question as much as a technical question - there's no agreed-upon way to measure it.(It drives me nuts too.)Personally I think null testing is unnnecessary in the great majority of cases. If new fails or malloc fails you have bigger issues and the chance of recovering is just about nil in cases where you're not writing a memory checker! Also null testing hides bugs a lot in the development phases since the \"null\" clauses are frequently just empty and do nothing.When you can specify which compiler is being used, for system functions such as \"new\" checking for null is a bug in the code.  It means that you will be duplicating the error handling code.  Duplicate code is often a source of bugs because often one gets changed and the other doesn't.  If you can not specify the compiler or compiler versions, you should be more defensive.As for internal functions, you should specify the contract and make sure that contract is enforce via unit tests.  We had a problem in our code a while back where we either threw an exception or returned null in case of a missing object from our database.  This just made things confusing for the caller of the api so we went through and made it consistant throughout the entire code base and removed the duplicate checks.   The important thing (IMHO) is to not have duplicate error logic where one branch will never be invoked.  If you can never invoke code, then you can't test it, and you will never know if it is broken or not.I'd say it depends a little on your language, but I use Resharper with C# and it basically goes out of it's way to tell me \"this reference could be null\" in which case I add a check, if it tells me \"this will always be true\" for \"if (null != oMyThing && ....)\" then I listen to it an don't test for null.Whether to check for null or not greatly depends on the circumstances.For example in our shop we check parameters to methods we create for null inside the method.  The simple reason is that as the original programmer I have a good idea of exactly what the method should do.  I understand the context even if the documentation and requirements are incomplete or less than satisfactory.  A later programmer tasked with maintenance may not understand the context and may assume, wrongly, that passing null is harmless.  If I know null would be harmful and I can anticipate that someone may pass null, I should take the simple step of making sure that the method reacts in a graceful way.I only check for NULL when I know what to do when I see NULL. \"Know what to do\" here means \"know how to avoid a crash\" or \"know what to tell the user besides the location of the crash\". For example, if malloc() returns NULL, I usually have no option but to abort the program. On the other hand, if fopen() returns NULL, I can let the user know the file name that could not be open and may be errno. And if find() returns end(), I usually know how to continue without crashing.Lower level code should check use from higher level code. Usually this means checking arguments, but it can mean checking return values from upcalls. Upcall arguments need not be checked.The aim is to catch bugs in immediate and obvious ways, as well as documenting the contract in code that does not lie.I don't think it's  code. A fair amount of Windows/Linux API calls return NULL on failure of some sort. So, of course, I check for failure in the manner the API specifies. Usually I wind up passing control flow to an error module of some fashion instead of duplicating error-handling code.If I receive a pointer that is not guaranteed by language to be not null, and am going to de-reference it in a way that null will break me, or pass out put my function where I said I wouldn't produce NULLs, I check for NULL.It is not just about NULLs, a function should check pre- and post-conditions if possible.It doesn't matter at all if a contract of the function that gave me the pointer says it'll never produce nulls. We all make bugs. There's a good rule that a program shall fail early and often, so instead of passing the bug to another module and have it fail, I'll fail in place. Makes things so much easier to debug when testing. Also in critical systems makes it easier to keep the system sane.Also, if an exception escapes main, stack may not be rolled up, preventing destructors from running at all (see C++ standard on terminate()). Which may be serious. So leaving bad_alloc unchecked can be more dangerous than it seems.Fail with assert vs. fail with a run time error is quite a different topic.Checking for NULL after new() if standard new() behavior has not been altered to return NULL instead of throwing seems obsolete.There's another problem, which is that even if malloc returned a valid pointer, it doesn't yet mean you have allocated memory and can use it. But that is another story.My first problem with this, is that it leads to code which is littered with null checks and the likes. It hurts readability, and i\u2019d even go as far as to say that it hurts maintainability because it really is easy to forget a null check if you\u2019re writing a piece of code where a certain reference really should never be null. And you just know that the null checks will be missing in some places. Which actually makes debugging harder than it needs to be. Had the original exception not been caught and replaced with a faulty return value, then we would\u2019ve gotten a valuable exception object with an informative stacktrace. What does a missing null check give you? A NullReferenceException in a piece of code that makes you go: wtf? this reference should never be null!So then you need to start figuring out how the code was called, and why the reference could possibly be null. This can take a lot of time and really hurts the efficiency of your debugging efforts. Eventually you\u2019ll figure out the real problem, but odds are that it was hidden pretty deeply and you spent a lot more time searching for it than you should have.Another problem with null checks all over the place is that some developers don\u2019t really take the time to properly think about the real problem when they get a NullReferenceException. I\u2019ve actually seen quite a few developers just add a null check above the code where the NullReferenceException occurred. Great, the exception no longer occurs! Hurray! We can go home now! Umm\u2026 how bout \u2018no you can\u2019t and you deserve an elbow to the face\u2019? The real bug might not cause an exception anymore, but now you probably have missing or faulty behavior\u2026 and no exception! Which is even more painful and takes even more time to debug. At first, this seemed like a strange question:  checks are great and a valuable tool.  Checking that  returns  is definitely silly.  I'm just going to ignore the fact that there are languages that allow that.  I'm sure there are valid reasons, but I really don't think I can handle living in that reality :)  All kidding aside, it seems like you should at least have to specify that the  should return  when there isn't enough memory.Anyway, checking for  where appropriate leads to cleaner code.  I'd go so far as to say that never assigning function parameters default values is the next logical step.  To go even further, returning empty arrays, etc. where appropriate leads to even cleaner code.  It is nice to not have to worry about getting s except where they are logically meaningful.  Nulls as error values are better avoided.Using asserts is a really great idea.  Especially if it gives you the option of turning them off at runtime.  Plus, it is a more explicitly contractual style :)
Java

I'm curious and need to find this answer quick. Google won't help much.The Java Persistence API has these properties that tell the framework to cascade operations on associated entities:I know what the first two mean: when I persist object A which has B, persist B as well, and when I delete A, delete B as well.But I can't make any sense of what the other two accomplish. Help?REFRESH means \"pull any state changes from the database into my representation\".  Cascading this is simple; it means that all associated entities are refreshed.MERGE means something complex that approximates \"save\" but is more like \"push this detached entity back into managed status and save its state changes\"; the cascading means that all associated entities get pushed back the same way, and the managed-entity handle you get back from  has all managed entities associated with it.:I myself see them this way (more readable):
Java

mvn archetype:generate provides way too many options and I am looking to create a simple java utility with junit test cases. I would like to know what archetype I should be using here?When you do a , a default selection appears in enclosing curly brackets , e.g. , if you scroll up to see what #3 is, it is usually the default Java archetype to try out or start out with, if doing simple Java projects.I use two archetypes. It depends on what kind of application you will create. If you want a web application, use , or if you want a simple application use . They are useful because you will be able to expand them with no problem.I'm using command like below:I will get a  of achetypes only from  groupId. The good ones for starting is  and  like my predecessors said.I think you should use EDITAccording to the maven : I would start with a very simple pom.xml file which has only what you need. Something likefrom 
Java

I'm trying to create a very simple webapp with maven and eclipse, but I'm having no joy at all, in fact the reverse of joy.I go to File -> New Project, select Maven Project, and select the maven-archetype-webapp. When I finish the wizard, a webapp structure gets generated but with no 'java' directory under main, just resources and webapp. So I right click on main and select new Class. The class gets created under resources (?!), and furthermore, there seems to be no compilation of it by java. I can make stupid errors and no syntax highlighting comes up. It's like java isn't recognizing it.Alternatively I have tried creating a new 'java' directory under main where it should be, but still with the same non-existent java symptoms.What gives? This is driving me insane..Thanks all!Simply create a  directory under  (i.e. ) and   on your project and select .Anything else is likely to be down to the archetype and how you've configured your . The directory structure you describe is identical to the one  creates on the command line.Simply create a java directory under main (i.e. src/main/java) and right-click -> Build Path -> Use a Source FolderThis is a great article that I read when I was having trouble understanding how to build multiple projects into one using Maven. Specifically, this article explains how to set up a WEB project (war file) to consume an inner standard java project (jar file).If you have a basic understanding of Maven, skip to the sections at the end:\nHow do I build other types of projects? \nHow do I build more than one project at once? If you aren't familiar with Maven yet, check out: Trust me, mkyong knows what is up!There is an option to create a source directory in eclipse. Or you can go to build path under project properties, and add an existing directory as a source directory.If you are going to use non-standard directory structure you will have to specify it in maven thoughCreate src/main/java on your own.after creating appropriate dir structure execute the maven commandthen refresh the project in eclipse.-SEfor src/main/java \n  your project >> properties >> java build path >> source >>\n    search \"Your Project src/main/java (missin)\"   >>>       and if  errors still don't disapearSimply create new folder named java under src/main/Then right click on project and select maven->update projectin IntelliJ IDEA 13 you must first create \"java\" folder in main folder then --> go to \"open module setting\"- for this you can click on project name and press f4- , and set label of \"java\" folder to \"source\" .Here is my solution. It works without any issue. There could be questions regarding why all this steps are required and i believe they are pretty genuine. But this is one of the ways to make your web application or any other component working on eclipse using Maven from .1) Open a command window2) mvn archetype:generate -DgroupId= -DartifactId= -DarchetypeArtifactId=  -DinteractiveMode=false3) cd 4) mvn eclipse:eclipse -Dwtpversion=2.05) Go to file system. Go to your newly created project. create folders, \n              a) java under main\n              b) test under src\n              c) java and resources under test6) mvn eclipse:clean7) mvn eclipse:eclipse -Dwtpversion=2.08) import  project in eclipseThanks,\nSidDo it the other way around. First make a webapp project, then add the Maven framework (in Intellij - right click project and select Add framework support). It will create the right folders for you.Right click the Maven Project -> Build Path -> Configure Build Path\nIn Order & Export tab, you can see the message like select 'JRE System Library' and 'Maven Dependencies' checkbox\nClick OK\nNow you can them
Java

I'm trying to write a Unit Test for a simple bean that's used in my program to validate forms. The bean is annotated with  and has a class variable that is initialized using I would like to write unit tests for the validation methods inside this class, however, if possible I would like to do so without utilizing the properties file. My reasoning behind this, is that if the value I'm pulling from the properties file changes, I would like that to not affect my test case. My test case is testing the code that validates the value, not the value itself. Is there a way to use Java code inside my test class to initialize a Java class and populate the Spring @Value property inside that class then use that to test with?I did find this  that seems to be close, but still uses a properties file. I would rather it all be Java code.ThanksIf possible I would try to write those test without Spring Context. If you create this class in your test without spring, then you have full control over its fields.To set the  field you can use Springs  - it has a method  to set private fields.@see If you want, you can still run your tests within Spring Context and set the required properties inside Spring configuration class. If you use JUnit, use SpringJUnit4ClassRunner and define dedicated configuration class for your tests like that:The class under test:The test class:And the configuration class for this test:Having that said, I wouldn't recommend this approach, I just added it here for reference. In my opinion much better way is to use Mockito runner. In that case you don't run tests inside Spring at all, which is much more clear and simpler.Since Spring 4.1 you could set up property values just in code by using  annotation on Unit Tests class level. You could use this approach even for injecting properties into dependent bean instancesFor example It's necessary to have instance of  in Spring contextThis seems to work, although still a bit verbose (I'd like something shorter still):Adding PropertyPlaceholderConfigurer in configuration is working for me.}And in test class}
Java

Java PreparedStatement provides a possibility to explicitely set a Null value. This possibility is:Are the semantics of this call the same as when using a setType with a null value??This  says:6.1.5 Sending JDBC NULL as an IN parameterThe setNull method allows a programmer to send a JDBC NULL (a generic SQL NULL) value to the database as an IN parameter. Note, however, that one must still specify the JDBC type of the parameter.A JDBC NULL will also be sent to the database when a Java null value is passed to a setXXX method (if it takes Java objects as arguments). The method setObject, however, can take a null value only if the JDBC type is specified. but watch out for this....-thows null pointer exception-because the protype isNOTnice one to catch you out eh.Finally I did a small test and while I was programming it it came to my mind, that without the setNull(..) method there would be no way to set null values for the Java primitives. For Objects both ways and behave the same way.You could also consider using 
Java

I am going through a socket program. In it,  is called on the  object in the catch block.\nWhat does  actually do?I am unaware of its purpose. What is it used for? It .It's a very simple, but very useful tool for diagnosing an Exception. It tells you what happened and where in the code this happened.I was kind of curious about this too, so I just put together a little sample code where you can see what it is doing:It helps to trace the exception. For example you are writing some methods in your program and one of your methods causes bug. Then printstack will help you to identify which method causes the bug. Stack will help like this:First your main method will be called and inserted to stack, then the second method will be called and inserted to the stack in LIFO order and if any error occurs somewhere inside any method then this stack will help to identify that method. helps the programmer to understand where the actual problem occurred.  is a method of the class  of  package. It prints several lines in the output console. \nThe first line consists of several strings. It contains the name of the Throwable sub-class & the package information. \nFrom second line onwards, it describes the error position/line number beginning with \"\". The last line always describes the destination affected by the error/exception. The second last line informs us about the next line in the stack where the control goes after getting transfer from the line number described in the last line. The errors/exceptions represents the output in the form a stack, which were fed into the stack by  method of  class, which itself fills in the program control transfer details into the execution stack. The lines starting with , are nothing but the values of the execution stack. \nIn this way the programmer can understand where in code the actual problem is.Along with the  method, it's a good idea to use .printStackTrace() : prints the locations where the exception occurred in the source code, thus allowing the author who wrote the program to see what went wrong. But since it shows problems in the source code, the user(s) who may or may not have any coding experience may not be able to understand what went wrong, so if the program allows the user to send error messages to the authors, the users may not be able to give good data on what went wrong.You should consider the: Logger.getLogger() method, it offers a better exception handling (logging) facility, and besides printStackTrace() without arguments is considered to be obsolete and should ONLY be used for debugging purposes, not for user display.Well, the purpose of using this method  is to see what exactly wrong is. For example, we want to handle an exception. Let's have a look at the following Example.I've used method  in order to show exactly what is wrong. In the output, we can see the following result. 
Java

How does spring resolve this. Bean A is dependent on bean b, and bean b on bean a.As the other answers have said, Spring just takes care of it, creating the beans and injecting them as required.One of the consequences is that bean injection / property setting might occur in a different order to what your XML wiring files would seem to imply.  So you need to be careful that your property setters don't do initialization that relies on other setters already having been called.  The way to deal with this is to declare beans as implementing the  interface.  This requires you to implement the  method, and this is where you do the critical initialization.  (I also include code to check that important properties have actually been set.)The  explains how circular dependencies are resolved. The beans are instantiated first, then injected into each other.Consider this class:And a similar class :If you then had this configuration file:You would see the following output when creating a context using this configuration:Note that when  is injected into ,  is not yet fully initialised.It just does it. It instantiates  and , and injects each one into the other (using their setter methods).What's the problem?In the codebase I'm working with (1 million + lines of code) we had a problem with long startup times, around 60 seconds. We were getting 12000+ .What I did was set a conditional breakpoint in where it does  I printed the exception with conditional breakpoint code:Apparently this happens when s are involved in a cyclic dependency graph. We solved it by implementing  and   and manually injecting the beans. This cut down the startup time to around 15 secs.So don't always assume that spring can be good at solving these references for you.For this reason I'd recommend disabling cyclic dependency resolution with  to prevent many future problems.From the : The Spring container is able to resolve Setter-based circular dependencies but gives a runtime exception BeanCurrentlyInCreationException in case of Constructor-based circular dependencies.\nIn case of Setter-based circular dependency, the IOC container handles it differently from a typical scenario wherein it would fully configure the collaborating bean before injecting it. \nFor eg., if Bean A has a dependency on Bean B and Bean B on Bean C, the container fully initializes C before injecting it to B and once B is fully initialized it is injected to A. But in case of circular dependency, one of the beans is injected to the other before it is fully initialized.If you generally use constructor-injection and don't want to switch to property-injection then Spring's -injection will let one bean lazily lookup the other and hence workaround the cyclic dependency. See here: Say A depends on B, then Spring will first instantiate A, then B, then set properties for B, then set B into A.But what if B also depends on A?My understanding is: Spring just found that A has been constructed (constructor executed), but not fully initialized (not all injections done), well, it thought, it's OK, it's tolerable that A is not fully initialized, just set this not-fully-initialized A instances into B for now. After B is fully initialized, it was set into A, and finally, A was fully initiated now.In other words, it just expose A to B in advance.For dependencies via constructor, Sprint just throw BeanCurrentlyInCreationException, to resolve this exception, set lazy-init to true for the bean which depends on others via constructor-arg way.
Java

I have a question regarding the usage of the  method.Imagine the following code:Is there any reason why you should use  instead of  (or vice versa). I think that the second option is more readable (a matter of taste of course). But, is there any \"real\" reason why one should be preferred?As of the current JRE implementation,  will always return the same instance while each occurrence of  will not only create its own instance but even have a distinct implementation class. For more details, see .The reason is that the compiler generates a synthetic method holding the trivial body of that lambda expression (in the case of , equivalent to ) and tell the runtime to create an implementation of the functional interface calling this method. So the runtime sees only different target methods and the current implementation does not analyze the methods to find out whether certain methods are equivalent.So using  instead of  might save some memory but that shouldn\u2019t drive your decision if you really think that  is more readable than .You may also consider that when compiling with debug information enabled, the synthetic method will have a line debug attribute pointing to the source code line(s) holding the lambda expression, therefore you have a chance of finding the source of a particular  instance while debugging. In contrast, when encountering the instance returned by  during debugging an operation, you won\u2019t know who has called that method and passed the instance to the operation.In your example there is no big difference between  and  since internally it is simply .But sometimes we can't use . Take a look herethis will compile finebut if you will try to compile you will get compilation error since  expects , which is not related to . Also  doesn't have  method.From the :So, no, as long as it is syntactically correct.
Java

I'm looking for a way to get a list of files that match a pattern (pref regex) in a given directory.I've found a tutorial online that uses apache's commons-io package with the following code:But that just returns a base collection (According to  it's a collection of ). Is there a way to do this that returns a type safe generic collection?See .Since Java 8 you can use lambdas and achieve shorter code:The following code will create a list of files based on the accept method of the .Since java 7 you can the  package to achieve the same result:What about a wrapper around your existing code:I will throw a warning though. If you can live with that warning, then you're done. 
Java

I have a JLabel which has a lot of text on it. Is there a way to make the JLabel have a max width so that it will wrap the text to make it not exceed this width?ThanksNo. You can use HTML in the label, but then you must hard code the break tag.A better approach is to use a JTextArea and turn wrapping on. You can change the background,foreground, font etc. of the text are to make it look like a label.As per @darren's answer, you simply need to wrap the string with  and  tags:You do not need to hard-code any break tags.  The text wraps as the component resizes.Yes there are two similar ways (first with css style=\"width:...px\", second with html WIDTH=...:1.2.or simply use JXLabel in the  supports wrappingYou can use HTML without hard coding break tags if you use paragraph tags instead.There's a good technique , scroll to the end of the article.Other than wrapping the text in  tags, you also have to put the label into a container that respects the preferred height and sets the width to maximum. For example, you can put the label in to the NORTH of a .Here is a simple but complete working program to illustrate this. You can resize the frame in any way you want; the label will occupy the whole width and the height will adjust accordingly to wrap the text. Notice that all that I'm doing is using  tags and putting the label in the NORTH of the .If you only want to use JLabel than you can try this approach,just display the number of characters you want to display on label using substring method.
Java

This question was posted on some site. I didnt find right answers there, so I am posting it here again.     My query is not about stopping a Thread. Let me rephrase my question.\nLine A(see code above) starts a new Thread; and Line B make the thread reference null. So, the JVM now has a Thread Object(which is in running state) to which no reference exists (as t=null in Line B).\nSo my question is, why does this thread(that has no reference anymore in the main thread) keeps on running until the main thread is running. Per my understanding, the thread object should have been garbage collected post Line B. I tried to run this code for 5 minutes and more, requesting Java Runtime to run GC, but the thread just does not stop.Hope both the code and question is clear this time.A running thread is considered a so called garbage collection root and is one of those things keeping stuff from being garbage collected. When the garbage collector determines whether your object is '' or not, it is always doing so using the set of garbage collector roots as reference points.Consider this, why is your main thread not being garbage collected, no one is referencing that one either.As was explained, running threads are, by definition, immune to GC. The GC begins its work by scanning \"roots\", which are deemed always reachable; roots include global variables (\"static fields\" in Java-talk) and the stacks of all running threads (it can be imagined that the stack of a running thread references the corresponding  instance).However, you can make a thread a \"daemon\" thread (see ). A daemon thread is no more garbage-collected than a non-daemon thread, but the JVM exits when all running threads are daemon. One way to imagine it is that every thread, when it terminates, checks whether there remain some non-daemon running threads; if not, the terminating thread forces a  call, which exits the JVM (killing off the running daemon threads). This is not a GC-related issue; in a way, threads are allocated manually. However, this is how the JVM can tolerate semi-rogue threads. This is typically used for  instances.The JVM has a reference to all running threads.No thread (or the things it refers to) will be garbage-collected while it is still running.The Thread is not garbage collected because there are references to the threads that you cannot see. For example, there are references in the runtime system. When the Thread is created it is added to the current thread group. You can get a list of Threads in the current thread group, so that is another way to get a reference to it.
Java

I'm trying to use Apache Lucene for tokenizing, and I am baffled at the process to obtain Tokens from a .The worst part is that I'm looking at the comments in the JavaDocs that address my question.Somehow, an  is supposed to be used, rather than s.  I'm totally at a loss.  Can anyone explain how to get token-like information from a TokenStream?Yeah, it's a little convoluted (compared to the good ol' way), but this should do it:According to Donotello,  has been deprecated in favor of . According to jpountz (and Lucene's documentation),  is more desirable than .This is how it should be (a clean version of Adam's answer):There are two variations in the OP question:Recent versions of the  say (emphasis added):And  says its API:The other answers to this question cover #2 above: how to get  information from a  in the \"new\" recommended way using attributes.  Reading through the documentation, the Lucene developers suggest that this change was made, in part, to reduce the number of individual objects created at a time.But as some people have pointed out in the comments of those answers, they don't directly answer #1: how do you get a  if you really want/need that type?With the same API change that makes  an ,  now implements  and can be used with  just like the other answers show for  and .  So they really did answer that part of the original question, they simply didn't show it.It is important that while this approach will allow you to access  while you're looping, it is still only a single object no matter how many logical tokens are in the stream.  Every call to  will change the state of the  returned from ; So if your goal is to build a collection of different  objects to be used outside the loop then you will need to do extra work to make a   object as a (deep?) copy.
Java

I have the following parametrised JPA, or Hibernate, query:I want to pass the parameter as an ArrayList<String>, is this possible? Hibernate current tells me, thatIs this possible at all?: Collections as parameters only work with named parameters like \"\", not with JDBC style parameters like \"\".Are you using Hibernate's  object, or JPA? For JPA, it should work fine:For Hibernate's, you'll need to use the setParameterList:in HQL you can use query parameter and set Collection with setParameterList method.Leaving out the parenthesis and simply calling 'setParameter' now works with at least Hibernate.Using pure JPA with  as the actual provider the following seems to work with positional parameters as well:Entity.java:Dao.java:
Java

Can I define an abstract class without adding an abstract method?Of course.Declaring a class abstract only means that you don't allow it to be instantiated on its own.Declaring a method abstract means that subclasses have to provide an implementation for that method.The two are separate concepts, though obviously you can't have an abstract method in a non-abstract class. You can even have abstract classes with  methods but never the other way around.Yes you can do it. Why don't you just try doing that?Yes you can. The abstract class used in java signifies that you can't create an object of the class. And an abstract method the subclasses have to provide an implementation for that method.So you can easily define an abstract class without any abstract method.This is fine.Yes, you can declare a class you cannot instantiate by itself with only methods that already have implementations. This would be useful if you wanted to add abstract methods in the future, or if you did not want the class to be directly instantiated even though it has no abstract properties.YES You can create abstract class with out any abstract method the best example of abstract class without abstract method is HttpServlet\nAbstract Method is a method which have no body, If you declared at least one method into the class, the class must be declared as an abstract its mandatory BUT if you declared the abstract class its not mandatory to declared the abstract method inside the class.You cannot create objects of abstract class, which means that it cannot be instantiated. Yes we can have an abstract class without Abstract Methods as both are independent concepts. Declaring a class abstract means that it can not be instantiated on its own and can only be sub classed. Declaring a method abstract means that Method will be defined in the subclass. Yes, you can define an abstract class without an abstract method. However, if there is no method inside you might better go with an interfaceyes you can do that.declaring class abstract means that class will not be instantiated by any other class.and there should be at least one abstract method inside that and meaning of that you can declare abstract method in that class if you are not declaring method than its ok.example:this will work for sure.Yes you can. Sometimes you may get asked this question that what is the purpose doing this?\nThe answer is: sometimes we have to restrict the class from instantiating by its own. In that case, we want user to extend our Abstract class and instantiate child classyes, we can declare an abstract class without any abstract method. the purpose of declaring a class as abstract is not to instantiate the class.so two cases 1) abstract class with abstract methods.these type of classes, we must inherit a class from this abstract class and must override the abstract methods in our class,\nex: GenricServlet class2) abstract class without abstract methods.these type of classes, we must inherit a class from this abstract class, \nex: HttpServlet class\npurpose of doing is although you if you don't implement your logic in child class you can get the parent logic 
Java

I am building a generic web service and need to grab all the query parameters into one string for later parsing. How can I do this?You can access a single param via  or all of the params via the context:The key is the  , which can be used to access:The unparsed query part of the request URI can be obtained from the  object:\n
Java

I have a  representation of a date that I need to create a  or  object from. I've looked through  and  APIs but haven't found anything that can do this other than creating my own ugly parse method. I know there must be a way, does anyone know of a solution?In brief:See  for more.And to turn it into a , do:Java 8 and later has a new  framework that makes these other answers outmoded. This framework is inspired by , defined by , and extended by the  project. See the .The old bundled classes, java.util.Date/.Calendar, are notoriously troublesome and confusing. Avoid them.Like Joda-Time, java.time has a class  to represent a date-only value without time-of-day and without time zone. If your input string is in the standard  format of , you can ask that class to directly parse the string with no need to specify a formatter. The ISO 8601 formats are used by default in java.time, for both parsing and generating string representations of date-time values.If you have a different format, specify a formatter from the  package. You can either specify your own formatting pattern or let java.time automatically localize as appropriate to a  specifying a human language for translation and cultural norms for deciding issues such as period versus comma.Read the  class doc for details on the codes used in the format pattern. They vary a bit from the old outmoded  class patterns.Note how the second argument to the  method is a , syntax added to Java 8 and later.Dump to console.Or rather than specify a formatting pattern, let java.time localize for you. Call , and be sure to specify the desired/expected  rather than rely on the JVM\u2019s current default which can change at any moment during runtime(!).Dump to console. The  is also worth a look.  This is basis for the new  that is pencilled in for Java 7.  The design is neat, intuitive,  and avoids a lot of the clumsiness of the original  /  classes.  Joda's  can parse a String to a Joda .Try this:The  class has a  method.See  for more information.
Java

I currently use the following code to print a double:This works well, except that Java uses my Locale's decimal separator (a comma) while I would like to use a point. Is there an easy way to do this?Use the overload of  which lets you specify the locale:If you're  formatting a number - as you are here - then using  would probably be more appropriate. But if you need the rest of the formatting capabilities of , this should work fine.A more drastic solution is to set your Locale early in the main().Like:You can pass an additional Locale to java.lang.String.format as well as to java.io.PrintStream.printf (e.g. System.out.printf()):This results in the following (on my PC):See  in the Java API.You can use NumberFormat and DecimalFormat.Take a look at this link from Java Tutorials The section titled Locale-Sensitive Formatting is what you need.Way too late but as other mentioned here is sample usage of  (and its subclass )
Java

I'm trying to get a target to build that has quite a long list of  and  elements in its  element (in the build.xml file).  I keep getting \"package com.somecompany.somepackage does not exist\" errors, and I'm having a hard time chasing down these packages and making sure I've synced them from our repository.I'm new to this team so I'm unfamiliar with the build, but I would prefer to figure this out myself if possible (so I don't bother the other very busy team members).  I have very limited experience with Ant.I think it would save me quite a bit of time if I could have Ant print out the classpath for the target I'm trying to build.Use the  task to convert a path to a property.This is even easier with versions of Ant > 1.6See  for more information
Java

Could you help me write spring mvc style analog of this code?And how to add an element that is annotated by  annotation to session and then get access to it?If you want to deleting object after each response no need to session,If you want keep object during user session ,\nIt has some ways:5.Pass HttpSession to method:  6.Make ModelAttribute in session By @SessionAttributes(\"ShoppingCart\"):or you can add Model To entire Controller Class Such  each one has advantage and disadvantage:@session may use more memory in cloud systems it copies session to all nodes, and direct method (1 and 5) has messy approach, it is not good to unit test.To access session jsp in Jstl :in Thymeleaf:Use See the docs: \"\" also gives a very good overview of Spring MVC sessions and explains how/when s are transferred into the session (if the controller is  annotated).That article also explains that it is better to use  on the model instead of setting attributes directly on the HttpSession because that helps Spring MVC to be view-agnostic. annotation is the simplest and straight forward instead of getting session from request object and setting attribute.\n \nIn below eg,  will be available in session.The below annotated code would set \"value\" to \"name\"To access the same in JSP use \n.For the  see this When I trying to my login (which is a bootstrap modal), I used the @sessionattributes annotation. But problem was when the view is a redirect (\"redirect:/home\"), values I entered to session shows in the url. Some Internet sources suggest to follow  But I used the HttpSession instead. This session will be there until you close the browsers.\nHere is sample code You don't change specific thing on view side.After login add above codes to anyplace in you web site. If session correctly set, you will see the values there. Make sure you correctly added the jstl tags and El- expressions (Here is link to set jstl tags )Isn't it easiest and  that way? I knew it and just tested it - working perfect here:p.s.\n
Java

I'm trying to show an icon next to an item within my menu for my navigation drawer, but for some reason the icon always appears in grey rather than the original colour (brown). Is there any way of preventing this from happening in order to show the icon's original colour?I found the answer here:  To avoid the link its pretty straightforward:This disables all state based tinting, but you can also specify your own list too.  It worked great for me!Here is where you can get the details on creating a color state list, but its pretty simple too: \nUse it's right. Also If all your icons in one color scheme (i had all white)\nyou can setup through xml file -         app:itemIconTint=\"@android:color/white\"My case:I've tried something similar in one of my app. And yes, it appears that the icon color doesn't change. But I've managed to do with another workaround. Here's my Which I believe is something similar to you but it doesn't have any effect and doesn't change the color. So what I did is this.And it seems working. Here's the result.You can try using a tinted drawable, not sure if it works below 5.0. Create a drawable and add the following code.And then change your menu item drawable to the one you just created. If that doesn't work, then I'm not sure of any other solutions. You can try this library:  I use it a lot in my projects.Just add one line in xml 
Java

What is the most efficient way to make the first character of a  lower case?I can think of a number of ways to do this:I am sure there are many other great ways to achieve this. What do you recommend?I tested the promising approaches using . Full benchmark .Assumption during the tests (to avoid checking the corner cases every time): the input String length is always greater than 1.The score are operations per second, the more the better. If the String length is always greater than 0, use .If not, we have to check the corner cases:If you are sure that your text will be always in ASCII and you are looking for extreme performance because you found this code in the  bottleneck, use .I came across a nice alternative if you don't want to use a third-party library:When it comes to string manipulation take a look to Jakarta Commons Lang .Despite a char oriented approach I would suggest a String oriented solution.\n is Locale specific, so I would take this issue into account.  is to prefer for lower-caseing according to .\nAlso a char oriented solution is not full unicode compatible, because   cannot handle supplementary characters.\nAs an example how important the locale setting is let us lowercase  in turkish and german:will output two different results:Strings in Java are immutable, so either way a new string will be created.Your first example will probably be slightly more efficient because it only needs to create a new string and not a temporary character array.If you want to use Apache Commons you can do the following:Result: someStringIf what you need is very simple (eg. java class names, no locales), you can also use the  class in the  library.Or you can prepare and reuse a converter object, which could be more efficient.To better understand philosophy of the Google Guava string manipulation, check out .A very short and simple static method to archive what you want:I have come accross this only today.  Tried to do it myself in the most pedestrian way.  That took one line, tho longish. Here goesGives:Before str = TaxoRanksAfter str = taxoRanks
Java

How many objects are created as a result of the statements in the sample code above and why? Is there any IDE in which we can see how many objects are created (maybe in a debug mode)?The answer, surprisingly, is zero.All the s from -128 to +127 are pre-computed by the JVM.Your code creates  to these  objects.The strictly correct answer is that the number of  objects created is .  It could be between 0 and 3, or 256 or even more, depending onThe  values for -128 to 127 are not strictly required to be .  In fact,  which specified the Boxing conversion says this:Two things to note:Even the javadoc for  does not  that the results are cached eagerly.If we examine the Java SE source code for  from Java 6 through 8, it is clear that the current Java SE implementation strategy is to precompute the values.  However, for various reasons (see above) that is still not enough to allow us to give a definite answer to the \"how many objects\" question. First of all: The answer you are looking for is , as others already mentioned.But let's go a bit deeper. As Stephen menthioned it depends on the time you execute it. Because the cache is actually lazy initialized. If you look at the documentation of java.lang.Integer.IntegerCache:This means that if it is the first time you call any Integer you actually create:From the second time on you call them, you create 0 Objects.Things get more funny once you make the numbers a bit higher. E.g. by the following example:Valid options here are: 0, 1 or any number between 1629 to 2147483776 (this time only counting the created Integer-values.\nWhy? The answer is given in the next sentence of Integer-Cache definition:So you actually can vary the size of the cache which is implemented.Which means you can reach for above line:  This is only guaranteed on Oracle / Open JDK (i checked Version 7 and 8)As you can see the completely correct answer is not so easy to get. But just saying  will make people happy.PS: using the menthoned parameter can make the following statement true: The compiler unboxes the  objects to s to do arithmetic with them by calling  on them, and it calls  to box the  results when they are assigned to  variables, so your example is equivalent to:The assignment  is a completely normal object reference assignment which creates no new objects. It does no boxing or unboxing, and doesn't need to as  objects are immutable.The  method is allowed to cache objects and return the same instance each time for a particular number. It is  to cache ints \u2212128 through +127. For your starting number of , all the numbers are small and guaranteed to be cached, so the number of objects that need to be created is . Strictly speaking,  is allowed to cache instances lazily rather than having them all pre-generated, so the example might still create objects the first time, but if the code is run repeatedly during a program the number of objects created each time  approaches 0.What if you start with a larger number whose instances will not be cached (e.g., )? Then each  call must create one new  object, and the total number of objects created each time is .(, maybe it's still zero, or maybe it's millions. Remember that compilers and virtual machines are allowed to rewrite code for performance or implementation reasons, so long as its behavior is not otherwise changed. So it could delete the above code entirely if you don't  the result. Or if you try to print , it could realize that  will always end up with the same constant value after the above snippet, and thus do all the arithmetic at compile time, and print a constant value. The actual amount of work done behind the scenes to run your code is always an implementation detail.)You can debug the Integer.valueOf(int i) method to find out it by yourself.\nThis method is called by the autoboxing process by the compiler.
Java

I have a string with lots of special characters. I want to remove all those, but keep alphabetical characters.How can I do this?That depends on what you mean. If you just want to get rid of them, do this:\nor the equivalent:(All of these can be significantly improved by precompiling the regex pattern and storing it in a constant)Or, with :But if you want to turn accented characters into something sensible that's still ascii, look at these questions:I am using this. It replace all special characters from string.Here \\w : A word character, short for [a-zA-Z_0-9]\\W  : A non-word characterYou can use the following method to keep alphanumeric characters.And if you want to keep only alphabetical characters use thisHere all the special characters except space, comma, and ampersand are replaced. You can also omit space, comma and ampersand by the following regular expression.Where Input is the string which we need to replace the characters.You can use basic regular expressions on strings to find all special characters or use pattern and matcher classes to search/modify/delete user defined strings. This link has some simple and easy to understand examples for regular expressions: You can get unicode for that junk character from charactermap tool in window pc and add \\u e.g. \\u00a9 for copyright symbol.\nNow you can use that string with that particular junk caharacter, don't remove any junk character but replace with proper unicode.
Java

I have an object called , and it has , , , etc. For the , I have to generate random string consist of seven numeric charaters,\neg.And I have to make sure that there is no duplicate id.Generating a random string of characters is easy - just use  and a string containing all the characters you want to be available, e.g.Now, for uniqueness you'll need to store the generated strings somewhere. How you do that will really depend on the rest of your application.This is very nice: If you want uniqueness (with high probability) consider using MD5 or SHA hashes. You can also use UUID class from java.util package, which returns random uuid of 32bit characters String. The first question you need to ask is whether you really need the ID to be random. Sometime, sequential IDs are good enough.Now, if you do need it to be random, we first note a generated sequence of numbers that contain no duplicates can not be called random. :p Now that we get that out of the way, the fastest way to do this is to have a  or  containing all the IDs already generated. Whenever a new ID is generated, check it against the hashtable, re-generate if the ID already occurs. This will generally work well if the number of students is much less than the range of the IDs. If not, you're in deeper trouble as the probability of needing to regenerate an ID increases, P(generate new ID) = number_of_id_already_generated / number_of_all_possible_ids. In this case, check back the first paragraph (do you need the ID to be random?).Hope this helps.Many possibilities...You know how to generate randomly an integer right?\nYou can thus generate a char from it... (ex 65 -> A)It depends what you need, the level of randomness, the security involved... but for a school project i guess getting UUID substring would fit :)I think the following class code will help you. It supports multithreading but you can do some improvement like remove sync block and and sync to getRandomId() method.
Java

I have a \nI want to convert into a string array.\nHow do I do it?\nIs there any java built in function? Manually I can do it but I'm searching for a java built in function.I want an array where each character of the string will be a string.\nlike char 'n' will be now string \"n\" stored in an array.To start you off on your assignment,  splits strings on a regular expression, this expression may be an empty string:Yields the array:Getting rid of the empty 1st entry is left as an exercise for the reader :-)Note: In Java 8, the empty first element is no longer included.The second line allocates a String array with the length of 1. Note that you don't need to specify a length yourself, such as:instead, the length is determined by the number of elements in the initalizer. Usingcreates an array with a length of 3.Assuming you really want an array of single-character strings (not a  or )1. Using a regex:The zero width negative lookahead prevents the pattern matching at the start of the input, so you don't get a leading empty string.2. Using :I guess there is simply no need for it, as it won't get more simple thanOf course if you insist, you could write:[Edit]\nIf you want single-letter Strings, you can use:Unfortunately s[0] will be empty, but after this the letters n,a,m,e will follow. If this is a problem, you can use e.g. System.arrayCopy in order to get rid of the first array entry.In java 8, there is a method with which you can do this: toCharArray():This results to the following array:String array = array of characters ? Or do you have a string with multiple words each of which should be an array element ?Convert it to type ?An additional method:As was already mentioned, you could convert the original String \"name\" to a char array quite easily:To continue this train of thought, you could then convert the char array to a String array:At this point, your stringArray will be filled with the original values from your original string \"name\".\nFor example, now callingWill return the value \"n\" (as a String) in this case.Method  will generate empty 1st, you have to remove it from the array. It's boring. You could use , though this is quite lengthy and only works with java 8. Here are a few more methods:\n\n\nThe last one is just unnecessarily long, it's just for fun!Based on the title of this question, I came here wanting to convert a String into an array of substrings divided by some delimiter. I will add that answer here for others who may have the same question.This makes an array of words by splitting the string at every space:This creates the following array:Tested in Java 8here is have convert simple string to string array using split method.OutputSplitting an empty string with  returns a . In most cases you'd probably prefer to get an empty array, or a null if you passed in a null, which is exactly what you get with .Another option is google guava  and  which return an iterator and a list correspondingly. Unlike the apache version Splitter will throw an NPE on :If you want a list rather than an iterator then use the  flavour.
Java

I am trying to read the contents of a file using FileReader . But i want to read the file without reading a line by line . Is it possible to read the whole file without loop.\nI am using the following codeIf the file is , you can read the whole data once:Java 7 one line solutionor You can try using  if you are using JDK5 or higher.Or you can also use If you are using Java 5/6, you can use  for read file to string. The class  contais several method for read files.e.g. using the method :
Java

In CDI there is the  and the ()  pseudo-scope. What is the difference between them? Besides the fact that  is proxied, and  is not.Can I just change my  bean to ? Can  bean have two (or more) instances? is not part of the CDI specification. It is part of EJB and  (JSR-330). It is not mentioned in the spec what is its behaviour, so you can only rely on what's written in the Weld documentation.\n(and works as expected in mine!)Additionally to the other answers so far I'd like to add some more points for clarification in real world scenarios.For me this question developed out of \nIn some discussion there I stated this and can't find a valid argument against it so far:(debatable but not conclusive) arguments (from my point of view) against it so far:\n(@BalusC and all others: I'd like to see them beeing conclusive, but if not, the above may hold true and nevertheless the arguments may still help the reader to get the differences/advantages/disadvantages/ bad/good practices)but:... which still holds true in my case.but:(I can't see the sledgehammer here - sorry ...)\nIt's good to know the locking defaults (I was not aware of it), but this seems to be incorrect again:  in JSR-299 refers to Singleton session beans (, not ), not JSR-299 managed beans in a built-in scope called Singleton.  You might find in your server that  is one-per EAR or one-per WAR/EJB-JAR as it is not clear in the specification, but you should definitely not expect it to be one per JVM.There is one more difference:\n@Singleton is not bean defining annotations, as the Singleton scope is not a normal scope.\nThen @ApplicationScoped is bean defining annotations.With CDI 1.1 spec: When application in discovery-mode = annotated, Weld does not identify beans with @Singleton and not  loaded thisOne of the major differences that you can write your class with default contractor has private access modifier when using , but your class should have default contractor with at least default access modifier when using  and this is  implementation 
Java

I downloaded Android Studio, fixed the JDK Environmental Variable, but when I try to create a New Project, I get an error that saysI opened up android.bat in the SDK but it said I was already running version 22.Anyone else getting this?It just happened because you already have your SDK setted up for Android Developers Bundle with eclipse. Simply open your SDK manager in the ADT Bundle and update you Android SDK Tools from 21.1 to 22 and you are good to go.Worked for me.First of all, on Windows and Mac, the individual tools and other SDK packages are saved with the Android Studio application directory.Make sure your android-sdk-path is correct and the sdk tool version is 22 or later.Then open the Configure--> Project Defaults --> Project Structure, set your project sdk is Android SDK.enjoy.As for me, i make next:I did all of the above and still got the \"....missing templates blah blah\". What worked for me was to go to Configure>Project Defaults>Project Structure>Project and select Android SDK\nthen  Configure>Project Defaults>Project Structure>SDKs map the Android SDK home path to the sdk folder in the ADT bundle (for me it was \"C:\\Users\\home\\Toolbox\\adt-bundle-windows-x86\\sdk\").\nI then selected Android 4.1.2 clicked apply and it worked.\nI then went back to the Configure>Project Defaults>Project Structure>SDKs and then selected Android 4.2.2 and now that worked too (strange though as when I selected Android 4.2.2 first time the Apply button was grayed out)I ran into this problem because I wanted to update from an old version. In doing this, I downloaded the latest version from the , then unzipped and copied over my existing Android Studio install which did have the sdk folder inside.Going back and looking at it, I see quite plainly that there was a note that I previously ignored:For OS X users, this means going to your old version of Android Studio (if you haven't copied over it yet) and right-clicking and selecting , then copying the  folder that's inside, then putting that into the new version of Android Studio.If, like me, you already copied over the old version, then you'll need to  first which does contain the SDK.They released a new sdk today. You need to update to it.I was still hitting this, and figured it was due to something I had misconfigured (which turned out to be the case).  The error message is a little confusing, too, because I believe that they are referring to is the version of the ADT tools, not the SDK.  For example, the version of Android 4.3 (which is about the latest) is 18. As of the latest source for Android Studio (which you can clone from here: ), that message is generated from NewProjectWizard.java at about line 75 if TemplateManager.templatesAreValid() is false.  And it checks that by looking for the existence of the file [rootTemplatesFolder]/gradle/wrapper/gradlew .It gets the [rootTemplatesFolder] from the SDK(s) you specified in the \"Project Structure\" settings for default projects.  In my case, I had several specified - both the new ones pointing to the sdk directory that's (thankfully) part of the Android Studio, and a few old ones I had somewhere else.  I should not have included the old ones at all, but I'm a newb to this and the GUI let me do it.  The NewProjectWizard was checking the tools area of that one first, which did not have that file, since the tools version with it was older than version 22.I had to use dtruss to watch the system calls of Android Studio to see where it was looking for that file, at which point I could tell what my silly problem was.  I have a few more notes on this, including a screenshot of my particular misconfiguration, at Note: It seems you have to restart Android Studio for the \"New Project Settings\" here to take effect.for ubuntu: \nOpen sdk manager from Android Studio or configuration.\nmake sure you download or update the latest release SDK and build tools.just Update sdk with sdk manager \nit worked for me 
Java

I haven't been able to find an adequate answer to what exactly the following error means: Notes:Relevant code:This usually means that there was a network error, such as a TCP timeout. I would start by placing a sniffer (wireshark) on the connection to see if you can see any problems.  If there is a TCP error, you should be able to see it.  Also, you can check your router logs, if this is applicable.  If wireless is involved anywhere, that is another source for these kind of errors.This also happens if your TLS client is unable to be authenticate by the server configured to require client authentication.The only time I've seen something like this happen is when I have a bad connection, or when somebody is closing the socket that I am using from a different thread context.Are you accessing http data?  Can you use the HttpClient library instead of the standard library?  The library has more options and will provide better error messages.Try adding 'autoReconnect=true' to the jdbc connection stringThis error occurs when a connection is closed abruptly (when a TCP connection is reset while there is still data in the send buffer). The condition is very similar to a much more common 'Connection reset by peer'. It can happen sporadically when connecting over the Internet, but also systematically if the timing is right (e.g. with keep-alive connections on localhost).An HTTP client should just re-open the connection and retry the request. It is important to understand that when a connection is in this state, there is no way out of it other than to close it. Any attempt to send or receive will produce the same error.Don't use , use Apache-Commons  which has a retry mechanism, connection pooling, keep-alive and many other features.Sample usage:This will happen from time to time either when a connection times out or when a remote host terminates their connection (closed application, computer shutdown, etc). You can avoid this by managing sockets yourself and handling disconnections in your application via its communications protocol and then calling  and  to clear up the session.Look if you have another service or program running on the http port. It happened to me when I tried to use the port and it was taken by another program.If you are using Netbeans to manage Tomcat, try to disable HTTP monitor in Tools - ServersI too had this problem. My solution was:COPY FROM A WEBSITE -->By using the  method, you can explicitly set a delay before a reset is sent, giving more time for data to be read or send.Maybe it is not the answer to everybody but to some people.
Java

The book \"Essential JNI: Java Native Interface\" by Rob Gordon contains the following code example to convert a jstring to a C string:Note that it only calls  if  is true. But the book  (alternate link: ) says:I am correct in assuming this is a bug in Gordon's book?Yes, your assumption is correct (you should always call ReleaseStringUTFChars).
Java

I have seen the question  and I understand the difference between JSRs 308 and 305. I also understand that, at this time, 308 is slated for Java 7, and 305 is not, and I am curious about the overall status of 305.Specifically, I am using  and  in some of my projects (in a similar manner to what ) and was wondering if there is a more \"future direction\"-friendly approach I should be using instead. I am planning to also ask about this on the JSR-305 group, but that group does not have much activity and I was just wondering if anyone here had any more info.As described in this ,  proposes new annotations such as , while  proposes allowing annotations in new places such as on generic declarations. JSR 308 (annotations in new places) is included in  under .As far as I can tell, JSR-305 (new annotations) is dormant.  A  about it's status in the google group has been unanswered since 2010.  There is a reference implementation of the JSR-305 annotations  which is used by many projects, including guava.  With maven you can use the JSR-305 reference implementation by adding this to your pom,JSR 305 will not be part of Java 8:Java 8 is described by JSR 337: the specification has reached Final status: .According to Alex Millers , JSR-308 (and 305) are scheduled to go in to Java 7.  Perhaps he will show up here and give you more information.
Java

C# has Int.TryParse: The great thing with this method is that it doesn't throw an exception for bad data.In java,  will throw an exception, and in cases where this may happen a lot performance will suffer.Is there a way around this somehow for those cases where performance is an issue?The only other way I can think of is to run the input against an regex, but I have to test to see what is faster.No. You have to make your own like this:  ...and you can use it like this:  Apache Commons has an  class which appears to do what you want. Java provides no in-built method for doing this. -- just saw your comment about the performance problems associated with a potentially bad piece of input data. I don't know offhand how try/catch on parseInt compares to a regex.  I would guess, based on very little hard knowledge, that regexes are not hugely performant, compared to try/catch, in Java.Anyway, I'd just do this:
Java

In , all the methods that require the lock copy it to a local  variable before calling .Is there any reason to copy  to a local variable  when the field  is ?Additionally, it also uses a local copy of  before acting on it:It's an extreme optimization Doug Lea, the author of the class, likes to use. Here's a post on  on the core-libs-dev mailing list about this exact subject which answers your question pretty well.from the post: gives some answers. In substance:
Java

This is a basic question but I can't find an answer.  I've looked into floating point arithmetic and a few other topics but nothing has seemed to address this.  I'm sure I just have the wrong terminology.Basically, I want to take two quantities - completed, and total - and divide them to come up with a percentage (of how much has been completed).  The quantities are s.  Here's the setup:I've tried reassigning the result to a double - it prints .  Where am I going wrong?Incidentally, the next step is to multiply this result by 100, which I assume should be easy once this small hurdle is stepped over.BTW not homework here just plain old numskull-ness (and maybe too much coding today).Converting the  is too late; the calculation has already taken place in integer arithmetic.  You need to convert the  to :Note that you don't actually need to convert  of them; so long as one is , the other will be implicitly converted.  But I prefer to do both, for symmetry.You don't even need doubles for this. Just multiply by 100  and then divide. Otherwise the result would be less than 1 and get truncated to zero, as you saw.edit: or if overflow is likely, if it would overflow (ie the dividend is bigger than 922337203685477581), divide the divisor by 100 first.Convert both  and  to  or at least cast them to  when doing the devision. I.e. cast the varaibles to double not just the result.Fair warning, there is a  when working with  and .If you don't explicitly cast one of the two values to a float before doing the division then an integer division will be used (so that's why you get 0). You just need one of the two operands to be a floating point value, so that the normal division is used (and other integer value is automatically turned into a float).Just try with and it will be fine.Just type cast either of them.As explain by the , integer operation are quite simple.So to make it short, an operation would always result in a  at the only exception that there is a  value in it.Note that the priority of the operator is important, so if you havethe  operation would result in an , it would be promote into a  during the operation 
Java

I am wondering if it is possible to call python functions from java code using jython, or is it only for calling java code from python?You can easily call python functions from Java code with Jython. That is as long as your python code itself runs under jython, i.e. doesn't use some c-extensions that aren't supported.If that works for you, it's certainly the simplest solution you can get. Otherwise you can use  from the new Java6 interpreter support.A simple example from the top of my head - but should work I hope: (no error checking done for brevity)Hey I thought I would enter my answer to this even though its late. I think there are some important things to consider first with how strong you wish to have the linking between java and python.  Do you only want to call functions or do you actually want python code to change the data in your java objects? This is very important. If you only want to call some python code with or without arguments, then that is not very difficult. If your arguments are primitives it makes it even more easy. However if you want to have java class implement member functions in python, which change the data of the java object, then this is not so easy or straight forward. are we talking cpython or will jython do? I would say cpython is where its at! I would advocate this is why python is so kool! Having such high abstractions however access to c,c++ when needed. Imagine if you could have that in java. This question is not even worth asking if jython is ok because then it is easy anyway.So I have played with the following methods, and listed them from easy to difficult:  Trivially easy. Have actual references to java objects No CPython, Extremely Slow!Jython from java is so easy, and if this is really enough then great. However it is very slow and no cpython! Is life worth living without cpython I don't think so! You can easily have python code implementing your member functions for you java objects.Pyro is the remote object module for python. You have some object on a cpython interpreter, and you can send it objects which are transferred via serialization and it can also return objects via this method. Note that if you send a serialized python object from jython and then call some functions which change the data in its members, then you will not see those changes in java. You just need to remember to send back the data which you want from pyro. This I believe is the easiest way to get to cpython! You do not need any jni or jna or swig or .... You don't need to know any c, or c++. kool huh? Access to cpython, not as difficult as following methods Cannot change the member data of java objects directly from python. Is somewhat indirect, (jython is middle man).OMG this method is not for the faint of heart. And I can tell you it has taken me very long to achieve this in with a decent method. Main reason you would want to do this is so that you can run cpython code which as full rein over you java object. There are major major things to consider before deciding to try and bread java (which is like a chimp) with python (which is like a horse). Firstly if you crash the interpreter that's lights out for you program! And don't get me started on concurrency issues! In addition, there is allot allot of boiler, I believe I have found the best configuration to minimize this boiler but still it is allot! So how to go about this:\nConsider that C++ is your middle man, your objects are actually c++ objects! Good that you know that now. Just write your object as if your program as in cpp not java, with the data you want to access from both worlds. Then you can use the wrapper generator called swig () to make this accessible to java and compile a dll which you call System.load(dll name here) in java. Get this working first, then move on to the hard part!\nTo get to python you need to embed an interpreter. Firstly I suggest doing some hello interpreter programs or this tutorial . Once you have that working, its time to make the horse and the monkey dance! You can send you c++ object to python via [boost][3] . I know I have not given you the fish, merely told you where to find the fish. Some pointers to note for this when compiling.When you compile boost you will need to compile a shared library. And you need to include and link to the stuff you need from jdk, ie jawt.lib, jvm.lib, (you will also need the client jvm.dll in your path when launching the application) As well as the python27.lib or whatever and the boost_python-vc100-mt-1_55.lib.\nThen include Python/include, jdk/include, boost and only use shared libraries (dlls) otherwise boost has a teary. And yeah full on I know. There are so many ways in which this can go sour. So make sure you get each thing done block by block. Then put them together. It depends on what do you mean by python functions? if they were written in  you can not directly call them you will have to use , but if they were written in  you can easily call them from java, as jython ultimately generates java byte code.Now when I say written in cpython or jython it doesn't make much sense because python is python and most code will run on both implementations unless you are using specific libraries which relies on cpython or java.see here You can call any language from java using Depending on your requirements, options like  could be useful, which can be used to remotely call functions virtually in any language supporting the protocol.Several of the answers mention that you can use JNI or JNA to access cpython but I would not recommend starting from scratch because there are already open source libraries for accessing cpython from java. For example:Jython has some limitations:you can simply call python scripts (or bash or Perl scripts) from Java using Runtime or ProcessBuilder and pass output back to Java: Here a library that lets you write your python scripts once and decide which integration method (Jython, CPython/PyPy via Jep and Py4j) to use at runtime:  Since each method has its own benefits/drawbacks as explained in the link.It's not smart to have python code inside java. Wrap your python code with flask or other web framework to make it as a microservice. Make your java program able to call this microservice (e.g. via REST).Beleive me, this is much simple and will save you tons of issues. And the codes are loosely coupled so they are scalable.
Java

The code says it all :-) Thanks for any help in advance!EDIT: What I actually want is that the \"???\" above are replaced by the value of the field . A link would not be perfect, but better than nothing :-)Do you mean ?
Java

I'm having trouble generating a session factory in Hibernate 4. In Hibernate 3 I simple did:Now I need to pass a ServiceRegistry class to buildSessionFactory, but the Javadocs are extremely vague on how to go about this. Any tips?Yes, they have deprecated the previous buildSessionFactory API, and it's quite easy to do well.. you can do something like this.. : ServiceRegistryBuilder is deprecated. you must use StandardServiceRegistryBuilderFor more reference and in depth detail, you can check the hibernate's official test case at  function (buildSessionFactory()).Try this!The following expresses the experience I had with hibernate 4.0.0.Final.The javadoc (distributed under LGPL license) of  class states that:After looking at issue 2578, i used something like this:For it to start reading configuration, i had to modify my hibernate 3.2.6 configuration and mapping files to use  and  and also remove the dtd specifications.I couldn't find a way for it to inspect mappings defined in hibernate.cfg.xml and    prefix for hibernate-related properties in  is no longer optional.This might work for some.I, for one, ran into some error because mapping files contained  and ended up using deprecated Configuration way:I had to programatically append event listeners because Configuration no longer looks for them in hibernate.cfg.xmlEven there is an update in 4.3.0 API. ServiceRegistryBuilder is also deprecated in 4.3.0 and replaced with the StandardServiceRegistryBuilder. Now the actual code for creating the session factory would look this .[quote from http://www.javabeat.net/session-factory-hibernate-4/]There are many APIs deprecated in the hibernate core framework. One of the frustrating point at this time is, hibernate official documentation is not providing the clear instructions on how to use the new API and it stats that the documentation is in complete. Also each incremental version gets changes on some of the important API. One such thing is the new API for creating the session factory in Hibernate 4.3.0 on wards. In our earlier versions we have created the session factory as below: and it is replaced with the new API. If you are using the hibernate 4.3.0 and above, your code has to be: It looks like there will be lot of changes in the 5.0 release. Still there is not much clarity on the deprecated APIs and the suitable alternatives to use. Every incremental release comes up with more deprecated API, they are in way of fine tuning the core framework for the release 5.0.The method  is deprecated from the Hibernate 4 release and it is replaced with the new API. If you are using the Hibernate 4.3.0 and above, your code has to be:In earlier versions session factory was created as below:The method buildSessionFactory is deprecated from the hibernate 4 release and it is replaced with the new API. If you are using the hibernate 4.3.0 and above, your code has to be like:
Java

How can I easily detect when a variable changes value? I would like the execution of the program to break on the debugger whenever a specified variable changes value. Right now I'm using Eclipse's debugger. For a class or instance variableOR\nToggle  Breakpoint on the line where the variable is declared, then right-click on the resulting entry, select \"breakpoint properties\" and deselect \"Field Access\".
Java

I'm new to a team working on a rather large project, with lots of components and dependencies. For every component, there's an  package where the exposed interfaces for that component are placed. Is this a good practice?My usual practice has always been interfaces and implementations go in the same package.Placing both the interface and the implementation is common place, and doesn't seem to be a problem.Take for example the Java API -- most classes have both interfaces and their implementations included in the same package. Take for example the  package:It contains the interfaces such as , , , while also having the implementations such as ,  and .Furthermore, the Javadocs are designed to work well in those conditions, as it separates the documentation into the  and  views when displaying the contents of the package.Having packages only for interfaces may actually be a little bit excessive, unless there are enormous numbers of interfaces. But separating the interfaces into their own packages just for the sake of doing so sounds like bad practice.If differentiating the name of a interface from an implementation is necessary, one could have a naming convention to make interfaces easier to identify:For any language, putting them together in the same package is fine. The important thing is what's exposed to the outside world, and how it looks from outside. Nobody's going to know or care if the implementation is in that same package or not.Let's look at this particular instance.If you have all public things in one package, and private things in another package that is not publicly exposed, the client of the library sees one package. If you move the private things to the package with the publicly exposed things, but do not expose them from within the package, the client sees exactly the same thing.Thus, this has the smell of a rule with no good reason: it's making a decision based on something being publicly visible without that decision having any effect on what's publicly visible.That said, if in any particular instance it seems like a good idea to split the interface and implementation in to separate packages, go right ahead and do that. Reasons for doing this that come to mind are that the package is huge, or you have an alternate implementation you might want to link in instead of the standard one.In many frameworks, such as OSGi, you almost have to. I think this promotes looser coupling, at the package instead of the jar level.One argument for putting interfaces in different packages is that it is easier to create 'api' jars that can be distributed to consumers of your product or service. It's perfectly possible to do this with interfaces and implementations together, but simpler to script if they are in different packages.We do this where I work (ie: put interface in one package and implementation in another) and the main advantage we get out of this is we can easily swap between implementations.I haven't much Java experience, but I like to do this as a good practice in C#/.NET because it allows for future expansion where the assemblies with the concrete classes which implement the interfaces may not be distributed all the way down to the client because they are proxied by a middleman factory or across the wire in a web service scenario.Yes, it's a very good practice, because it allows you to publish the interface without publishing your specific implementation.  That said, if you have no need to publish external interfaces, there's no problem with putting the interface definitions in the same package as the implementation.I'm doing this on a project and it is working well for me because of these reasons:Questions of program design generally involve benefits and drawbacks and there is no one-size-fits all answer.  Like why would you ever use this technique in a tiny 200-line program?  It makes sense for me, given my other architectural choices, for my specific problem. :)The book  advocates for putting interfaces in seperate projects/packages. The PCMEF+ architecture which the book talks about has the following principles:The description of principle #3 and #7 explain why it is a good idea:See this link: Put them in packages that reflect your projects.  It is fine and common to put interfaces and implementations together if they're part of the same project, but if you're writing an API, then someone else would likely be choosing a package name relevant to their project.In general, if it's for the same project, I don't see any benefit in keeping the interfaces in a separate package from their impls.  If it's getting cluttered, there may be other package naming issues, irrespective of the interface arrangement.I prefer them in the same package. Feels pointless to create a package specifically for interfaces. This is especially redundant for teams that simply love their interface prefixes and suffixes (e.g. the \"I\", and \"Impl\" for Java).If there's a needs to publish a set of interfaces as public API, it makes more sense to keep them in an entirely separate project and create project dependencies instead. But it all boils down to preference and convenience of the situation I suppose.I normally put Interfaces with the implementation however I can sort of see why you may want to keep them separate. Say, for instance, someone wanted to reimplement classes based upon your interfaces, they would need a jar/lib/etc with your implementation rather than just the interfaces. With them separate you could just say \"Here's my implementation of that interface\" and be done with it. Like I said, not what I do but I can sort of see why some might want to.I think it is important to note that for the OSGi framework, it is nicer that they are in different packages so that you can easily export a whole package while hiding the implementation packages.There are a lot of good reasons for putting interfaces in a separate package from implementation.  For example you may want to use container that supports  to wire up the necessary implementation(s) at run time, in which case only the interface needs to be present at build time and the implementation can be supplied at run time.  Alternatively, you may want to provide multiple implementations (for example using  implementations for testing) or multiple versions of a particular implementation at run time (for example for A/B testing, etc).  For these kinds of use cases it's more convenient to package interface and implementation separately.
Java

Does Java have a using statement that can be used when opening a session in hibernate?In C# it is something like:So the object goes out of scope and closes automatically.Java 7 introduced  which brings this feature to the Java platform. Prior versions of Java didn't have anything resembling .As an example, you can use any variable implementing  in the following way:Java's  interface, implemented by streams, automagically extends , so you can already use streams in a  block the same way you would use them in a C#  block. This is equivalent to C#'s .As of  and can be auto-closed in ARM blocks. In previous versions of Hibernate . So you'll need to be on Hibernate >= 5.0 in order to use this feature., there was  such feature in Java (for Java 7 and up see  regarding ).You needed to do it manually and it :And that's just the code when neither  nor  can throw any exceptions.If you  only want to limit the scope of a variable, then a simple code block does the job:But that's probably not what you meant.Since Java 7 it does: The syntax for the code in the question would be:Note that  needs to implement  or one of its (many) sub-interfaces.The closest java equivalent isTechnically:No, Java has no  statement equivalent.As of now, no.However there is a proposal of  for Java 7.If you're interested in resource management,  offers the  annotation. Taken directly from their site:Please see this .To imitate such  behaviour, you will have to use a  block, where you would dispose of the resources within ., from  will be in Java 7.  This is feature is intended to bring similar functionality to Java as the .Net using syntax.To answer the question regarding limiting scope of a variable, instead of talking about automatically closing/disposing variables.In Java you can define closed, anonymous scopes using curly brackets. It's extremely simple.The variable  is only available in this scope, and not outside it.This can be useful if you have repeating variables which are only temporary.For example, each with index. Just like the  variable is closed over the for loop (i.e., is only available inside it), the  variable is closed over the anonymous scope.I also use this sometimes if you don't have a for loop to provide variable scope, but you want to use generic variable names.In java 8 you can use try. Please refer to following page. 
Java

Consider this code:When using the  keyword, Java will create the   again right?\nWill this be stored on the regular heap or the  pool?\nHow many s will end in the  pool?If you use the  keyword, a new  object will be created. Note that objects are always on the heap - the string pool is not a separate memory area that is separate from the heap.The string pool is like a cache. If you do this:then the Java compiler is smart enough to make just one  object, and  and  will both be referring to that same String object. If you do this:then there will be one  object in the pool, the one that represents the literal , and there will be a separate  object, not in the pool, that contains a copy of the content of the pooled object. Since  is immutable in Java, you're not gaining anything by doing this; calling  never makes sense in Java and is unnecessarily inefficient.Note that you can call  on a  object. This will put the  object in the pool if it is not already there, and return the reference to the pooled string. (If it was already in the pool, it just returns a reference to the object that was already there). See the API documentation for that method for more info.See also  (Wikipedia).In , the first assignment is:whereas the second is:So the first is in the pool (at position #2) whereas the second will be stored in the heap.Since the   (16 bits, unsigned) the pool can contain at max  =  references. In the case you care .Each time your code create a string literalfor example: the JVM checks the string literal pool first. If the string already exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object instantiates, then is placed in the pool. Java can make this optimization since strings are immutable and can be shared without fear of data corruptionThe only time you should use new String(foo) is when you want to break ==, which is an odd case, or when foo is a substring of a much larger string that has a limited lifetime, such asandBoth expression gives you String object, but there is subtle difference between them. When you create String object using new() operator, it always create a new object in heap memory. On the other hand, if you create object using String literal syntax e.g. \"Java\", it may return an existing object from String pool (a cache of String object in Perm gen space, which is now moved to heap space in recent Java release), if it's already exists. 
Java

I'm trying to run this simple HelloWorld code written in Java from my browser ():I compiled it with , and then I created a WebApplication project. The  code that runs the applet is:If run the applet from NetBeans it works. But when I run the HTML code by double clicking it, the following message pops up from the browser:I tried with Internet\u00a0Explorer and Firefox but nothing.This message started to appear after the last update of Java. Where is the problem?After reading  mention....I was wondering how this would go for loose class files - the 'simplest' applets of all.That is the dialog seen for an applet consisting of loose class files being loaded off the  when the JRE is set to the default 'High' security setting.Note that a slight quirk of the JRE only produced that on point 3 of.If you load the simple applet (loose class file) seen at this  off the  - which boasts an  element of:It also seems to load successfully.  Implying that:- As of Java 7 update 51.I faced the same issue today, and I was able to fix the issue by changing the security settings on the Java Control Panel from  to .Well, setting the Java Security Setting to MEDIUM permanently is not really recommended as this will allow potentialy malicious software to run on your system and not be blocked. So I suggest after running your applet you may want to change back the setting to HIGH.If you are using , these settings are available using  (or your path setting to get the current Java tools). You can also edit the files in  to set \"deployment.security.level=MEDIUM\".Surprisingly, this information is not readily available from the Oracle web site. I miss java.sun.com...That's it!If you have no Medium security level, then you should add your application to the  ( \u2192  tab).If you are like me whose Java Control Panel  under Security Tab to change security level from High to Medium then follow these instructions: .Java applets do create a security risk, hence are disabled in most modern browsers. You have to lower the security to run it. There is a  for that.My problem case was to run portecle.jnlp file locally using Java8.What worked for me wasOn step 3, you might try also to add file:///c:/path/portecle.jnlp, but this addition didn't help with my case.
Java

How do I redirect verbose garbage collection output to a file?  Sun\u2019s website shows an example for Unix but it doesn't work for Windows.From the output of :Documented :So the output looks something like this:If in addition you want to pipe the output to a separate file, you can do:On a ON an To add to the above answers, there's a good article:  by Patrick Peschlow.A brief excerpt:The flag  (or the alias ) activates the \u201csimple\u201d GC logging modeBy default the GC log is written to stdout. With  we may instead specify an output file. Note that this flag implicitly sets  and  as well.If we use  instead of , we activate the \u201cdetailed\u201d GC logging mode which differs depending on the GC algorithm used.With  a timestamp reflecting the real time passed in seconds since JVM start is added to every line.If we specify  each line starts with the absolute date and time. introduces a common logging system for all components of the JVM which will change (and IMO simplify) how logging works with GC. JEP 158 added a new command-line option to control logging from all components of the JVM: For example, the following option:will log messages tagged with  tag using  level to . Or this one:would log messages tagged with  tag using  level to a file called  with no decorations. For more detailed discussion, you can checkout the examples in the  page.
Java

I don't have much memory on my PC and a pretty weak processor. Although netbeans is by far my favorite IDE it is almost unbearable to use on my present computer because of the project scanning that starts automatically when I open the program.Is there a way to prevent netbeans from scanning projects?Hey George I don't know  if this is much of an answer but I right-click and choose 'close' on the projects that I don't need open. There's no point in having all your past projects listed there. Just have the one that you are developing open. You  can always reopen the other projects from the menu. Once all the projects you aren't using are closed they won't be scanned each time you start Netbeans.In addition to creating smaller  for the folders you really work on and then a  to group them (Mateng), you can try excluding folders that you will never work on such as  folders and so on. To ignore those folders, go to:From NetBeans Help: Try this: i know this is an old question but this may help others...\nTo enable or disable background scanning you can find the option under menu Tools -> Options -> Miscellaneus -> FilesIn addition to  (David) you can create project groups containing related projects (or just one): . Project groups can then be opened by pointing at them from the same menu. Best of all: Each group remembers which files were open in the editor windows the last time. I organize all my projects into groups and it reduces scanning significantly. (btw: There's a handy plugin providing a ) \nI am also using  for a while now - really good. Kudos for that answer. Stop NetBeans scanning projects :  I don't know whether you can disable the project scanning or not. Even if you can, I doubt it will ever work properly again. There are a few tips which I have done and it speed up my Netbeans.Netbeans consumes a lot of memory so adding memory also increases its performance (OS does not need to swap between memory and page file when memory is running low) (but this is probably not an option for you). Also, Netbeans consists of hundreds of files which needs to be loaded at start up so the bottom neck is the speed of your hard disk.And another quick thing you can do just delete the nbproject folder inside your project then open the NeteBeans. then the project remove from the list. this I do some times when it got freeze I've stumbled upon this problem aswell.The most simple thing is to edit the netbeans config so it doesn't load all your projects. \nyou can always reopen the other projects from the menu. once all the projects you arent using are closed they wont be scanned each time you start netbeans\nJust change the following line in netbeans.conf found under etc folder# ${HOME} will be replaced by JVM user.home system property\n netbeans_default_userdir=\"${HOME}/.netbeans/changeme\"Try this Netbeans plugin. This reduces the load for some extend.Not exactly the case of question, but sometimes \"scanning projects\" can be stopped just by restarting Netbeans. In my case, with jdk 1.8, there is a big issue when there are multiple static imports (see the example). It seems that there is a problem with javac. The compiler is very slow when checking such a .java file and NetBeans scanning is very very slow. It seems that the compilation and scanning time is increasing very fast with each repeated static  import. So, if that is your case, just remove repeated importsScanning performance of Netbeans can be improved using the following procedure :\n1) Go to Window-->Files. This opens the Files Tab.\n2) In the Files Tab for each opened project open the nbproject folder and inside it open the project.properties file.\n3) Now in this file below the property \"excludes\" there are file references listed for all your referred Libraries (JARs)\n4) There might be some repeated file references with paths that may be old or on someone else's machine(if you are working in a group and transferred projects from someone's machine)\n5) Delete those old path references.\nExample -\n\n\n\n\n  6)Also locate the property \"javac.classpath\" and delete the unnecessary classpath entries corresponding to the deleted references as described above.\nExample -\n\n\n\n\n  7) So now the file reference mentioned in the file reference section and the javac.classpath property is same and points to a valid Library (JAR) address on your machine or network.\nExample -\n\n\n\n\n\n\n\n\n\n  The reason the above procedure worked (in my case) is because it prevents Netbeans from scanning unnecessary Library paths that may not be present on your machine/network.Plugin download - Direct DownloadI have the quickest and easiest way.Just put the netbeans metadata to another location instead of putting it on the project directoryIf your project is a Maven structured project you can use a simple trick to make your and NetBeans life a lot easier. I have my projects inside of c:\\dev on my machine. That's the place where Netbeans is working with. If I build in this folder then NetBean's background process get very busy. But if I copy the  project for example to  before I start  inside of  then NetBeans does not need to scan the changes that happen in this folder. It does not know about it. I use on a windows machine:It is a windows native command. No additional installation necessary. It helped me a lot decrease build time and also to avoid never ending scans on Netbeans.If you use tools like JRebel you can still work like this when you update the changed classes to your c:\\deploy\\trunk folder. You can use the same command. It is of course a bit of a workaround, but it helps a lot. :-), the  plugin from  does not work. Use  instead, as it is current and works fine on stable releases.On a personal note, this brought my netbeans memory consumption for general use down from 20gb+ during idle to about 2gb consistently, and provides a good workaround for the scanner constantly hanging and leaking memory, particularly in very large projects or those with a ton of symlinks.My project became Very Big over timeIn the below 2 cases, it is too slow:  \n1. Doing Window > Reset Windows only solves temporarily\n2. Sometimes felt my GIT repository integration with Netbeans is the main issue, but there was no clear proof for it  Run below commands:   Below commands have automated delete commandsAnd, the problem 1) is now rarely comes up, other times Netbeans loads almost immediately.  root\n....f1\n........f11\n........f12\n....f2\n........f21\n........f22  root is a folder and also it's the main NetBeans project\nf1, f2 are just folders\nf11, f12, f21, f22 are sub-folders that are also NetBeans projects too  Earlier, I was opening root Netbeans project, and the system became too slow due to netbeans scanning the whole project from root, and antivirus was working very hard to cooperate with Netbeans project scanning, result everything in system gets slow.  Now, the solution is open sub-projects like f11, f12, f21, f22, etc. you can open many small sub-project, the Netbeans project scanning issue is fully gone.My Netbeans 8.0.2 would crash on my Macbook pro due to \"Scanning projects...\" hogging up my CPU. I couldn't stop the process, however, I could make the process finish quicker by increasing the Java heap memory in netbeans.conf.Replace this:with:
Java

Since Java8 has been recently released and its brand new lambda expressions looks to be really cool, I was wondering if this means the demise of the Anonymous classes that we were so used to.I've been researching a bit about this and found some cool examples about how Lambda expressions will systematically replace those classes, such the Collection's sort method, which used to get an Anonymous instance of Comparator to perform the sort: Now can be done using Lambdas: And looks surprisingly concise. So my question is, is there any reason to keep using those classes in Java8 instead of Lambdas?Same question but in the opposite direction, what are the benefits of using Lambdas instead of Anonymous classes, since Lambdas can only be used with single method interfaces, is this new feature only a shortcut only used in few cases or is it really useful?An anonymous inner class (AIC) can be used to create a subclass of an abstract class or a concrete class. An AIC can also provide a concrete implementation of an interface, including the addition of state (fields). An instance of an AIC can be referred to using  in its method bodies, so further methods can be called on it, its state can be mutated over time, etc. None of these apply to lambdas.I'd guess that the majority of uses of AICs were to provide stateless implementations of single functions and so can be replaced with lambda expressions, but there are other uses of AICs for which lambdas cannot be used. AICs are here to stay.Another difference between AICs and lambda expressions is that AICs introduce a new scope. That is, names are resolved from the AIC's superclasses and interfaces and can shadow names that occur in the lexcially enclosing environment. For lambdas, all names are resolved lexically.Lambdas though a great feature, will only work with SAM types. That is, interfaces with only a single abstract method. It would fail as soon as your interface contains more than 1 abstract method. That is where anonymous classes will be useful.So, no we cannot just ignore anonymous classes. And just FYI, your  method can be more simplified, by skipping the type declaration for  and :You can also use method reference here. Either you add a  method in  class, and use:or, add a getter for , directly get the  from  method:When application is launched each class file must be loaded and verified.Anonymous classes are processed by compiler as a new subtype for the given class or interface, so there will be generated a new class file for each.Lambdas are different at bytecode generation, they are more efficient, used invokedynamic instruction that comes with JDK7.For Lambdas this instruction is used to delay translate lambda expression in bytecode untill runtime. (instruction will be invoked for the first time only)As result Lambda expression will becomes a static method(created at runtime).\n(There is a small difference with stateles and statefull cases, they are resolved via generated method arguments)Lambda's in java 8 was introduced for functional programming. Where you can avoid boilerplate code. I came across this interesting article on lambda's.It's advisable to use lambda functions for simple logics. If implementing complex logic using lambdas will be a overhead in debugging the code in case of issue.
Java

Is there some way to see the native code produces by the JIT in a JVM?Assuming you're using the Sun Hotspot JVM. Add the flag To whatever you're running. This will only print the assembly for code that has been JIT'd (i.e. you don't get to see assembly for non JIT'd stuff) but I think that's what you want. If you want to see what everything would like if it were JIT'd you could probably tweak the JIT threshold via:As explained by other answers, you can run with the following JVM options:You can also filter on a specific method with the following syntax:Notes:If you are running Windows,  has instructions on how to build and install  and  which are required to make it work. We copy below and extend the content of that page* for reference:You can download prebuilt binaries for Windows from the  projectThe DLL can now be installed by copying it from  or  to your JRE's  or  directory. You can find all such directories on your system by searching for .Bonus tip: if you prefer Intel ASM syntax to AT&T, specify  alongside any other PrintAssembly options you use.You need an hsdis plugin to use . A convenient choice is the hsdis plugin based on FCML library.It can be compiled for UNIX-like systems and on Windows you can use pre-built libraries available in the FCML  section on Sourceforge:Additional configuration parameters: Print machine code before the mnemonic.\n Use the Intel syntax.\n Use the AT&T assembler syntax (GNU assembler compatible).\n Prints IMM and displacement as decimal values.\n Padding for the mnemonic part of the instruction.\n Padding for the machine code.\n Shows the default segment registers.\n Show leading zeros in case of HEX literals.The Intel syntax is a default one in case of Windows, whereas the AT&T one is a default for the GNU/Linux.For more details see the For the HotSpot (was Sun) JVM, even in product modes:Some assembly required:  it needs a plugin.I believe WinDbg would be helpful if you are running it on windows machine.\nI have just run one jar.Highlighted lines is direct running JIT-ed code on JVM.For additional info here is the  how to trace back JIT-ed code from memory dumps using process explorer and WinDbg.Another way to see machine code and some performance data is to use AMD's CodeAnalyst or OProfile, which have a Java plugin to visualize executing Java code as machine code.Print the assembly of your hotspots with JMH's perfasm profilers ( or ). JMH does require the  library since it relies on .
Java

I have some Junit unit tests that require a large amount of heap-space to run - i.e. 1G. (They test memory-intensive functionality for a webstart app that will only run with sufficient heap-space, and will be run internally on Win 7 64-bit machines - so redesigning the tests isn't a practical suggestion.)I am developing in Intellij IDEA, so I know I can set the JVM parameters (e.g. -Xmx1024M) for the test class. However, this is only for running the whole test class - if I want to run an individual test, I have to recreate the run congfigurations for that test method. Also, those are IDE and box specific - so if I switch boxes (I develop on multiple machines) or one of my colleagues tries to run the tests, those settings are not transferred. (Also, other IDEs like Eclipse and NetBeans are used by my colleagues.) FWIW, we're using mercurial for source code control.For the build cycle, we're using Maven, so I know how to specify the JVM parameters for that.So:\n- I'm looking for a way of specifying the JVM parameters that will apply for the whole test class and the individual test methods; and\n- I'd like to share those specification across IDEs on any machine (having picked up the code from the repository).In IntelliJ you can specify default settings for each run configuration. In  configuration dialog (the one you use to configure heap per test) click on  and . These settings will be automatically applied to each new JUnit test configuration. I guess similar setting exists for Eclipse.However there is no simple option to transfer such settings (at least in IntelliJ) across environments. You can commit IntelliJ project files to your repository: it might work, but I do not recommend it.You know how to set these for . Good. This is the most portable way (see Ptomli's answer for an example).For the rest - you must remember that JUnit test cases are just a bunch of Java classes, not a standalone program. It is up to the runner (let it be a standalone JUnit runner, your IDE,  to set those options. That being said there is no \"portable\" way to set them, so that memory settings are applied irrespective to the runner.To give you an example: you cannot define  parameter when developing a servlet - it is up to the container to define that. You can't say: \"this servlet should always be run with .In Maven you can configure the surefire pluginIf you use Maven for builds then this configuration will be carried in the source tree and applied when tests are carried out. See the  documentation.I agree with the others who said that there is no simple way to distribute these settings. For Eclipse: ask your colleagues to set the following:After that all test will run with  but unfortunately you have set it in every Eclipse installation. Maybe you could create a custom Eclipse package which contains this setting and give it to you co-workers.The following working process also could help: If the IDE cannot run a test the developer should check that Maven could run this test or not.Parameters can be set on the fly also.  See According to this support question\nthe -Xmx argument for an IntelliJ junit test run will come from the maven-surefire-plugin, if it's set.This pom.xml snippetseems to pass the -Xmx1024 argument to the junit test run, with IntelliJ 2016.2.4.An eclipse specific alternative limited to the java.library.path JVM parameter allows to set it for a  specific source folder rather than for  the whole jdk as proposed in another response: For those interested on detail on why maven argline tag should be preferred to the systemProperties one, look, for example:   You can use systemPropertyVariables (java.protocol.handler.pkgs is your JVM argument name):
Java

I am implementing a class to be Serializable (so it's a value object for use w/ RMI). But I need to test it. Is there a way to do this easily?: I'm implementing the class, so it's trivial to stick Serializable in the class definition. I need to manually serialize/deserialize it to see if it works.I found this , is there a similar answer for Java?The easy way is to check that the object is an instance of  or , but that doesn't really prove that the object really is serializable.The only way to be sure is to try it for real. The simplest test is something like:and check it doesn't throw an exception. provides a rather more brief version:and again, check for the exception.You can be more rigourous still, and check that it deserializes back into something equal to the original:and so on.utility methods based on skaffman's answer:The short answer is, you can come up with some candidate objects and actually try to serialize them using the mechanism of your choice.  The test here is that no errors are encountered during marshalling/unmarshalling, and that the resulting \"rehydrated\" object is equal to the original.Alternatively, if you don't have any candidate objects, you could implement a reflection-based test that introspects the (non-static, non-transient) fields of your class to ensure that they too are Serializable.  Speaking from experience, this gets surprisingly complex surprisingly quickly, but it can be done to a reasonable extent.The downside to this latter approach is that if a field is e.g. , then you can either fail the class for not having a strictly serializable field, or simply assume that a serializable implementation of List will be used.  Neither is perfect.  (Mind you, the latter problem exists for examples too; if every example used in the test uses serializable Lists, there's nothing to prevent a non-serializable version being used by some other code in practice).You can do following test:Here is example for serializing and deserializing object to file:This code should do it...This only works for fully populated objects, if you require that any objects composed in your top level object are also serializable then they cannot be null for this test to be valid as serialization/deserialization skips the null objects
Java

I am new to Linux system and there seem to be too many Java folders. java -version gives me:When I am trying to build a Maven project , I am getting error:Could you please tell me which files I need to modify for root as well as not-root user and where exactly is java located?For all users, I would recommend placing the following line in This will update dynamically and works well with the  system. Do note though that the update will only take place in a new login shell.You could use /etc/profile or better a file like /etc/profile.d/jdk_homeYou have to remember that this file is only loaded with new login shells.. So after bash -l or a new gnome-session and that it doesn't change with new Java versions.None of the other answers were \"sticking\" for me in RHEL 7, even setting  and  directly in  or  would not work. Each time I tried to check if  was set, it would come up blank:What I had to do was set up a  in :I initially neglected the first line (the ), and it won't work without it.Now it's working:Doing what Oracle does (as a former Sun Employee I can't get used to that one)ln -s latestJavaRelease /usr/java/default\nWhere latestJavaRelease is the version that you want to usethen export JAVA_HOME=/usr/java/defaultCopy the bin file path you installed\"YOUR PATH\"open terminal and edit environment file by typing following command,\"sudo nano /etc/environment\"In this file, add the following line (replacing YOUR_PATH by the just copied path):JAVA_HOME=\"YOUR_PATH\"That should be enough to set the environment variable. Now reload this file:\"source /etc/environment\"now test it by executing:echo $JAVA_HOMEOn Linux I add this line to my ~/.profile:It's Very easy to set path in Linux . Do as follows : Open terminal and type  sudo gedit .bashrc It will ask you your password . After typing password ,it will   open the bash file . Then go to end  and type below  \n               Then save the file and exit from fileProbably a good idea to source whatever profile you edit to save having to use a fresh login.either:\nsource /etc/\nor\n. /etc/Where  is whatever profile you edited.I use the line:to my ~/.profile so it uses the base of the default java directory at login time. This is for bash.While we are up to setting JAVA_HOME, let me share some benefits of setting JAVA_HOME or any other environment variable:1) It's easy to upgrade JDK without affecting your application startup and config file which points to JAVA_HOME. you just need to download new version and make sure your JAVA_HOME points to new version of Java. This is best benefit of using environment variable or links.2) JAVA_HOME variable is short and concise instead of full path to JDK installation directory.3) JAVA_HOME variable is platform independence i.e. if your startup script uses JAVA_HOME then it can run on Windows and UNIX without any modification, you just need to set JAVA_HOME on respective operating system.Read more: This is a very simple script to solve the problemAnd for testing:
Java

When I run my project, I get numerous outputs of this error:I notice that this problem has a pattern of being asked all over the web, but with no real answers. What is a general cause for this kind of error?NoClassDefFound error is a nebulous error and is often hiding a more serious issue. It is  the same as ClassNotFoundException (which is thrown when the class is just plain not there).NoClassDefFound  indicate the class is not there, as the javadocs indicate, but it is typically thrown when, after the classloader has loaded the bytes for the class and calls \"defineClass\" on them.  Also carefully check your full stack trace for other clues or possible \"cause\" Exceptions (though your particular backtrace shows none).The first place to look when you get a NoClassDefFoundError is in the static bits of your class i.e. any initialization that takes place during the defining of the class. If this fails it will throw a NoClassDefFoundError - it's supposed to throw an ExceptionInInitializerError and indicate the details of the problem but in my experience, these are rare. It will only do the ExceptionInInitializerError the first time it tries to define the class, after that it will just throw NoClassDefFound.  So look at earlier logs.I would thus suggest looking at the code in that HibernateTransactionInterceptor line and seeing what it is requiring. It seems that it is unable to define the class SpringFactory. So maybe check the initialization code in that class, that might help. \nIf you can debug it, stop it at the last line above (17) and debug into so you can try find the exact line that is causing the exception. Also check higher up in the log, if you very lucky there might be an ExceptionInInitializerError.You're missing the necessary class definition; typically caused by required JAR not being in classpath.From :I had faced the same issue, because the jar library was copied by other Linux user(root), and the logged in user(process) did not have sufficient privilege to read the jar file content.
Java

I'm trying to implement paging using row-based limiting (for example:  and ) on a Hibernate Criteria query that has joins to other tables.Understandably, data is getting cut off randomly; and the reason for that is explained .As a solution, the page suggests using a \"second sql select\" instead of a join. How can I convert my existing criteria query (which has joins using ) to use a nested select instead?You can achieve the desired result by requesting a list of distinct ids instead of a list of distinct hydrated objects.Simply add this to your criteria:Now you'll get the correct number of results according to your row-based limiting. The reason this works is because the projection will perform the distinctness check  the sql query, instead of what a ResultTransformer does which is to filter the results for distinctness  the sql query has been performed.Worth noting is that instead of getting a list of objects, you will now get a list of ids, which you can use to hydrate objects from hibernate later.I am using this one with my codes.Simply add this to your criteria:that code will be like the select distinct * from table of the native sql. Hope this one helps.A slight improvement building on FishBoy's suggestion.It is possible to do this kind of query in one hit, rather than in two separate stages. i.e. the single query below will page distinct results correctly, and also return entities instead of just IDs.Simply use a DetachedCriteria with an id projection as a subquery, and then add paging values on the main Criteria object. It will look something like this:A small improvement to @FishBoy's suggestion is to use the id projection, so you don't have to hard-code the identifier property name.This helped me :DThe solution:works very well.I will now explain a different solution, where you can use the normal query and pagination method without having the problem of possibly duplicates or suppressed items.This Solution has the advance that it is:The complete Article can be found on Hibernate gives the possibility to define the association fetching method not only at design time but also at runtime by a query execution. So we use this aproach in conjunction with a simple relfection stuff and can also automate the process of changing the query property fetching algorithm only for collection properties.First we create a method which resolves all collection properties from the Entity Class:After doing that you can use this little helper method do advise your criteria object to change the FetchMode to SELECT on that query.Doing that is different from define the FetchMode of your entities at design time. So you can use the normal join association fetching on paging algorithms in you UI, because this is most of the time not the critical part and it is more important to have your results as quick as possible.if you want to use ORDER BY, just add:Below is the way we can do Multiple projection to perform DistinctExtraProjections.javaSample Usage:Referenced from  in some cases!\nWithout \nall query goes well!\nThis solution is bad!Another way is use SQLQuery. In my case following code works fine: In opposite to:where distinction is done in memory, after load entities!
Java

What I am trying to do is read a .java file, and pick out all of the identifiers and store them in a list.  My problem is with the .split() method.  If you run this code the way it is, you will get ArrayOutOfBounds, but if you change the delimiter from \".\" to anything else, the code works.  But I need to lines parsed by \".\" so is there another way I could accomplish this? takes a regex, and '.' has a special meaning for regexes.You (probably) want something like:Some folks seem to be having trouble getting this to work, so here is some runnable code you can use to verify correct behaviour.When splitting with a string literal delimiter, the safest way is to use the  method:As described by other answers, splitting with  is correct, but  will do this escaping for you.The argument to split is a regular expression. The period is a regular expression metacharacter that matches anything, thus every character in  is considered to be a split character, and is thrown away, and all of the empty strings between them are thrown away (because they're empty strings). The result is that you have nothing left.If you escape the period (by adding an escaped backslash before it), then you can match literal periods. ()Have you tried escaping the dot? like this:The argument to split is a regular expression.  \".\" matches anything so your delimiter to split on is anything.If performance is an issue, you should consider using  instead of .  is much much faster than , even though it is a \"legacy\" class (but not deprecated).You might be interested in the  class. However, the java docs advise that you use the .split method as StringTokenizer is a legacy class. This is  the best way to do this but, I got it done by doing something like following.   Output,   
Java

I am integrating OAuth login for Google+ on my android application, following the .According to the tutorial, I should add the Google Service plugin by adding\n dependency to top-level    in my android project.However, when I sync the gradle with the changes, I see the error as follows:In my :It seems that the android studio is not able to find google-services plugin from repositories. Does anybody have the same issue? Or, am I missing something?Any input will be greatly appreciated!Best regards,I ran into the same issue today. In the samples they use this line instead:\n\nThis works.For me I had to switch the repository to .  I was using mavenCentral and getting this error.  As soon as I switched to  it pulled the dependency down.To do this, open your  and replace each instance of  with Google updated . Where it was classpath 'com.google.gms:google-services:1.0' now reads classpath 'com.google.gms:google-services:1.3.0-beta1' like joluet suggested.Google now released the plugin v1.3.0 I was able to solve it using :For me i resolved this issue by doing following things :Apart from this make sure you have updated google play service and google repository in SDK.Hope this Helps , Cheers.As of , google released a newer version.Try adding:\nAnd don't forget to add  repository under buildscript.Thanks.I think you forgotten gradle's project level,From :Add the dependency to your  build.gradle\nAdd the plugin to your  build.gradle:\nGoogle has updated  go check it and for that you have to update your Android Studio too.I would advise you against doing what you are doing. I did it too (by following  blindly) but ended up with exceeding 65K method limit.So, you should remove the following lines from your gradle:Now import APIs of Google Plus with simple gradle import:Adding  repository to project level build.gradle helped in my case:I was trying to setup firebase for my android app when I faced this problem. Following screenshot should clarify things -Couple of things I would like to point out -\n1. Once you This line should be at the bottom of the app level gradle file. Not sure why but putting at the top did not workout for me.You maybe miss this stepHave fun.You need to check the current version as in the link below says, by now:Check this answer:We have to look for the last version in my case was: you can find a list of the versions.I got a similar problem while following the  for implementing a GCM client in Android Studio, however, the message I got was :Although I never figured out what was wrong, I simply copied my sources, resources, manifest, and keystore into a new Android Studio project. I then edited the auto-generated gradle build files for the new project by manually re-adding my dependencies.I made sure not to copy over my build files from the old project verbatim (since the source of the error likely lay in them somewhere).It is not a satisfying solution, but it worked for me and it took little time.For me adding this under  workedIf you use Android Studio, try to add google service with the IDE.Inside the  exists a  file that defines the . I suggest you to close Android Studio, then  and then import the project again. The .idea would be generated by the IDE again. For me this solution works.You should just add classpath '' to  of your  the  that has the . Hope this helps!I recently updated to Android Studio 2.3 and somehow apply plugin doesn't work. After that, I tried various ways and then what work is when I commented out app's build.gradle: and then I add this to top-level build.gradle (below ):and then it works.
Java

I want to delete an object I created, (a oval which follows you), but how would I do this? didn't work.EDIT:Okay, I'll give some more context. I'm making a small game with a oval you can control, and a oval which follows you. Now I've got files named: DrawPanel.class, this class draws everything on the screen, and handles collisions, sounds, etc. I got an enemy.class, which is the oval following the player. I got an entity.class, which is the player you can control. And if the player intersects with the follower, I want my player object to get deleted. The way I'm doing it:You should remove the references to it by assigning null or leaving the block where it was declared. After that, it will be automatically deleted by the garbage collector (not immediately, but eventually).Example 1:Example 2:Not something that you are currently looking for, but FYI: you can invoke the garbage collector with the call Your C++ is showing.There is no  in java, and all objects are created on the heap. The JVM has a garbage collector that relies on reference counts.Once there are no more references to an object, it becomes available for collection by the garbage collector.  may not do it; for example:All this does is set the reference  to null, it does not affect the object  once pointed to except to simply decrement the reference count by 1. Since  still refers to that object, it is not yet available to be collected.If you want help an object go away, set its reference to null.Setting reference to null will make it more likely that the object will be garbage collected, as long as there are no other references to the object. You don't need to delete objects in java. When there is no reference to an object, it will be collected by the garbage collector automatically.Yea, java is Garbage collected, it will delete the memory for you.You can remove the reference using .Let's say You have class :last statement will remove the reference of the object  and that object will be \"garbage collected\" by JVM.\nIt is one of the easiest ways to do this.
Java

I was wondering if there is any way to pull that in Java. I think it is not possible without native support for closures.Java 8 (released March 18th 2014) does support currying. The example Java code posted in  can be rewritten as:... which is quite nice. Personally, with Java 8 available I see little reason to use an alternative JVM language such as Scala or Clojure. They provide other language features, of course, but that's not enough to justify the transition cost and the weaker IDE/tooling/libraries support, IMO.Currying and partial application is absolutely possible in Java, but the amount of code required will probably turn you off.FWIW here is the Haskell equivalent of above Java code:: As of 2014 and Java 8, functional programming in Java is now not only possible, but also not ugly (I dare to say beautiful). See for example .Java isn't best choice, if you are going to use functional programming techniques. As missingfaktor wrote, you will have to write quite big amount of code to achieve what you want. On the other hand, you are not restricted to Java on JVM - you can use  or  which are functional languages (Scala is, in fact, both functional and OO).There are a lot of options for Currying with Java 8. Function type Javaslang and jOO\u03bb both offering Currying out of the box (I think this was an oversight in the JDK), and   has a set of static methods for Currying JDK Functions and method references. E.g.'Currying' is also available for Consumers. E.g to return a method with 3 params, and 2 of those already applied we do something similar to this requires to return a . This is not possible with java (no function pointers) but we can define and return a type that contains a function method:Now let's  a simple division. We need a :and a :Now we can do a curried division:Currying a method is always possible in Java, but it does not support it in a standard way. Trying to achieve this is complicated and makes the code pretty unreadable. Java is not the appropriate language for this.Well, , Clojure or Haskell (or any other functional programming language...) are definitely  to use for currying and other functional tricks.Having that said is certainly possible to curry with Java without the super amounts of boilerplate one might expect (well, having to be explicit about the types hurts a lot though - just take a look at the  example ;-)). The tests bellow showcase both,  a  into :as well as , although it's not really typesafe in this example:This is taken from a Proof Of Concept I've just implemented for fun before JavaOne tomorrow in an hour \"because I was bored\" ;-) The code is available here:  The general idea could be expanded to FunctionN => FunctionM, relatively easily, though \"real typesafety\" remains a problem for the partia application example and the currying example would need a hell lot of boilerplaty code in , but it's doable.All in all, it's doable, yet in Scala it's out of the box ;-)One can emulate currying with Java 7 MethodHandles:\nWhile you can do Currying in Java, it is ugly (because its not supported)  In Java is it simpler and faster to use plain loops and simple expressions. If you post an example of where you would use currying, we can suggest alternatives which do the same thing.One more take on the Java 8 possibilities:You can also define utility methods like this one:Which gives you an arguably more readable syntax:
Java

When trying to check the current version of Java in which I am running, I receive the error \"'java' is not recognized as an internal or external command, operable program or batch file.\". I am running Windows 7 OS and have downloaded the latest JDK and feel I may have accidentally deleted the java from machine as before I was able to check the Java version using the command \"java -version\". What software must I download to get Java working on my machine again? EDIT: I have managed to get Java running from my cmd again after ensuring all environment variables pointed to the current java sdk. Thank you for all answers to my question, KarenYou need to configure your environment variables,  and . must contain the path to java, and you should add  to Alternatively, you can simply add to your  the whole path to the bin folder, without the  variable, however, this makes a little more annoying when you need to have more than one java version on your machine (that way you only need to change  and don't even bother with )For Windows 7:\n1. This sets the path for the computer, not for the individual user. It may be that you're working on a computer which other developers also use, in which case you'd rather set the user variables, rather than the system variablesIt sounds like you haven't added the right directory to your path.First find out which directory you've installed Java in. For example, on my box it's in . Once you've found it, try running it directly. For example:Once you've definitely got the right version, add the  directory to your  environment variable.Note that you don't need a  environment variable, and haven't for some time. Some tools may use it - and if you're using one of those, then sure, set it - but if you're just using (say) Eclipse and the command-line / tools, you're fine without it. Yes, this has reminded me that I need to update...Step 1. Open your windows property i.e. (windows+Pause Break) then goto Advance System setting .\n2. select Advance Tab---> Env.variable --> add variable as shown in figure. \nNow Open your command prompt and check for:\n1. java 2. Javac  are executing successfully. If still error is there i.e. \"\" then check whether you have installed jdk twice. If yes then uninstall and follow above step.For me its start working after putting ,: in the starting of the  system variable path :--\nThis problem is on Windows 8.\nFirst copy your Path of java jdk - e.g. C:\\Program Files\\Java\\jdk1.7.0_51\\bin.Paste the path and add a ';' at the end - e.g. C:\\Program Files\\Java\\jdk1.7.0_51\\bin;I had the same problem. Just Install the exact bit of java as of your computer. If your PC is 64 bit then install 64 bit java. If it is 32 bit then vice versa :)if you have cygwin installed in the Windows Box, or using UNIX Shell then This will tell you whether java is in your classpath or NOT.In my case, PATH was properly SET but PATHEXT has been cleared by me by mistake with .exe extension. That why window can't find java or anything .exe application from command prompt. Hope it can help someone. I had this problem too.finally i solve it.you should enter a space between 'java' and '-'.  i.e you should enter 'java -version' in cmd.I did all of it, and it didn't work for me, but , finally, I found where I was mistaking all that time :).\nI didn't type \"space\" between java and -version.\nIt should be typed like this: java -version.\n With space between \"java\" and  \"-version\".\nNow it works for me. My solution was to put same value (path to JDK bin folder) in  and  \n 
Java

I have a problem with authorized SSL connection. I have created Struts Action that connects to external server with Client Authorized SSL certificate. In my Action I am trying to send some data to bank server but without any luck, because I have as a result from server the following error: My Method from my Action class that sends data to serverMy merchant.properties file:For the first time I thought this is a certificate problem, I converted it from .pfx to .jks, but I have the same error, with no changes.The handshake failure could have occurred due to various reasons:Since, the underlying failure cannot be pinpointed, it is better to switch on the   to enable debugging of the SSL connection established. With the debug switched on, you can pinpoint what activity in the handshake has failed.Based on the details now available, it appears that the problem is due to an incomplete certificate trust path between the certificate issued to the server, and a root CA. In most cases, this is because the root CA's certificate is absent in the trust store, leading to the situation where a certificate trust path cannot exist; the certificate is essentially untrusted by the client. Browsers can present a warning so that users may ignore this, but the same is not the case for SSL clients (like the  class, or any HTTP Client library like Apache ).Most these client classes/libraries would rely on the trust store used by the JVM for certificate validation. In most cases, this will be the  file in the JRE_HOME/lib/security directory. If the location of the trust store has been specified using the JVM system property , then the store in that path is usually the one used by the client library. If you are in doubt, take a look at your  class, and figure out the class/library it is using to make the connection.Adding the server's certificate issuing CA to this trust store ought to resolve the problem. You can refer to my  for this purpose, but the  is sufficient for this purpose.: The trust store is essentially the list of all CAs that you trust. If you put in an certificate that does not belong to a CA that you do not trust, then SSL/TLS connections to sites having certificates issued by that entity can be decrypted if the private key is available.The keystore and the truststores used by the JVM are usually listed at the very beginning, somewhat like the following:If the wrong truststore is used, then you'll need to re-import the server's certificate to the right one, or reconfigure the server to use the one listed (not recommended if you have multiple JVMs, and all of them are used for different needs).If you want to verify if the list of trust certs contains the required certs, then there is a section for the same, that starts as:You'll need to look for if the server's CA is a subject.The handshake process will have a few salient entries (you'll need to know SSL to understand them in detail, but for the purpose of debugging the current problem, it will suffice to know that a handshake_failure is usually reported in the ServerHello.A series of entries will be reported when the connection is being initialized. The first message sent by the client in a SSL/TLS connection setup is the ClientHello message, usually reported in the logs as:Note the cipher suites used. This  with the entry in your merchant.properties file, for the same convention might be employed by the bank's library. If the convention used is different, there is no cause of worry, for the ServerHello will state so, if the cipher suite is incompatible.The server responds with a ServerHello, that will indicate if the connection setup can proceed. Entries in the logs are usually of the following type:Note the cipher suite that it has chosen; this is best suite available to both the server and the client. Usually the cipher suite is not specified if there is an error. The certificate of the server (and optionally the entire chain) is sent by the server, and would be found in the entries as:If the verification of the certificate has succeeded, you'll find an entry similar to:One of the above steps would not have succeeded, resulting in the handshake_failure, for the handshake is typically complete at this stage (not really, but the subsequent stages of the handshake typically do not cause a handshake failure). You'll need to figure out which step has failed, and post the appropriate message as an update to the question (unless you've already understood the message, and you know what to do to resolve it).I don't think this solves the problem to the first questioner, but for googlers coming here for answers: On update 51, java 1.8 prohibited[1] RC4 ciphers by default, as we can see on the Release Notes page:If your server has a strong preference for this cipher (or use only this cipher) this can trigger a  on java.You can test connecting to the server enabling RC4 ciphers (first, try without  argument to see if triggers a , then set :1 - This can also happend when the client needs to present a certificate. After the server lists the certificate chain, the following can happen:\nThe server will issue a certificate request from the client. The request will list all of the certificates the server accepts.\nThis is the certificate the client is sending to the server. If there isn't a certificate in the chain and the server requires one, you'll get the handshake error here. A likely cause is the path to your certificate wasn't found.\nThe client asks the server to verify the certificate    This step will only happen if you are sending a certificate.\nThe server will respond with a verify responseInstalling Java Cryptography Extension (JCE) Unlimited Strength ( | ) will fix this bug. Unzip the file and follow the readme to install it.I have this error while I tried to use JDK 1.7.\nWhen I upgraded my JDK to jdk1.8.0_66 all started to work fine. So the simplest solution for this problem could be -  and it could start to work well.Assuming you're using the proper SSL/TLS protocols, properly configured your  and , and confirmed that there doesn't exist any issues with the certificates themselves, you may need to .As mentioned in , one possible reason you receive this error is due to incompatible cipher suites being used. By updating my  and  jars in my JDK's  folder with the ones provided in the , I was able to complete the handshake successfully.The handshake failure could be a buggy TLSv1 protocol implementation. In our case this helped with java 7:  The jvm will negotiate in this order. The servers with the latest update will do 1.2, the buggy ones will go down to v1 and that works with the similar v1 in java 7.I meet the same problem today with OkHttp client to GET a https based url. It was .You will get many detail info, the key info is listed as follows:\nThis will get what we want.I was getting this error while using Parasoft SOATest to send request XML(SOAP) .The issue was that I had  from the dropdown after adding the certificate and authenticating it.Mine was a  version incompatible error.Previously it was  I changed it  this solved my problem.I am using com.google.api http client.  When I communicate with an internal company site, I got this problem when I mistakenly used https, instead of http.  In my case moving from jdk 1.7.0_71 to jdk 1.8.0_60 fixed the error I had a similar issue; upgrading to Apache HTTPClient 4.5.3 fixed it.
Java

I'm creating a regexp for password validation to be used in a Java application as a configuration parameter.The regexp is:The password policy is:I\u2019m missing just point 5. I'm not able to have the regexp check for space, tab, carriage return, etc.Could anyone help me?Try this:Explanation:It's easy to add, modify or remove individual rules, since every rule is an independent \"module\".The  construct eats the entire string () and backtracks to the first occurrence where  can match. It succeeds if  is found, it fails otherwise. The alternative would be using a reluctant qualifier: . For a password check, this will hardly make any difference, for much longer strings it could be the more efficient variant.The most efficient variant (but hardest to read and maintain, therefore the most error-prone) would be , of course. For a regex of this length and for this purpose, I would dis-recommend doing it that way, as it has no real benefits.simple example using regexExplanations:All the previously given answers use the same (correct) technique to use a separate lookahead for each requirement.  But they contain a couple of inefficiencies and a potentially massive bug, depending on the back end that will actually use the password.I'll start with the regex from the accepted answer:First of all, since Java supports  and  I prefer to use those to make sure the entire string is validated, independently of .  This doesn't affect performance, but avoids mistakes when regexes are recycled.Checking that the password does not contain whitespace and checking its minimum length can be done in a single pass by using the all at once by putting variable quantifier  on the shorthand  that limits the allowed characters:If the provided password does contain a space, all the checks will be done, only to have the final check fail on the space.  This can be avoided by replacing all the dots with :The dot should only be used if you really want to allow any character.  Otherwise, use a (negated) character class to limit your regex to only those characters that are really permitted.  Though it makes little difference in this case,  is a very good habit.  I see far too many cases of  because the developer was too lazy to use something more appropriate than the dot.Since there's a good chance the initial tests will find an appropriate character in the first half of the password, a lazy quantifier can be more efficient:But now for the really important issue: none of the answers mentions the fact that the original question seems to be written by somebody who thinks in ASCII.  But in Java strings are Unicode.  Are non-ASCII characters allowed in passwords?  If they are, are only ASCII spaces disallowed, or should all Unicode whitespace be excluded.By default  matches only ASCII whitespace, so its inverse  matches all Unicode characters (whitespace or not) and all non-whitespace ASCII characters.  If Unicode characters are allowed but Unicode spaces are not, the  flag can be specified to make  exclude Unicode whitespace.  If Unicode characters are not allowed, then  can be used instead of  to match all ASCII characters that are not a space or a control character.Which brings us to the next potential issue: do we want to allow control characters?  The first step in writing a proper regex is to exactly specify what you want to match and what you don't.  The only 100% technically correct answer is that the password specification in the question is ambiguous because it does not state whether certain ranges of characters like control characters or non-ASCII characters are permitted or not.You should not use overly complex Regex (if you can avoid them) because they areAlthough there might be a small performance overhead in using many small regular expressions, the points above outweight it easily.I would implement like this:Password Requirement :I tested it and it worksI think this can do it also (as a simpler mode):
Java

I have a  using a  to serve several fragments. Each is a  with the following layout:When starting the activity, the soft keyboard shows. To remedy this, I did the following inside the fragment:I save the incoming  parameter from  as a way to access the window token for the main activity. This runs without error, but the keyboard doesn't get hidden from the call to  in .Originally, I tried using the inflated layout instead of , i.e:but this threw a , presumably because the fragment itself isn't an activity and doesn't have a unique window token?Is there a way to hide the soft keyboard from within a fragment, or should I create a method in the  and call it from within the fragment?As long as your Fragment creates a View, you can use the IBinder (window token) from that view  it has been attached.  For example, you can override onActivityCreated in your Fragment:Nothing but the following line of code worked for me:If you add the following attribute to your activity's manifest definition, it will completely suppress the keyboard from popping when your activity opens. Hopefully this helps:(Add to your Activity's manifest definition):Keep an instance of my root view in my classUse the view to hide the keyboardException for  though, focus of the embedded  must be hidden, instead only the first  within the embedded OnCreateView of the Fragment you want to hide the keyboard:add the following line wherever you want to hide the keyboard - inside a fragment or an activity or a method (onClick, onResume, onCreateView, etc).
Java

I just downloaded Maven and was trying to run the simple command found on the \"Maven in Five Minutes\" page (). This is the command:When I run it I get an error with SSL certificate and cannot download from the central Maven repository at . The error is \"SunCertPathBuilderException: unable to find valid certification path to requested target\". I am sitting behind a corporate firewall and have correctly configured the proxy settings for both  and  access via the  file. I doubt that everyone who downloads Maven and runs it for the first time has to import the SSL certificate of the Maven repository, so the problem must be with the proxy. Does anyone have any experience with this?Here's the stack trace in full debug mode (-X):The fact is that your maven plugin try to connect to an https remote repository\n(e.g )This is a new SSL connectivity for Maven Central was made available in august, 2014 !So please, can you verify that your settings.xml has the correct configuration.You can alternatively use the simple http maven repository like thisPlease let me know if my solution works ;)J.The answer above is a good working solution, but here's how to do it if you want to use the SSL repo:You can use the  environment variable so you don't have to worry about it again. See more info on the  variable :I just stumbled on this bug report:It appears to be the cause of our problems here.  Something with ca-certificates-java encountering an error and not fully populating cacerts.  For me, this started happening after I upgraded to 15.10 and this bug probably occurred during that process.The workaround is to execute the following command:If you check the contents of the keystore (as in my original answer), you'll now see a whole bunch more, including the needed DigiCert Global Root CA.If you went through the process in my original answer, you can clean up the key we added by running this command (assuming you did not specify a different alias):Maven will now work fine.I'd just like to expand on Andy's answer about adding the certificate and specifying a keystore.  That got me started, and combined with information elsewhere I was able to understand the problem and find another (better?) solution.Andy's answer specifies a new keystore with the Maven cert specifically.  Here, I'm going a bit more broad and adding the root certificate to the default java truststore.  This allows me to use mvn (and other java stuff) without specifying a keystore.For reference my OS is Ubuntu 15.10 with Maven 3.3.3.Basically, the default java truststore in this setup does not trust the root certificate of the Maven repo (DigiCert Global Root CA), so it needs to be added.I found it here and downloaded:Then I found the default truststore location, which resides here:You can see what certs are currently in there by running this command:When prompted, the default keystore password is \"changeit\" (but nobody ever does).In my setup, the fingerprint of \"DigiCert Global Root CA\" did not exist (DigiCert calls it \"thumbprint\" in the link above).  So here's how to add it:This should prompt if you trust the cert, say yes.Use keytool -list again to verify that the key exists.  I didn't bother to specify an alias (-alias), so it ended up like this:Then I was able to run mvn commands as normal, no need to specify keystore.This may not be the best solution. I changed my maven from 3.3.x to 3.2.x. And this issue gone.I was getting the same error about the SSL certificate when Maven tried to download the necessary modules automatically. \nAs a remedy, I was attempting to implement Luke's answer above, but found that the DigiCert Global Root CA certificate is already in Java's trusted keystore.\nWhat helped me was adding  to the Path variable (I am running Windows). And  is a JDK location, not just a JRE location, since Maven needs a JDK.\nI am not certain why it helped, but it did. I am absolutely sure that this was the only thing I changed.I actually had the same problem.when I run on my maven project, I get this certificate error by the maven tool.I followed @Andy 's Answer till the point where I downloaded the  fileafter that the rest of the answer didn't work for me but I did the following(I am running on Linux Debian machine)first of all, run:for example in my case it is:if it asks about the password, just hit enter.this command is supposed to list all the ssl certificates accepted by the java.\nwhen I ran this command, in my case I got 93 certificates for example.Now add the downloaded file  to the  file by running the following command:write your sudo password then it will ask you about the the default one is then say  that you trust this certificate.if you run the command once again, in my case, I got 94 contents of the  fileit means, it was added successfully. 
Java

I need to sort my  according to the values stored in it. The  contains the contacts name stored in phone.Also I need that the keys get automatically sorted as soon as I sort the values, or you can say the keys and values are bound together thus any changes in values should get reflected in keys.Required output:Assuming Java, you could sort hashmap just like this:Just a kick-off example. This way is more useful as it sorts the HashMap and keeps the duplicate values as well.Try below code it works fine for me. You can choose both Ascending as well as descending order In Java 8:You don't, basically. A  is fundamentally unordered. Any patterns you  see in the ordering should  be relied on.There are sorted maps such as , but they traditionally sort by key rather than value. It's relatively unusual to sort by value - especially as multiple keys can have the same value.Can you give more context for what you're trying to do? If you're really only storing numbers (as strings) for the keys, perhaps a  such as  would work for you?Alternatively, you could store two separate collections encapsulated in a single class to update both at the same time?As a kind of simple solution you can use temp TreeMap if you need just a final result:This will get you strings sorted as keys of sortedMap.I extends a TreeMap and override entrySet() and values() methods. Key and value need to be Comparable.Follow the code:Unit Tests:found a solution but not sure the performance if the map has large size, useful for normal case.
Java

For this two imports;I got this error:How can I resolve this error?That error is caused by your Eclipse configuration. You can reduce it to a warning. , use a Base64 encoder that isn't part of a non-public API. Apache Commons has , or when you're already on Java 1.8, then use .Go to Window-->Preferences-->Java-->Compiler-->Error/Warnings.\nSelect . Change it to \nChange  and  Reference and change it to warning. (or as your need.)Sure - just don't use the Sun base64 encoder/decoder. There are plenty of other options available, including  or this .Then read .Java 6 ships the . This class provides two static methods that support the same decoding & encoding:\nSince Java 8 we now have a much better  Support.Use this and you will not need an extra library, like .Yup, and sun.misc.BASE64Decoder is way slower: 9x slower than java.xml.bind.DatatypeConverter.parseBase64Binary() and 4x slower than org.apache.commons.codec.binary.Base64.decodeBase64(), at least for a small string on Java 6 OSX.Below is the test program I used. With Java 1.6.0_43 on OSX:Btw that's with commons-codec 1.4. With 1.7 it seems to get slower:Didn't test Java 7 or other OS.I had this problem on jdk1.6.0_37.\nThis is the only JDE/JRE on my system. I don't know why, but the following solved the problem:Maybe clarification in answer from   (Mar 16 at 9:00) has to do something with that.This error (or warning in later versions) occurs because you are compiling against a Java Execution Environment. This shows up as  in the Build path of your Eclipse Java project. Such environments only expose the Java standard API instead of all the classes within the runtime. This means that the classes used to  the Java standard API are not exposed.You can allow access to these particular classes using access rules, you could configure Eclipse to use the JDK directly or you could disable the error. You would however be hiding a serious error as  (see below for a short explanation).Java contains a  in the standard API since Java 1.8. See below for an example how to use it:Java 8 import statement:Java 8 example code:If Java 8 is not available a library such as  or  should be used.. Those classes are used to  Java. They have got public methods to allow instantiation from other packages. A good build environment however  protect you from using them.Using internal classes may break compatibility with future Java SE runtimes; the implementation and location of these classes can change at any time. It should be strongly discouraged to disable the error or warning.This works because you have multiple classes in different jar files. Removing and re-adding the jre lib will make the right classes be first. If you want a fundamental solution make sure you exclude the jar files with the same classes.I am using unix system. In eclipse project-> Properties -> Java Compiler -> Errors/Warning -> Forbidden Access(access rule) -> Turn it to warning/Ignore(Previously it was set to Error).I know this is very Old post. Since we don't have any thing sun.misc in maven \nwe can easily use StringUtils.newStringUtf8(Base64.encodeBase64(encVal));\nFrom org.apache.commons.codec.binary.Base64This error is because of you are importing below two classes\nimport sun.misc.BASE64Encoder; import sun.misc.BASE64Decoder;.Yeah instead of sun.misc.BASE64Encoder you can import\n .Now change the previous encode method as belowNow change the previous decode method as belowNow everything is done , you can save your program and run. It will run without showing any error.
Java

I'm dealing with a problem in my . I created some  and I did instant  with them. Then I dragged the model elements of the classes to the Class diagram. I modified the class diagram adding some operations to these classes and I tried to update the code. But I got the warning and the  have not been updated with the new operations.Could someone help me with this error?Check the version of your SDE. Versions lower than 4.2 are not well maintained. Moreover the integration capabilities have been merged with Visual Paradigm-UML now. Its Latest Version is 14.0 right now.
Java

I have been using Spring Security 3.x for handling user authentication for my projects, and so far, it has worked flawlessly.I recently received the requirements for a new project. In this project, it requires 2 sets of user authentication: one to authenticate employees against LDAP, and another to authenticate customer against database. I'm a little stumped on how to configure that in Spring Security.My initial idea was to create a login screen that has the following fields:-If the user selects \"employee\", then I want Spring Security to authenticate them against LDAP, otherwise the credential will be authenticated against database. However, the problem is the form will be submitted to  and there's no way for me to send the radio button field to my implemented custom authentication provider. My initial thought is I probably need two form submission URLs rather than relying on the default . Each URL will be handled by different authentication providers, but I'm not sure how to configure that in Spring Security.I know in Spring Security, I can configure fall back authentication, for example if LDAP authentication fails, then it will fall back to database authentication, but this is not what I'm shooting for in this new project. Can someone share how exactly I should configure this in Spring Security 3.x?Thank you.I'm trying to do the following:-The reason I want 2 different form logins is to allow me to handle the authentication differently based on the user, instead of doing a fall-back authentication. It is possible that employee and customer have same user ID, in my case.I incorporated @EasyAngel's idea, but have to replace some deprecated classes. The problem I'm currently facing is neither filter processes URLS seem registered in Spring Security because I keep getting . My gut feeling is the  bean is not wired properly, thus my custom filters are not used at all.By the way, I'm using WebSphere and I do have  property set in the server. I'm able to hit the default  without problem.Here's my complete security configuration:-I'm starting a bounty here because I can't seem to get this working for several days already... frustration is the word. I'm hoping someone will point out the problem(s), or if you can show me a better or cleaner way to handle this (in code). I'm using Spring Security 3.x. Thank you.Okay, I managed to get @Ritesh's approach to work very closely to what I wanted. I have the radiobutton that allows user to select whether they are customer or employee. It seems like this approach is working fairly well, with one problem... Here's my updated configuration. It has to be some really small tweak I need to do to prevent the authentication fall back but I can't seem to figure it out now.  Thank you.Okay, I think I have solved the problem here. Instead of having  to rely on the default , I created  for it, just like the one I created  for . These providers will then override the :-... and WALAA! It works perfectly now after several days of frustration! Hopefully, this post will be able to help somebody who is doing the same thing as I am here.You don't need to create  and  . The default one will work just fine with radio button field idea.In the custom login , you need to create different tokens for employee and customer.Here are the steps:You can define several  filters. Each of them can have different URL like  and . Here is example of the security application context that demonstrates this idea:As you can see, in this scenario you have also different s - for DB auth and LDAP. I think it's good idea to have different auth URLs for customers and employee (especially if they use different authentication strategies). You can even have different login pages for them.You can store this information in DB. For example you can have column called  in  table. You can look at my other answer (as an example):If you carefully look at  class, you will notice, that I actually test this LDAP flag and take user password either from LDAP or database.it's me again :) Can you try to use filters like this:instead of defining bean .
Java

Weld, the JSR-299 Contexts and Dependency Injection reference implementation, considers itself as a kind of successor of Spring and Guice. What makes Weld more capable for enterprise application compared to Guice? Are there any advantages or disadvantages compared to Guice? What do you think about Guice AOP compared to Weld interceptors? What about performance?In the end I decided to use Guice because I like the clean programming model which comes almost without annotations besides @Inject by default. It is much easier to use external libs with Guice than with CDI. AOP is also pretty simple with Guice.Before trying to answer your question, let me just add an important piece of information:  () was standardized by Guice and Spring projects () and is being . This covers basic DI mechanisms in terms of declaring an injection point.Now, back to the question - with the disclaimer that I have far more experience with Spring than with Guice.This is a very heavily discussed topic, and I cannot favor one over the other. Both mechanisms are very powerful but require at least a minimum understanding of the application's architecture. Also have look at  and the previously referenced . It is best to go with the right tool, but don't forget that if a developer has to work with one of these mechanisms it is a good thing if he/she understands the concept.Unfortunately I could not look into this yet, but there are a few rules I try to follow, especially when using a framework that gives you a lot of functionality without you noticing it:CDI (Weld) hasn't yet been used widely, so a comparison is hard to make. A few points:The most important feature CDI has opposed to Guice, is that it is a  part of Java EE 6.  The importance of this cannot be underestimated, as it means that CDI is the DI-standard you should use when coding web applications.A while back I had a look at the technologies to be able to determine how we could have a standard core distribution - suitably prepared - where we could add extra modules at will which could override existing functionality without having to change the core modules.  I.e. add an extra jar, and the functionality activates automatically. It turned out that the best way for us to do this for a code base used in both desktop and web applications, was to use JSR-330 annotations for our code, and then use either CDI or  Guice (SVN, coming real soon now in 3.0) as the engine. After a few projects I've found that I like the Guice configuration best instead of the opaque magic happening in Weld.  Additionally I found that the way to do what we want as described above with Weld, I have to mark the class in the extra jar as @Alternative, and then mention in beans.xml that I want the alternative class enforced (and that is not robust against refactoring).But, all in all,  JSR-330 allows us to do something which was very tedious and fragile before (because  binds so extremely tightly), and that is a great win.  I can strongly recommend looking into DI if you have any need like this. is a nice comparison. Another differentiator is that CDI is very Java EE oriented.  It provides a mechanism to  the different  together.Ie. By annotating a bean with , the bean becomes known in the unified EL (Expression Language) as ''.Then you can use it in a JSF page for instance:
Java

How is it that for a scanner object the  method returns true  while the  method returns false?Note: Based on the input file, the  method is returning the result as expected; the  does not seem to be returning the correct result.Here's the code I'm running that's creating the results below:The following is the actual content of the file that I'm passing to this scanner:The following is the end of what's printed in the console when I run my code, and includes the portion I can't make sense of:Since the scanner's delimiter is whitespace, and the  is also white space, it is possible for there to be a  in the buffer but no parseable tokens.Typically, the most common way to deal with this issue by always calling  after parsing all the tokens (e.g. numbers) in each line of your text. You need to do this when using  when reading a user's input too from . To advance the scanner past this whitespace delimiter, you must use  to clear the line delimiter. See:  is defined to be a  that matches this:The default token delimiter is this :The reason is that  checks if there are any more non-whitespace characters available.  checks to see if there is another line of text available. Your text file probably has a newline at the end of it so it has another line but no more characters that are not whitespace.Many text editors automatically add a newline to the end of a file if there isn't one already.In other words, your input file is not this (the numbers are line numbers):It is actually this:You have an empty line at the end of the file.If you take your content and save it for example into a txt file, some editors will add an empty new line to your file.The editors behave this way, because this is part of the  standard:This topic has been discussed in .Here is the documentation from the .Because of the above described facts,  will return , but  cannot find anything, which it can recognize as  and returns therefore .For additional infos see  post.You are consuming the value of , but asking for  and . , per default, returns everything to the next . So you are iterating through all whitespace seperated strings, and after each of them you are asking about the . -> ? True. ? Also true. -> ? True. ? Also true (still a whitespace left) -> ? True (Line Seperator, probably). haxNext? False, no whitespace anymore.
Java

I'm trying to verify that a (void) method is being called inside of a DAO - I'm using a commit point that sends a list of results up to that point, resets the list and continues.\n Say I have 4 things in the list and I have a commit point of 1, I would expect the \"send\" method to be called 4 times.\n I can verify that the method gets called once by writingit passes.. but I want to verify the number of times it was called. I would think thatwould be sufficient, but it says the parameters are not correct for verify. Incidentally, if I change   to   or   I get the same error. Thoughts on this?The necessary method is : is your mocked object and  is the  that describes how the mock should be verified. :You'll need these static imports from the  class in order to use the  method and these verification modes:(The class  also provides the mentioned verification modes. So you could also use this class for the static imports.)So in your case the correct syntax will be:This verifies that the method  was called  times on the mocked object. It will fail if it was called less or more than 4 times.If you just want to check, if the method has been called once, then you don't need to pass a . A simplewould be enough. It internally uses .
Java

I have a console application that after performing its tasks, must give feedback to the user, such as \"operation completed\" or \"operation failed\" and the detailed error.The thing is, if I just \"let it run\", the output message will be printed but the console will close shortly afterwards, leaving no time to read the message.As far as I remember, in C++, every console application will end with a \"press any key to exit\" or something like that. In C# I can simulate this behavior with a But how can I do it in Java? I'm using the Scanner class, but given that \"input\" is my instance of Scanner:\"Any key\" will work, except for return, which is quite a big deal here. Any pointers?In Java this would be I'd like to add that usually you'll want the program to wait only if it's connected to a console. Otherwise (like if it's a part of a ) there is no point printing a message or waiting. For that you could use Java's  like this:The problem with Java console input is that it's buffered input, and requires an enter key to continue.There are these two discussions:\n and The latter of which used  to get his problem solved.I personally haven't used it.I've put in what x4u said. Eclipse wanted a try catch block around it so I let it generate it for me.It can probably have all sorts of bells and whistles on it but I think for beginners that want a command line window not quitting this should be fine.Also I don't know how common this is (this is my first time making jar files), but it wouldn't run by itself, only via a bat file.The above is what the bat file had in the same folder. Seems to be an install issue.Eclipse tutorial came from:\nSome of the answer also came from: I used simple hack, asking windows to use cmd commands , and send it to null.You can just use  as pauseHowever any button you press except Enter you have to press Enter after that but I found it better than This  is pretty good option as it will help us run next line whenever the enter key is pressed 
Java

After searching literally 1 day on facebook and google for an up-to-date and  way to do something seemingly simple:I am looking for a step-by-step explanation to get offline_access for a user for a facebook app and then using this (session key) to retrieve offline & not within a browser friends & profile data.Preferrably doing this in the Fb Java API.Thanks.And yes I did check the facebook wiki.Update: Anyone? this:\n\ngives me offline_Access, however how to retrieve the session_key?Why can't facebook just do simple documentation, I mean there are like 600 people working there?The seemingly same question:\n\nDoes not answer how to retrieve the session keyEdit: I am still stuck with that. I guess nobody really tried such a batch access out yet...With the new Facebook Graph API, things got a bit simpler but far less well documented.  Here's what I did to be able to load my wall posts as me from a server side only (not part of a browser session) php script:Noting that the graph api and rest api return not just different structures, but also different information -- so here, I prefer the results from the rest api (the first one) even though I like being able to restrict the fields in the new graph api (the second one).Look at  in the sections \"Requesting Extended Permissions\" and \"Authenticating Users in a Web Application\" for the official (sparse) details.If you want to do this routinely, i.e. programmatically, here's the automated version of steps 2+3:Put this on your web server as \"facebook_access_token.php\":And direct users in their browsers to:\nIf you want finally want to use PHP, with the Facebook PHP SDK v3 (), it is pretty simple. To log someone with the  permission, you ask it when your generate the login URL. Here is how you do that.First you check if the user is logged in or not :If he is not, you generate the \"Login with Facebook\" URL asking for the  permission :And then display the link in your template :Then you can retrieve the offline access token and store it. To get it, call :To use the offline access token when the user is not logged in :And now you can make API calls for this user :Hope that helps !I did a tutorial not too long ago on my blog.  It doesn't require any plugins or whatnot, it is done in PHP, and I have tested it.  I did it for mainly wall posts, but after you authenticate you can use whatever function you want.EDIT: Post no longer exists.  FB API is updated anyway... You want to start by reading the  section in the authentication guide. Basically, start with this URL:Add your  () to the URL, which in OAuth parlance is :Add the   or  in OAuth parlance:Add a  which is where Facebook will redirect to after the user completes the authorization step (\"Allow\" or \"Dont Allow\", look at docs for response format or just try it out):If you follow , it will take you to a prompt, and then upon clicking Allow/Dont Allow it'll take you to a page that \"echos\" back the request. If you click Allow, you'll get a  parameter back, which you can exchange for an  by making an HTTP request to Facebook from your server, which does something along the lines of this:You need to pass in your , your  must be passed in as the , the same  as you used earlier and the  you received as the response. This will return the  enabled  for that user.One thing to keep in mind though is that even if you request  your application must gracefully handle invalid or expired access_tokens, as that can happen for various reasons.I know two solutions: Java and JavaScriptJava :\na.  servlet code (don't forget to import relevant jar's) ://You will get prompt to log in to facebook and permit the extended permissionsb. Don't forget to define your ConnectUrl(in your facebook account application) as c. make another servlet : YOUR_FaceBookCallback_SERVLET (see above) with this code:d. Use this secret session_key like this:If anybody wants the JavaScript solution(the big hole in security) write meI figured out how to \"retrieve\" the offline access infinite session key after a lot of hair-splitting, some trial and error & wondering about all the other productive ways I could have spent that time... agree facebook documentation could be a lot better  1) If you are using the facebook-java-api.. then take a look at the facebook demo site for \"mobile web\" on how to format the URL for requesting offline access\n    2) As to how get the offline session key from the session..The trick is : when facebook redirects the user to the \"next\" url right after granting offline access, you should get the facebook session \"again\"..this new session will have the infinite session key.\nhere is an example for mobile web...you should be able to figure it out for a regular website.The auth_token is used only for mobile web sites.. you may not need it for a regular web site  For session access, i had to use the loginurl provided by the facebook php api, as there seem to be 2/3 additional variables that it sends in the auth request, including return_session and session_version. Also the new php5-sdk sends the request to login.facebook.com instead of . Here's how i worked it out :To ask for authentication : Rember to include offline_access in $scope. \nOnce you are redirected to this page (after logging in to fb, and granting permissions), you will have a $_GET['session'] in json format.Just store it wherever you want (I do it in a database). The next time you wish to do something with the user's account, just use the following:After this any requests that the api makes will be via this user's access.The worst thing about the current facebook graph api is (correct me if I'm wrong) that the current api neglects the session (which seems to be a remain from the old api) in all its documentation and only talks about the access_token. But the current api (php5-sdk) has got no feature to send an actual request using only the access_token. If there is a function to start a session a session using only the access_token, I'm not aware of it.
Java

I'm getting a  with some frequency from my code.  The URL I am trying to hit is up.  The same code works for some users, but not others.  It seems like once one user starts to get this exception they continue to get the exception.Here is the stack trace:Here is a snippet from my code:Connection timeouts (assuming a local network and several client machines) typically result froma) some kind of firewall on the way that simply eats the packets without telling the sender things like \"No Route to host\"b) packet loss due to wrong network configuration or line overloadc) too many requests overloading the serverd) a small number of simultaneously available threads/processes on the server which leads to all of them being taken. This happens especially with requests that take a long time to run and may combine with c).Hope this helps.If the URL works fine in the web browser on the same machine, it might be that the Java code isn't using the HTTP proxy the browser is using for connecting to the URL.I'd recommend raising the connection timeout time before getting the output stream, like so:Where 1000 is in milliseconds (1000 milliseconds = 1 second).There is a possibility that your IP/host are blocked by the remote host, especially if it thinks you are hitting it too hard.This can be a IPv6 problem (the host publishes an IPv6 AAAA-Address and the users host thinks it is configured for IPv6 but it is actually not correctly connected). This can also be a network MTU problem, a firewall block, or the target host might publish different IP addresses (randomly or based on originators country) which are not all reachable. Or similliar network problems.You cant do much besides setting a timeout and adding good error messages (especially printing out the hosts' resolved address). If you want to make it more robust add retry, parallel trying of all addresses and also look into name resolution caching (positive and negative) on the Java platform.The reason why this happened to me was that a remote server was allowing only certain IP addressed but not its own, and I was trying to render the images from the server's URLs... so everything would simply halt, displaying the timeout error that you had... Make sure that either the server is allowing its own IP, or that you are rendering things from some remote URL that actually exists.The error message says it all: your connection timed out. This means your request did not get a response within some (default) timeframe. The reasons that no response was received is likely to be one of:a) The IP/domain or port is incorrectb) The IP/domain or port (i.e service) is downc) The IP/domain is taking longer than your default timeout to respondd) You have a firewall that is blocking requests or responses on whatever port you are usinge) You have a firewall that is blocking requests to that particular hostf) Your internet access is downg) Your live-server is down i.e in case of \"rest-API call\".Note that firewalls and port or IP blocking may be in place by your ISP
Java

If I have a  like this:and I want to obtain a collection of values sorted using natural ordering, which method is fastest?Create an instance of a sortable collection like , add the values, then sort it:Create an instance of an ordered collection like , then add the values:Note that the resulting collection is never modified, so the sorting only needs to take place once.TreeSet has a   time complexity guarantuee for  methods.\nSorting an  takes  operations, but  takes only  operation.So if you're mainly retrieving, and don't sort often,  is the better choice. If you sort often but dont retrieve that much  would be a better choice.Theoretically, sorting at the end should be faster.\nMaintaining sorted state through the process could involve additional CPU time.From the CS points of view, both operations are NlogN, but 1 sort should have lower constant.Why not use the best of both worlds? If you are never using it again, sort using a TreeSet and initialize an ArrayList with the contentsEDIT:I have created a benchmark (you can access it at ) to test the three approaches (ArrayList + Collections.sort, TreeSet and my best of both worlds approach) and mine always wins. The test file creates a map with 10000 elements, the values of which have an intentionally awful comparator, and then each of the three strategies get a chance to a) sort the data and b) iterate over it. Here is some sample output (you can test it yourselves):EDIT: I have added an aspect that logs calls to Thingy.compareTo(Thingy) and I have also added a new Strategy based on PriorityQueues that is much faster than either of the previous solutions (at least in sorting).Strangely, my approach performs best in iteration (I would have thought there would be no differences to the ArrayList approach in iteration, do I have a bug in my benchmark?)Disclaimer: I know this is probably an awful benchmark, but it helps get the point across to you and I certainly did not manipulate it to make my approach win.(The code has a dependency to apache commons / lang for the equals / hashcode / compareTo builders, but it should be easy to refactor it out)Be sure to read my comment about TreeSet at the bottom if you choose to implement B)If your app only does occasional sorts but iterates through it a lot, I'd say you're best off using a straightforward unsorted list. Sort it the once and then benefit from faster iteration. Iteration is especially fast on an array list.However if you want sort order to be guaranteed all of the time or you are possibly adding / removing elements frequently then use a sorted collection and take the hit on iteration.So in your case I would say A) is the better option. The list is sorted once, doesn't change and therefore benefits from being an array. Iteration should be very fast, especially if you  its an ArrayList and can directly use the ArrayList.get() instead of an Iterator.I'd also add that TreeSet by definition is a Set which means objects are unique. A TreeSet determines equality by using compareTo on your Comparator / Comparable. You could easily find yourself missing data if you try to add two objects whose compareTo returns a value of 0. e.g. adding \"C\", \"A\", \"B\", \"A\" to a TreeSet will return \"A\", \"B\", \"C\" uses mergeSort which has O(nlog n). has Red-Black tree underlying, basic operations has O(logn). Hence n elements has also O(nlog n). So both are same big O algorithm.
Java

I'm wondering what techniques and/or library to use to implement the functionality of the linux command \"tail -f \".  I'm essentially looking for a drop in add-on/replacement for .  Client code could look something like this:The missing piece is a reasonable implementation of .  It should be able to read parts of the file that exist before the file is opened as well as the lines that are added.  The ability to continue to read a file, and wait around until the file has some more updates for you shouldn't be that hard to accomplish in code yourself. Here's some pseudo-code:I would assume that you would want to put this type of functionality in its own Thread, so that you can sleep it and not affect any other areas of your application. You would want to expose  in a setter so that your main class / other parts of the application can safely shut the thread down without any other headaches, simply by calling  or something similar.Take a look at Apache Commons implementation of  class. It does seem to handle log rotation as well.Check , which does this logic.The main point in the code is:I've built a short implementation of \"tail -f\" in Scala some time ago: . It takes care of file rotation as well and you may define your own logic what to do when it reaches EOF or finds the file has been renamed.You may take a look and port it to Java, since actually there is nothing complex in there. Few notes: the main file is  and basically it defines  which takes care of EOF/rename and  method, which wraps  into an unbounded enumeration in . So, as soon as  ends,  requests next element from an  and another  gets created.I stumbled recently over , It is an extension of . In contrast to the other solutions this makes use of Java's NIO. Here's a short story which you could use as a pointer:I've coded TailingInputStream at work for the very same reason. It basically uses File and refreshed its contents on demand and checked against internal buffer if it has changed significantly (4kB memory stamp IIRC) and then did what the tail -f does. A bit hacky, yes, but it works perfectly and doesn't mess with Threads or anything fancy like that - it's compatible all the way back to 1.4.2 at least.That said, it was a lot easier to do than ReverseInputStream which went from file's end to start and didn't die if the file was updated on the fly...If your code only ever will have to run on Unix systems, you may be able to get away with just shelling out and calling  directly.As a more involved alternative, you could take a look at the implementation of GNU tail and port that over to Java. (I'm not sure whether this wouldn't already make your code a derivative work, though.)Just was faced with the same issue - found the \"simplest\" implementation here: .* - ready for production ;)I found this nice tail implementation.Author : amelandri Souce from : 
Java

How can I watch the contents of several variables (for example, TreeSet's) simultaneously? I can watch contents of one TreeSet, clicking on it in \"Variables\" window, but I have no idea how to do that for several variables.You can use Expressions windows: while debugging, menu window -> Show View -> Expressions, then it has place to type variables of which you need to see contentsYou can add a  for each variable you're interested in.This video does an excellent job of showing you how to set breakpoints and watch variables in the Eclipse Debugger.\nYou can do so by these ways.Add  and while debugging you can see variable in  under variable tab.\nOR\nAdd  and see in console.
Java

In theory, Dalvik executes any virtual machine byte code, created for example with the compilers of Are there already working versions of bytecode compilers for Dalvik available for other languages than Java?Scala works very well.I'm programming my Android application projects in Scala (, ), and it is pretty easy to setup the evnviroment (without IDE, using SBT as build tool).It could access every API in Android SDK, so anything you could do in Java, you could do it in Scala too.You may check this  to see how to build Android application with Scala and SBT. is a lovely but little known variant of Scheme that has existed quietly for many years and runs on both the JVM and Dalvik, .  Therefore, its output includes no extra VM and only includes explicitly imported libraries.  To the end-programmer, this means Kawa's performance and executable size are nearly identical to standard Java (ProGuard not required).Kawa also includes lots of macros (including some specific to Android APIs) that make for a nice clean syntax (assuming one is not averse to parentheses), and adds some tasty goodies on top of Scheme, like \"promises\" (lazy eval and futures in one).  The language is quite robust and well-documented, and has been actively maintained and evolving since the early days of Java. summarizes Kawa's merits with some informative examples and links.I haven't played with it but I know that Scala works.Another JVM language that works on Android is  with , both from .  also works on Android, using its Java backend.  I've written a  that should help someone get started (there are still few other examples), and  also for this purpose (although at this exact moment, it's short a few commits.  And neither are using ProGuard yet, so the  size is shocking.)Although the other posts here are cheerful about Scala-on-Android, posters in Scala forums are more concerned by Scala's ability to blow through some of Dalvik's limitations, and people who do use it say they reserve it for non-production code.  (Some discussion about Scala's problems .)  I can't say yet if Mercury has its own problems with Dalvik, but I've switched to it from Scala for the time being.The dynamically typed languages wont be possible until Dalvik supports JIT (Just In Time) compiling. I believe there is JIT support in one of the experimental Eclair branches, but it is not yet officially available/supported in Android.There is a  compiler available now which creates executables for the Android platform.With this solution, developers have access to practically the entire  and Android toolsets. This includes not only the complete set of Android widgets and a graphical designer for laying them out, but also access to the complete Android runtime. The Eclipse IDE will also build the executable and launch the Android emulator (using Run As | Android Application).
Java

I wrote a thread, it is taking too much time to execute and it seems it is not completely done. I want to stop the thread gracefully. Any help ?The  way to do it is to have the  of the Thread guarded by a  variable and set it to  from the outside when you want to stop it, something like:Once upon a time a  method existed but as the documentation statesThat's why you should have a guard..The bad part about using a flag to stop your thread is that if the thread is waiting or sleeping then you have to wait for it to finish waiting/sleeping. If you call the interrupt method on the thread then that will cause the wait or sleep call to be exited with an InterruptedException. Calling interrupt() also sets an interrupted property that you can use as a flag to check whether to quit (in the event that the thread is not waiting or sleeping). You can write the thread's run method so that the InterruptedException is caught outside whatever looping logic the thread is doing, or you can catch the exception within the loop and close to the call throwing the exception, setting the interrupt flag inside the catch block for the InterruptedException so that the thread doesn't lose track of the fact that it was interrupted. The interrupted thread can still keep control and finish processing on its own terms.Say I want to write a worker thread that does work in increments, where there's a sleep in the middle for some reason, and I don't want quitting the sleep to make processing quit without doing the remaining work for that increment, I only want it to quit if it is in-between increments:You should not kill Thread from other one. It's considered as fairly bad habit. However, there are many ways. You can use  statement from thread's  method.\nOr you can check if thread has already been interrupted and then it will cancel it's work. F.e. :Make a volatile boolean  somewhere. Then in the code that runs in the thread, regularly doTo stop the thread, set  to .I think you must do it manually this way. After all, only the code running in the thread has any idea what is and isn't graceful.You need to send a stop-message to the Thread and the Thread itself needs to take action if the message has been received. This is pretty easy, if the long-running action is inside loop:For a thread to stop itself, no one seems to have mentioned (mis)using exception:A subclass just need to override doRun() normally as you would with a Thread, and call stopSelf() whenever it feels like it wants to stop. IMO it feels cleaner than using a flag in a while loop. 
Java

What is the difference between Reader and InputStream?\nAnd when to use what?\nIf I can use Reader for reading characters why I will use inputstream, I guess to read objects?An InputStream is the raw method of getting information from a resource.  It grabs the data byte by byte without performing any kind of translation.  If you are reading image data, or any binary file, this is the stream to use.A Reader is designed for character streams.  If the information you are reading is all text, then the Reader will take care of the character decoding for you and give you unicode characters from the raw input stream.  If you are reading any type of text, this is the stream to use.You can wrap an InputStream and turn it into a Reader by using the InputStreamReader class.InputStreams are used to read bytes from a stream. So they are useful for binary data such as images, video and serialized objects.Readers on the other hand are character streams so they are best used to read character data.One accepts bytes and the other accepts characters.
Java

(for clarity and to reduce ambiguity):I'm going to start tinkering around with android apps.  I was planning on writing the in C++ using the NDK (since I have more experience in C++ and prefer it to Java) but came across the following on the :I was under the impression that you should use the language that you prefer, as long as it fits the job.  Could somebody explain why it is so heavily advised not to use C/C++ for android development?I'm going to start tinkering around with mobile apps, specifically android which is the OS of my current phone, and I was wondering if writing the app in C++ (or at least the core, then wrapping in Java) was an acceptable option.  Some background, I'm a computer science major who has taken 3 C++ courses(intro, intermediate, OOP, and am taking an STL course in the spring) and only 1 Java course(intermediate).  Because of this, I am more comfortable with C++ and prefer it to Java.  I came across the following on the :Any advice would be much appreciate.ps: many of the answers on this subject are from years ago and there are very few follow up answers that mention the NDK allowing the development of full native apps on android 2.3 and newer.Think of it this way.  You have the ability using the Java SDK to build a full working application that takes advantage of 100% of the APIs available to developers.  There is nothing you can do with the NDK that cannot be done with the SDK (from an API perspective), the NDK just provides higher performance.Now look at it in reverse.  If you choose to write an application 100% in the NDK, you can still write a fully functional application, but you are limited in the number of framework APIs you can access.  Not all of the Android framework can be accessed at the native layer; most APIs are Java only.  That's not to say that all the APIs  may need aren't available in the NDK, but nowhere near  the APIs are exposed.Beyond this, the NDK introduces platform-specific code which expands the size of your distribution.  For every device architecture you intend to support, your native code must be built into .so files (one for armv5, armv7 and x86) all packaged up into the same APK.  This duplication of executable code makes your app 3x the size (i.e. a \"fat binary\") unless you take on the task of building separate APKs for each architecture when you distribute the application.  So the deployment process becomes a bit more work if you don't want your APK to grow in size significantly.Again, while none of this is prohibits you from doing what you choose, it points out why Google describes Java as the \"preferred\" method for the majority of your code and the path of least resistance. I hope it sheds some light on why the documentation is worded the way it is.If you're only going to develop one app in your life, use the NDK.If you're aiming at learning Android development with the intention of developing more than one application during your lifetime - and want to be able to properly support them all - you're very likely to do better in the long run if you learn Java and use Android's Java SDK instead.The programmers at King use C++ for their game logic. And they seem to be doing fine judging by their turnover. In my experience, C++ is for problem solvers and Java is for problem avoiders. I love either language, but C++ is quite rewarding when you write good code. However, it may just take several moments of wizardry to get there. You could recommend C++ for Data scientists as well, who would normally get their job done by, say, Python or R. C++ can do the same with as good or not better performance, but it just takes being a genius in the language. That is why I'd never  recommend C++ to the one that wants to do it - I'd just give a heads up to the treat that they're in for. I don't see any reason to not use C++ for normal android development , If you have extensive experience in working in C++ and with complex OS like windows or any other such, then you can grasp android quickly and is not as much complicated as the other OS are. while learning java or working without learning it would be more frustrating and complex !I found this interesting article from: \nC++ was built specifically for platform independence and as such is found on every single operating system in existence. Your typical mobile user may know that Android apps are written Java and iOS apps in Objective-C, but what many don\u2019t know is that there is more C/C++ code in memory on your devices than anything else. C/C++ drives much of the technology of small devices (like the kernel, which interacts with the hardware, as well as typical run time libraries) and the telecommunications networks that enable these devices. More importantly for a development team, is that there are C/C++ interfaces and libraries for anything you need to do on any device and platform. The Android NDK toolset is a great example of full C/C++ support that was added originally for game development teams to enable them to get the best possible performance out of the device by avoiding Java and the Android Java runtime Dalvik, the virtual machine on which Android Java code is executed on. It has been regularly improved to enable every Android service.The general intent for both Java and Android is that you write the majority if not all your app in Java and use native things only when there is no other option... so everything about writing the app will lend itself to doing so in Java.You'll spare yourself a lot of aggravation in bridging between the native and Java worlds by writing in Java.As well, you will do yourself a big favor if you take the plunge and learn Java.  Not only will your Android app be the better for it, but you will expose yourself to a significantly different approach to OO and you will be a better programmer for it.Add to that the fact that you will side-step a whole bunch of security risks by writing in Java.In my mind, this is a no-brainer - use Java.I would say use java for main app. But if you have some c++ code you need to port or some library you need that is efficiently implemented in c++, then use ndk for those bits
Java

Why does Eclipse give me the warming \"Resource leak: 'in' is never closed\" in the following code?Because you don't close your ScannerAs others have said, you need to call 'close' on IO classes.  I'll add that this is an excellent spot to use the try - finally block with no catch, like this:This ensures that your Scanner is always closed, guaranteeing proper resource cleanup.Equivalently, in Java 7 or greater, you can use the \"try-with-resources\" syntax:It is telling you that you need to close the Scanner you instantiated on  with . Normally every reader should be closed.Note that if you close , you won't be able to read from it again. You may also take a look at the  class.You need call , in a  block to ensure it occurs.From the Eclipse documentation, here is  it flags this particular problem ( mine):Full explanation .You should  your Scanner when you're done with it:If you are using JDK7 or 8, you can use try-catch with resources.This will automatically close the scanner.above line will invoke Constructor of Scanner class with argument System.in, and will return a reference to newly constructed object.It is connected to a Input Stream that is connected to Keyboard, so now at run-time you can take user input to do required operation.To remove the memory leak - Generally, instances of classes that deal with I/O should be closed after you're finished with them. So at the end of your code you could add .The Scanner should be closed. It is a good practice to close Readers, Streams...and this kind of objects to free up resources and aovid memory leaks; and doing so in a finally block to make sure that they are closed up even if an exception occurs while handling those objects.adding  does not really fix the problem, it only clears out the warning.\nMaking the scanner static means it remains open forever (or until the class get's unloaded, which nearly is \"forever\"). \nThe compiler gives you no warning any more, since you told him \"keep it open forever\". But that is not what you really wanted to, since you should close resources as soon as you don't need them any more.HTH,\nManfred.I fixed it by declaring in as a private static Scanner class variable. Not sure why that fixed it but that is what eclipse recommended I do.It will close  and shut the warning.
Java

Following is the annotation codeI would like to make  an optional parameter, for exampleshould be a valid code.Seems like the first example in the  says it all ...To make it optional you can assign it a default value like that:Then it doesn't need to be specified when using the Annotation.
Java

The question is a bit theoretical, what is the cost of creating JAXB context, marshaller and unmarshaller?I've found that my code could benefit from keeping the same JAXB context and possibly the same marshaller for all marshaling operations rather than creating context and marshaller on each marshaling.So what is the cost of creating JAXB context and marshaller/unmarshaller? Is it okay to create context+marshaller for each marshaling operation or it's better to avoid it?  I'm the  lead and a member of the JAXB 2 () expert group. is thread safe and should only be created once and reused to avoid the cost of initializing the metadata multiple times.   and  are not thread safe, but are lightweight to create and could be created per operation.Ideally, you should have a singleton  and local instances of  and .  instances are thread-safe while  and  instances are  thread-safe and should never be shared across threads.It's a pity that this isn't specifically described in the javadoc. What I can tell is that Spring uses a global JAXBContext, shared between threads, whereas it creates a new marshaller for each marshalling operation, with a  in the code saying that JAXB marshallers are not necessarily thread-safe.The same is said on this page: .I would guess that creating a JAXBContext is a costly operation, because it involves scanning classes and packages for annotations. But measuring it is the best way to know.I solved this problem using shared thread safe  and thread local  \n\nwith synchronization only on 's initialization.Even better!! Based on the good solution from the post above, create the context  in the constructor, and save it instead of the class. Replace the line:with this one:And the main constructor with this one:so in the getMarshaller/getUnmarshaller you can remove this line:This improvement makes, in my case, that processing times drops from 60~70ms to just 5~10msJAXB 2.2 () has this to say, in section \"4.2 JAXBContext\":Unfortunately, the specification does not make any claims regarding thread-safety of  and . So it is best to assume they are not.I usually solve problems like this with a  class pattern. \nGiven the fact that you need a different marshaller for each Class, you can combine it with a -map pattern. To save you 15 minutes, of work. Here follows my implementation of a thread-safe Factory for Jaxb Marshallers and Unmarshallers.It allows you to access the instances as follows ...And the code you will need is a little Jaxb class that looks as follows:
Java

The only way that some JDBC drivers to return  is to do something of the following:Is there a way to do the same with ?The reason I asked if I can do the same with  consider the following scenario:In the  table there's a  which is a  (hence why you don't see it in the  String.Now, I populate the  using . I want to return . How can I achieve this?You can either use the  method taking an additional  parameterFor some JDBC drivers (for example, Oracle) you have to explicitly list the column names or indices of the generated keys:You mean something like this?   Not having a compiler by me right now, I'll answer by asking a question:Have you tried this? Does it work?Disclaimer: Obviously, I haven't compiled this, but you get the idea. is a subinterface of , so I don't see a reason why this wouldn't work, unless some JDBC drivers are buggy.
Java

I've searched for this, but couldn't find an answer and for whatever reason I was too ashamed to ask professor, due to that feeling when hundreds of people stare at you... Anyhow, my question is what's the importance of having brackets? Is it OK if I omit them? Example:vsI know both of them will work, but if I omit the brackets (which I tend to do a lot, due to visibility) will that change anything, anything at all? As I said, I know it works, I tested it dozen of times, but now some of my uni assignments are getting larger, and for some reason I have irrational fear that in the long run, this my cause some problems? Is there a reason to fear that?It won't change anything at all  the maintainability of your code. I've seen code like this:which means this:... but which  have been this:Personally I  include the brackets to reduce the possibility of confusion when reading or modifying the code.The coding conventions at every company I've worked for have required this - which is not to say that some other companies don't have different conventions...And just in case you think it would never make a difference: I had to fix a bug once which was pretty much equivalent to the code above. It was remarkably hard to spot... (admittedly this was years ago, before I'd started unit testing, which would no doubt have made it easier to diagnose).Using braces makes the code more maintainable and understandable. So you should consider them .I sometimes skip using braces on  to make the code more compact. My requirement for this is that they're  statements that are followed by a  statement, like  or . Also, I keep them in the same line to draw attention to the idiom, e.g:.They also apply to code inside loops:And to other jump-conditions from methods that are not necessarily at the top of the method body.Some languages (like Perl or Ruby) have a kind of , where braces don't apply:I consider it to be  to what I just described, but explicitly supported by the language.There is no difference. The main problem with the second version is you might end up writing this:when you update that method, thinking that  is called inside the loop. (And that leads to head-scratching debug sessions.)There is a second problem that the brace version doesn't have, and its possibly even harder to spot:So keep the braces unless you have a good reason, it is just a few keystrokes more.I don't see the point of the convention.The reason for always use braces is pretty weak, because it's supposed that a programmer knows the language syntax, and knows that an if-statement without braces applies only to the first statement following itself.if the Oracle decides that it's a \"good practice\" always write if-statement with braces, then why don't they just change the syntax?My opinion:If I write an \"without braces statement\", I always put it in a single line. Put in two lines this kind of code is weird:I don't like conventions based on such silly reasons.Added: many people in this post have agreed on the same: you should do it to improve readability. But I think do it to avoid mistakes is unnecessary.Do you consider that change a code like this:into this:would improve readability? I don't think so. It could be in a more complex if-statement. But everybody I know code this way only in simple if-statements. True to be said, the first case looks more clear.But someone thinks that there is a possibility for some programmer to do this:thinking that the statement would be part of the if. I think there is no\nneed to worry about this. Because if some programmer is capable of such,\nit would be capable of worse.I think, what should be avoided is writing an without braces if-statement in two lines like this:or nest unbraces statements like:this I agree its error prone, and it is often done by beginners. You should avoid to write complex if alike statements without braces as well.If you have a single statement you can omit the brackets, for more that one statements brackets is necessary for declaring a block of code.When you use brackets you are declaring a block of code : The brackets should be used also with only one statement when you are in a situation of nested  statement for improve readability, so for example : it is more readable written with brackets also if not necessary : If you use brackets your code is more readable.\nAnd if you need to add some operator in same block you can avoid possible errors I think that loosing curly braces is good, if you are also using  auto-format, because than your indentation is always correct, so it will be easy to spot any errors that way.Saying that leaving the curly braces out is bad, weird or unreadable is just wrong, as whole language is based on that idea, and it's pretty popular (python).But I have to say that without using a formatter it can be dangerous.Using the brackets future proofs the code against later modifications.  I've seen cases where brackets were omitted and someone later added some code and didn't put the brackets in at that time.  The result was that the code they added didn't go inside the section they thought it did.  So I think the answer is that its good practice in light of future changes to the code.  I've seen software groups adopt that as a standard, i.e. always requiring brackets even with single line blocks for that reason.For most cases, the answers mentioned so far are correct.  But there are some disadvantages to it from the security perspective of things.  Having worked in a payments team, security is a much stronger factor that motives such decisions. Lets say you have the following code:Now lets say you have this code is not working due to some internal problem.  You want to check the input.  So you make the following change:Say you fix the problem and deploy this code (and maybe the reviewer & you think this won't cause a problem since its not inside the 'Prod' condition).  Magically, your production logs now print customer credit card information that is visible to all the personnel who can see the logs.  God forbid if any of them (with malicious intent) gets hold of this data.Thus not giving a brace and a little careless coding can often lead to breach of secure information.  It is also classified as a vulnerability in JAVA by .More support for the \"always braces\" group from me.  you omit braces for single-statement loops/branches, put the statement on the same line as the control-statement,that way it's harder to forget inserting braces when the body is expanded. Still, use curlies anyway.If you remove braces, it will only read the first line of instruction. Any additional lines will not be read. If you have more than 1 line of instruction to be executed pls use curly brace - or else exception will be thrown.Only two things to consider.If you have only one statement inside the loop it is same.For example see the following code:we have only one statement in above code. so no issueHere we are having two statements but only first statement comes into inside the loop but not the second statement.If you have multiple statements under single loop you must use braces.using redundant braces to claim that code is more maintainable raises the following question: if the guys writing, wondering about and further maintaining the code have issues like the ones described before (indentation related or readability related) perhaps they should not program at all...it should be a reflex to reformat the code as well... that is of course for professional programmers in professional teams
Java

Guava provides us with great factory methods for Java types, such as .But are there also builders for java Maps?There is no such thing for HashMaps, but you can create an ImmutableMap with a builder:And if you need a mutable map, you can just feed that to the HashMap constructor.Not quite a builder, but using an initializer: This is similar to the accepted answer, but a little cleaner, in my view:There are several variations of the above method, and they are great for making static, unchanging, immutable maps.A simple map builder is trivial to write:You can use:It's not as classy and readable, but does the work. is mutable; there's no need for a builder.If you don't use Guava but want to have something like Jake Toronto suggested. You'll get ClassCastException if the args are wrong.I had a similar requirement a while back. Its nothing to do with Guava but you can do something like this to be able to cleanly construct a  using a fluent builder.Create a base class that extends Map.Then create the fluent builder with methods that suit your needs:You can then implement it like this:This is something I always wanted, especially while setting up test fixtures. Finally, I decided to write a simple fluent builder of my own that could build any Map implementation - \n
Java

Can anyone provide a simple example that explains the difference between  and  polymorphism in Java? is the polymorphism existed at run-time. Here, Java compiler does not understand which method is called at compilation time. Only JVM decides which method is called at run-time. Method overloading and method overriding using instance methods are the examples for dynamic polymorphism. is the polymorphism exhibited at compile time. Here, Java compiler knows which method is called. Method overloading and method overriding using static methods; method overriding using private or final methods are examples for static polymorphismFor more details please read \"What is Polymorphism\" (Google it).\nPolymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.Run time Polymorphism also known as method overriding. In this Mechanism by which a call to an overridden function is resolved at a Run-Time.Inside start method of CarWhich method is to be called is decided at compile-time only.Output:\nInside Collection sort metho is an example of / because method binding between method call and method definition happens at compile time and it depends on the reference of the class(reference created at compile time and goes to stack). is an example of / because method binding between method call and method definition happens at run time and it depends on the object of the class (object created at runtime and goes to the heap) .   : Same method name is  with different  type  or number of parameters in  (different signature). Targeted method call is resolved at compile time. :  Same method is  with same signature in . Type of object on which method is being invoked is not known at compile time but will be decided at run time.Generally overloading won't be considered as polymorphism. From java tutorial  :You can find good examples of polymorphim at SE documentation topics
Java

I have a j2ee application using hibernate with annotation. How do I annotate the Id field in my pojo class to set it as auto increment or auto generated. and in adding the bean do I leave that field in my bean null?and you leave it  () when persisting. ( if you use the  /  wrappers)In some cases the  strategy is resolved to  rathen than to  or , so you might want to manually set it to  or  (depending on the underlying database).It seems  +  worked for you.Do it as follows :-You can use any arbitrary name instead of kaugen.\nIt worked well, I could see below queries on consoleHibernate defines five types of identifier generation strategies: - either identity column, sequence or table depending on the underlying DB - table holding the id - identity column - sequence \u2013 the identity is copied from another entityExample using Tablefor more details, check the .FYIUsing   with a  *auto_increment* column, creates you an attribute with the following annotations:This was getting me the same an error saying the column must not be null, so i simply removed the @NotNull anotation leaving the attribute null, and it works!If you have a numeric column that you want to auto-increment, it might be an option to set  directly. This has the advantage, that the schema auto-generates the value even if it is used without hibernate. This might make your code db-specific though:
Java

Is there a way to get the path of main class of the running java program.structure isI want to get the path as .I tried  but the problem is, if I run like Is there any way to do this?By This printed out:By Note that most class files are assembled into JAR files so this won't work in every case (hence the ). However, you can locate the JAR that contains the class with this technique, and you can get the content of the class file by substituting a call to  in place of , and that will work whether the class is on the file system or in a JAR.Try this code:replace 'MyClass' with your class containing the main methodUsesee You can also split it into it's elements easilyYou actually do not want to get the path to your main class. According to your example you want to get the current working directory, i.e. directory where your program started. In this case you can just say 
Java

How can i convert a string to a ?I have seen examples like:But my strings are like:As you use Joda Time, you should use :If using Java 8 or later, then refer to Since Java 1.8, you can achieve this without an extra library:The syntax is nearly the same though.You may have to go from DateTime to LocalDate.Datetime formatting is performed by the . Three classes provide , and this is one. The others are  and .  is an immutable datetime class representing a date .  is , provided that the  is as well. All standard Chronology classes supplied are thread-safe and immutable. 
Java

I am confused about StringPool in Java. I came across this while reading the String chapter in Java. Please help me understand, in layman terms, what StringPool actually does.This prints  (even though we don't use  method: correct way to compare strings)When compiler optimizes your string literals, it sees that both  and  have same value and thus you need only one string object. It's safe because  is immutable in Java.\nAs result, both  and  point to the same object and some little memory saved.Name 'string pool' comes from the idea that all already defined string are stored in some 'pool' and before creating new  object compiler checks if such string is already defined.I don't think it actually does much, it looks like it's just a cache for string literals.  If you have multiple Strings who's values are the same, they'll all point to the same string literal in the string pool. In case 1, literal s1 is created newly and kept in the pool. But in case 2, literal s2 refer the s1, it will not create new one instead.   Let's start with a quote from the virtual machine spec: - This is a hint, that there's something special about  objects. Usually, invoking a constructor will  create a new instance of the class. This is not the case with Strings, especially when String objects are 'created' with literals. Those Strings are stored in a global store (pool) - or at least the references are kept in a pool, and whenever a new instance of an already known Strings is needed, the vm returns a reference to the object from the pool. In pseudo code, it may go like that:So in this case, variables  and  hold references to  object. IN this case, we have .This is not the case if we use the constructor:Again,  is created on the pool but then we create a new instance from the same literal, and in this case, it leads to So  do we have a String pool? Strings and especially String literals are widely used in typical Java code. And they are immutable. And being immutable allowed to cache String to save memory and increase performance (less effort for creation, less garbage to be collected).As programmers we don't have to care much about the String pool, as long as we keep in mind:When the JVM loads classes, or otherwise sees a literal string, or some code s a string, it adds the string to a mostly-hidden lookup table that has one copy of each such string.  If another copy is added, the runtime arranges it so that all the literals refer to the same string object.  This is called \"interning\".  If you say something likeit'll return , because the first and second \"test\" are actually the same object.  Comparing interned strings this way can be much,  faster than , as there's a single reference comparison rather than a bunch of  comparisons.You can add a string to the pool by calling , which will give you back the pooled version of the string (which could be the same string you're interning, but you'd be crazy to rely on that -- you often can't be sure exactly what code has been loaded and run up til now and interned the same string).  The pooled version (the string returned from ) will be equal to any identical literal.  For example:
Java

May be this is silly question. I want to get rid of the fractional part of the  number. But I cant do that. It shows the error that incompatible types. What to do? conversion in one line....please help thanksIf you really should use Double instead of double you even can get the int Value of Double by calling:Else its already described by Peter Lawreys answer.All other answer are correct, but remember that if you cast double to int you will loss decimal value.. so 2.9 double become 2 int.You can use  function or simply do :Result is: myInt = 12try casting the value
Java

As I know ,  and  are all deprecated in Java and they are replaced with , , .These will in fact return the hour, minute and second for that particular moment. However, I would want to retrieved the hours and minutes from a Date variable. For instance,say the time retrieved from database is By retrieving the hours, minutes, and seconds, I getSo, how do I use Calendar for this function? Although the  has been deprecated but it still worked. I would still like to know if there is an alternative to this.Try this:For a time difference, note that the calendar starts at 01.01.1970, 01:00, not at 00:00. If you're using java.util.Date and java.text.SimpleDateFormat, you will have to compensate for 1 hour:This will print:Duration: 1:23:45.678I recommend looking at  - much better than the standard Java Date/Calendar classes. Their documentation is quite reasonable, you could also try searching stack overflow if you need help.
Java

I have a  object. I want to determine if the type that the  object represents implements a specific interface. I was wondering how this could be achieved?I have the following code. Basically what it does is gets an array of all the classes in a specified package. I then want to go through the array and add the Class objects that implement an interface to my map. Problem is the  takes an object as a parameter. I can't instantiate an interface. So I am kind of at a loss with this. Any ideas?You should use :you can use the below function to get all the implemented interfacesYou can use  and then check to see if the interface class is in there.You can also set the instance adding \".class\"
Java

This question is related to my previous question :I want to insert counter that starts from 0 in my for loop, I've tried several combinations so far :Problem with first approach is that outer loop has 3 items and inner loop has 7 items, so for each outer item the count starts from 0. The second one I get compile error. Here is basically what I want :I'm just not totally familiar with the syntax. thank youTry the following:The  references to  which has a  method.So:You can use varStatus in your c:forEach loop In your first example you can get the counter to work properly as follows...what led me to this page is that I set within a page then the inside of an included page I did the increment and here is the problem so to solve such a problem, simply use  when you declare  the variable or the increment hope this saves your time
Java

Suppose I have an enum  with 2 possible values:  and :Now suppose I have a switch statement for this enum where I have code for both possible values:Since I have code block for both possible values of the enum, what is the usage of  in the above code?Should I throw an exception if the code somehow reaches the  block like this?It is good practice to throw an Exception as you have shown in the second example. You improve the maintainability of your code by failing fast. In this case it would mean if you later (perhaps years later) add an enum value and it reaches the switch statement you will immediately discover the error. If the default value were not set, the code would perhaps run through even with the new enum value and could possibly have undesired behavior.The other answers are correct in saying that you should implement a  branch that throws an exception, in case a new value gets added to your enum in the future. However, I would go one step further and question why you're even using a  statement in the first place.Unlike languages like C++ and C#, Java represents Enum values as actual objects, which means that you can leverage object-oriented programming. Let's say that the purpose of your method is to provide an RGB value for each color:Well, arguably, if you want each color to have an RGB value, you should include that as part of its description:That way, if you add a new color later, you're pretty much forced to provide an RGB value. It's even more fail-fast than the other approach, because you'll fail at compile-time rather than run-time.Note that you can do even more complicated things if you need to, including having each color provide its own custom implementation of an abstract method. Enums in Java are really powerful and object-oriented, and in most cases I've found I can avoid needing to  on them in the first place.Compile time completeness of the switch cases doesn't guarantee runtime completenes.Class with a switch statement compiled against an older version of enum may be executed with a newer enum version (with more values). That's a common case with library dependencies.For reasons like these, the compiler considers the  without  case incomplete.In small programs, there is no practical use for that, but think of a complex system that speards among large number of files and developers - if you define the  in one file and use it in another one, and later on someone adds a value to the  without updating the  statement, you'll find it very useful...Yes, you should do it. You may change  but don't change . In the future it'll lead to mistakes. I think that  is the good practice.If you've covered all of the possibilities with your various  and the  cannot happen, this is the classic use case for :When the enum constants are too many and you need to handle only for few cases, then the  will handle the rest of the constants.Also, enum constants are references, if the reference is not yet set, or . You may have to handle such cases too. Yes, it is dead code until someone add a value to the enum, which will make your switch statement follow the principle of 'fail fast' ()This could relates to this question : To satisfy IDEs and other static linters, I often leave the default case in as a no-op, along with a comment such as  or i.e., if the switch is doing the typical thing of handling all possible enum values, either explicitly or via fall-throughs, then the default case is probably programmer error.Depending on the application, I sometimes put an assertion in the case to guard against programmer error during development. But this has limited value in shipping code (unless you ship with assertions enabled.)Again, depending on the situation I might be convinced to throw an Error, as this is really an unrecoverable situation -- nothing the user can do will correct what is probably programmer error.Apart from the possible future extending of the enum, which was pointed out by many, some day someone may 'improve' yout  or override it in a derived class and let it return an invalid value. Of course a compiler should catch that, unless someone explicitly forces unsafe type casting...But bad things just happen, and it's a good practice not to leave any unexpected  or  path unguarded.I'm surprised nobody else mentioned this. You can cast an int to an enum and it won't throw just because the value is not one of the enumerated values. This means (among other things), the compiler cannot tell that all the enum values are in the switch.Even if you write your code correctly, this really does come up when serializing objects that contain enums. A future version might add to the enum and your code choke on reading it back, or somebody looking to create mayhem may hexedit a new value in. Either way, running off the switch rarely does the right thing. So, we throw in default unless we know better.Here is how I would handle it, beside  value which would result in a null pointer exception which you can handle.If  is not , it has to be one of the singletons in , if you assign any reference to an object that is not one of the them this will cause a Runtime error.So my solution is to account for values that are not supported... or you can consider  as unsupported tooIn this case using Assertion in default is the best practice.
Java

There is a question which was recently asked to me in an interview.: There is a class meant to profile the execution time of the code. The class is like: The client is expected to create an instance of the StopWatch and call methods accordingly. User code can mess up the use of the methods leading to unexpected results. Ex, start(), stop() and getTime() calls should be in order.This class has to be \"reconfigured\" so that user can be prevented from messing up the sequence. I proposed use of custom exception if stop() is called before start(), or doing some if/else checks, but interviewer was not satisfied. : The class members and method implementations can be modified.We commonly use StopWatch from  check the pattern how they've provided.IllegalStateException is thrown when the stop watch state is wrong.Straight forward. First there is the fact that implementing an own Java profiler is a waste of time, since good ones are available (maybe that was the intention behind the question).If you want to enforce the correct method order at compile time, you have to return something with each method in the chain:External Construction of those helper classes as well as other ways of accessing their methods have to be prevented of course.With minor changes to the interface, you can make the method sequence the only one that can be called - even at compile time!The usage is straightforward - every method returns a different class which only has the currently applicable methods. Basically, the state of the stopwatch is encapsuled in the type system.In comments, it was pointed out that even with the above design, you can call  twice. While I consider that to be added value, it is theoretically possible to screw oneself over. Then, the only way I can think of would be something like this:That differs from the assignment by omitting the  method, but that's potentially good design, too. All would then depend on the precise requirements...Maybe he expected this 'reconfiguration' and question was not about method sequence at all:In hindsight it sounds like they were looking for the . They're usually used to do things like enforce closing of streams. This is also more relevant due to this line:The idea is you give the thing that does the \"executing around\" some class to do somethings with. You'll probably use  but it's not necessary.  In your  class add some method like thisYou would then call it like thisThis makes it fool proof. You don't have to worry about handling stop before start or people forgetting to call one and not the other, etc. The reason  is nice is because(If you were using it to enforce stream closing then you could put the actions that need to be done with a database connection inside so the end user doesn't need to worry about how to open and close it and you simultaneously force them to close it properly.)If you wanted, you could make some  instead leave  unmodified. You could also make  not return a time and make  public instead.The Java 8 way to calling it is even simplerTo me something like this seems to be good.The reason I believe this to be good is the recording is during object creation so it can't be forgotten or done out of order (can't call  method if it doesn't exist).One flaw is probably the naming of . At first I thought maybe  but that usually implies a restarting or some sort (or at least recording since last lap/start). Perhaps  would be better? This mimics the action of looking at the time on a stop watch. I chose  to keep it similar to the original class.The only thing I'm not 100% sure about is how to get the time. To be honest that seems to be a more minor detail. As long as both  in the above code obtain current time the same way it should be fine.Throwing an exception when the methods are not called in the correct order is common. For example, 's  will throw an  if called twice.You should have probably explained better how the instance would know if the methods are called in the correct order. This can be done by introducing a state variable, and checking the state at the start of each method (and updating it when necessary). I suggest something like:It will be used like thisYou can't invoke anything in wrong order. And if you invoke  twice you get meaningful result both time (maybe it is better rename it to  and return actual time each time it invoked)This can also be done with Lambdas in Java 8. In this case you pass your function to the  class and then tell the  to execute that code. Presumably the reason for using a stopwatch is that the entity that's interested in the time is distinct from the entity that's responsible for starting and stopping the timing intervals.  If that is not the case, patterns using immutable objects and allowing code to query a stop watch at any time to see how much time has elapsed to date would likely be better than those using a mutable stopwatch object.If your purpose is to capture data about how much time is being spent doing various things, I would suggest that you might be best served by a class which builds a list of timing-related events.  Such a class may provide a method to generate and add a new timing-related event, which would record a snapshot of its created time and provide a method to indicate its completion.  The outer class would also provide a method to retrieve a list of all timing events registered to date.If the code which creates a new timing event supplies a parameter indicating its purpose, code at the end which examines the list could ascertain whether all events that were initiated have been properly completed, and identify any that had not; it could also identify if any events were contained entirely within others or overlapped others but were not contained within them.  Because each event would have its own independent status, failure to close one event need not interfere with any subsequent events or cause any loss or corruption of timing data related to them (as might occur if e.g. a stopwatch had been accidentally left running when it should have been stopped).While it's certainly possible to have a mutable stopwatch class which uses  and  methods, if the intention is that each \"stop\" action be associated with a particular \"start\" action, having the \"start\" action return an object which must be \"stopped\" will not only ensure such association, but it will allow sensible behavior to be achieved even if an action is started and abandoned.I know this already has been answered but couldn't find an answer invoking builder with  for the control flow so here is my solution :\n(Name the interfaces in a better way than me :p)Usage :As Per Interview question ,It seems to like thisSo now All user need to create object of StopWatch class at beginning and getTime() need to call at EndFor e.gI'm going to suggest that enforcing the method call sequence is solving the wrong problem; the real problem is a unfriendly interface where the user must be aware of the state of the stopwatch. The solution is to remove any requirement to know the state of the StopWatch.This allows a simple use of the  method with a result returned and logging included.This gives the nice result of;
Java

Is there a way to shutdown a computer using a built-in Java method?Create your own function to execute an OS  through the ?For the sake of an example. But know where and why you'd want to use this as others note.Here's another example that could work cross-platform:The specific shutdown commands may require different paths or administrative privileges.Here is an example using  :This method takes into account a whole lot more operating systems than any of the above answers. It also looks a lot nicer and is more reliable then checking the  property. It now has the option for the user to enter a delay if they like!The quick answer is no. The only way to do it is by invoking the OS-specific commands that will cause the computer to shutdown, assuming your application has the necessary privileges to do it. This is inherently non-portable, so you'd need either to know where your application will run or have different methods for different OSs and detect which one to use.I use this program to shutdown the computer in X minutes.Better use .startsWith than use .equals ... work fineRa.You can use  to do it in whatever way you'd do it with C/C++.On Windows Embedded by default there is no shutdown command in cmd.\nIn such case you need add this command manually or use function ExitWindowsEx from win32 (user32.lib) by using JNA (if you want more Java) or JNI (if easier for you will be to set priviliges in C code).easy single linebut only work on windows
Java

At the moment, i'm trying to create a Java-application which uses CUDA-functionality. The connection between CUDA and Java works fine, but i've got another problem and wanted to ask, if my thoughts about it are correct.When i call a native function from Java, i pass some data to it, the functions calculates something and returns a result. Is it possible, to let the first function return a reference (pointer) to this result which i can pass to JNI and call another function that does further calculations with the result?My idea was to reduce the overhead that comes from copying data to and from the GPU by leaving the data in the GPU memory and just passing a reference to it so other functions can use it.After trying some time, i thought for myself, this shouldn't be possible, because pointers get deleted after the application ends (in this case, when the C-function terminates). Is this correct? Or am i just to bad in C to see the solution? Edit: \nWell, to expand the question a little bit (or make it more clearly): Is memory allocated by JNI native functions deallocated when the function ends? Or may i still access it until either the JNI application ends or when i free it manually?Thanks for your input :)I used the following approach:in your JNI code, create a struct that would hold references to objects you need. When you first create this struct, return its pointer to java as a . Then, from java you just call any method with this  as a parameter, and in C cast it to a pointer to your struct. The structure will be in the heap, so it will not be cleared between different JNI calls.EDIT: I don't think you can use  long ptr =  since address is a static variable. Use it the way Gunslinger47 suggested, i.e. create new instance of class or a struct (using new or malloc) and pass its pointer.In C++ you can use any mechanism you want to allocate/free memory: the stack, malloc/free, new/delete or any other custom implementation. The only requirement is that if you allocated a block of memory with one mechanism, you have to free it with the same mechanism, so you can't call  on a stack variable and you can't call  on ed memory.JNI has its own mechanisms for allocating/freeing JVM memory:These follow the same rule, the only catch is that local refs can be deleted \"en masse\" either explicitly, with , or implicitly, when the native method exits.JNI doesn't know how you allocated your memory, so it can't free it when your function exits. Stack variables will obviously be destroyed because you're still writing C++, but your GPU memory will remain valid.The only problem then is how to access the memory on subsequent invocations, and then you can use Gunslinger47's suggestion:Java wouldn't know what to do with a pointer, but it should be able to store a pointer from a native function's return value then hand it off to another native function for it to deal with.  C pointers are nothing more than numeric values at the core.Another contibutor would have to tell you whether or not the pointed to graphics memory would be cleared between JNI invocations and if there would be any work-arounds.I know this question was already officially answered, but I'd like to add my solution:\nInstead of trying to pass a pointer, put the pointer in a Java array (at index 0) and pass that to JNI. JNI code can get and set the array element using /.In my code, I need the native layer to manage a file descriptor (an open socket). The Java class holds a  array and passes it to the native function. The native function can do whatever with it (get/set) and put back the result in the array.If you are allocating memory dynamically (on the heap) inside of the native function, it is not deleted.  In other words, you are able to retain state between different calls into native functions, using pointers, static vars, etc. Think of it a different way: what could you do safely keep in an function call, called from another C++ program?  The same things apply here.  When a function is exited, anything on the stack for that function call is destroyed; but anything on the heap is retained unless you explicitly delete it. Short answer: as long as you don't deallocate the result you're returning to the calling function, it will remain valid for re-entrance later.  Just make sure to clean it up when you're done. While the accepted answer from @denis-tulskiy does make sense, I've personnally followed suggestions from .So instead of using a pseudo-pointer type such as  (or  if you want to save some space on 32bits arch), use instead a . For example:which you can later re-use with:For very simple cases, this solution is very easy to use. Suppose you have:On the Java side, you simply need to do:Which saves you from writing  of boilerplate code ! One should however pay attention to byte ordering as explained .Its best to do this exactly how Unsafe.allocateMemory does.Create your object then type it to (uintptr_t) which is a 32/64 bit unsigned integer.This is the only correct way to do it.Here is the sanity checking Unsafe.allocateMemory does.
Java

What's the difference between those? I'm just learning Java ATM, but it seems like I can write to a file both ways i.e. (I didnt copy the try-catch block here)andI understand the concept of buffering the data first, so does that mean the first example writes the characters one by one and the second first buffers it to the memory and writes it once?thanks for the helpBufferedWriter is more efficient if youIn your example, you have only one write, so the BufferedWriter just add overhead you don't need.In both cases, the string is written at once.If you use just FileWriter your write(String) callsThis makes one system call, per call to write(String).Where BufferedWriter improves efficiency is in multiple small writes.Without a BufferedWriter this could make 200 (2 * 100) system calls and writes to disk which is inefficient. With a BufferedWriter, these can all be buffered together and as the default buffer size is 8192 characters this become just 1 system call to write.You are right. Here is how  method of  looks:As you can see it indeed checks whether the buffer is full () and flushes the buffer. Then it adds new character to buffer ().BufferedWriter is more efficient. It saves up small writes and writes in one larger chunk if memory serves me correctly. If you are doing lots of small writes then I would use BufferedWriter. Calling write calls to the OS which is slow so having as few writes as possible is usually desirable.From the Java API specification:
Java

I'm trying to set up a multi-module Maven project, and the inter-module dependencies are apparently not being set up correctly.I have:in the parent POM (which has a packaging-type pom)\nand then subdirectories commons/ and storage/ which define JAR poms with the same name.Storage depends on Commons.In the main (master) directory, I run mvn dependency:tree and see:Why does the dependency on \"commons\" fail, even though the reactor has obviously seen it because it successfully processes its dependency tree?  It should definitely not be going to the 'net to find it as it's right there...The pom for storage:Thanks for any suggestions!(Edit)To clarify, what I am looking for here is this:  I don't want to have to install module X to build module Y which depends on X, given that both are modules referenced from the same parent POM.  This makes intuitive sense to me that if I have two things in the same source tree, I shouldn't have to install intermediate products to continue the build.  Hopefully my thinking makes some sense here...I think the problem is that when you specify a dependency Maven expects to have it as jar (or whatever) packaged and available from at least a local repo. I'm sure that if you run  on your commons project first everything will work.   As discussed in , the dependency:tree goal by itself will look things up in the repository rather than the reactor.  You can work around this by mvn installing, as previously suggested, or doing something less onerous that invokes the reactor, such asWorks for me.Realizing this is an older thread but it seems that either the tool evolved or this might have been missed the first time around.It is possible to perform a build that makes dependencies resolved without installing by doing a reactor build.If you start your build in the parent that describes the module structure of your project then  your dependencies between your modules will be resolved during the build itself through the internal Maven reactor.Of course this is not the perfect solution since it does not solve the build of a single individual module within the structure.  In this case Maven will not have the dependencies in his reactor and will bee looking to resolve it in the repository.  So for individual builds you still have to install the dependencies first.Here is some  describing this situation.for me, what led me to this thread was a similar problem and the solution was to ensure all module dependency pom's hadthe parent hadpommy model dep had pom - so there was no jar to be found.The only thing that workd for me : switching to gradle :(I have and I can just cd in war1 and use mvn tomcat7:run-war. \nI always have to install the whole project before, despite war1 references his parent and the parent references war1 and dep1 (as modules) so all dependencies should be known.I don't understand what the problem is.Make sure the module which is failing to get resolved, is pointing to the right parent by including the  configurations in the pom file of the module.
Java

Are enum names interned in Java?I.e. is it guaranteed that  in case of the same name? And is it safe to compare  to a String that is guaranteed to be interned.Although there is no explicit guarantee of this, the end result is bound to be such that the comparison always succeeds for  constants with identical names:The reason for this is that Java compiler constructs subclasses of  in such a way that they end up calling 's sole protected constructor, passing it the name of  value:The name is embedded into the generated code in the form of a string literal. According to  documentation,This amounts to an implicit guarantee of your expression succeeding when names of  constants are identical. However, I would not rely on this behavior, and use  instead, because anyone reading my code would be scratching his head, thinking that I made a mistake.  is the best answer we have so far. There he says:and there they get interned, because they're string constants.But, in , there's this:So we'll call the constructor, but we aren't forced to do it in any particular way, and we can manage our own constructor in the compiler.Therefore, it's completely possible for me to write a correct and JLS-compliant Java compiler that would not intern the names somehow, probably by not having the names stored as a literals. Yes, it would do it on purpose to maliciously break your code, but it would be correct behaviour per spec.Every sane implementation will intern the strings. I'd say it's safe to  this kind of behaviour. It's not guaranteed, though, and therefore if I saw this in real code, I'd be very unsatisfied with it even if it was thoroughly described in a comment.Please, don't rely on such unspecified and implementation-specific behaviour. If you really, really have to, write a unit test for it. And put an  in the code, and lots of explaining. Measure whether your approach will actually do anything. This doesn't work reliably. See comments.With strings you're going to want to use the equals method of Strings. That aside, you already have the enum that you could compare with the equality operator. Under what scenario would this arise?That being said, yes, the .equals method will return true if they are the same.I'm not sure about equality operator, and without looking it up, I can tell you that it's poor programming to use it if it is.The Oracle documentation about Enum says (first line):If this is true then, yes, your  is guaranteed to be true if the names are the same.Also, in the method  javadoc:For example, if you had two enums,  and , where SUNDAY is a common value, == between the enum object values, SUNDAY will return true as you are comparing two strings - see the working example in .
Java

Is there any built-in method in Java to find the size of any datatype?\nIs there any way to find size?No.  There is no such method in the standard Java SE class library.The designers' view is that it is not needed in Java, since the language removes the need for an application to know about how much space needs to be reserved for a primitive value, an object or an array with a given number of elements.You might think that a sizeof operator would be useful for people that need to know how much space their data structures take.  However you can also get this information and more, simply and reliably using a Java memory profiler, so there is no need for a sizeof method.@Davor makes the point that  would be more readable than .  I'm not sure that I agree ... because I think that every Java programmer  to know that an  is  32 bits (4 bytes).  (And besides, it is rarely necessary to use the size of a type in Java code ...) However if you accept that readability argument, then the remedy is in your hands.  Simply define a class like this ...... and statically import it ...Why haven't the Java designers implemented this in standard libraries?  My guess is that:The key word in the above is .  (It does not matter what you or I think about it ... unless you have some influence in the decision making process.)There is also the issue that the next demand would be for a  method, which is fraught with technical difficulties.From the The  library is typically used for calling native shared libraries from Java.  Within this library there exist methods for determining the size of Java objects:The  method and its overloads will provide the size for most classes.Alternatively, if your classes inherit from JNA's Structure class the  method will be available.You can do bit manipulations like below to obtain the size of primitives:As mentioned , there are possibilities to get the size of primitive types through their wrappers. e.g. for a  this could be  from java 1.5 (as mentioned by  already) or  as from java 8You can use Integer.SIZE / 8, Double.SIZE / 8, etc. for primitive types from Java 1.5.The Instrumentation class has a getObjectSize() method however, you shouldn't need to use it at runtime.  The easiest way to examine memory usage is to use a profiler which is designed to help you track memory usage.I decided to create an enum without following the standard Java conventions. Perhaps you like this.The short answer is no.  The long answer is here: No. A good explanation to your question can be found here::-)I don't think it is in the java API. but most datatypes which have a number of elements in it, have a  method. I think you can easily write a function to check for size yourself?EhCache provides a  class that will try to use the  agent and will fall back to a different approach if the agent is not loaded or cannot be loaded (). Also see .There's a class/jar available on SourceForge.net that uses Java instrumentation to calculate the size of any object. Here's a link to the description: 
Java

I am trying to automate keystore generation using the Java keystore tool. The command I am using is :But after this command, user is required to enter certain inputs as follows:Instead of the user entering these values , is there any way of providing these values without user interaction ,either within the command or through a script?ThanksTry this:See the   or by typing  without any arguments.Specifically you may want to look options  don't forget -noprompt, otherwise you will be asked to input Yes or No
Java

I'm trying out Android Studio. Upon creating a new project and adding a default  method to the create MyActivity class, when I try to commit the code to Git, I get a strange error I don't understand. The code is this:The error I get is this:If I try to change the method signature to , then the IDE tells me it can't resolve the symbol .What do I need to do to get rid of the warning?It's an annotation, but the correct name is :(And also)The purpose is to allow the  to warn when certain assumptions are being violated (such as a parameter of a method that should always have a value, as in this particular case, although there are others). From the  documentation:They are tools for static analysis. Runtime behavior is not altered at all.In this case, the particular warning is that the original method you're overriding (in ) has a  annotation on the  parameter, but you did not include it in the overriding method. Just adding it should fix the issue, i.e.A number of useful  were recently added in the Android support library. Their primary role is to annotate properties of various methods and parameters to help catch bugs. For example, if you pass  value to a parameter that is marked with the  annotation you will get a warning.The annotations can be added to your project with Gradle by adding the following dependency:You are getting the warning because the  parameter is marked with the  annotation and by overriding the method the annotation gets hidden. The right thing to do is to add the annotation to the overriden method's parameter as well.In addition to the other answers, the  (and it's opponent, ) annotation annotates a field, parameter or method return type. IntelliJ and thus Android Studio can warn you for possible s at compile time.An example is best here:These annotations do not alter runtime behavior (although I have  with this), but serve as a tool for preventing bugs. Note that the message you received was not an error, but just a warning, which is safe to ignore, if you choose to. The alternative is to annotate the parameter yourself as well, as Android Studio suggests:
Java

I'm looking for a good ORM for my android application and at first glance it seems like for a mobile device I would prefer to use something simpler maybe. The thing is I'm just assuming here with no real evidence, so I thought I would ask the community's opinion (maybe there's is someone that has been through the experience). It is a fairly large(for mobile) application and will be run on a dedicated tablet.What does everyone else think ? Is Hibernate too much for an android application ? Will there be performance problems ?What would you use instead if you think it is too much ?I am aware there are other questions asking for alternatives, but I decided to ask since most of those questions simply assumed it was an overkill and asked for other options and I started wondering \"Is it really and overkill ? Why ?\" Due to my lack of experience I simply think it it, but can't really provide an answer if I'm asked to explain why. Is it performance ? Is it too much configuration (Which I don't mind) ? Thanks!I'd like to recommend my  package.  It was designed to be  less heavy compared to Hibernate (and iBatis).  I think that Hibernate  too much for Android applications -- especially considering the size of the code and the number of dependencies.  The Android port of ORMLite makes direct calls to the Android database API.  A number of applications have been delivered using ORMLite successfully.Hibernate provides a number of features that cannot be supported by the Android database calls so you will be paying for complexity that you cannot even use.  I'm also not sure it has a native Android backend.  Using SQLite over JDBC is not officially supported by Android and I was unable to get it to work reliably.Yes hibernate is too much & others have searched for alternatives.Read here:Pick yours. :-)There are quite a few questions similar to yours already. Start with:though some of those questions might be outdated by now.
Java

I currently do a lot of WPF development and have started creating some basic Android apps. When creating WPF apps I often use MVVM, normally using Prism, and would like to know if there are any examples of MVVM for the Android platform?I am the developer of . Like @Brentley said, it's a very new project but I do hope to get more buzz and experience so that it can be improved. Back to your question, I have written some simple introduction/tutorials on MVVM with android-binding:Potential adopters please also register on the I sometimes use ViewModels to translate from a pure Model to what the Model should be displayed as, but so much of the MVVM-isms come from the fact that you have this massive data binding engine built into the WPF framework.  You probably won't find the exact experience of WPF + MVVM in the Android world, but you can take a lot of the good concepts and implement them (just without the automatic data binding stuff).For one, just create ViewModels.  You don't need a framework like Prism to create ViewModels.  You don't have all the PropertyChanged notifications and stuff like that, but you can translate your data into information that can be better used by your UI which will clean up your code.  A perfect example of this is something I did with a slider-heavy UI.  Android's SeekBar is always zero based and works with integer values, so you can't bind to min, max, and increment values from your model.  You can use a ViewModel to translate your min/max values into 0-based equivalents that your SeekBar can use...just an example.  Same goes for displaying colors and sizes based on value ranges, etc.  To me, that's what ViewModels are all about.As far as DependencyInjection stuff, check out RoboGuice.  I just started using this in one of my projects after seeing a presentation by its creator at a local Meetup, and it's probably just what you're looking for.There is now an Official Android Data Binding Plugin although its still in beta at the moment. Work is also being done to add tooling support for the binding syntax in the beta version of Android Studio.See below for more informationThere is a relatively new framework being developed that allows for Views to be bound to ViewModels called . Using this framework and  you can get your MVVM on. The framework still needs some work, but it's a good starting point. library is a tool for connecting data to user interface elements. Once the layout file created and each item is tagged, one line of code binds all the data to user interface elements and saves your time for other tasks.Recently I have implemented the MVVM pattern for building an Android app with Data Binding Library. Here you can read the detailed review of the work I have done and the code fragments: To learn more about the topic, you can also have a look at these app samples:  There are visual examples of work done with the search and list screen.A few years ago I also do some WPF&WP development\uff0cPrism & MVVM Light Toolkit is commonly use to build WP App,it is perfect for windows phone application architecture I think ! so I use my previous experience of WP development then imitate to create (A toolkit help to build Android MVVM Application\uff0cWe have more attributes for Data Binding of View(like Uri for ImageView) ,we create some command for deal with event( like click of Button),also have a global message pipe to communicate with other ViewModel)., there are samples for reference.  hope to help you!There is one project called .It's free, open-source and well designed MVVM framework, developed by Stuart Lodge.He implemented binding for Android and iPhone, so now MVVM is applicable to all of these platforms too.For me it is one of the best MVVM frameworks - it really shows the power of MVVM. With it you can write one code (model and viewmodel layers) for different platforms (WP7, Android, iPhone, WinRT) and just change application UI (view layer).Just to post as a reference to other people who may be interested. I am a contributor to  - A data-binding Presentation Model framework for the Android platform. It is another framework for the same purpose. Apart from helping with project structure, one major focus for RoboBinding is to make testing android apps with normal JUnit tests possible instead of Android unit tests, as Unit tests are so important to guarantee the quality of projects, but Android unit tests take ages to run and make unit tests somewhat impractical.  itself comes with more than 300 JUnit tests to ensure its quality.  originated from Microsoft as a specialization of the Presentation Model design pattern introduced by Martin Fowler. Other alternatives: Android-Binding, Bindroid and MvvmCross.You can follow these steps for DataBinding in Fragments: I have posted design and java class both in Example for Binding Data in Fragment.I found this  App series written about MVVM using Android Data Binding library is really nice. In the series he explained from simple example to recyclerview, and there are tests as well.You can maybe try the , too.
Java

Why does this not compile, oh, what to do?error copied from comment:Just ran into this post trying to fix it for myself. Gave me just enough information to work it out.You can give the compiler just enough to persuade it to compile by casting the return value from hasItems to a (raw) Matcher, eg:Just in case anybody else is still suffering ...Edit to add:\nIn spite of the up votes, this answer is wrong, as Arend points out below. The  answer is to turn the expected into an array of Integers, as hamcrest is expecting:hasItems checks that a collection contains some items, not that 2 collections are equal, just use the normal equality assertions for that. So either assertEquals(a, b) or using assertThatAlternatively, use the contains Matcher, which checks that an Iterable contains items in a specific orderIf you don't care about the order use  instead.You are comparing  with . The correct comparison is:-- Edit --I'm sorry, I've read it wrong. Anyway, the signature of  you want is:i.e., it accepts a variable number of arguments. I'm not sure if an  is compatible, just guessing here. Try sending each item from the expected list interspersed by comma.-- Edit 2 --Just pasting here my comment, there is an equivalent expression for what you want, without using Hamcrest:Tryto satisfy the matcher signature. No Eclipse around, so this might not work.That error message looks like one produced by the javac compiler. I've found in the past that code written using hamcrest just won't compile under javac. The same code will compile fine under, say, the Eclipse compiler.I think Hamcrest's generics are exercising corner cases in generics that javac can't deal with.I just came across the same problem and the following trick worked for me:You can get this error if you try to replace jUnit's hamcrest with a newer version. For example, using junit-dep together with hamcrest 1.3 requires that use assertThat from hamcrest instead of jUnit.So the solution is to useinstead ofFor these cases when code does compile in Eclipse but javac shows errors please do help hamcrest by providing explicitly type parameter e.g.\nMatchers.hasItem()hasItems(T..t) is being expanded by the compiler to:You are passing a single element array containing an ArrayList.  If you change the ArrayList to an Array, then your code will work.This will be expanded to:
Java

I am constructing an array of bytes in java and I don't know how long the array will be.  I want some tool like Java's StringBuffer that you can just call .append(byte b) or .append(byte[] buf) and have it buffer all my bytes and return to me a byte array when I'm done.  Is there a class that does for bytes what StringBuffer does for Strings?  It does not look like the ByteBuffer class is what I'm looking for.Anyone have a good solution?Try .  You can use  and it will grow as needed.Just to extend the previous answer, you can use  and it's method , where parameters are:If you want to use it as a \"byte builder\" and insert byte by byte, you can use this:Then you can use  method to convert the array to string. The advantage is when you need to set up encoding of input, you can simply use i.e.:I wrote one that is really easy to use and avoids a lot of byte array buffer copying.It has one method called add.You can add strings, bytes, byte, long, int, double, float, short, and chars to it.The API is easy to use and somewhat fail safe. It does not allow you to copy the buffer around and does not promote having two readers. It has a bounds check mode and a I KNOW WHAT I AM DOING MODE with no bounds checking.The bounds check mode auto-grows it so there is no hassle. Here is a complete step by step guide on how to use it. It is on github.Have you ever wanted an easy to use buffer array that grow automatically and/or you can give it a fix size and just add stuff to it? I have. I wrote one too.Look.. I can write strings to it (it converts them to UTF-8).Then later I can read the String out of the buffer:I never have to set the size of the array. It will auto-grow as needed in an efficient manner.If I know exactly how large my data is going to be than I can save some bounds checking by using . If I use create exact, then I am saying... hey.. I know exactly how big it can grow to and it will never go over this number and if it does...you can hit me over the head with a sack of rocks!The following hits you over the head with a sack of rocks!\nTHROWS AN EXCEPTION!!!!You can add all sorts of primitives to your byte array.Now we just verify that we can read everything back.Once you call then you are saying that you are done with the ByteBuffer!Once you ask for the bytes, it becomes useless as it sets the internal byte array to nothing.When you call readAndReset, it is giving you its buffer. Here is my internal state, you can have it, but I am going to set it to null so nobody else uses it.It is ok. Just create another if you are sure only one instance at a time is using the buffer (byte []).You can even use the buffer you were just using as in This is because no buffer gets copied. ByteBuf writes to the buffer you give it.\nIf you want another copy to be given to ByteBuf then do this:This is boon after all. :) Come check out boon. You get the above class and idx, and idxInt and idxLong for free!Let's see. There is the ByteBuffer class in Java.It has bulk methods that transfer contiguous sequences of bytes from a byte array to hardware buffers. It would do the trick.It also has absolute and relative get and put methods that read and write byte[]s and other primitives to / for the byte buffer.It also has methods for compacting, duplicating, and slicing a byte buffer.It also has a bulk put to put an array, which is pretty close to the append you were asking for:See:\nhttp://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html#put(byte[])I wrote my own little lib for manipulating byte arrays. :)You can add them like sothis would give you all of the contents of b, and c after the contents for a.If you wanted to grow a by 21, you could do the following:If you wanted to double the size of a, you could do the following:See...CreateIndexContainsSlice:GrowShrink:Copy:Add:The add actually adds them together by using System.arraycopy (considering Unsafe, but not yet).Add one array to another:Insert:Here is a peek at a few of the methods:More....
Java

So with regex in java, I want to write a regex that will match if and only if the pattern is not preceded by certain characters. For example:I want to match if bar is not preceded by foo. So output would be:I know this is probably a very simple question. I am trying to learn regex, but in the meantime I need something to work now.You want to use  like this: ...where  means \"only if it doesn't have \"x\" before this point\"See  for more information.(edit: added the  to capture the characters before (e.g. \"beach\"))
Java

This is what I did to round a double to 2 decimal places:This works great if the amount = 25.3569 or something like that, but if the amount = 25.00 or the amount = 25.0, then I get 25.0!  What I want is both rounding as well as formatting to 2 decimal places. Are you doing money? Creating a string and then converting it back is pretty loopy.Use BigDecimal. This has been discussed quite extensively. You should have a money class and the amount should be a BigDecimal. Even if you're not doing money, consider BigDecimal.Just use: (easy as pie)The output will be 651.52Use a digit place holder (), as with '' trailing/leading zeros show as absent:  You  'round a double to [any number of] decimal places', because doubles don't have decimal places. You can convert a double to a base-10 String with N decimal places, because base-10 does have decimal places, but when you convert it back you are back in double-land, with  fractional places.You can use org.apache.commons.math.util.MathUtils from apache commonThis is the simplest i could make it but it gets the job done a lot easier than most examples ive seen.The result is 1.46.Use this String.format(\"%.2f\", doubleValue) // change 2, according to your requirement.You can use Apache Commons Math:source: Your Money class could be represented as a subclass of Long or having a member representing the money value as a native long.  Then when assigning values to your money instantiations, you will always be storing values that are actually REAL money values.  You simply output your Money object (via your Money's overridden toString() method) with the appropriate formatting. e.g $1.25 in a Money object's internal representation is 125.   You represent the money as cents, or pence or whatever the minimum denomination in the currency you are sealing with is ... then format it on output.  No you can NEVER store an 'illegal' money value, like say $1.257.double amount = 25.00;NumberFormat formatter = new DecimalFormat(\"#0.00\");System.out.println(formatter.format(amount));If you want the result to two decimal places you can doThis result is not precise but Double.toString(double) will correct for this and print one to two decimal places.  However as soon as you perform another calculation, you can get a result which will not be implicitly rounded. ;) is one answer, Presuming the amount could be positive as well as negative, rounding to two decimal places may use the following piece of code snippet.Starting java 1.8 you can do more with lambda expressions & checks for null. Also, one below can handle Float or Double & variable number of decimal points (including 2 :-)).where num is the double numberYou can try this one:orHere is an easy way that guarantee to output the  rounded to two decimal places:The result is: First declare a object of DecimalFormat class. Note the argument inside the DecimalFormat is #.00 which means exactly 2 decimal places of rounding off.private static DecimalFormat df2 = new DecimalFormat(\"#.00\");Now, apply the format in your double value:double input = 32.123456;\nSystem.out.println(\"double : \" + df2.format(input));// Output: 32.12Note in case of double input = 32.1;Then the output would be 32.10 and so on.Hope this clarifies the question.
Java

I just prepare small update for my android app, but I get this strange bug when I try to build my app (in debug mode). It will be great if someone smarter could look at this to figure out what might been wrong. I was cleaning/rebuild/fix project properties, but with no results. I have no clues what is going on :(. Maybe something similar happen to anyone here?\nIf this can help I use following libraries: adMob(4.1.1), openfeint and libgdx.here is building log:You have same jar library included twice. Check your application and all referenced Android libraries and make sure you have all jars included exactly once.If that does not help, take a look at . Specifically look at first issue described in  section. Also you can read this post: I got this error after upgrading to R17.My cause was different (ie not the *_src issue that occurred in R15).  I had two different versions of a library in my \"libs\" folder.  It appears that the Android plugin now automatically adds any jars in \"libs\" to the \"Android Dependencies\" section in the Package Explorer.  Removing the old jar fixed the problem.for bugs appeared after the SDK update to r17 you could check out this:\nCheck duplicated jar files. \nCheck lib entries in project.properties. \nClean all the included libs and build from scratch.I have the same problem and here is the solution:Go to \"Build\" in the top and \"Clean Project\" and after \"Rebuild the project\" It helps me! Also you can go to \"Files\" and Invalidate caches\" and restart the Android StudioOf corse be sure that manifest is ok and no duplicate includes!I had same issue when I added android Ocr Api (tess-two) and imported sample application which was using this API but sample application and tess-two api had same packages thats why i was facing this issue, So I removed duplicate packages from my sample application and it was working fine. I had the same problem. In my case, I had 2 jars in my libs folder, let's say A and B. A was a custom jar that I created and already had B included. This wasn't a problem until I updated to R17.\n\nSolution: I removed B from libs.Have a maps project in google_play_services/samples. Install jar from libproject to maven repository, add dependency to maps project and found that error. Using provided scope in dependency section solves the issue.
Java

I am trying to understand the real purpose of session configuration in Web.xml for session timeout.Now let me tell you about my question.My application is importing/uploading a .txt file, which is bound to take more than 1 hour, since there are millions of records to be imported.\nBut the session times out after 1 hour though my application is still importing that .txt file which is in progress.\nSuch an application should not timeout as the application is doing some task in the background.To set a session-timeout that never expires is not desirable because you would be reliable on the user to push the logout-button every time he's finished to prevent your server of too much load (depending on the amount of users and the hardware). Additionaly there are some security issues you might run into you would rather avoid.  The reason why the session gets invalidated while the server is still working on a task is because there is no communication between client-side (users browser) and server-side through e.g. a http-request. Therefore the server can't know about the users state, thinks he's idling and invalidates the session after the time set in your .  To get around this you have several possibilities:  There was a similar question asked, maybe you can adapt parts of this solution in your project. Have a look at .  Hope this helps, have Fun!You can use \"-1\" where the session never expires. Since you do not know how much time it will take for the thread to complete.Send AJAX Http Requests to the server periodically (say once for every 60 seconds) through javascript to maintain session with the server until the file upload gets completed.Hacky way:You could increase the session timeout programmatically when a large up-/download is expected.When the process ends, you could set the timeout back to its default.But.. when you are on Java EE, and the up-/download doesn't take a complete hour, the better way was to run the tasks asynchronous (via JMS e.g.).In the above code  The session will expired after  So if you want to more time. For Example  that is described your session never expires.The docs says:You can see many options as answer for your question, however you can use \"-1\" where the session never expires. Since you do not know how much time it will take for the thread to complete. E.g.:Or if you don't want a timeout happening for some purpose:Another option could be increase the number to 1000, etc, etc, bla, bla, bla.BUT IF YOU REALLY WANT TO STOP AND YOU CONSIDER THAT IS UNNECESSARY FOR YOUR APPLICATION TO FORCE THE USER TO LOGOUT, JUST ADD A LOGOUT BUTTON AND THE USER WILL DECIDE WHEN TO LEAVE.Here is what you can do to solve the problem if you do not need to force to logout, and in you are loading files that could take time base on server and your computer speed and the size of the file.Just comment it or deleted that's it! Tan tararantan, tan tan!you can declare time in two ways for this problem..1) either give too long time that your file reading is complete in between that time.2)declare time which is never expires your session.Another option I would recommend is to create a separate application that is stateless that would take the large file.  On your main app open a new window or iframe that will accept the file and send it through that window then hide the window or iframe once the upload has started using Javascript.If you don't want a timeout happening for some purpose:Should result in no timeout at all -> infiniteYou should consider splitting the large file to chunks and rely on multi threading capabilities to process more than one file at a time \nOR \nlet the whole process run as a background task using TimerTask and write another query to know the status of it form the browser including a progress bar can be shown if you can know the process time of a file or record.Usually the session will not expire when request processing is happening. I think there is an LB or something in between which reads the entire file and then invokes the web container.This might be causing a delay which is leading to expiry of the session.
Java

I am running a program that I've written in Java in Eclipse. The program has a very deep level of recursion for very large inputs. For smaller inputs the program runs fine however when large inputs are given, I get the following error:Can this be solved by increasing the Java stack size and if so, how do I do this in Eclipse?@Jon SkeetThe code is traversing a parse tree recursively in order to build up a datastructure. So, for example the code will do some work using a node in the parse tree and call itself on the node's two children, combining their results to give the overall result for the tree.The total depth of the recursion depends on the size of the parse tree but the code seems to fail (without a larger stack) when the number of recursive calls gets into the 1000s.Also I'm pretty sure the code isn't failing because of a bug as it works for small inputs.Open the  for your application (Run/Run Configurations..., then look for the applications entry in 'Java application').The  tab has a text box , enter  (or a bigger parameter for the maximum stack size). The default value is 512 kByte (SUN JDK 1.5 - don't know if it varies between vendors and versions).It  be curable by increasing the stack size - but a  solution would be to work out how to avoid recursing so much. A recursive solution can always be converted to an iterative solution - which will make your code scale to larger inputs much more cleanly. Otherwise you'll really be guessing at how much stack to provide, which may not even be obvious from the input.Are you absolutely sure it's failing due to the size of the input rather than a bug in the code, by the way? Just how deep is this recursion?EDIT: Okay, having seen the update, I would personally try to rewrite it to avoid using recursion. Generally having a  of \"things still do to\" is a good starting point to remove recursion.Add the flag  in the VM Arguments. You can also increase stack size in  by using  for example .i also have the same problem while parsing schema definition files(XSD) using XSOM library,i was able to increase Stack memory upto 208Mb then it showed  for which i was able to increase only upto 320mb.the final configuration was  but then again it ran for some time and failed.My function prints recursively the entire tree of the schema definition,amazingly the output file crossed 820Mb for a definition file of 4 Mb(Aixm library) which in turn uses 50 Mb of schema definition library(ISO gml).with that I am convinced I have to avoid Recursion and then start iteration and some other way of representing the output, but I am having little trouble converting all that recursion to iteration.You need to have a launch configuration inside Eclipse in order to adjust the JVM parameters.After running your program with either F11 or Ctrl-F11, open the launch configurations in Run -> Run Configurations... and open your program under \"Java Applications\".  Select the Arguments pane, where you will find \"VM arguments\".This is where  goes.If you want the launch configuration to be a file in your workspace (so you can right click and run it), select the Common pane, and check the Save as -> Shared File checkbox and browse to the location you want the launch file.  I usually have them in a separate folder, as we check them into CVS.When the argument  doesn't do the job try deleting the temporary files from:This did the trick for me.Look at Morris in-order tree traversal which uses constant space and runs in O(n) (up to 3 times longer than your normal recursive traversal - but you save hugely on space). If the nodes are modifiable, than you could save the calculated result of the sub-tree as you backtrack to its root (by writing directly to the Node).   
Java

Is it possible from Spring to inject the result of calling a method on a ref bean? I'm trying to refactor some cut/pasted code from two separate projects into a common class. In one of the projects, the code lives in a class I'll call \"MyClient\" that is being instantiated from Spring. It is injected with another spring-instantiated class \"MyRegistry\", then the MyClient class uses that class to look up an endpoint. All I really need is the endpoint String in my refactored class, which can be initialized via a Setter. I really cannot have a dependency on MyRegistry from MyClient in the refactored code. So, my question is this... is there a way I can inject the endpoint String from spring that was looked up in the MyRegistry class. So, I currently have:But I'd like to have (and I know this is imaginary Spring syntax)where MyRegistry will have a method getEndPoint(Stirng endPointName)Hope that makes sense from a the standpoint of what I'm trying to achieve. Please let me know if something like this is possible in Spring!The nicest solution is to use Spring 3's expression language as described by @ChssPly76, but if you're using an older version of Spring, it's almost as easy:It's possible in Spring 3.0 via :Or in Spring 2.x, by using a BeanPostProcessorAnd register your BeanPostProcessor
Java

It was very confusing to me to observe this situation:So, as I think boxing operation is executed first (i.e. java tries to extract int value from ) and comparison operation has lower priority that's why the exception is thrown.The question is: why is it implemented in this way in Java? Why boxing has higher priority then comparing references? Or why didn't they implemented verification against  before boxing? At the moment it looks inconsistent when  is thrown with wrapped primitives and is not thrown with  object types.The key point is this:The above statements hold for any given  Java code. With this understanding, there is no inconsistency whatsoever in the snippet you presented.Here are the relevant JLS sections:This explains the following:Both operands are reference types, and that's why the  is reference equality comparison.This also explains the following:For  to be numerical equality, :This explains:Here's an excerpt from :There are places where you have no choice but to use boxed primitives, e.g. generics, but otherwise you should seriously consider if a decision to use boxed primitives is justified.Your NPE example is equivalent to this code, thanks to :Hence NPE if  is .i is an Integer and the 0 is an int so in the what really is done is something like thisAnd this cause the nullPointer because the i is null. For String we do not have this operation, thats why is no exception there.The makers of Java could have defined the  operator to directly act upon operands of different types, in which case given  the comparison  could ask the question \"Does  hold a reference to an  whose value is ?\"--a question which could be answered without difficulty even when  is null.  Unfortunately, Java does not directly check whether operands of different types are equal; instead, it checks whether the language allows the type of either operand to be converted to the type of the other and--if it does--compares the converted operand to the non-converted one.  Such behavior means that for variables , , and  with some combinations of types, it's possible to have  and  but  [e.g. x=16777216f y=16777216 z=16777217].  It also means that the comparison  is translated as \"Convert I to an  and, if that doesn't throw an exception, compare it to .\"It's because of Javas  feature. The compiler detects, that on the right hand side of the comparison you're using a primitive integer and needs to unbox the wrapper Integer value into a primitive int value as well. Since that's not possible (it's null as you lined out) the  is thrown.In  Java will try to do auto-unboxing and do a numerical comparison (i.e. \"is the value stored in the wrapper object referenced by  the same as the value ?\").Since  is  the unboxing will throw a .The reasoning goes like this:The first sentence of  reads like this:Clearly  is convertible to a numeric type and  is a numeric type, so the binary numeric promotion is performed on the operands. says (among other things): says (among other things):
Java

I have code to calculate the percentage difference between 2 numbers -  - where both of the numbers are s. I expected to have to add some sort of checking / exception handling in case oldNum is 0. However, when I did a test run with values of 0.0 for both oldNum and newNum, execution continued as if nothing had happened and no error was thrown. Running this code with s would definitely cause an arithmetic division-by-zero exception. Why does Java ignore it when it comes to s?The result of division by zero is, mathematically speaking, , which can be expressed with a float/double (as  - not a number), it isn't, however, wrong in any fundamental sense.As an integer must hold a specific numerical value, an error must be thrown on division by zero when dealing with them.Java's  and  types, like pretty much any other language out there (and pretty much any hardware FP unit), implement the  standard for floating point math, which mandates division by zero to return a special \"infinity\" value. Throwing an exception would actually violate that standard.Integer arithmetic (implemented as  representation by Java and most other languages and hardware) is different and has no special infinity or NaN values, thus throwing exceptions is a useful behaviour there.The way a double is stored is quite different to an int. See  for a more detailed explanation on how Java handles double calculations. You should also read up on Floating Point numbers, in particular the concept of . If you're interested in learning more about floating point representation, I'd advise reading  (Word format, sorry). It delves into the binary representation of numbers, which may be helpful to your understanding.Though Java developers know about the double primitive type and  class, while doing floating point arithmetic they don't pay enough attention to , ,  and other rules that govern the arithmetic calculations involving them. The simple answer to this question is that it will not throw  and return . Also, note that the comparison  always evaluates to , even if  itself is a .To test if  is a , one should use the method call  to check if given number is NaN or not. This is very close to  in .It may helpful for you.
Java

In Eclipse I was able to register a set of classes for static import auto-completion, e.g. Math., EasyMock.*With this enabled I was able to hit ctrl-space assertEquals, pow, createMock etc. would appear as valid code completions.I'm struggling to find this in IntelliJ but am sure it must exist. Can anyone help?Thanks!.In the middle of the pane is the \"Packages to Use Import with '*'\" table.  You can add an entry here of a fully-qualified class name, and tick the static box; now all static methods in this class will be available for auto-completion.(I'm not sure how the static import works with specifying a package, as I've never tried it, but I don't see why it wouldn't.  Specifying a super-package and ticking the \"with subpackages\" option could be even more interesting.)If you're using IntelliJ 10, try the following:Accepting a suggestion from the resulting popup list will, by default, insert a ClassName.methodName() reference (which you can convert to a static import using an Alt-Enter intention).You can also insert a statically imported method from the completion list by choosing \"Right\" in the completion menu, and selecting \"Import Statically\":Note that once you've statically imported a single method from a class (Assert.assertSame), other static methods from that class (like Assert.assertEquals) will be included in the \"regular\" code completion (Ctrl-Space).For Intellij 12 just hit . Then to import the method statically hit . Otherwise just hitting enter will insert the fully qualified name of the method.\nSometimes just using  works too. will do the trick. You have to have the whole expression at first, and the hit  on the method you want to statically import.Just do the reference once, then put the caret on the class name (ie Math), press alt+enter and choose \"add on demand static import for 'java.lang.Math'. Intellij will addto the top of the file.In OS X you need to do a option + return.To add to what loyalBrown said in his update, all we need to do is hit  instead of Ctrl + space. (Tested on IntelliJ 13)UPDATE: Looks like you need to duck type the entire statement first, and then alt + return.
Java

I was looking over some mock  questions. I came across a really baffling syntax. Here it is:Why does the output change between  and ?The question is just playing with you with confusing spacing. is the usual  (not equals) comparison.On the other hand: is better written as  which is parsed as:Thus it's two operators.The assignment operator returns the assigned value. Therefore,  evaluates to true - which is what you print out. means : the opposite of . is actually , an assignment. It's toggling 's value. An assignment evaluates to the value of the expression, so this will evaluate to  (along with having changed the value of ). is an assignment. It assigns  to  and the expression evaluates to the resulting value, which is .b =! byou are doing an assignment, you are saying that B should have the value of !B. b != bYou are asking if B is different than b
Java

I have a Spring Boot application with dependency \"spring-boot-starter-data-jpa\". My entity class has a column annotation with column name. For example:SQL generated by this created test_name as column name. After looking for solution I have found that  solved the problem (column name is taken from column annotation).Still, my question is why without naming_strategy set to  JPA is ignoring column annotation? Maybe hibernate dialect has something to do with it? I'm connecting to MS SQL 2014 Express and my logs contains:By default Spring uses  to generate table names. This is a very thin extension of . The  method in that class is passed a source  value but it is unaware if it comes from a  attribute or if it has been implicitly generated from the field name.The  will convert  to  where as the  just uses the table name unchanged.If you don't want to change the naming strategy you could always just specify your column name in lowercase:For hibernate5 I solved this issue by puting next lines in my application.properties file:It seems that is completely ignored unless there isspecified, so to me this is a bug. I spent a few hours trying to figure out why @Column(name=\"..\") was ignored., thank you so much.\nJust an added information so, everyone bumping into this question will be able to understand why.What  said is indicated on the Spring Boot Common Properties: Apparently,  is not a supported property for Spring JPA implementation using Hibernate 5.The only solution that worked for me was the one posted by teteArg above. I'm on Spring Boot 1.4.2 w/Hibernate 5. Namely For additional insight I'm posting the call trace so that its clear what calls Spring is making into Hibernate to setup the naming strategy.The only thing that worked for me was having both lines of code as posted above:Having only the single line proposed by ncaralicea did not work for me
Java

Why does this print 1? Can we mix casting and  unary operators? I know that we can do casting multiple times, but why doesn't putting  unary operators in between produce an error?You are not adding nor substracting. Those + and - operators are unary sign operators.See  at  section.The sequence at stake: is evaluated from right to left like this:  These  and  are unary ones.More specifically, it is in fact:if you remove all casting from your example, because in this case it will do nothingwill becomenow you can see that just the operators are still there and because  your result will be 1basically you can think of it like:It is simply a consequence of the consistency of Java's grammar. When you writewhat you actually wrote is a  which decomposes into two parts: Another example of a numeric expression is a  (also unary):Therefore you can substitute this for the original  above:Repeating the same consistent process we can end up with a nested unary expression of arbitrary complexity. To return to your key question:Because Java would actually need a specific rule  such expressions. 
Java

The moment I added the android support annotations to my dependenciesI got this error:Anybody else experienced this issue? I have tried the solutions from .The problem is that  used to be a separate library containing the android annotations, but for some reason these annotations are already included in recent versions of the  file.Deleting the annotations jar solved the issue.Build->clean Project ,and it workedI deleted the android-support-v4.jar and it worked.If this is cordova / ionic project this worked for meadd these line to build.gradle under platforms/android after line number 22 i.e after Solved this exact issue in a Cordova project that used the facebook plugin.  I was able to successfully build by commenting out this line from , as shown:And by commenting out this line from , as shown:Then doing the build.  The problem started when I installed (katzer/cordova-plugin-local-notifications) which added these lines, but it created a conflict since the library it was adding to the build was already part of the facebook plugin build.If you are sure that there are no dependencies problems you can try this:If you don't find the task in your file you can add itI had the same problem , but i deleted build files from the build folderprojectname/app/buildand it removed all the related error. \"can't clean the project\" and also \"dex errow with $anim\"I managed to fix this issue. The reason was that I included the android support library 19.0.0 as a dependency, but 19.1.0 is required. So it has to be If you import  as a library project and you also have  in libs elsewhere, make sure to import everywhere  library only (it already includes this annotations lib). Then delete all  to avoid merging multiple versions of this library.Updating Android SDK Tools fixed it for me, now it just sees the copy in .I had the same problem when using ant, and the annotations library was being included automatically by an outdated .  Clean project works as a temporary fix, but the issue will reappear on next compilation error.To fix more reliably, I had to update the dependency to android  to .For me the reason was the new data-binding libit somehow used a conflicting version of the annotations lib, which I could not force with but the new  and  versions seem to have fixed it, so just use those versionsPut in your  the dependency of support-annotations according with your compileSdkVersion. For instance: A project with the  you can put the following dependence:This will solve your problem.In my case I had a file called  under  in the root project folder. I deleted this file, rebuild the project and it worked for me.I deleted the android-support-v4.jar and it worked.Explain - android-support-v4.jar is conflicting with my other .jar files of project\\libs files ** specially when you are running with java 8 on AS.Put android-support-v4.jar in your libs folder in eclipse. Clean and build the project. It will resolve the issue.Another reason that messages such as these can come up in Android Studio when building and launching can be the cause of application tags in your libraries.If you have several Android Library projects that you imported as modules.  Go into those projects and remove the  tags and everything between them.  These can cause issues in the build process along with the support library issues already mentioned.From /platforms/android/libs/\ndelete android-support-v4.jar.\nIt works for me.
Java

I've got a few classes that implement  and some of these classes contain each other as properties. I'm marshalling the classes into a  to pass them between activities. Marshalling them TO the Parcel works fine, but when I try to unmarshall them I get the following error:The  class (where it's failing):Here's the  class:: As far as I can tell it's failing at the following bit of code (from ):Why is it not able to find the class? It both exists and implements .Because this was not answered in \"answer\" but in comment I will post an answer:\nAs @Max-Gontar pointed you should use LocationType.class.getClassLoader() to get the correct ClassLoader and get rid of ClassNotFound exception, i.e.:I had the same problem with the following setup: some handler creates a Message and sends its over a Messenger to a remote service.the Message contains a Bundle where I put my Parcelable descendant:I had the same exception when the remote service tried to unparcel. In my case, I had overseen that the remote service is indeed a separate os process. Therefore, I had to set the current classloader to be used by the unparcelling process on the service side:Bundle.setClassLoader sets the classloader which is used to load the appropriate Parcelable classes. In a remote service, you need to reset it to the current class loader.I found the problem was I was not passing my applications ClassLoader to the unmarshalling function:Rather than:ORI am not very familiar with Parcelable but if it's anything like Serialization each call to write an object that implements the interface will cause a recursive call to writeToParcel(). Therefore, if something along the call stack fails or writes a null value the class that initiated the call may not be constructed correctly. Try:\nTrace the writeToParcel() call stack through all the classes starting at the first call to writeToParcel() and verify that all the values are getting sent correctly.Just adding my 2 cents here, because I lost more than half a day scratching my head on this. You might get this error if you don't put the writes methods and reads methods in the exact same order. For instance the following would be wrong:By the way the author did this correctly but it might help someone one day.I got ClassNotFoundException too and posting my solution bc the answers here led me to the right direction. My scenario is that I have nested parcelable objects. Object A contains an ArrayList of Object's B. Both implement Parcelable. \nWriting the list of B Object's in class A:Reading the list in class A:Thank you! Instead of using writeParcelable and readParcelable use writeToParcel and createFromParcel directly.  So the better code is:Well I had the same problem and solve it in a very silly way that  I dont know if its called a solution at all.lets say you have this class you want to pass to another activityThats it When I changed the:toThe problem was solved???!!!!If you have an Object with a property of type of List objects you should pass the class loader when you read the property for example:
Java

I am wondering if I am going about splitting a string on a  the right way? My code is: I only need the first part of the string that's why I return the first item. I ask because i noticed in the API that . means any character so now I'm stuck. accepts a regular expression, so you need to escape  to not consider it as a regex meta character. Here's an exemple :Split uses regular expressions, where '.' is a special character meaning anything. You need to escape it if you actually want it to match the '.' character:(one '\\' to escape the '.' in the regular expression, and the other to escape the first one in the Java string)Also I wouldn't suggest returning fn[0] since if you have a file named , which is a valid name you won't be returning the actual file name. Instead I think it's better if you use:the String#split(String) method uses regular expressions.\nIn regular expressions, the \".\" character means \"any character\".\nYou can avoid this behavior by either escaping the \".\"or telling the split method to split at at a character class:Character classes are collections of characters. You could writeand filename would be split at every \"-\", \".\", \";\", \"l\", \"d\" or \"7\". Inside character classes, the \".\" is not a special character (\"metacharacter\").You need to know few things about .  method:You also need to know that  is  in . It represents  (except line separators but this can be changed with  flag).So for string like  if we split on   method will which means we will get as result empty array  (with no elements, not even empty string), so we can't use  because there is no index 0.To solve this problem you simply need to create regex which will represents dot. To do so we need to escape that . There are few ways to do it, but simplest is probably by using  (which in String needs to be written as  because  is also special there and requires another  to be escaped).So solution to your problem may look likeYou can also use other ways to escape that dot like As DOT( . ) is considered as a special character and split method of String expects a regular expression you need to do like this - In java the special characters need to be escaped with a \"\\\" but since \"\\\" is also a special character in Java, you need to escape it again with another \"\\\" !Usually its NOT a good idea to unmask it by hand. There is a method in the Pattern class for this task:The split must be taking regex as a an argument...  Simply change  to Wouldn't it be more efficient to useif you only want what's up to the first dot? takes a regex as argument. So you should pass \".\" instead of \".\" because \".\" is a metacharacter in regex.
Java

I am receiving hex color values from a server (in this form,  , example  for black)How do I convert this to an integer value? I tried doing  to get an even more hextastic  result, but this isn't intepreted as an  here, any other suggestions?I receive an error: I am using the Android SDK for their  function, which takes - as you might have guessed - an integer color value.This is the OPPOSITE of this question: The real answer is to use: in Android,  being the  value like  or  or .However, this function  such as .I have the same problem that I found some color in form of  and I want to conver that into a form that android could make use of. \nI found that you can just use  so that android could automatically tell the color. Notice the first  is telling  value. \nHope it helpsI was facing the same problem. This way I was able to solved it. \nAs CQM said, using Color.parseColor() is a good solution to this issue.Here is the code I used:In this case my target was to change the Button's text color (Button_C) when I change the color selection from my Preferences (color_prefs). The real answer is this simplest and easiest ....Try this, create drawable in your resource...then use...with color... \"#FFFFFF\"if the color is transparent use... setAlpha with x float 0-1 Ej (0.9f)Good Luck
Java

I want to implement custom  which must look like this:So questions:This is pretty much as close as you'll get if you want to use the  APIs. I'm not sure you can place a colorstrip above the  without doing some weird  hacking, it's not worth the trouble. As far as changing the  goes, you can make those tighter via a style. It would be something like this, but I haven't tested it.If you want to customize it more than this, you may consider not using the  at all, but I wouldn't recommend that. You may also consider reading through the  to get a better idea on how to design your  If you choose to forgo the  and use your own layout instead, you should be sure to add action-able  when users long press your \"MenuItems\". This can be easily achieved .1 You can use a drawable2 Create a style for the action bar and use a custom background:3 Style again android:actionBarDividerThe  is very usefull for that.Please write following code in menu.xml file:Also write this java code in activity class file:This is the easiest way to display menus in action bar.
Java

I want to subtract two timeperiods say 16:00:00 from 19:00:00. Is there any java function for this? The results can be in milliseconds, seconds, or minutes.Difference is in milliseconds.I modified .TO get pretty timing differences, then Java 8Java 8 has a  - Instant and DurationExample:Just like any other language; convert your time periods to a unix timestamp (ie, seconds since the Unix epoch) and then simply subtract.\nThen, the resulting seconds should be used as a new unix timestamp and read formatted in whatever format you want.Ah, give the above poster (genesiss) his due credit, code's always handy ;)\nThough, you now have an explanation as well :)and, to show in a nicer format, you can use:The painful way is to convert to millis and do the subtraction and then back to whatever seconds or so you want. The better way is to use .\u0410lternative option if time from different days is taken, for example: 22:00 and 01:55.Now minutes will be the correct duration between two time (in minute).class TimeCalculator\n{\n    String updateTime;}
Java

I know that the convention in Java for boolean getters is include the prefix \"is\". But what if the subject is plural? That is, what if instead of wanting to know if a store is open, I wanted to know if all the stores are open? doesn't make sense in English.I'm tempted to write getters like:And I think that would make sense, but I've been told by others that I should just suck it up and abandon subject verb agreement and use , , . Anyway, what should I do for boolean getters which operate on a plural subject? I can't remember which book this was from, but the essence is that code will be read many more times than it's written.  Write for readability.How about having decent enough english and following Java standard: or When in doubt of the right word I always like to hit up the thesaurus.The convention is to prefix the getter-method with \"is\" not the variale itself. For the plural scenario, you know the variable is just one.e.g.andIt might not make sense from the readability point of view. But, what about the the Java convention itself? It's been set already, and way too much code has been written already to change to make it sensible according to English grammer. Lots of tools expect  or  and won't likely recognize .Try rephrasing them, like  or  or things like that for better compatibility and conventions.The Java Bean specification says to use  for getters unless it's a  then use .  is non-standard and will not be recognized by anything that expects standard Bean naming.  can also be written as  in . Its just a good habit to follow the naming conventions, help when you are working with .In general I think code should be as easily readable as possible so that a method can almost be read as a paragraph (as espoused by ). Therefore, I would name the method to sound / read as easily as possible and go with the grammer rule of . With modern IDEs it is easy to find methods without looking specifically for  / .However, Kumar makes a good point about beans. A lot of tools will only look for  / . In that case I might consider having both methods. One for ease of reading and one for tool use.In object-oriented programming, this should rarely, if ever, occur since  or  or what have you should be a separate class, with its own  or  method.  If you have a higher type, consider splitting down to the more atomic level that you're actually using.  In general, objects should not be plural at the lowest level.What language do you writing at:  or ?When I am reading Java code, I expect things to be there, having me to search for both getters, with  and  prefixes, will be more complicated than searching for just one prefix.However from other hand, when I read newspaper in the morning, I am not looking for anything, so you can write in more traditional way of English.return 0;In your question you're explicitly asking about getters. A getter returns some information about one instance of your class. For example you have a class . Now,  is a perfectly fine method name for a getter.Next, you mention a method that checks if all stores are open. This method isn't a getter at all, because it doesn't return information about one instance but for all. Of course unless there is a class . If this is the case, you should rethink your design, because Java already has ways to store a number of instances, e.g. arrays or collections, so you don't have to write extra classes.If this is not the case, then this method name is perfectly fine. An alternative may be just  without the 'is'.TL;DR: If you're dealing with multiple instances, it's not a getter. If it is, your design is bad.Quite honestly I would say definitely forget about the  and stick with . Think of the  as the variable meaning and make a better name if possible. I would say is isStoresOpen doesn't sound that bad, but you can make isStoresAreOpen if that sounds better for you. But my general idea would be to stick to the conventions. Which is using \"get\" for getters and \"is\" for boolean types. Personally I think using \"is\" is sometimes already problematic. Yes - it does look good in \"if\" conditions, but sometimes I just write \"get\" when coding and check the drop down list for my needed variable and start wondering what's wrong and why I can't find it, then I realize it starts with \"is\"... in this StoresOpen is seems like a plural,When you follow that Java Naming Convention and Java Beans Standards, they have predefined prefix's for boolean and other type, so you should follow Java Beans Naming Convention. Let's come to your point\nWhen you see  as in an English prospective, yes it looks like plural.\nOnce again take deep observation into that word, Here is plural according to English grammar,The out come of the  is not plural, instead of it is singular or you can say it is scalar in terms of programming convention.It's out come is boolean, just true or falseNot like your English plural statement  or Not an array of  or , or not a collections of  or  So, here we can say that, here we are concerned with value that is return from that boolean bean method, not the name given to the property of class to point real world entity.One more important thing is, whenever such boolean properties are used in classes and those are used by predefined libraries in any framework, then framework with use prefix '' for retrieving  boolean values, why means it's not that much of smarter than you as you know English grammar like plural/singular, multiplexer etc...
Java

Please advice how to convert a  to  using  library. What I unsuccesfully do: You don't need to use . You should be using Gson to convert to/from JSON strings and your own Java objects.See the :To do it in a simpler way, consider below:Looks like the above answer did not answer the question completely.I think you are looking for something like below:where my response is something like this:As you can see, the variable name should be same as the Json string representation of the key in the key value pair. This will automatically convert your gson string to JsonObject.I do this ,and it is worked.
Java

How do you define a field, eg  as having an index using JPA annotations. We need a non-unique key on  because there are literally millions of queries on this field per day, and its a bit slow without the key.I have seen a hibernate specific annotation but I am trying to avoid vendor specific solutions as we are still deciding between hibernate and datanucleus.UPDATE:As of JPA 2.1, you can do this. See: As far as I know, there isn't a cross-JPA-Provider way to specify indexes. However, you can always create them by hand directly in the database, most databases will pick them up automatically during query planning.With JPA 2.1 you should be able to do it.: If you ever need to create and index with two or more columns you may use commas. For example:JPA 2.1 (finally) adds support for indexes and foreign keys! See  for details. JPA 2.1 is a part of Java EE 7, which is out .If you like living on the edge, you can get the latest snapshot for eclipselink from their  (groupId:org.eclipse.persistence, artifactId:eclipselink, version:2.5.0-SNAPSHOT). For just the JPA annotations (which should work with any provider once they support 2.1) use artifactID:javax.persistence, version:2.1.0-SNAPSHOT.I'm using it for a project which won't be finished until after its release, and I haven't noticed any horrible problems (although I'm not doing anything too complex with it).UPDATE (26 Sep 2013): Nowadays release and release candidate versions of eclipselink are available in the central (main) repository, so you no longer have to add the eclipselink repository in Maven projects. The latest release version is 2.5.0 but 2.5.1-RC3 is also present. I'd switch over to 2.5.1 ASAP because of issues with the 2.5.0 release (the modelgen stuff doesn't work).Just go for one of them.I'd really like to be able to specify database indexes in a standardized way but, sadly, this is not part of the JPA specification (maybe because DDL generation support is not required by the JPA specification, which is a kind of road block for such a feature).  So you'll have to rely on a provider specific extension for that. Hibernate, OpenJPA and EclipseLink clearly do offer such an extension. I can't confirm for DataNucleus but since indexes definition is part of JDO, I guess it does.I really hope index support will get standardized in next versions of the specification and thus somehow disagree with other answers, I don't see any good reason to not include such a thing in JPA (especially since the database is not always under your control) for optimal DDL generation support.By the way, I suggest downloading the JPA 2.0 spec.In JPA 2.1 you need to do the followingIn the above example the table TEST_PERSON will have 3 indexes: Note 1: You get the compound index by having two @Index annotations with the same nameNote 2: You specify the column name in the columnList not the fieldNameOpenJPA allows you to specify non-standard annotation to define index on property.Details are .EclipseLink provided an annotation (e.g. ) to define an index on columns.  There is an  of its use.  Part of the example is included...The firstName and lastName fields are indexed, together and individually.To sum up the other answers:I would just go for one of them. It will come with JPA 2.1 anyway and should not be too hard to change in the case that you really want to switch your JPA provider.It's not possible to do that using JPA annotation. And this make sense: where a UniqueConstraint clearly define a business rules, an index is just a way to make search faster. So this should really be done by a DBA.This solution is for EclipseLink 2.5, and it works (tested):This assumes ascendant order.
Java

I would like to get a list of files with a specific extension in a directory. In the API (Java 6), I see a method  which would do this.Since I need a specific extension, I created a . However I get a compilation error when I use  with this. I assumed that since , I should be able to do this. Code follows:The last line shows a compilation error:I am trying to use , not . Why does the compiler not recognize this?This works if I write my own extension filter extending . I would rather use  than write my own. What am I doing wrong?The  class is intended for  to be used in a .Try using a  instead. For example:Is there a specific reason you want to use ?  I know this works..  One-liner in java 8 syntax: Duh.... listFiles requires java.io.FileFilter. FileNameExtensionFilter extends javax.swing.filechooser.FileFilter. I solved my problem by implementing an instance of java.io.FileFilterEdit: I did use something similar to @cFreiner's answer. I was trying to use a Java API method instead of writing my own implementation which is why I was trying to use FileNameExtensionFilter. I have many FileChoosers in my application and have used FileNameExtensionFilters for that and I mistakenly assumed that it was also extending java.io.FileFilter. Here's something I quickly just made and it should perform far better than File.getName().endsWith(\".xxxx\");Here's an example for various images formats.With java lambdas (available since java 8) you can simply convert  to  in one line.
Java

I'm having trouble fully understanding the role that the  fulfils in Streams  method. For example, the following code doesnt compile : Compile error says : \n      but this code does compile :I understand that the combiner method is used in parallel streams - so in my example it is adding together two intermediate accumulated ints. But I dont understand why the first example doesnt compile without the combiner or how the combiner is solving the conversion of string to int since it is just adding together two ints.Can anyone shed light on this? The two and three argument versions of  which you tried to use don't accept the same type for the .The two argument  is  :In your case, T is String, so  should accept two String arguments and return a String. But you pass to it an int and a String, which results in the compilation error you got - . Actually, I think passing 0 as the identity value is also wrong here, since a String is expected (T).Also note that this version of reduce processes a stream of Ts and returns a T, so you can't use it to reduce a stream of String to an int.The three argument  is  :In your case U is Integer and T is String, so this method will reduce a stream of String to an Integer.For the  accumulator you can pass parameters of two different types (U and ? super T), which in your case are Integer and String. In addition, the identity value U accepts an Integer in your case, so passing it 0 is fine.Another way to achieve what you want :Here the type of the stream matches the return type of , so you can use the two parameter version of .Of course you don't have to use  at all : described the differences between the two-arg and three-arg versions of  in that the former reduces  to  whereas the latter reduces  to . However, it didn't actually explain the need for the additional combiner function when reducing  to .One of the design principles of the Streams API is that the API shouldn't differ between sequential and parallel streams, or put another way, a particular API shouldn't prevent a stream from running correctly either sequentially or in parallel. If your lambdas have the right properties (associative, non-interfering, etc.) a stream run sequentially or in parallel should give the same results.Let's first consider the two-arg version of reduction:The sequential implementation is straightforward. The identity value  is \"accumulated\" with the zeroth stream element to give a result. This result is accumulated with the first stream element to give another result, which in turn is accumulated with the second stream element, and so forth. After the last element is accumulated, the final result is returned.The parallel implementation starts off by splitting the stream into segments. Each segment is processed by its own thread in the sequential fashion I described above. Now, if we have N threads, we have N intermediate results. These need to be reduced down to one result. Since each intermediate result is of type T, and we have several, we can use the same accumulator function to reduce those N intermediate results down to a single result.Now let's consider a hypothetical two-arg reduction operation that reduces  to . In other languages this is called a \"fold\" or \"fold-left\" operation so that's what I'll call it here. Note this doesn't exist in Java.(Note that the identity value  is of type U.)The sequential version of  is just like the sequential version of  except that the intermediate values are of type U instead of type T. But it's otherwise the same. (A hypothetical  operation would be similar except that the operations would be performed right-to-left instead of left-to-right.)Now consider the parallel version of . Let's start off by splitting the stream into segments. We can then have each of the N threads reduce the T values in its segment into N intermediate values of type U. Now what? How do we get from N values of type U down to a single result of type U?What's missing is another function that  the multiple intermediate results of type U into a single result of type U. If we have a function that combines two U values into one, that's sufficient to reduce any number of values down to one -- just like the original reduction above. Thus, the reduction operation that gives a result of a different type needs two functions:Or, using Java syntax:In summary, to do parallel reduction to a different result type, we need two functions: one that  T elements to intermediate U values, and a second that  the intermediate U values into a single U result. If we aren't switching types, it turns out that the accumulator function is the same as the combiner function. That's why reduction to the same type has only the accumulator function and reduction to a different type requires separate accumulator and combiner functions.Finally, Java doesn't provide  and  operations because they imply a particular ordering of operations that is inherently sequential. This clashes with the design principle stated above of providing APIs that support sequential and parallel operation equally.Since I like doodles and arrows to clarify concepts... let's start!Suppose having 4 strings: your goal is to concatenate such strings into one. You basically start with a type and finish with the same type.You can achieve this withand this helps you to visualize what's happening:The accumulator function converts, step by step, the elements in your (red) stream to the final reduced (green) value. The accumulator function simply transforms a  object into another .Suppose having the same 4 strings: your new goal is to sum their lengths, and you want to parallelize your stream.What you need is something like this:and this is a scheme of what's happeningHere the accumulator function (a ) allows you to transform your  data to an  data. Being the stream parallel, it's splitted in two (red) parts, each of which is elaborated independently from eachother and produces just as many partial (orange) results. Defining a combiner is needed to provide a rule for merging partial  results into the final (green)  one.What if you don't want to parallelize your stream? Well, a combiner needs to be provided anyway, but it will never be invoked, given that no partial results will be produced.There is no  version that takes two different types without a  since it can't be executed in parallel (not sure why this is a requirement). The fact that  must be associative makes this interface pretty much useless since:Produces the same results as:
Java

I just started learning Java and I'm confused about the topic of platform independence.Doesn't \"independent\" imply that Java code should run on any machine and need no special software to be installed? Yet the JVM needs to be present in the machine.For example, we need to have the Turbo C Compiler in order to compile C/C++ source code and then execute it. The machine has to have the C compiler.Could somebody please what is meant when Java is described as \"platform independent\"?Typically, the compiled code is the exact set of instructions the CPU requires to \"execute\" the program.  In Java, the compiled code is an exact set of instructions for a \"virtual CPU\" which is required to work the same on every physical machine.So, in a sense, the designers of the Java language decided that the language and the compiled code was going to be platform independent, but since the code eventually has to run on a physical platform, they opted to put all the platform dependent code in the JVM.This requirement for a JVM is in contrast to your Turbo C example.  With Turbo C, the compiler will produce platform dependent code, and there is no need for a JVM work-alike because the compiled Turbo C program can be executed by the CPU directly.With Java, the CPU executes the JVM, which is platform dependent.  This running JVM then executes the Java bytecode which is platform independent, provided that you have a JVM available for it to execute upon.  You might say that writing Java code, you don't program for the code to be executed on the physical machine, you write the code to be executed on the Java Virtual Machine.The only way that all this Java bytecode works on all Java virtual machines is that a rather strict standard has been written for how Java virtual machines work.  This means that no matter what physical platform you are using, the part where the Java bytecode interfaces with the JVM is guaranteed to work only one way.  Since all the JVMs work exactly the same, the same code works exactly the same everywhere without recompiling.  If you can't pass the tests to make sure it's the same, you're not allowed to call your virtual machine a \"Java virtual machine\".Of course, there are ways that you can break the portability of a Java program.  You could write a program that looks for files only found on one operating system (cmd.exe for example).  You could use JNI, which effectively allows you to put compiled C or C++ code into a class.  You could use conventions that only work for a certain operating system (like assuming \":\" separates directories).  But you are guaranteed to never have to recompile your program for a different machine unless you're doing something really special (like JNI).Before going into the detail,first you have to understand what is the mean of platform?\nPlatform consists of the computer hardware(mainly architecture of the microprocessor) \nand OS.\nPlatform=hardware+Operating SystemAnything that is platform indepedent can run on any operating system and hardware.Java is platform indepedent so java can run on any operating system and hardware.\nNow question is how it is platform independent?This is because of the magic of Byte Code which is OS indepedent.\nWhen java compiler compile any code then it generate the byte code not the machine native code(unlike C compiler).Now this \nbyte code need a interpreter to execute on a machine.This interpreter is JVM.So JVM read that byte code(that is machine indepedent)\namd execute it.\nDifferent JVM is designed for different OS and byte code is able to run on different OS.In case of C or C++(language that are not platform indepedent) compiler generate the .exe file that is OS depedent so when we\nrun this .exe file on another OS it will not run because this file is OS depedent so is not compatible with the another OS.Finally an intermediate OS indepedent Byte code make the java platform independent.It means the Java programmer does not (in theory) need to know machine or OS details.  These details do exist and the JVM and class libraries handle them.  Further, in sharp contrast to C, Java binaries (bytecode) can often be moved to entirely different systems without modifying or recompiling.No, it's the other way around. It's because you use the virtual machine that the Java program gets independend.The virtual machine is not independent, you have to install one that is specifically made for your type of system. The virtual machine creates an independent platform on top of the operating system.The JVM is a \"simulated machine\" that can be installed on different systems. In this way, the same Java code can run on different systems, because it relies on the JVM, not on the operational system itself.That is to say, this allows the programmer to communicate with the virtual system (JVM) and utilize its functions, instead of the specific machine and OS functions.\nSince Java only relies on JVM, it is platform independent (if the platform has JVM installed).So in short, Java is not platform independent as such, it requires a JVM-installation for all systems it should run on. However, it will run on all systems that has the JVM installed.The JVM abstracts from the concrete platform. Your program relies only upon the JVM and since the JVM is available for different platforms like Windows and Linux, your program is platform independent (but jvm depended).In c/c++ the source code(c program file) after the compilation using a compiler is directly converted to native machine code(which is understandable to particular machine on which u compiling the code). And hence the compiled code of c/c++ can not run on different OS.But in case of Java : the source file of java(.java) will be compiled using JAVAC compiler(present in JDK) which provides the Byte code(.class file) which is understandable to any JVM installed on any OS(Physical System).Here we need to have different JVM (which is platform dependent) for different operating Systems where we want to run the code, but the .class file(compiled code/Intermediate code)remains same, because it is understandable to any of the JVM installed on any OS.In c/c++ : only source code is machine independent.\nIn Java : both the source code and the compiled code is platform independent.This makes Java Platform(machine) independent.java is not platform Independent, itself is a platform,based on that platform java apps runs,but java platform itself is platform dependent(i.e java virtual machine)is a collection of programs which contains lot of files which provides various functionatiles present on a folder(i.e collections of programs on middle level format)as called . helps not to be overloaded on  where its helps to execute only the  files or java applications only by itself only.It helps to make its equalities middle level format after compliation by the java compiler then its provide the byte code (.class file)reprsentation which is not specific to  and  .\n2:jvm makes byte code to  file for proccessor to understandable and prsents memory allocation for every functions after recieving frm byte code.\n3:jvm also releases memory alocation from ram after control makes finishes thier execution .Java is not platform independent in that it runs on the JVM. Having said that, you gain platform independence via programming against a single abstract machine that has concrete realizations on most common OS platforms (and some embedded appliances).A related idea is the hardware abstraction layer present in many operating systems that allows the same OS to run on disparate hardware.In you original question, Turbo C is analagous to the javac program, and the JVM is the OS/HAL.With Java, you can compile source code on Windows and the  (bytecode to be precise) can be executed (interpreted) on any platform running a JVM. So yes you need a JVM but the JVM can run any compiled code, the compiled code is . In other words, you have both portability of source code and portability of compiled code.The machine doesn't have to have a C compiler, the machine has to use a platform specific binary. With C or C++, the  is specific to each architecture, it is . In other words, with C / C++ you have portability of source code (with some discipline) but not portability of compiled code: you need to recompile for each architecture into platform specific binaries.JVM will be platform dependent.\nBut whatever it will generate that will be platform independent. [which we called as bytecode or simply you can say...the class file]. for that why Java is called Platform independent.\nyou can run the same class file on Mac as well on Windows but it will require JRE. JVM is os dependent.\nfor every os JVM different.\".class\" is same for all JVMs.\nso, every JVM understand that \".class\" file data.windows dependent JVM give windows dependent instruction to windows\nlinux dependent JVM give linux dependent instruction to linux.that's like it for other operating systems.\nso,java runs on any operating system.that's why java is os independent.Java is platform-independent as it has JVM(Java virtual machine). Let us illustrate it with a real life example. Let's assume you are free to your family members. But why? Because you know them well and they know you as well. But, you are not free to my family members. Because you don't know them and they don't know you either. But, if I'm your friend and when I can introduce you to my family members, hence you will be able to talk to them freely.In a similar way, if you are a code and I am a JVM. Also, your family is windows platform and mine is the Linux platform. In the case you were a C or other platform-dependent languages, you only know your family members and vice versa. That's why only the platform on which you were written knows that Code and will support it. But if you are a JAVA code and when you come to my family viz. the Linux platform and if there you find me, JVM, then I can introduce you to my family, the Linux platform and you will be able to interact with it.For platform-dependent languages, there isn't any friend like JVM available to them to introduce themselves to any platform family. That is how Java is platform-independent. :)bytecode is not plateform independent, but its JVM that makes bytecode independent. Bytecode is not the matchine code. bytecodes are compact numeric codes, constants, and references (normally numeric addresses) which encode the result of parsing and semantic analysis of things like type, scope, and nesting depths of program objects. They therefore allow much better performance than direct interpretation of source code. bytecode needs to be interpreted before execution which is always done by JVM interpreter.Just a side note to the discussion about JVM and JIT Compilation.\nThis is the same principle as with C# and the CLR and to some extent in Python, and when somebody says that the code runs \"directly on hardware\" that is actually true in that instructions that is already compiled will be able to take advantage of optimization on the machine/cpu it's being run on. So even if the initial compilation of a module is rather slow, the next time this module is run, the code being executed runs at native speed and thus runs directly on hardware so to say.Java is platform independent in aspect of java developer,but this is not the case for the end-user, who need to have platform dependent JVM to run java code. Basically, when java code is compiled, a bytecode is generated which is typically platform independent. Thus, the developer has to have write a single code for entire platform series. But, this benefit comes with a headache for end-user who need to install JVM in order to run this compiled code. This JVM is differnt for every platform. Thus, dependency comes into effect only for end-user. \u2013 compiler that converts source code to byte code. \n- interpreter that converts byte code to machine language code. As we know java is both  based language. Once the java code also known as source code is compiled, it gets converted to native code known as BYTE CODE which is portable & can be easily executed on all operating systems. Byte code generated is basically represented in . This format is same on every platform be it Solaris work station or Macintosh, windows or Linux. After compilation, the interpreter reads the generated byte code & translates it according to the host machine. . Hope it helps!!!When we compile C source data, it generate native code which can be understood by current operating system.\nWhen we move this source code to the other operating system, it can't be understood by operating system because of native code that means representation is change from O.S to O.S.\nSo C or C++ are platform dependent .Now in case of java, after compilation we get byte code instead of native code. When we will run the byte code,\nit is converted into native code with the help of JVM and then it will be executed.So Java is platform independent and C or C++ is not platform independent.well good question but when the source code is changed into intermediate native byte code by a compiler in which it converts the program into the byte code by giving the errors after the whole checking at once (if found) and then the program needs a interpreter which would check the program line by line and directly change it into machine code or object code and each operating system by default cannot have an java interpreter because of some security reasons so you need to have jvm at any cost to run it in that different O.S platform independence as you said here means that the program can be run in any os like unix, mac, linux, windows, etc but this does not mean that each and every os will be able to run the codes without a jvm which saysspecification, implementation, and instance , if i advance then by changing the configuration of your pc so that you can have a class loader that can open even the byte code then also you can execute java byte code, applets, etc.\n-by nimish :) best of luckHow this is happening ?Ans: JVM have capability to read  and Response In Accordance with the underlying OS As the JVM is in Sync with OS.So we find, we need JVM with Sync with Platform.But the main thing is that the programmer dont have to know specific knowledge of the Platform and program his application keeping one specific platform in mind. This Flexibility of write Program in Java --- compile to  and run on any Machine (Yes need to have Platform DEPENDENT JVM to execute it) makes Java Platform Independent. Java doesn't directly run on anything. It needs to be converted to bytecode by a JVM.Because JVMs exist for all major platforms, this makes Java platform-independent THROUGH the JVM.
Java

While developing a camera app I've encountered an exception that only happened when I switch to other app ( for my app).I did some research and found out that I need to addas a workaround for Android's camera stackmy  now looks like this:and my :and finally my  method:any ideas on how to fix this?I've got the same problem.  didn't help. In my activity I've added this to :and it works now.@ookami.kb solution worked for me too, as well as @srunni commented.I removed onDestroy method too.The docs clearly say that  releases all camera resources. After this call camera reference can not be used any more.If you want to use camera again you have to acquire it via a  method.It's all described in the .To Resume correctly, you need to do this:And also just to remind that in oncreate() do nothing except defining FrameLayout preview and Button captureButton.And re initialize the camera in on Resume function.Adding to okambi's answer.This is the function messing everything up when you resume:The try{} is not catching the exception being thrown. Namely that mCamera doesn't exist, and then when it tries to call setPreviewDisplay(holder), there is a crash.So by removing the callback, this surfaceCreated doesn't get called and avoids the crash. This is VERY POORLY DOCUMENTED by Google.I faced same issue, i fixed it by\n- Adding  in  method of  class.and\n- Adding in  method of my CameraActivity.If you got:I agree with @ookami.kb -  is not enough, behind it also add this:I have put between.and and it worked for me.
Java

I've been wondering what the best (i.e. cleanest/safest/most efficient) way of handling multiple constructors in Java is? Especially when in one or more constructors not all fields are specified:What should I do when fields are not specified? I've so far been using default values in the class so that a field is never null, but is that a \"good\" way of doing things?A slightly simplified answer:Consider using the Builder pattern. It allows for you to set default values on your parameters and initialize in a clear and concise way. For example:Edit: It also removes the need for multiple constructors with different signatures and is way more readable.You need to specify what are the class invariants, i.e. properties which will always be true for an instance of the class (for example, the title of a book will never be null, or the size of a dog will always be > 0).These invariants should be established during construction, and be preserved along the lifetime of the object, which means that methods shall not break the invariants. The constructors can set these invariants either by having compulsory arguments, or by setting default values:However, the choice of these invariants highly depends on the class you're writing, how you'll use it, etc., so there's no definitive answer to your question. You should always construct a valid and legitimate object; and if you can't using constructor parms, you should use a builder object to create one, only releasing the object from the builder when the object is complete.On the question of constructor use: I always try to have one base constructor that all others defer to, chaining through with \"omitted\" parameters to the next logical constructor and ending at the base constructor.  So:If this is not possible, then I try to have an private init() method that all constructors defer to.And keep the number of constructors and parameters small - a max of 5 of each as a guideline.Some general constructor tips:The overall flow ends up being:For a nice example of evil, try figuring out what the following will print, then run itI'll add comments describing why the above works as it does... Some of it may be obvious; some is not...Another consideration, if a field is required or has a limited range, perform the check in the constructor:I would do the following:I am making the assumption here that:1) the title will never change (hence title is final)\n2) the isbn will never change (hence isbn is final)\n3) that it is not valid to have a book without both a title and an isbn. Consider a Student class:There a Student must be created with an id, a first name, and a last name.  The student ID can never change, but a persons last and first name can change (get married, changes name due to losing a bet, etc...).When deciding what constrructors to have you really need to think about what makes sense to have.  All to often people add set/get methods because they are taught to - but very often it is a bad idea. Immutable classes are much better to have (that is classes with final variables) over mutable ones.  This book:  (Effective Java) has a good discussion on immutability.  Look at items 12 and 13.Several people have recommended adding a null check.  Sometimes that's the right thing to do, but not always.  Check out this excellent article showing why you'd skip it.
Java

I have the following hashmap in java:How should I go about sorting the hashmap such that the Alphabet, followed by the numerical figures are taken into account?The resulting hashmap should look like this:Appreciate the help!Use sorted :It will automatically put entries sorted by keys. I think natural  ordering will be fine in your case.Note that  due to lookup optimizations does not preserve order.Use a TreeMap with a custom comparator.As you add new elements, they will be automatically sorted.In your case, it might not even be necessary to implement a comparator because String ordering might be sufficient. But if you want to implement special cases, like lower case alphas appear before upper case, or treat the numbers a certain way, use the comparator. is your best bet for these kind of sorting (Natural).  naturally sorts according to the keys. does not preserve insertion order nor does it sort the map.  keeps the insertion order but doesn't sort the map automatically. Only  in the  interface sorts the map according to natural order (Numerals first, upper-case alphabet second, lower-case alphabet last).Use a , although having a map \"look like that\" is a bit nebulous--you could also just sort the keys based on your criteria and iterate over the map, retrieving each object.Just use a . It implements the  interface, and thus automatically sorts the keys it contains. Your keys can just be sorted alphabetically to get the desired result, so you don't even need to provide a comparator.HashMaps are never sorted. The only thing you coulkd do with a HashMap is get all the keys, and store them in a sorted set or in a List and sort the List.Using the  you can sort the Map.
Java

I have noticed the following code is redirecting the User to a URL inside the project, whereas, the following is redirecting properly as intended, but requires http:// or https://I want the redirect to always redirect to the URL specified, whether it has a valid protocol in it or not and do not want to redirect to a view. How can I do that?Thanks,You can do it with two ways. First:Second:Looking into the actual implementation of  and  the redirect will always be contextRelative if your redirect target starts with /. So also sending a //yahoo.com/path/to/resource wouldn't help to get a protocol relative redirect.So to achieve what you are trying you could do something like:You can use the . Copied from the :Example:You can also use a , e.g.And of course, return  as mentioned by others.Another way to do it is just to use sendRedirect method:For external url  you have to use \"\" as the redirect url.This is explained in the  of Spring reference documentation. will redirect relative to the current Servlet context, while a name such as will redirect to an absolute URLDid you try  where you can provide the contextRelative parameter?For me works fine:In short  or  will lend you to .where as  will lend you  ie for ex- 
Java

I've mapped the Spring MVC dispatcher as a global front controller servlet on .However, this mapping stops the access to static files like CSS, JS, images etc which are all in the  folder.How can I access them anyway?I've run into this also and never found a great solution.  I ended up mapping my servlet one level higher in the URL hierarchy:And now everything at the base context (and in your /res directory) can be served up by your container.Map the controller servlet on a more specific  like , put the static content in a specific folder like  and create a  listening on  which transparently continues the chain for any static content and dispatches requests to the controller servlet for other content.In a nutshell:with the following in filter's :No, this does not end up with  in browser address bar. It's fully transparent. You can if necessary make  and/or  an  of the filter.With  and higher you can useAs seen in .If you use Tomcat, you can map resources to the default servlet:and access your resources with url http://{context path}/static/res/...Also works with Jetty, not sure about other servlet containers.What you do is add a welcome file in your web.xmlAnd then add this to your servlet mappings so that when someone goes to the root of your application, they get sent to index.html internally and then the mapping will internally send them to the servlet you map it toEnd result: You visit /Application, but you are presented with /Application/MainActions servlet without disrupting any other root requests.Get it? So your app still sits at a sub url, but automatically gets presented when the user goes to the root of your site. This allows you to have the /images/bob.img still go to the regular place, but '/' is your app.Serving static content with appropriate suffix in multiple servlet-mapping definitions solved the security issue which is mentioned in one of the comments in one of the answers posted. Quoted below:which helped me a lot.\nAnd here is how I solved it:As of 3.0.4 you should be able to use  in combination with  as described in the spring documentation to achieve this.'Static' files in App Engine aren't directly accessible by your app. You either need to upload them twice, or serve the static files yourself, rather than using a static handler.The reason for the collision seems to be because, by default, the context root, \"/\", is to be handled by org.apache.catalina.servlets.DefaultServlet. This servlet is intended to handle requests for static resources.If you decide to bump it out of the way with your own servlet, with the intent of handling dynamic requests, that top-level servlet must also carry out any tasks accomplished by catalina's original \"DefaultServlet\" handler.If you read through the tomcat docs, they make mention that True Apache (httpd) is better than Apache Tomcat for handling static content, since it is purpose built to do just that. My guess is because Tomcat by default uses org.apache.catalina.servlets.DefaultServlet to handle static requests. Since it's all wrapped up in a JVM, and Tomcat is intended to as a Servlet/JSP container, they probably didn't write that class as a super-optimized static content handler. It's there. It gets the job done. Good enough. But that's the thing that handles static content and it lives at \"/\". So if you put anything else there, and that thing doesn't handle static requests, WHOOPS, there goes your static resources. I've been searching high and low for the same answer and the answer I'm getting everywhere is \"if you don't want it to do that, don't do that\".So long story short, your configuration is displacing the default static resource handler with something that isn't a static resource handler at all. You'll need to try a different configuration to get the results you're looking for (as will I).The best way to handle this is using some kind of URL re-writing.  In this way, you can have clean restful URLs, and NOT with any extensions i.e abc.com/welcom/register as opposed to abc.com/welcome/resister.htmlI use  which is pretty cool.It's got instructions on how to set up your web app.I have set it up with my Spring MVC web app. Of course, everything was fine until I wanted to use annotations for Spring 3 validations like  or  for domain objects.  When I add the Spring mvc directives:.. it breaks the good ol Tuckey code. Apparently,  replaces Tuckey, which I'm still trying to solve. Add the folders which you don't want to trigger servlet processing to the  section of your appengine-web.xml file.I just did this and looks like things are starting to work ok.  Here's my structure://pages/<.jsp files>/cssI added \"/pages/**\" and \"/css/**\" to the  section and I can now forward to a .jsp file from inside a servlet doGet without causing an infinite loop.After trying the filter approach without success (it did for some reason not enter the doFilter() function) I changed my setup a bit and found a very simple solution for the root serving problem:Instead of serving \" / * \"\nin my main Servlet, I now only listen to dedicated language prefixes\n\"EN\", \"EN/ *\", \"DE\", \"DE/ *\"Static content gets served by the default Servlet and the empty root requests go to the index.jsp which calls up my main Servlet with the default language:I found that using in the spring MVC servlet bean definition file works for me. It passes any request that isn't handled by a registered MVC controller on to the container's original default handler, which should serve it as static content.  Just make sure you have no controller registered that handles everything, and it should work just fine.  Not sure why @logixplayer suggests URL rewriting; you can achieve the effect he's looking for just adequately using Spring MVC alone.I'd recommend trying to use a Filter instead of a default servlet whenever possible.Other two possibilities:Write a FileServlet yourself. You'll find plenty examples, it should just open the file by URL and write its contents into output stream. Then, use it to serve static file request.Instantiate a FileServlet class used by Google App Engine and call service(request, response) on that FileServlet when you need to serve the static file at a given URL.You can map /res/* to YourFileServlet or whatever to exclude it from DispatcherServlets' handling, or call it directly from DispatcherServlet.And, I have to ask, what does Spring documentation say about this collision? I've never used it.I found a simpler solution with a dummy index file.Create a Servlet (or use the one you wanted to respond to \"/\") which maps to \"/index.html\"\n(Solutions mentioned here use the mapping via XML, I used the 3.0 version with annotation @WebServlet)\nThen create a static (empty) file at the root of the static content named \"index.html\"I was using Jetty, and what happened was that the server recognized the file instead of listing the directory but when asked for the resource, my Servlet took control instead. All other static content remained unaffected.In Embedded Jetty I managed to achieve something similar by adding a mapping for the \"css\" directory in web.xml. Explicitly telling it to use DefaultServlet:and if you want to use annotation based configuration use below code
Java

Why are empty Strings valid and empty chars are not ?\nI would have thought an empty String is not a string but just a placeholder. The same for a char, but creating an empty char does not even compile. What im wondering is why the following occurs - \nCompiles - Does not compile -Because  represents a single character, which  isn't. A String can contain zero or more characters, but a character cannot be anything other than a single character.Because a string literal represents a String which may consist of  characters, but a (valid) character literal represents  character.Yes.  In theory it could have been defined that way.  But trust me, if you think through  the issues (e.g. how you'd represent an empty char, how an application would deal with it, etc) you will conclude that the there are few benefits, and significant downsides.Anyway, doing this  so that there was a syntactic consistency between String and char literals would be totally crazy.  You don't break a language's performance and/or semantics so that the syntax looks nice.One comments on the accepted answer proposes that  should mean the same as .  But the counter argument to this is that  does not mean no characters.  It means one character whose value is zero.  So if   means one character it is misleading.  And since there is already a way of denoting this ...  ... a second way of denoting it is redundant.If some piece of new language syntax is both misleading and redundant, it is hard to justify adding it.In respose to SoloBold's comment, while it would be possible to define a character type to do that, it would require more space.  At least 1 bit, and more likely 16 bits to avoid awkward memory alignment problems.  A 32-bit  type would not be acceptable ... even though it does solve other problems. is an empty array of characters. is simply not a character.An empty string is like a container that holds nothing. A  must have a value and without exactly one character there is no where to derive that value from.You could see a String as a sequence of characters. Having an empty sequence with no characters makes sense, having a character that isn't a character doesn't. Also never use , just  is enough.Mathematically, an alphabet A is a set of symbols, suppose alphabet A = {a, b, c, d, ..., z}. A string L is a sequence of zero or more characters from an alphabet, i.e. L = A*. An empty string is simply a sequence of zero characters; while an \"empty chars\" is not a member of the alphabet.You can't have an empty character, it is illogical.char is a primitive type, so you need to give a value (whatever it is).\nIf you want to leave you variable as \"undefined\", you can use the wrapper object:In this way you variable c is not containing (yet) any value. But then be sure to add a value! :)By the way, you can use the object wrapper for primitive  type:This can be useful when you want a field to be \"either a character or nothing\".Probably because char is a primitive type, and String is an object. \nboolean, int etc. also don\u00b4t allow \"empty\" values.A char is a single character, that is a letter, a digit, a punctuation mark, a tab, a space or something similar. String is a set of characters which could be 0 or more. so empty strings are valid- which dont have any character. BUt char represents the primitive type of Character which has to be one valid character, which '' is not.i think you should try to know the difference between blank character/string and empty character/string. blank char/string refers to character/string that has some content, such as ' '(SPACE), '\\t' and so on, while empty ones doesn't have any content, and can be seen as an empty container.
Java

I have the following Layout which does not work:This is a common problem.  Try using the following:.............. the scrollHorizontally is the \"special sauce\" that makes it work.This will also make a single line with ellipsiseThe way it worked for me on multiple devices / APIs was programmatically like this (where tv is your TextView):android:ellipsize=\"end\"\nandroid:singleLine=\"true\"android:ellipsize=\"end\"\nandroid:maxLines=\"1\"When you use maxlines = 1 it will some time truncate most of the characters.
Java

How to get the double value that is only two digit after decimal point.for example if this code generating .But I want only .So what shoud I do?Use . - -How about ?Here i will demonstrate you that how to make your decimal no shorter, here i am shorter it it to 4 value after decimal.I think the best and simplest solution is (KISS):First thing that should pop in a developer head while formatting a number into char sequence should be care of such details like do it will be possible to reverse the operation.And other aspect is providing proper result. So you want to  truncate the number or round it. So before you start you should ask your self, am i interested on the value or not. To achieve your goal you have multiple options but most of them refer to  and , but i just suggest to look in .
Java

I want the message text within my dialog box to be center aligned.Create your own TextView object and then supply it to popup builder as View:You can control all other text parameters (style, color, size ...). To control margins you may programatically create LinearLayout, set LayoutParams, and then put TextView into it.Of course, you can always set the gravity of the original text view. This allows you to not have to worry about formatting and padding. For exampleBuilding off of Chase's answer, here's how to also center the title.  I think this is the easiest way.  Why android doesn't center by default or make it a simple constructor param is beyond me.we can use as like.try this in your TextView:Just use that method and your dialog title and message will appear at center:public static void openDialog(Context context, String message) {you can try this code
Java

This is related to a previous question that I asked here earlierI am trying to parse the same JSON, but now I have changed my classes a little bit.My class now looks like:This code throws an exception, The exception is understandable, because as per the solution to my previous question, GSON is expecting the Enum objects to be actually be created as  But since this is syntactically impossible, what are the recommended solutions, workarounds?From :Following is one such approach.I want to expand a bit NAZIK/user2724653 answer (for my case). Here is a Java code:in the json file you have just a field , where N=0,1,2,3 - depend on the Status values. So that's all,  works fine with the values for the nested  class. In my case i've parsed a list of  from  array:Use annotation :With GSON version 2.2.2 enum will be marshalled and unmarshalled easily.
Java

I have milliseconds. \nI need it to be converted to date format of example:How to achieve it?any help is really appreciated.Just Try this Sample code:-I hope this help...Convert the  value to  instance and pass it to the choosen formatter.Call this functiontry this code might help, modify it suit your needsi finally find normal code that works for meShort and effective:You can construct java.util.Date on milliseconds. And then converted it to string with java.text.DateFormat.
Java

I'm trying to send an email in Java but when I read the body of the email in Outlook, it's gotten rid of all my linebreaks. I'm putting \\n at the ends of the lines but is there something special I need to do other than that? The receivers are always going to be using Outlook. I found a page on microsoft.com that says there's a 'Remove line breaks' \"feature\" in Outlook so does this mean there's no solution to get around that other than un-checking that setting?ThanksYou need to use  as a solution.I've just been fighting with this today. Let's call the behavior of removing the extra line breaks \"continuation.\" A little experimenting finds the following behavior:Please note that I tried all of this with Outlook 2007. YMMV.\nSo if possible, end all bullet items with a sentence-terminating punctuation mark, a tab, or even three spaces.You can force a line break in outlook when attaching one (or two?) tab characters (\\t) just before the line break (CRLF).Example:It seems to work on Outlook 2010. Please test if this works on other versions.See also Microsoft Outlook 2002 and above removes \"extra line breaks\" from text messages by default .  That is, Outlook seems to simply ignore line feed and/or carriage return sequences in text messages, running all of the lines together.This can cause problems if you're trying to write code that will automatically generate an email message to be read by someone using Outlook.For example, suppose you want to supply separate pieces of information each on separate lines for clarity, like this:Transaction needs attention!\nPostedDate: 1/30/2009\nAmount: $12,222.06\nTransID: 8gk288g229g2kg89\nPostalCode: 91543Your Outlook recipient will see the information all smashed together, as follows:Transaction needs attention! PostedDate: 1/30/2009 Amount: $12,222.06 TransID: 8gk288g229g2kg89 ZipCode: 91543There doesn't seem to be an easy solution.  Alternatives are:I had the same issue, and found a solution. Try this:   to add a line break.I had been struggling with all of the above solutions and nothing helped here, because I used a String variable (plain text from a JTextPane) in combination with \"text/html\" formatting in my e-mail library.So, the solution to this problem is to use \"text/plain\", instead of \"text/html\" and no need to replace return characters at all:Put the text in  Tags and outlook will format and display the text correctly. i defined it in CSS inline in HTML Body like: CSS:i defined the font-family to have to font set. HTML: Because it is a query, only percent escaped characters work, means %0A gives you a line break. For example,I have used  html line break  instead of \"\\n\" . It worked fine.The trick is to use the  functionality from js:RESULT:You need to send HTML emails.   With s in the email, you will always have your line breaks.In my application, I was trying to send an email whose message body was typed by the user in text area. When mail was send, outlook automatically removed line break entered by user.e.g if user entered\nYadav\nMaheshoutlook displayed it as \nYadavMahesh I changed the line break character \"\\r\\n\" with \"\\par \" ( remember to hit space at the end of RTF code \"\\par\" )and line breaks are restrored.Cheers,\nMaheshIf you can add in a '.' (dot) character at the end of each line, this seems to prevent Outlook ruining text formatting.Try this:Regards,\nMohammad Rasool JaveedTry  instead of . I think @Robert Wilkinson had it right. . Memory just isn't what it used to be.The  largely works for us, but Outlook does sometimes take it upon itself to remove the line breaks as you say.I have a good solution that I tried it, it is just add the Char(13) at end of line like the following example:if the message is text/plain using, \\r\\n should work; \nif the message type is text\\html, use  must be helpful for you. try \"%0A\" instead of \"\\n\". The real source is You need to add \"%0A\" where ever you need a new line in your code. In your case I also had this issue with plain/text mail type. Earlier, I used \"\\n\\n\" but there was two line breaks. Then, I used \"\\t\\n\" and it worked. I was using  in java to append content.\nThe content got printed in next line in Outlook 2010 mail.I also had this issue with plain/text mail type.Form Feed   worked for me. For Outlook 2010 and later versions, use  rather than using \\r\\n.Sometimes you have to enter \\r\\n twice to force outlook to do the break.This will add one empty line but all the lines will have break.if work need to be done with formatted text with out html encoding.\nit can be easy achieved with following scenario that  and using  html element to keep formatting.Adding \"\\t\\r\\n\"  ( \\t for TAB)   instead of \"\\r\\n\"  worked for me on Outlook 2010  .  Note : adding 3 spaces at end of each line also do same thing but that looks like a programming hack! will not work until you set body type as text.
Java

Is there a way to format a decimal as following:If it is a round number, omit the decimal part. Otherwise format with two decimal places.I doubt it. The problem is that 100 is never 100 if it's a float, it's normally 99.9999999999 or 100.0000001 or something like that. If you do want to format it that way, you have to define an epsilon, that is, a maximum distance from an integer number, and use integer formatting if the difference is smaller, and a float otherwise.Something like this would do the trick:I'd recommend using the java.text package: This has the added benefit of being locale specific.But, if you must, truncate the String you get back if it's a whole dollar: orOutputIf you don't want to use sign use this method I did not find any good solution after google search, just post my solution for other to reference. use  to format money.Yes.  You can use . You can use a formatting string like \"%10.2f\"I'm using this one (using StringUtils from commons-lang):You must only take care of the locale and the corresponding String to chop. I think this is simple and clear for printing a currency:output: $12,345.68And one of possible solutions for the question:Output:100100.10you should do something like this:which prints:100100,10I know this is an old question but...You can just do something like this and pass in the whole number and then the cents after.I agree with @duffymo that you need to use the  methods for this sort of things.  You can actually do all the formatting natively in it without doing any String compares yourself:Couple bits to point out: Whatever your logic for determining whether or not the decimals should get truncated,  should get used.If you want work on currencies, you have to use BigDecimal class. The problem is, there's no way to store some float numbers in memory (eg. you can store 5.3456, but not 5.3455), which can effects in bad calculations.There's an nice article how to cooperate with BigDecimal and currencies:Format from 1000000.2 to 1 000 000,20This post really helped me to finally get what I want. So I just wanted to contribute my code here to help others. Here is my code with some explanation.The following code:Will return:The actual jeroensFormat() method:The method displayJeroensFormat that calls the method jeroensFormat() Will have the following output:This code uses your current currency. In my case that's Holland so the formatted string for me will be different than for someone in the US.Just watch the last 3 characters of those numbers. My code has an if statement to check if the last 3 characters are equal to \",00\". To use this in the US you might have to change that to \".00\" if it doesn't work already.We will usually need to do the inverse, if your json money field is an float, it may come as 3.1 , 3.15 or just 3.In this case you may need to round it for proper display (and to be able to use a mask on an input field later):This is what I did, using an integer to represent the amount as cents instead:The problem with  is that sometimes you really want $20 to be $20, it just looks better than $20.00.If anyone finds a better way of doing this, using NumberFormat, I'm all ears.
Java

I  that Unicode is permitted within Java source code not only as Unicode characters (eg.  ) but also as escaped sequences (eg.  ).The first variant makes sense to me - it allows programmers to name variables and methods in an international language of their choice. However, I don't see any practical application of the second approach.Here are a few pieces of code to illustrate usage, tested with Java SE 6 and NetBeans 6.9.1:This code will print out 3.141592653589793Explanation: \u03c0 and \\u03C0 are the same Unicode characterThis code will not print out anythingExplanation: The code above actually encodes:Which comments out the print satement.Just from my examples, I notice a number of potential problems with this language feature.First, a bad programmer could use it to secretly comment out bits of code, or create multiple ways of identifying the same variable. Perhaps there are other horrible things that can be done that I haven't thought of.Second, there seems to be a lack of support among IDEs. Neither NetBeans nor Eclipse provided the correct code highlighting for the examples. In fact, NetBeans even marked a syntax error (though compilation was not a problem).Finally, this feature is poorly documented and not commonly accepted. Why would a programmer use something in his code that other programmers will not be able to recognize and understand? In fact, I couldn't even find something about this on the .My question is this:Why does Java allow escaped Unicode sequences to be used within syntax?\nWhat are some \"pros\" of this feature that have allowed it to stay a part Java, despite its many \"cons\"?Unicode escape sequences allow you to store and transmit your source code in pure ASCII and still use the entire range of Unicode characters. This has two advantages:Both will result in exactly the same byte code and have the same power as a language feature. The only difference is in the source code.If you're concerned about a programmer  sabotaging your code's readability, this language feature is the least of your problems.That's hardly the fault of the feature or its designers. But then, I don't think it was ever intended to be used \"manually\". Ideally, the IDE would have an option to have you enter the characters normally and have them displayed normally, but automatically save them as Unicode escape sequences. There may even already be plugins or configuration options that makes the IDEs behave that way.But in general, this feature seems to be very rarely used and probably therefore badly supported. But how could the people who designed Java around 1993 have known that?The nice thing about the  encoding is that it is much less likely to be munged by a text editor with the wrong encoding settings.  For example a bug in my software was caused by the accidental transformation from UTF-8  into a MacRoman  by a misconfigured text editor.  By specifying the Unicode codepoint, it's completely unambiguous what you mean.The \\uXXXX syntax allows Unicode characters to be represented unambiguously in a file with an encoding not capable of expressing them directly, or if you want a representation guaranteed to be usable even in the lowest common denominator, namely an 7-bit ASCII encoding.You  represent all your characters with \\uXXXX, even spaces and letters, but there is rarely a need to.First, thank you for the question. I think it is very interesting.\nSecond, the reason is that the java source file is a text that can use itself various charsets. For example the default charset in Eclipse is Cp1255. This endoding does not support characters like \u03c0. I think that they thought about programmers that have to work on systems that do not support unicode and wanted to allow these programmers to create unicode enabled software. This was the reason to support \\u notation. 
Java

I am using a linkedHashMap to guarantee order when someone tries to access it. However, when it comes time to iterate over it, does using entrySet() to return key/value pairs guarantee order as well? No changes will be made while iterating. Also, are there any adverse effects from iterating through the map by iterating through its keys and calling get? According to the , yes.As for the edit, no, it should work just fine. But the entry set is somewhat faster since it avoids the overhead of looking up every key in the map during iteration.If you're sure no changes will be made during the iteration, then proper ordering with  is guaranteed, as stated in the .
Java

In java, if a class implements Serializable but is abstract, should it have a serialVersionUID long declared, or do the subclasses only require that?In this case it is indeed the intention that all the sub classes deal with serialization as the purpose of the type is to be used in RMI calls.The serialVersionUID is provided to determine compatibility between a deseralized object and the current version of the class.  (Of course, it does generate a compiler warning, which you want to get rid of, right?)It turns out james' comment is correct.  The serialVersionUID of an abstract base class  get propagated to subclasses.  In light of that, you  need the serialVersionUID in your base class.The code to test:Run the main in Sub once to get it to create and save an object.  Then change the serialVersionUID in the Base class, comment out the lines in main that save the object (so it doesn't save it again, you just want to load the old one), and run it again.  This will result in an exceptionYes, in general, for the same reason that any other class needs a serial id - to avoid one being generated for it.  Basically any class (not interface) that implements serializable should define serial version id or you risk de-serialization errors when the same .class compile is not in the server and client JVMs.There are other options if you are trying to do something fancy.  I'm not sure what you mean by \"it is the intention of the sub classes...\".  Are you going to write custom serialization methods (eg. writeObject, readObject)?  If so there are other options for dealing with a super class.see:\nHTH TomActually, pointing out of Tom's link if missing  is actually calculated by serialization runtime i.e. not during compilationThis makes things even more complicated having different versions of JRE.Conceptually, the serialized data look like this:So when you deserialize, mismatch in version in any of the classes in the hierarchy causes the deserialization to fail. Nothing is stored for interfaces, so there's no need to specify version for them. yes, you do need to provide  in the base abstract class as well. Even if it does not have fields ( are stored even if there are no fields).Also note the following:In simple words: you can reorder fields, add and remove them, even change the class hierarchy. You should not rename fields or classes (it won't fail, but the values won't be deserialized). You cannot change type of fields with primitive type, and you can change reference type fields provided the new type is assignable from all values.Note: if the base class doesn't implement Serializable and only the subclass does, then fields from the base class would behave as .
Java

I'm about to build an Android application that will use a RESTful Web Service. I don't want to write the REST client by myself, as I want it to be as effective and stable as possible (this is the first time I'm using REST).Are there any (free) frameworks or utilities avaibale for Android/Java that I can use in my project? is an excellent REST framework and has an Android edition.Any HTTP Client library should be perfectly adequate to interact RESTfully with a web API.   E.g. try out Spring Android - is has very handy class RestTemplate.I'm also looking for a SMALL solution for rest client on Android. After a quick comparison, I found:Please correct me if any miss.check out Resting - \"Lightweight Java component to consume REST service and transform response into objects\"i haven't used it myself, but i plan to. to go along with it, i'm searching for example source code to implement the best practices described in this google IO session. 
Java

First time I hear about markers when read:I check available methods for  object:and found interfaces:More in-depth info I get from:but still confused... Note that I ask , not  to use them, so this is not a duplicate of: Seems that when you use markers  you also required to write custom Java code instead doing configuration in  or  files... From This is a rehashed version  to the question \"\".Markers can be used to  or mark a  log statement. What you do with these colors, i.e. markers, is entirely up to you. However, two patterns seem to be common (the first more common than the second) for marker usage.Before the advent of Markers, to achieve similar behavior, you had the option 1) using custom levels 2) use modified logger names. SLF4J API currently does not support custom levels. As for option 2, suffixing (or prefixing) logger names is workable if a one or two loggers need to be modified. The approach becomes unpractical as soon 3 or more loggers need to be \"sub-classed\" because the associated configuration files become unmanageable.
Java

Our company is using eclipse since several years now (we are using WTP since release 0.7)I am currently evaluating  which should replace eclipse 3.4.2 with WTP 3.0.4 as being our main IDE.And I have to say that once again I am quite disappointed in concerns of performance:\n\nIn fact I am really wondering why WTP gets slower with each release.One of our applications (dynamic web project) contain about . We only need basic WTP functionality for developing jsps, xmls and xsd. We don't need high sophistic features like  (should JPA tools really covered by a ?),  or a  in the first place.Another interesting point is that WTP seems to .\nSWT is non-reponsive for some fraction of seconds, cpu usage is very high (especially after a built took place - if you look at the system jobs, several jsp/javascript indexers are doing work for some minutes, even if all WTP build validators have been disabled), opening new files are slower, navigating through the project etc.This can be especially seen on older machines which do contains only a single core cpu.\n(e.g. have a look at the  page - last update took place in 2008).Bug reports and Newsgroup posts regarding to performance of basic features (e.g. jsp editing/validating) are often ignored or closed after some time, some examples: , , .I don't want to blame WTP.\nIn fact I believe that WTP is a good open-source project developed by a talented team.\nBut obviously the , especially in terms of performance which affects usability and user acceptance.I just want to point out that the team should focus on the things which are  in the first place and afterwards work on implementing super-duper-features.I'd like to make an update on this question to reflect the current answers and \nto sum up the current results:So this question turns a little bit into some kind of an open letter from the community to the WTP team:To respond, I'm the lead for the projects that supply the JSP, XML, and JavaScript source editing functionality in WTP.  The simple fact is that we don't spend much time on performance tests because we lack resources for doing that.  Of course we'd like to be proactive about it rather than reactive, but we tend to allocate our time to functional problems first.  We do have an adopter product running performance regression tests regularly, but I expect that tests are run on multi-core machines by now--and we haven't had any new red flags reported to us for some time.Of the 3 bugs you linked to, 2 predate the 3.0.4 version you laud and the third is either a formatting performance issue (since addressed) or one with as-you-type validation specific to XML files (the fixing of which would have triggered a memory leak in Xerces, iirc, hence us not putting it in at that time).  If you have concrete projects that you can attach to a bug and say \"doing X is slower in 3.2 by Y amount\", we'll do what we can to figure out where there's a regression.As for the indexers, they should at least  complete.  The on-disk information that is stored has changed between WTP versions, and those files need to be reprocessed so they're again included in search and (where implemented) refactoring operations.  Once the initial indexing is complete, it should act incrementally and be virtually unnoticeable.  One architectural change you may be running into is that for JSPs, the entire workspace needs to be indexed in a  workbench session for that index to be considered \"up to date\".  Shutting down Eclipse out of frustration will only prolong the impact of that reprocessing.It sounds like your company's standard install includes the entirety of WTP rather than rolling your own custom distribution.  I urge you to check the  preference page and turn off early startup of any functionality you're not interested in using.  Nothing you've mentioned interest in makes use of that facility, but there are other areas of WTP and the Platform that do.  Anything you're not interested in validating is fair game on the  preference page, as well as the setting to validate JSP fragments by default on the  /  /  preference page.We have the same problem with WTP 3.2.3 here, too. We use it in our product for several years, too but the acceptance of our developers and customers in this tool is decreasing every year because in every newer release it is slower and slower. I would like to use it if I could disable all \"advanced\" features but as you mentioned you cannot disable the indexers at all. Also you cannot stop the validator of JSP files if it is already running (you can test this if you have that many files as you have and we also have around 1000 JSP files and many tag files in our project). I also can prove that increasing the memory does not help. It only prevents crashes of the whole eclipse but it does not reduce the UI blocking internal operations of WTP.In the newest version  I got many hangs when I  from within the . The  just  about . It's not only me who has the hangs, it's all my colleagues who work on Windows have the same problem. On Linux I do not know about this problem.Also there are problems in WTP when you have no access to the internet. It seems there are request to some registries to download schemas or such things and if you do not have a connection then it just hangs and waits for the time out.  I don't know who's to blame: WTP or JBoss Tools.\nThe fact is that, as I work with GWT (minimal JSP), I went the opposite way: No WTP at all!!! I'm now using plain Eclipse for Java, and use a run configuration to deploy (programatically invoking ANT) and start the server, and I never looked back!!!\nEclipse used to take ~1.5GB and crashed several times. Now, it sits on ~800MB, and the whole environment became more stable.I have seen similar effects, here's one solution that might be suitable in some project environments...To guarantee fast and responsible Eclipse Web project environment, consider this:Result: fast & responsive Eclipse when compared to many other Eclipse installations that use Eclipse EE version with WTP stuff.Why? It might be that some Eclipse feature or plugin contains bugs or simply uses resources in a bad way and this makes Eclipse UI sluggish.Non-Java EE Eclipse is good enough even for many Java EE project environments, it all depends on your architecture and what tools you are using..Here's a quick tutorial to get started in case you wish to try Jetty Servlet Container out with Eclipse. See  . Download VaadinProjectForAnyIDE.zip, it's an Eclipse project. Just ignore that Vaadin stuff and replace HelloWorldApplication.java with your own servlet and edit web.xml accordingly.One more thing. With Eclipse EE version, you might also wish to try J2EE preview server which actually is Jetty embedded into Eclipse bundle. However, this also uses WTP mechanism.I also think the stability and performance of Eclipse/WTP is somewhat alarming. I'm using Eclipse since mid 2003 and have been trying WTP since its very first releases.At first the quality was absolute abysmal, but for a 0.x version I couldn't complain of course. While waiting for WTP to mature, I used MyEclipse, which was sort of okay but had its flaws too (and being partially based on WTP, inherited some of WTP).When MyEclipse became heavier and heavier, slower and slower and we ran into several stability issues, we switched to 'pure WTP'. All we were using was really the basic JSP/JSF editor and deployer.Since WTP doesn't do incremental deployment (at least not for the JBoss server runtime) we added the separate server runtime from JBoss tools. When we adopted Facelets, we also switched to the editor from JBoss tools.We do however run into a lot of problems we also had with MyEclipse. There are unexplainable slowdowns, but much worse are various stability problems. There are lots of awkward exceptions and crashes. A typical .log file on many different workstations I examined is chockfull of exceptions. A small selection of the last 10 exceptions in my log:1.2.3.4.5.6.7.8.9.10.Note that these are just the last 10, there are many, many more exceptions.The casual reaction would be: \" Yes, I might have a local problem, but this \"local problem\" seems widespread as many Eclipse installs I inspected seem to have this stuff in their logs.I'm also having problems with deployments like reported at the following link in various incarnations:  It may be JBoss tools specific or it may be based on the underlying WTP or even Eclipse code. I don't know, but I do know it's a nasty problem. Every WTP and JBoss tools version there is 'something' fixed, and every version a problem like that resurfaces in a slightly different form.Between the stability problems I'm able to get some work done and I love the auto completion and navigate-into features the editors offer me (which keeps me from switching to a text editor and building completely on the command line), but I sure would love some increased stability.By far the best way for speeding up my projects has been to precompile code that I am not currently using. We have about 20 projects that make up our system and when working on any specific problem I'm only touching a specific subset of those java files. Compiling most of the code that I won't be touching and throwing it into some .jar's, then using that as the source instead of including the projects has proven to speed up things by quite a bit. I imagine it will help you as well if you have 4k+ files.\nEach project just has a little build.xml that will make a jar out of it to include.As for the mind numbing slowness in the JSP editing. I have the same problems, it's just so dam slow. I don't have many more than 100 jsp files but I have the same issues as you. My solution has just been to throw money at hardware, which I must admit I enjoy doing :P.To answer the following question:\nTurning off validation and auto-building after file-saving is a good start to increase performance.I've disabled the WTP JSP editor for the reasons you mentioned above: It just needs too many resources. Some more things you should consider:WTP (3.2.3) is slow for me too. I belive I have found some ways to make it not so slow:If you need barebones Java EE then you are better off with Netbeans, if you need everything but just working you are better off with IDEA. It is as simple as that.Couldn't comment so I will just put my comment in to this answer.Have you tried upping Eclipse's memory allocation, I know it used to crash all the time when I used it on Mac OS X awhile ago. There is a config file that has the base RAM allocation in it, once I modified that file and gave it an extra 128 megabytes of memory it behaved better. Not sure if this will affect WTP, I am commenting more in regards to the core Eclipse application itself.
Java

I have an Ant file that compiles my program. I want the javac task to fail if any warning was reported by the compiler. Any clue on how to do that?Use the  flag. It's not listed in the  output, but it works.I found it through  and tested on my own code (in NetBeans with Ant). The output was:Note that this is Java 6 only, though.: Example of specifying this in Ant buildfile:
Java

Each java application will run in a specific Java Virtual Machine Instance.  I am really getting confused on below aspects and Googling has confused me even more. Different articles on different sites.Yes it can.  How it is done depends on the O/S and on the web server container itself.No.  Each Java application uses an independent JVM.  Each JVM is a separate process, and that means there is no sharing of stacks, heaps, etcetera.  (Generally, the only things that might be shared are the read only segments that hold the code of the core JVM and native libraries ... in the same way that normal processes might share code segments.)The mechanism for deciding how big to make the heap if you don't specify a size depends on the JVM / platform / version you are using, and whether you using the \"client\" or \"server\" model (for Hotspot JVMs).  The heuristic doesn't take account of the number or size of other JVMs.Reference:  In practice, you would probably be better off specifying the heap size directly.Neither.  The number of JVM instances is determined by the actions of various things that can start processes; e.g. daemons scripts, command scripts, users typing commands at the command line, etcetera.  Ultimately, the OS may refuse to start any more processes if it runs out of resources, but JVMs are not treated any different to other processes.No.  The JVMs are independent processes.  They don't share any mutable state.  Garbage collection operates on each JVM independently.If your instances have to coordinate their work, you can create single main instance which would run/stop other instances.You did not explain why you need multiple JVM instances. Probably, single instance would work better. 
Java

I am trying hard to get the count of unicode string and tried various options. Looks like a small problem but struck in a big way.Here I am trying to get the length of the string str1. I am getting it as 6. But actually it is 3. moving the cursor over the string \"\u0b95\u0bc1\u0bae\u0bbe\u0bb0\u0bcd\" also shows it as 3 chars. Basically I want to measure the length and print each character. like \"\u0b95\u0bc1\", \"\u0bae\u0bbe\", \"\u0bb0\u0bcd\" .PS : It is tamil language.Found a solution to your problem.Based on  I made a program that uses regex character classes to search for letters that may have optional modifiers. It splits your string into single (combined if necessary) characters and puts them into a list:where  means a Unicode letter, and  means a Unicode mark.The output of the snippet is:See  for a working DemoI now checked my regex with all valid Tamil letters taken from the tables in . I found out that with the current regex we do not capture all letters correctly (every letter in the last row in the Grantha compound table is splitted into two letters), so I refined my regex to the following solution:With this Pattern instead of the above one you should be able to split your sentence into every valid Tamil letter (as long as wikipedia's table is complete).The code I used for checking is the following one:Have a look at the  class. There is an explanation of what may be the cause of your problem. In Unicode, you can encode characters in several ways, e.g :or      You can try to use  to convert your string to the composed form and then iterate over the characters. Based on the article suggested by @halex above, try this in Java:The result I get is . If it doesn't work for all your strings, try fiddeling with other Unicode character categories in the  block.This turns out to be  ugly....\nI have debugged your string and it contains following characters (and their hex position):\u0b95  0x0b95\n\u0bc1  0x0bc1\n\u0bae   0x0bae\n\u0bbe 0x0bbe\n\u0bb0 0x0bb0\n\u0bcd 0x0bcd So tamil language obviously use diacritics-like sequences to get\nall characters which unfortunately count as separate entities.This is not a problem with UTF-8 / UTF-16 as erronously claimed by\nother answers, it is inherent in the Unicode encoding of the Tamil\nlanguage.The suggested Normalizer does not work, it seems that tamil has\nbeen designed by Unicode \"experts\" to explicitly use combination\nsequences which cannot be normalized. Aargh.My next idea is not to count , but , the visual\nrepresentations of characters.The result:\u0b95  b95 [x=0.0,y=-6.0,w=7.0,h=6.0]\n\u0bc1  bc1 [x=8.0,y=-6.0,w=7.0,h=4.0]\n\u0bae  bae [x=17.0,y=-6.0,w=6.0,h=6.0]\n\u0bbe  bbe [x=23.0,y=-6.0,w=5.0,h=6.0]\n\u0bb0  bb0 [x=30.0,y=-6.0,w=4.0,h=8.0]\n\u0bcd  bcd [x=31.0,y=-9.0,w=1.0,h=2.0]As the glyphs are intersecting, you need to use Java character type\nfunctions like in the other solution.SOLUTION:I am using this link: You need to exclude the combination characters and count them accordingly.As has been mentioned, your string contains 6 distinct code points. Half of them are letters, the other half are vowel signs. (Combining marks)You could use  built into the ICU4J library, to remove all of the vowel signs which are not Letters using the rule: [:^Letter:] Removeand count the resulting string. Try it out on their demo site: I wouldn't display the resultant string to an end user, and I'm not an expert so the rules may need to be tweaked to get to the general case but it's a thought.
Java

Starting with the following code...When I try compiling this code I will get the following error...... but if  is final...the file will compile successfully.Moving on to the following code...... will print ... which is fine. The value is copied to a final variable and it can not be changed any more. Playing with the value in the array does not change the value of the  (as expected...).Why does the following require a cast?How is this different than the second example in this question? Why is the compiler giving me the following error?How can this happen?The JLS () has special rules for assignment conversion with :If we follow the link above, we see these in the definition of :If we follow the second link above, we see thatIt follows that  can only be assigned to  if  is a . To apply that to your cases:Note that whether  is itself  doesn't matter.The value 1 fits nicely into a byte; so does 1+1; and when the variable is final, the compiler can do . (in other words: the compiler doesn't use  when doing that + operation; but the \"raw\" 1 values)But when the variable is not final, then all the interesting rules about conversions and promotions kick in (see ; you want to read section 5.12 about widening primitive conversions).For the second part: making an array final still allows you to  any of its fields; so again; no constant folding possible; so that \"widening\" operation is kicking in again.It is indeed what compiler do in constant folding when used with , as we can see from byte code:And if you change your final byte to 127, it will also complain:in which cases, the compiler compute the result and know it out of limit, so it will still complain they are incompatible.More:And  is another question about constant folding with string:
Java

I'm looking for a free Java library to visualize some data. I want to do something similar as the following two images. Is there any possibility? I first thought of prefuse, but this isn't developed since 2007. So any oher libraries?Have you considered looking at ?Graphviz (short for Graph Visualization Software) is a package of open-source tools initiated by AT&T Labs Research for drawing graphs specified in DOT language scripts. It also provides libraries for software applications to use the tools. Graphviz is free software licensed under the Eclipse Public License.You can do some fairly cool stuff with it:For the timeline part, you should really consider  which contains annoted timelines, ...Try , which seems to be the successor of Prefuse and may be a good alternative option. It is written in JavaScript, but a  is available. is the successor of Protovis today. (Recommended by Protovis.) is a possibility.Check ou:Further links can be found at:An other alternative is to use  framework. If you are looking for browser/Javascript based libraries as well, checkout Another library you could consider is JGraph. It works mainly with graphs but you can easily implement a timeline as a one. The project can be found on GitHub  and was recently updated.You'd have to no doubt do a lot of customization, but Google's Chart Tools offers a lot of flexibility and options ().  I have not done anything as involved as the images that you pasted above, but it was fairly easy to set up various charts using the Google Visualization API.  It might be worth it to post your images on the Google Visualization API group () to see if anyone has done more involved charts like those you've proposed above using the Visualization API...I am surprised this hasn't been listed. I used  a while back: If you are explicitly looking for a swing library, ignore this answer!\nBut in the world of web,  and  are my favorites. Back-end could be implemented in java.If you dont mind to use javascript solution  is what you need for the second screenshot.
Java

The Javadoc for  does not define any maximum or minimum.  However, it does say:(emphasis added)Is there such a maximum, even in theory?  Or is the way  operates fundamentally different, such that there is in reality  maximum except for the amount of memory available on the computer?The number is held in an  - the maximum size of an array is . So the maximum BigInteger probably is .Admittedly, this is implementation dependent, not part of the specification.In Java 8, some information was added to , giving a minimum supported range and the actual limit of the current implementation:From .It is implemented using an :From From the Wikipedia article :The first maximum you would hit is the length of a String which is 2-1 digits.  It's much smaller than the maximum of a BigInteger but IMHO it loses much of its value if it can't be printed.
Java

On this Oracle page , it lists  as being available and on by default.  However in Java 6 update 29, it is off by default and in Java 7 update 2 it reports a warningDoes anyone know the thinking behind removing this option? With , this example took 4.541 seconds with the option on and 5.206 second with it off in Java 6 update 29. It is hard to see that it impacts performance.Note: Java 7 update 2 requires 2.0 G whereas Java 6 update 29 without compressed strings requires 1.8 GB and with compressed string requires only 1.0 GB.Originally, this option was added to improve SPECjBB performance.  The gains are due to reduced memory bandwidth requirements between the processor and DRAM.  Loading and storing bytes in the byte[] consumes 1/2 the bandwidth versus chars in the char[].However, this comes at a price.  The code has to determine if the internal array is a byte[] or char[].  This takes CPU time and if the workload is not memory  constrained, it can cause a performance regression.  There is also a code maintenance price due to the added complexity.Because there weren't enough production-like workloads that showed significant gains (except perhaps SPECjBB), the option was removed.There is another angle to this.  The option reduces heap usage.  For applicable Strings, it reduces the memory usage of those Strings by 1/2.  This angle wasn't considered at the time of option removal.  For workloads that are memory  constrained (i.e. have to run with limited heap space and GC takes a lot of time), this option can prove useful.If enough memory  constrained production-like workloads can be found to justify the option's inclusion, then  the option will be brought back. An average server heap dump uses 25% of the space on Strings.  Most Strings are compressible.  If the option is reintroduced, it could save half of this space (e.g. ~12%)! A feature similar to compressed strings is coming back in JDK 9 .Since there were up votes, I figure I wasn't missing something obvious so I have logged it as a bug (at the very least an omission in the documentation)(Should be visible in a couple of days)Just to add, for those interested...The  interface (which  implements), allows more compact representations of Strings than UTF-16.Apps which manipulate a lot of strings, should probably be written to accept CharSequence, such that they would work with , . 8-bit (UTF-8), or even 5, 6, or 7-bit encoded, or even compressed strings can be represented as .CharSequences can also be a lot more efficient to manipulate - subsequences can be defined as views (pointers) onto the original content for example, instead of copying.For example in , a suffix tree of ten of Shakespeare's plays,  using -based nodes, and  if using char[] or String-based nodes.Java 9 executes the  twice as fast on my machine as Java 6 and also only needs 1G of memory as it has -XX:+CompactStrings enabled by default.  Also, in Java 6, the compressed strings only worked for 7-bit ASCII characters, whereas in Java 9, it supports Latin1 (ISO-8859-1).  Some operations like charAt(idx) might be slightly slower though.  With the new design, they could also support other encodings in future.I wrote a newsletter about this on .In OpenJDK 7 (1.7.0_147-icedtea, Ubuntu 11.10) it simply fails with an when JAVA_OPTS (or command line) contains . It seems Oracle really removed the option.
Java

I'm creating a generic class and in one of the methods I need to know the Class of the generic type currently in use. The reason is that one of the method's I call expects this as an argument.Example:Clearly the example above doesn't work  and results in the following error: Illegal class literal for the type parameter T.My question is: does someone know a good alternative or workaround for this?Still the same problems : Generic informations are erased at runtime, it cannot be recovered. A workaround is to pass the class T in parameter of a static method : It's ugly, but it works.I was just pointed to this solution:This works if  is given a concrete type by a subclass:Unfortunately Christoph's solution as written only works in very limited circumstances. [EDIT: as commented below I no longer remember my reasoning for this sentence and it is likely wrong: \"Note that this will only work in abstract classes, first of all.\"] The next difficulty is that  only works from DIRECT subclasses of . We can fix that, though:This will work in many situations in practice, but not ALL the time. Consider:This will throw a , because the type argument here isn't a  or a  at all; it's the  . So now you would be stuck trying to figure out what type  was supposed to stand for, and so on down the rabbit hole.I think the only reasonable, general answer is something akin to Nicolas's initial answer -- in general, if your class needs to instantiate objects of some other class that is unknown at compile-time, users of your class need to pass that class literal (or, perhaps, a Factory) to your class explicitly and not rely solely on generics.i find another way to obtain the Class of the generic objectI will elaborate on Christoph's solution.Here is the ClassGetter abstract class:Here is a static method which uses the above class to find a generic class' type:As an example of it's usage, you could make this method:And then use it like this:T can be resolved pretty easily using :
Java

Description for  from the Java docs:Is there an equivalent for  in the .NET-Framework?
Java

This is the class:Now I'm trying to get \"reflect\" this method from the class:There's just an .An alternative is .The same applies on other primitives.
Java

I am trying to learn spring data JPA by testing some CRUD operation via .I came across two methods  and .\nI don't get the difference between these two. On calling  also my changes are getting saved into database so what is the use of .On , changes will be flushed to DB immediately in this command. With , this is not necessarily true, and might stay just in memory, until  or  commands are issued. But be aware, that even if you flush the changes in transaction and do not commit them, the changes still won't be visible to the outside transactions until the commit in this transaction.In your case, you probably use some sort of transactions mechanism, which issues  command for you if everything works out fine.Depending on the hibernate flush mode that you are using ( is the default) save may or may not write your changes to the DB straight away. When you call saveAndFlush you are enforcing the synchronization of your model state with the DB.If you use flush mode AUTO and you are using your application to first save and then select the data again, you will not see a difference in bahvior between  and  because the select triggers a flush first. See the .
Java

Is it possible to add a file (not necessarily a jar file) to java classpath at runtime.\nSpecifically, the file already is present in the classpath, what I want is whether I can add a modified copy of this file to the classpath.Thanks,You can only add folders or jar files to a class loader. So if you have a single class file, you need to put it into the appropriate folder structure first. is a rather ugly hack that adds to the SystemClassLoader at runtime:The reflection is necessary to access the protected method . This could fail if there is a SecurityManager.Try this one on for size.This edits the system class loader to include the given library jar. It is pretty ugly, but it works.The way I have done this is by using my own class loaderAnd create the following class:Works without any reflectionYou coud try java.net.URLClassloader with the url of the folder/jar where your updated class resides and use it  instead of the default classloader when creating a new thread. yes, you can.  it will need to be in its package structure in a separate directory from the rest of your compiled code if you want to isolate it.  you will then just put its base dir in the front of the classpath on the command line.  Yes I believe it's possible but you might have to implement your own classloader.  I have never done it but that is the path I would probably look at.  My solution:
Java

Consider the following code.I am getting i value up to  correctly. After catching the  output getting wired as follows.Consider  demo here. It is working correctly up to . Actually how this happen?  I did following code to realize what is happening here.Now previous issue not there. now value of  up to  correct and and runs further. I am hopping this may runs up to value of (max value of int) without an issue.There is some issue with . There are similar answers bellow too. But why? What will be the actual reason?Note the absence of newline characters in . It indicates that something wrong happens inside .The essential point here is that  requires some stack space to work, so that  is thrown from .Here is your code with marked points:Let's imagine what happens at level N of recursion when i = :After this point the situation repeats with . I'm not sure why some numbers are printed correclty between sequences without newlines, perhaps its related to internal work of  and buffers it uses.What I suspect being happening is this:When Exception is thrown by try Block,  has same value when it comes in catch block (as its not incremented due to exception) and then inside catch block same exception is thrown and which is again caught by catch block !  when try block throws exception it is caught by catch block but when it goes to  again Exception is thrown 4 times (in my eclipse)   Without printing As in above output, i have tested it by printing \"Before\" Text which is printed four times before it prints If the execution of  (or one of the methods called by it) causes a stack overflow, you will print the same  value from the catch clause of the enclosing  incarnation.The exact behavior is rather unpredictable as it depends on the stack space still available.As the other answers already explain it has to do with System.out.println requiring extra space on the stack and thus throwing itself a StackOverflowError.Try this code here to see some different behaviour which shows that at some point there is exceptions being thrown all over the place so that i++ cannot occur anymore.The important lession to learn is: Never catch Errors as they really indicate that there is something serious wrong with your JVM which cannot be handled normally.The bottom line is that  is an error, not an exception. You are handling an error, not an exception.So the program has already crashed when it enters the catch block.Regarding the strange behaviour of the program, below is the explanation on basis of java buffers from  official doc:The  internally calls the  which is buffered. You don't loose any data from the buffer, it gets all written to the output( terminal in your case) after it fills up, or when you explicitly call flush on it. Coming back to this scenario, it depends on the internal dynamics of how much the stack is filled up and how many print statements were able to get executed from the catch in  and those number of characters were written to the buffer. Here after the first try is executed, i.e. in the event of first occurence of the stack overflow, the first System.out.println() fails to print the new line so it flushed the buffer with remaining characters. axtavt Answer is very complete but I'd like to add this:As you may know the stack is used to store the memory of variables, based on that you cannot create new variables when you reach the limit, it is true that System.out.println will need some stack resourcesThen after calling the print, the error does not allow you to even call the newLine, it breaks again right on the print. Based on that you can make sure that's the case by changing your code like this:Now you will not ask the stack to handle the new lines, you will use the constant \"\\n\" and you may add some debugging to the exception printing line and your output will not have multiple values in the same line:And it will keep broken until get some resources to allocate new data and pass to the next i value.
Java

I wonder if there are any suggestions for declarative GUI programming in Java. (I abhor visual-based GUI creator/editor software, but am getting a little tired of manually instantiating JPanels and Boxes and JLabels and JLists etc.)That's my overall question, but I have two specific questions for approaches I'm thinking of taking: lots of great answers here! (& I added #3 above) I'd be especially grateful for hearing any experiences any of you have had with using one of these frameworks for real-world applications.p.s. I did try a few google searches (\"java gui declarative\"), just didn't quite know what to look for.You might have a look at ; it uses  to build Swing UIs.A simple example from the  [PDF]:Alternatively:Or even:As the author of CookSwing, a tool that does what you need, I've given this subject a long hard look before doing the actual implementation.  I made a living writing Java Swing GUI applications.IMO, if you are going to use any kind of imperative programming languages to describe Java Swing component, you might as well just use Java.  Groovy etc only adds complications without much simplification.Declarative languages are much better, because even non-programmers can make sense out of it, especially when you need to delegate the task of fine tuning of specific layouts to artists.  XML is perfect for declarative languages (over other choices) because of simplicity, readability, and plenty of editors/transformation tools etc available.Here are the problems faced in declarative GUI programming, not in any particular order.  These issues have been addressed in CookSwing.If conciseness is important you might want to consider the double brace idiom:You then don't lose any of the power of a well known general purpose programming language (you know you are going to need it, and JellyTags suck). All you need is the one little extra idiom.It's not used very much, because actually people pissing around with XML weren't solving real pain points.In general you can use builder layers to abstract repeated code. GUI code doesn't have to be badly written, it's just that almost all of it is (including in text books).I strongly recommend  - it takes a few days to get used to the syntax, but once you've got it, it works wonders.  I used JGoodies Forms for quite awhile, and Karsten's builder concept works well, but it is a bit cryptic...  MiG is easier to pick up, and results in wonderfully concise code.If you're willing to step slightly outside plain Java, 's \"builder\" concept works pretty well with GUIs. Of course you can interop between Groovy and Java fairly easily. See the  page for more information.give Swiby a try: \"Swiby is a blend of Swing and Ruby for truly rich distributed applications.\"\nIn other words Swiby is a domain specific language mixing swing and ruby. does exactly what you need. Its a tiny (283k), unobtrusive, easy to learn declarative Swing framework.SDL/Swing is open source but enjoys commercial support. We (Ikayzo.com) developed it over a period of years and have deployed it in production systems for many customers ranging from life science companies to banks.I can find the following examples of what you're asking for:I recently come across .something new..., will be included in eclipse e4I've tried many solutions, such as SWIXML, Javabuilders, MigLayout, Cookswing. I finally found the javaFX and javaFX-Scenebuilder the best an fastest solution, XML-based GUI tool. you'd like the way scenebuilder creates GUI (with drag & drop items!). plus, it uses CSS (Cascading Style Sheets) for the GUI theme. Jsut trust the Oracle, it's the best GUI tool for java applications.\ntake a tour for creating javaFX apps with scenebuilder, here:\nAlthough it is not declarative and is limited exclusively to layouts, you might want to take a look at  which allows to programmatically define Swing layouts in a very concise manner (it's open source).Main advantages:As often, it's always a good idea to perform a search when you're looking for something.  is the first link in google while looking for \"java xml gui\", it a very nice plugin, which included GWT,XWT,SWT,Swing etc
Java

Take a look at the following example:The first  writes  but the second throws a .Why is only the second line worth an exception? And what is the difference between the two s? Is there a   and a   in Java?The first invocation will call the  method, as you have explicitly typecasted  to  reference. Conversely, the second one will invoke the overloaded  method, as  is more specific than  for a  argument. There are other overloaded versions of this method that accept primitive parameters, but those are not a valid match for a  argument.From :Now check the source code of both the methods:There are lots of overloaded  methods in Java. Further, in Java  has any and all types so that anything (that isn't a primitive) can be .So, when you call  you call the  method that takes an  as use explicitly cast  to .In the second example you don't explicitly cast the  to any particular type so in fact you call the  method with a  which throws an NPE.From the In this case  is  than  so it is called when no explicit cast of  is made.Although I accepted already an answer I would like to add the exact answer to the question, because the two answers concentrate on explaining the trap I walked into.The difference between  and  is that the type of the first is forced to  but the type of the second is not, as one could think, forced to . Instead it could also be an array instead of an object.So the conclusion is: pass  instead of  as an argument to a method to be sure to get exactly the method working on objects instead of any other method working on arrays.
Java

I'm working on a project, written in Java, which requires that I build a very large 2-D sparse array.  Very sparse, if that makes a difference.  Anyway: the most crucial aspect for this application is efficency in terms of time (assume loads of memory, though not nearly so unlimited as to allow me to use a standard 2-D array -- the key range is in the billions in both dimensions).Out of the kajillion cells in the array, there will be several hundred thousand cells which contain an object.  I need to be able to modify cell contents VERY quickly.Anyway: Does anyone know a particularly good library for this purpose?  It would have to be Berkeley, LGPL or similar license (no GPL, as the product can't be entirely open-sourced).  Or if there's just a very simple way to make a homebrew sparse array object, that'd be fine too.I'm considering , but haven't heard any opinions on its quality.Sparsed arrays built with hashmaps are very inefficient for frequently read data. The most efficient implementations uses a Trie that allows access to a single vector where segments are distributed.A Trie can compute if an element is present in the table by performing only read-only TWO array indexing to get the effective position where an element is stored, or to know if its absent from the underlying store.It can also provide a default position in the backing store for the default value of the sparsed array, so that you don't need ANY test on the returned index, because the Trie guarantees that all possible source index will map at least to the default position in the backing store (where you'll frequently store a zero, or an empty string or a null object).There exists implementations that support fast-updatable Tries, with an otional \"compact()\" operation to optimze the size of the backing store at end of multiple operations. Tries are MUCH faster than hashmaps, because they don't need any complex hashing function, and don't need to handle collisions for reads (With Hashmaps, you have collision BOTH for reading and for writing, this requires a loop to skip to the next candidate position, and a test on each of them to compare the effective source index...)In addition, Java Hashmaps can only index on Objects, and creating an Integer object for each hashed source index (this object creation will be needed for every read, not just writes) is costly in terms of memory operations, as it stresses the garbage collector.I really hoped that the JRE included an IntegerTrieMap<Object> as the default implementation for the slow HashMap<Integer, Object> or LongTrieMap<Object> as the default implementation for the even slower HashMap<Long, Object>... But this is still not the case.You may wonder what is a Trie?It's just a small array of integers (in a smaller range than the full range of coordinates for your matrix) that allows mapping the coordinates into an integer position in a vector.For example suppose you want a 1024*1024 matrix containing only a few non zero values. Instead of storing that matrix in a array containing 1024*1024 elements (more than 1 million), you may just want to split it into subranges of size 16*16, and you'll just need 64*64 such subranges.In that case, the Trie index will contain just 64*64 integers (4096), and there will be at least 16*16 data elements (containing the default zeroes, or the most common subrange found in your sparse matrix).And the vector used to store the values will contain only 1 copy for subranges that are equal with each other (most of them being full of zeroes, they will be represented by the same subrange).So instead of using a syntax like , you'd use a syntax like:which will be more conveniently handled using an access method for the trie object.Here is an example, built into a commented class (I hope it compiles OK, as it was simplified; signal me if there are errors to correct):Note: this code is not complete because it handles a single matrix size, and its compactor is limited to detect only common subranges, without interleaving them.Also, the code does not determine where it is the best width or height to use for splitting the matrix into subranges (for x or y coordinates), according to the matrix size. It just uses the same static subrange sizes of 16 (for both coordinates), but it could be conveniently any other small power of 2 (but a non power of 2 would slow down the  and  internal methods), independantly for both coordinates, and up to the maximum width or height of the matrix.ideally the  method should be able to determine the best fitting sizes.If these splitting subranges sizes can vary, then there will be a need to add instance members for these subrange sizes instead of the static , and to make the static methods  and  into non static; and the initialization arrays and  will need to be dropped or redefined differently.If you want to support interleaving, basically you'll start by dividing the existing values in two of about the same size (both being a multiple of the minimum subrange size, the first subset possibly having one more subrange than the second one), and you'll scan the larger one at all successive positions to find a matching interleaving; then you'll try to match these values. Then you'll loop recursely by dividing the subsets in halves (also a multiple of the minimum subrange size) and you'll scan again to match these subsets (this will multiply the number of subsets by 2: you have to wonder if the doubled size of the subrangePositions index is worth the value compared to the existing size of the values to see if it offers an effective compression (if not, you stop there: you have found the optimum subrange size directly from the interleaving compression process). In that case; the subrange size will be mutable, during compaction.But this code shows how you assign non-zero values and reallocate the  array for additional (non-zero) subranges, and then how you can optimize (with  after assignments have been performed using the  method) the storage of this data when there are duplicate subranges that may be unified within the data, and reindexed at the same position in the  array.Anyway, all the principles of a trie are implemented there:Note that the generic Colt library, though very good as it is, is not as good when working on sparse matrice, because it uses hashing (or row-compresssed) technics which do not implement the support for tries for now, despite it is an excellent optimization, which is both space-saving  time-saving, notably for the most frequent getAt() operations. Even the setAt() operation described here for tries saves lot of time (the way is is implemented here, i.e. without automatic compaction after setting, which could still be implemented based on demand and estimated time where compaction would still save lot of storage space at the price of time): the time saving is proportional to the number of cells in subranges, and space saving is inversely proportional to the number of cells per subrange. A good compromize if then to use a subrange size such the number of cells per subrange is the square root of the total number of cells in a 2D matrix (it would be a cubic root when working with 3D matrice).Hashing technics used in Colt sparse matrix implementations have the inconvenience that they add a lot of storage overhead, and slow access time due to possible collisions. Tries can avoid all collisions, and can then warranty to save linear O(n) time to O(1) time in the worst cases, where (n) is the number of possible collisions (which, in case of sparse matrix, may be up to the number of non-default-value cells in the matrix, i.e. up to the total number of size of the matrix times a factor proportional to the hashing filling factor, for a non-sparse i.e. full matrix).The RC (row-compressed) technics used in Colt are nearer from Tries, but this is at another price, here the compression technics used, that have very slow access time for the most frequent read-only get() operations, and very slow compression for setAt() operations. In addition, the compression used is not orthogonal, unlike in this presentation of Tries where orthogonality is preserved. Tries would also be preserve this orthogonality for related viewing operations such as striding, transposition (viewed as a striding operation based on integer cyclic modular operations), subranging (and subselections in general, including with sorting views).I just hope that Colt will be updated in some future to implement another implementation using Tries (i.e. TrieSparseMatrix instead of just HashSparseMatrix and RCSparseMatrix). The ideas are in this article.The Trove implementation (based in int->int maps) are also based on hashing technics similar to the Colt's HashedSparseMatrix, i.e. they have the same inconvenience. Tries will be a lot faster, with a moderate additional space consumed (but this space can be optimized and become even better than Trove and Colt, in a deferred time, using a final compact()ion operation on the resulting matrix/trie).Note: this Trie implementation is bound to a specific native type (here double). This is voluntary, because generic implementation using boxing types have a huge space overhead (and are much slower in acccess time). Here it just uses native unidimensional arrays of double rather than generic Vector. But it is certainly possible to derive a generic implementation as well for Tries... Unfortunately, Java still does not allow writing really generic classes with all the benefits of native types, except by writing multiple implementations (for a generic Object type or for each native type), and serving all these operation via a type factory. The language should be able to automatically instanciate the native implementations and build the factory automatically (for now it is not the case even in Java 7, and this is something where .Net still maintains its advantage for really generic types that are as fast as native types).Following framework to test Java Matrix Libraries, provides also a good list of these!\nTested Libraries:Here is a paper you may be interested in which talks about data structures for matrix computations, including sparse arrays:You can download the paper as PDF or PS.  It includes source code, too.Maybe  is of help. It provides a sparse matrix implementation.This seems to be simple.You could use a binary tree of the data using row*maxcolums+column as an index.To find item, you simply calculate row*maxcolums+column and binary search the tree looking for it, if it's not there, you can return null (it's \u041e(log n) where n is the number of cells which contain an object).Not the fastest runtime solution probably, but the fastest I could come up with that seems to work. Create an Index class and use it as a key for a SortedMap, like:My Index class looks like this (with some help from Eclipse code generator).I've just used  which provided much better performance than Colt while using the int->int map (used to implement a sparse matrix). You migth look at  (Linear Algebra for Java) library. It supports  as well as  internal representaions for sparse matrices. So, these are the most efficient and fast internal stuctures for sparse data.Here is the brief example of using sparse matrices in :you could just use a nested map although if you need to do matrix calculus on it that might not be the best optionmaybe instead of object use some tuple for the actual data so you can work with it easier after extraction, something like:null check etc omitted for brevitySuanShu has a suite of  and .HashMap rocks. Just concatenate the indexes (as strings) with a separator, say '/', using StringBuilder (not + or String.format), and use that as the key. You can't get faster and more memory-efficient than that. Sparse matrices are soo 20th century. :-)
Java

I have a 2\u00a0GB file () in which every line in the file is a word, just like:I need to write a program to read every word in the file and print the word count. I wrote it using Java and C++, but the result is surprising: Java runs 2.3 times faster than C++. My code are as follows:C++:Output:Java:Output:Why is Java faster than C++ in this situation, and how do I improve the performance of C++?You aren't comparing the same thing. The Java program reads lines, depening on the newline, while the C++ program reads white space delimited \"words\", which is a little extra work.Try .You might also try and do an elementary read operation to read a byte array and scan this for newlines. On my old Linux notebook, jdk1.7.0_21 and don't-tell-me-it's-old 4.3.3 take about the same time, comparing with C++ getline. (We have established that reading words is slower.) There isn't much difference between -O0 and -O2, which doesn't surprise me, given the simplicity of the code in the loop.\nAs I suggested, fin.read(buffer,LEN) with LEN = 1MB and using memchr to scan for '\\n' results in another speed improvement of about 20%, which makes C (there isn't any C++ left by now) faster than Java.There are a number of significant differences in the way the\nlanguages handle , all of which can make a difference, one way\nor another.Perhaps the first (and most important) question is: how is the\ndata encoded in the text file. If it is single-byte characters\n( or ), then Java has to convert it into \nbefore processing; depending on the locale, C++ may (or may not)\nalso convert or do some additional checking.As has been pointed out (partially, at least), in C++,  uses\na locale specific ,  will simply compare for\n, which is probably faster. (Typical implementations of\n will use a bitmap, which means an additional memory\naccess for each character.)Optimization levels and specific library implementations may\nalso vary. It's not unusual in C++ for one library\nimplementation to be 2 or 3 times faster than another.Finally, a most significant difference: C++ distinguishes\nbetween text files and binary files. You've opened the file in\ntext mode; this means that it will be \"preprocessed\" at the\nlowest level, before even the extraction operators see it. This\ndepends on the platform: for Unix platforms, the \"preprocessing\"\nis a no-op; on Windows, it will convert CRLF pairs into ,\nwhich will have a definite impact on performance. If I recall\ncorrectly (I've not used Java for some years), Java expects\nhigher level functions to handle this, so functions like\n will be slightly more complicated. Just guessing\nhere, but I suspect that the additional logic at the higher\nlevel costs less in runtime than the buffer preprocessing at the\nlower level. (If you are testing under Windows, you might\nexperiment with opening the file in binary mode in C++. This\nshould make no difference in the behavior of the program when\nyou use ; any extra CR will be considered white space. With\n, you'll have to add logic to remove any trailing\n to your code.)I would suspect that the main difference is that  performs better than the  because it buffers, while the ifsteam does not. The BufferedReader reads large chunks of the file in advance and hands them to your program from RAM when you call , while the std::ifstream only reads a few bytes at a time when you prompt it to by calling the -operator.Sequential access of large amounts of data from the hard drive is usually much faster than accessing many small chunks one at a time.A fairer comparison would be to compare std::ifstream to the unbuffered java.io.FileReader. I am not expert in C++, but you have at least the following to affect performance:Since  cost is the major cost here, I guess 1 and 2 are the major reasons.I would also try using  instead of standard file read/write. This should let your OS handle the reading and writing while your application is only concerned with the data.There's no situation where C++ can't be faster than Java, but sometimes it takes a lot of work from very talented people. But I don't think this one should be too hard to beat as it is a straightforward task.mmap for Windows is described in  ().
Java

Why does BigInteger class has constant TEN and ONE? Any practical uses for having them as constants?  I can understand some use cases for ZERO. Let's say you have written a function that returns  after some calculations and db operations. You often may need to return values like null, 0, 1. It's easy to return . This values are public since they are needed .Also  is commonly used for power/divide/mod operations.Checkout  public methods. You will easily see their common use cases. is probably the most fundamental number in mathematics (alongside zero). Seems to deserve its own constant on that alone. Practically, it's a useful number to have as a constant in many algorithms. is important in the BigInteger context because it is the base of the decimal number system. This is important because several BigInteger functions need a radix base (e.g. . It's therefore a pretty useful constant to have.IMHO that was a design decision because 1 and 10 are used in other parts of the Java API code base. Creating Big* is an expensive operation and using constant avoid new object creation (Big* are immutable anyway) and the code is more readable.Probably other constants weren't needed by the rest of the API.Making them public was probably a fault. (The java API is full of \"bad\" design decisions)I don't know actually, but maybe:Maybe they just used these constans a lot internally? (I haven't checked the source code, but it's Open Source).E.g.:After looking at the code I think the reason is because they use ZERO and ONE a lot internally. Probably thought that others might profit from these constants as well given the reasons above. Or maybe they use these constants in some other classes as well.TEN has been added in v1.5\nIt doesn't seem to be used internally, but maybe by another class?10, 0 and 1 can answer almost everything. for example if you want to arrive at 42, you can do a (10 + 10 + 10 + 10 + 1 + 1) :)
Java

On the following code:I'm getting the error:Why?Capacity does not equal size. The size parameter that you are passing in simply allocates enough memory for the size. It does not actually define elements. It's actually kind of a silly requirement of , but it is one nonetheless.The key part from the :You should just pass the  to the 's constructor to copy all of the  to avoid the issue altogether.That's a very good question and it almost certainly has to do with the fact that setting a collections capacity does not necessarily allocate the underlying objects, but why are you doing it that way when you can just:The constructor  will copy every elements from  into the newly created instance, thus copying  into . It is the same as  also, which is really what you need.It does make sense that  requires the  array to be large enough to hold all elements from the  array. A similar analogy is the C function  and the like.
Java

I get the following runtime error message (along with the first line of the stack trace, which points to line 94).  I'm trying to figure out why it says no such method exists.Line 94 of writeSummaryLink is shown below.\nWhat does \"ILcom\" or \"Z\" mean?\nWhy there are four types in parentheses \n    (ILcom/sun/javadoc/ClassDoc;Lcom/sun/javadoc/MemberDoc;Ljava/lang/String;Z) \nand one after the parentheses\n    Ljava/lang/String;\nwhen the method printDocLinkForMenu clearly has five parameters?\nThe writeSummaryLink method is:Here's the method line 94 is calling:From  of the JVM Spec:From :Thus, translates to:A method with , , ,  and  as parameters, and which returns a . Note that only reference parameters are separated with a semicolon, since the semicolon is part of their character representation.There are five parameters (int, ClassDoc, MemberDoc, String, boolean) and one return type (String).Those are mapping types for native types. You can find an overview .As to your next question:Because you're not running the code you think you're running. The  running code is trying to call exactly that method described in the error message, with actually five parameters (the  should be counted separately) and a return type, but this method doesn't exist in the runtime classpath (while it was available in the compiletime classpath), hence this error. Also see the : So, verify if you're actually running the right version of the code as you've posted in your question and are using the right dependencies in the runtime classpath and not having duplicate different versioned libraries in the classpath.: the exception signifies that the  code is (implicitly) trying to use the method like as follows:Because it is expecting a  outcome while it is declared .
Java

Given:Is there a regex that works with  to grab (up to) two words at a time, such that:results in this:This question is about . It is  about \"finding a work-around\" or other \"making it work in another way\" solutions.Is this what you are looking for? \noutput: is previous match,  is negative lookbehind.In  we are trying to Only confusion that I had at start was how would it work for first space since we want that space to be ignored. . So before first iteration regex in negative look-behind will look like  and since first space  have  before, it can't be match for split. Next space will not have this problem, so it will be matched and informations about it (like its  in  String) will be stored in  and used later in next negative look-behind.So for 3rd space regex will check if there is previously matched space  and word  before it. Since result of this test will be positive, negative look-behind wont accept it so this space wont be matched, but 4th space wont have this problem because space before it wont be the same as stored in  (it will have different position in  String).Also if someone would like to separate on lets say every 3rd space you can use this form (based on 's  which was deleted when I posted this fragment of answer) Instead of 100 you can use some bigger value that will be at least the size of length of longest word in String.I just noticed that we can also use  instead of  if we want to split with every odd number like every 3rd, 5th, 7th for exampleThis will work, but maximum word length needs to be set in advance:I like Pshemo's answer better, being shorter and usable on arbitrary word lengths, but this (as @Pshemo pointed out) has the advantage of being adaptable to groups of more than 2 words.this worked for me \nexample You can try this:
Java

I'm reading about volatile keyword in Java and completely understand the theory part of it.But, what I'm searching for is, a good case example, which shows what would happen if variable wasn't volatile and if it were.Below code snippet doesn't work as expected ( )Ideally, if keepRunning wasn't volatile, thread should keep on running indefinetely. But, it does stop after few seconds.I've got two basic question :-Volatile --> Guarantees visibility and NOT atomicitySynchronization (Locking) --> Guarantees visibility and atomicity (if done properly)Use volatile only when you are updating the reference and not performing some other operations on it.Example:will not be thread safe without use of synchronization or AtomicInteger as incrementing is an compound operation.Well that depends on various circumstances. In most cases JVM is smart enough to flush the contents. discusses various possible uses of volatile. Using volatile correctly is tricky, I would say \"When in doubt, Leave it out\", use synchronized block instead.Also:. For your particular example: if not declared volatile the server JVM could hoist the  variable out of the loop because it is not modified  the loop (turning it into an infinite loop), but the client JVM would not. That is why you see different results.General explanation about volatile variables follows:When a field is declared , the compiler and runtime are put on notice that this variable is shared and that operations on it should not be reordered with other memory operations. Volatile variables are not cached in registers or in caches where they are hidden from other \nprocessors, so . The visibility effects of volatile variables extend beyond the value of the volatile variable itself. When thread A writes to a volatile variable and subsequently thread B reads that same variable, the values of all variables that were visible to A prior to writing to the volatile variable become visible to B after reading the volatile variableThe  most  common  use  for  volatile  variables  is  as  a completion, interruption, or status flag:Volatile variables can be used for other kinds of state information, but more care is required when attempting this. For example, the semantics of volatile are not strong enough to make the increment operation () atomic, unless you can guarantee that the variable is written only from a single thread.You can use volatile variables only when all the following criteria are met: : be sure to always specify the -server JVM command line switch when invoking the JVM, even for development and testing. The server JVM performs more optimization than the client JVM, such as hoisting variables out of a loop that are not modified in the loop; code that might appear to work in the development environment (client JVM) can break in the deployment environment \n(server JVM).This is excerpt from Java Concurrency in Practice, the best book you can find about this subject.I have modified your example slightly. Now use the example with keepRunning as volatile and non volatile member :When a variable is , it is guaranteeing that it will not be cached and that different threads will see the updated value. However, not marking it  does not guarantee the oppostie.  was one of those things that was broken in the JVM for a long time and still not always well understood (and often left out by developers). So the JVM is somewhat smart about not caching variable values indefinitely, though you should mark it .Consider the code ,first  keyword,this program should  until  is pressed. But on  it may happen that variable  is  and you cannot change its value from shutdown() method which results in  printing of hello text.Thus using volatile keyword ,it is  that your variable will not be cached ,ie will  on . Thus using volatile keyword is a  and . is not going to necessarily create giant changes, depending on the JVM and compiler. However, for many (edge) cases, it can be the difference between optimization causing a variable's changes to fail to be noticed as opposed to them being correctly written.Basically, an optimizer may choose to put non-volatile variables on registers or on the stack. If another thread changes them in the heap or the classes' primitives, the other thread will keep looking for it on the stack, and it'll be stale. ensures such optimizations don't happen and all reads and writes are directly to the heap or another place where all threads will see it.Please find the solution below,The value of this variable will never be cached thread-locally: all reads and writes will go straight to \"main memory\". The volatile force the thread to update the original variable for each time. Please refer this link  to get more clarity in it.if you declare a variable as volatile, then it will not be stored in the local cache. Whenever thread are updating the values, it is updated to the main memory. So, other threads can access the updated value.If you are running in a single-processor or if your system is very busy, the OS may be swapping out the threads which causes some levels of cache invalidation.   As others have mentioned, not having a  doesn't mean that memory will  be shared but the JVM is trying to not synchronize memory if it can for performance reasons so the memory may not be updated.Another thing to note is that  is synchronized because the underlying  does synchronization to stop overlapping output.  So you are getting memory synchronization \"for free\" in the main-thread.  This still doesn't explain why the reading loop sees the updates at all however.Whether the  lines are in or out, your program spins for me under Java6 on a MacBook Pro with an Intel i7.I think your example is good.  Not sure why it isn't working with all  statements removed.  It works for me.In terms of memory synchronization,  throws up the same memory barriers as a  block except that the  barrier is uni-directional versus bi-directional.   reads throw up a load-barrier while writes throw up a store-barrier.  A  block is a bi-directional barrier.In terms of , however, the answer is \"it depends\".  If you are reading or writing a value from a field then  provides proper atomicity.  However, incrementing a  field suffers from the limitation that  is actually 3 operations: read, increment, write.  In that case or more complex mutex cases, a full  block is in order.Objects that are declared as volatile are usually used to communicate state information among threads,To ensure CPU caches are updated, that is, kept in sync, in the presence of volatile fields, a CPU instruction, a memory barrier, often called a membar or fence, is emitted to update CPU caches with a change in a volatile field\u2019s value.The volatile modifier tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of your program.The volatile variable must be used in Thread Context only. see the example 
Java

I have a small Java project in Eclipse. I have a class of JUnit tests for each class in the project. I'm using JUnit 4, and this is not a maven project.Is there an easy way to tell Eclipse to run all tests in all test classes at once?Right click on a source folder then .Select the source directory containing all test classes, right-click, select \"Run as...\" and select JUnit test.
Java

This code produces different outputs in Java 6 and Java 7.\nIn Java 6 the  condition returns  and in Java 7 the  returns . Why?Why does this program produces different output in Java 6 and Java 7?It seems that JDK7 process intern in a different way as before.\nI tested it with build 1.7.0-b147 and got \"both are equal\", but when executing it (same bytecode) with 1,6.0_24 I do not get the message.\nIt also depends where the  line is located in the source code. The following code also does not output the message:  it seems like  after not finding the String in its pool of strings, inserts the actual instance s1 into the pool. The JVM is using that pool when s2 is created, so it gets the same reference as s1 back. On the other side, if s2 is created first, that reference is stored into the pool.\nThis can be a result of moving the interned Strings out from the permanent generation of the Java heap.  Found here:   Not sure if that is a bug and from which version... The JLS 3.10.5 states  so the question is how pre-existing is interpreted, compile-time or execute-time: is \"Goodmorning\" pre-existing or not?\nI prefer the way it WAS implemented before 7...Let's omit unnecessary details from the example:Let's consider  as a black box. Based on a few test cases run, I would conclude that implementation is as following:Java 6:\nif the pool contains object equals to , then return reference to that object,\nelse create new string (equal to ), put to the pool, and return reference to that created instance.Java 7:\nif the pool contains object equals to , then return reference to that object,\nelse put  to the pool, and return .Neither Java 6 nor Java 7 breaks the .It seems that new intern method behavior was a result of the fix of this bug: . compares the references. The intern method makes sure strings with the same value have the same reference.The javadoc for the  explains:So without interning the compiler looks at the constants in the java code and builds its constant pool from that. There is a different pool maintained by the String class, and interning checks the string passed in against the pool and makes sure the reference is unique (so that == will work).In jdk6:\n creates a String object \"Good\" in constant pool. creates another String object \"morning\" in constant pool but this time actually JVM do: .Now as the  operator creates an object in heap therefore the reference in  is of heap not constant pool \nand the  creates a String object \"Goodmorning\" in constant pool whose reference is stored in .Therefore,  condition is false.But what happens in jdk7?FIRST CASE:In the first code snipped you are actually adding three Strings in the Pool of Strings.\n1. s1 = \"Good\"\n2. s1 = \"Goodmorning\" (after concatenating)\n3. s2 = \"Goodmorining\"While doing if(s1==s2), the objects are same but reference as different hence it is false.SECOND CASE:In this case you are using s1.intern(), which implies that if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned. You need to use . Using  with  objects compares the object references themselves.Edit: When I run your second code snippet, I do not get \"both are equal\" printed out.Edit2: Clarified that references are compared when you use '=='.there are mainly 4 ways to compare string:Whenever you are comparing between two String, don't use  and use  becaue you are comparing objects not references:The result code dependents runtime:If you write like this:the reason is ' ldc #N ' (Load string from constant pool) and String.intern() both will use StringTable in hotspot JVM. For detail I wrote a pool english article: 
Java

I have a web archive with a file placed in the WEB-INF directory.How do I load that file in a java class?I know I can put it in the classes directory and load it from there. It would just be put it in WEB-INF. Use the  method on the ServletContext object, e.g.How you get a reference to the ServletContext depends on your application... do you want to do it from a Servlet or from a JSP?EDITED: If you're inside a Servlet object, then call . If you're in JSP, use the predefined variable .Here is how it works for me with no Servlet use.Let's say I am trying to access web.xml in project/WebContent/WEB-INF/web.xml
Java

Why can't I do:Because  doesn't extend . Here is an .As to why that's an interesting question. This isn't exactly your question but it sheds some light on it. From the :That basically suggests to me that Sun wants to distance themselves from Enumeration, which is very early Java with quite a verbose syntax.Using Collections utility class, Enumeration can be made iterable like:I have solved this problem with two very simple classes, one for  and one for .  The enumeration wrapper is as follows:Which can be used either with a static utility method (which is my preference):or by instantiating the class:The new-style-for-loop (\"foreach\") works on arrays, and things that implement the  interface.It's also more analogous to  than to , so it wouldn't make sense for  to work with foreach unless  did too (and it doesn't). \n is also discouraged in favor of . doesn't implement  and as such can't be used directly in a foreach loop. However using  it's possible to iterate over an enumeration with:You could also use a shorter syntax with  but this is less efficient (two iterations over the elements and more memory usage) :Because an Enumeration (and most classes derived from this interface) does not implement Iterable.You can try to write your own wrapper class.
Java

I am a little confused over the term \"package private\" that some of the documentation uses, along with the usage of \"default access.\" Aren't package private and default access both synonymous with protected?Yes, it's almost the same. The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, , by a subclass of its class in another package. The \"default\" access modifier (the one where none of them are explicitly given) is \"package-private\", which means only things in the same package can access them. However, being in the same package implies nothing about the inheritance relationship between classes -- it's purely a naming convention.\"Protected\" means that not only classes in the same package, but also subclasses (regardless of which package those subclasses are in) will be able to access it.The default access for  is package-private, however the default access for  members is public.e.g.The default access rules for interfaces are not the same as for classes.package private and default access are synonym... An object also can access protected member of the objects whose classes are on the same package.. An object also can access protected member of its superclasses without a condition about their package. As a concrete example ;'Package private' and default access are the same. In early releases of the compiler around 1.1.2/3, 'package' was an allowed modifier, but ignored, meaning the same as no modifier, i.e. 'package private'. Shortly afterwards there was a short lived fashion for putting  (as a comment) in such situations. Similarly at that time you could declare things like synchronized classes, although again there was no actual semantic effect.Neither of them is the same as 'protected', which extends to derived classes in other packages.From  and  both are same, which means both can be used by any class till they are in same package.The  term, actually, is termed by the meaning of  modifier as  means it is available only in same class and no other classes or subclasses can access it within same package or without.Hence  means same as .
Java

I was wondering how Java orders items in the  ( or ) when they are added. Are the keys ordered by the hashcode, memory reference or by allocation precedence...?It's because I've noticed same pairs in the  are not always in the same order is unordered; you can't and shouldn't assume anything beyond that. uses insertion-order., a , uses either natural or custom ordering of the keys.First of all:  specifically  provide a stable and/or defined ordering. So anything you observe is simply an implementation detail and you  depend on it in any way.Since it is sometimes useful to know the reason for the seemingly random ordering, here's the basic idea:A  has number of buckets (implemented as an array) in which to store entries.When an item is added to the map, it is assigned to a buckets based on a value derived of its  and the bucket size of the . (Note that it's possible that the bucket is already occupied, which is called a collision. That's handled gracefully and correctly, but I'll ignore that handling for the description because it doesn't change the concept).The perceived ordering of the entires (such as returned by iterating over the ) depends on the order of the entries in those buckets.Whenever the size is rehashed (because the map exceeded its fullness threshold), then the number of buckets changes, which means that the position of each element might change, since the bucket position is derived from the number of buckets as well. does not sort at all. For a map that sorts by key values you should use  instead.From the JavaDocs for :From the documentation of :A  is not an ordered data structure - you should not rely on entries in a  being in a certain order. Some  implementations such as  and  do guarantee a certain order, but  does not.If you really want to know what happens internally, lookup the source code of  - you can find it in  which should be in your JDK installation directory.A  has a number of \"buckets\" in which it stores its entries. Which bucket an entry is stored in is determined by the hash code of the key of the entry. The order in which you see the entries in the  depends on the hash codes of the keys. But don't write programs that rely on entries being in a certain order in a  - the implementation might change in a future version of Java and your program then would not work anymore.hashmap has a not defined order of the elementsThere is no defined ordering in a hash table. Keys are placed into a slot, based on the hash code, but even that isn't a trivial order-by-hash-code.HashMap stores the values using the unique hash-value generated using a part of the key. This hash-value maps to the address where it is going to be stored. This is how it ensures an access O(1).LinkedHashmap on the other hand preserves the order in which you added to the map.
Java

I'm new to Android programming and I'm having problems while passing an ArrayList of a Parcelable to a fragment.\nThis is the Activity that is launched(working well!) where  is an ArrayList of a parcelable .The fragment Activity onCreate() method:The Fragment code:I think the problem is in the line Finally this is my Music class:When I run this code the problem I get is a .\nI would appreciate a lot if someone pointed me in the right direction to see where I am failing.: Problem solved: I just needed to add this line to the fragment Activity onCreate() method(othwewise the getArguments() would return null):And add this to the fragment code:where, listMusics is an  of  Music.Two things. First I don't think you are adding the data that you want to pass to the fragment correctly. What you need to pass to the fragment is a bundle, not an intent. For example if I wanted send an  value to a fragment I would create a bundle, put the  into that bundle, and then set that bundle as an argument to be used when the fragment was created. Second to retrieve that information you need to get the arguments sent to the fragment. You then extract the value based on the key you identified it with. For example in your fragment:What you are getting changes depending on what you put. Also the default value is usually  but does not need to be. It depends on if you set a default value for that argument. Lastly I do not think you can do this in . I think you must retrieve this data within your fragment's  method. My reasoning is as follows.  runs after the underlying activity has finished its own  method. If you are placing the information you wish to retrieve within the bundle durring your activity's  method, it will not exist during your fragment's . Try using this in  and just update your  contents later. There is a simple why that I prefered to the bundle due to the no duplicate data in memory. It consists of a init public method for the fragment In two words, you create an instance of the fragment an by the init method (u can call it as u want) you pass the reference of your list without create a copy by serialization to the instance of the fragment. This is very usefull because if you change something in the list u will get it in the other parts of the app and ofcourse, you use less memory.I prefer  = no boilerplate code. For passing data to other Fragments or Activities  does not matter.I would also always provide a helper method for a  or , this way you always know, what data has to be passed. Here an example for your :great answer by @Rarw. Try using a bundle to pass information from one fragment to another
Java

I want to split a string by '=' charecter. But I want it to split on first instance only. How can I do that ? Here is a JavaScript example for '_' char but it doesn't work for me\nExample :When I try String.split('='); it gives But I needThanksAs  explains:Yes you can, just pass the integer param to the split methodHere is a java doc reference : As many other answers suggest the limit approach, This can be another wayYou can use the  method on String which will returns the first Occurance of the given character, Using that index you can get the desired outputString slpitString[] = stringInToSearch.split(\"pattern\", 2);i like writing own methods :)
Java

How can I extract a .war file with linux command prompt?Using Using Or A war file is just a zip file with a specific directory structure. So you can use unzip or the jar tool for unzipping. If you add the war file into the webapps directory of Tomcat the Tomcat will take care of extracting/installing the war file.You can use the  command.
Java

For some reason Eclipse is no longer showing me Java compilation Errors in the Problems View.It is still showing Warnings.This has suddenly happened and I cannot think of anything that I have changed which would affect this.I am using the \"Maven Integration for Eclipse\" plugin but I have been for some time - not sure if this could have affected it or not.Any ideas?I had same problem and randomly did such things as (several times): 1) Project->Clean..., \n2) close and open Eclipse again, \n3) Run As...And it started to work again, without changing configuration.Right-click your project and go to Properties > Java Build Path > Source.Make sure your source directory (for example MyProject/src) is listed as a Source folder. Otherwise you won't get any red markers.I want to post my story here if Google brings you to this question.Somehow, \"Project->Build Automatically\" got turned off.Turning it back on produces correct errors list.In my case it has nothing to do with m2e 1.0.  This is default behavior for any Java project and goes back as far as Ganymede ( at the point of writing this post I am running Indigo )This is not totally an answer to your question, but is related. I thought eclipse stopped showing red/yellow flags next to files in my project. The solution was very simple - I was looking at the  tab (which doesn't show error/warning flags) instead of the  tab.I installed and deinstalled ajdt-plugin and got the same problem.Check .\nIt should have a 'Java Builder'.This code should be in the .project file (file is in the root of your project):I have the same problem in slight different situation. I have a parent POM and multiple modules under it. Project was existing and I imported it into eclipse. I can change the \"Dependency management\" only to parent project but not projects under it. They are not showing any compilation warnings. Next I'm going to try to change them all into individual projects... that's not what I wanted, but I haven't been able to solve this otherwise...I was experiencing this problem as well today.  The other solutions presented here (such as cleaning the project and restarting Eclipse) did not work or were not applicable to my setup.  What did work for me was right-clicking on the project in the Package Explorer and selecting Maven->Update Project Configuration.  Evidently some source folder restructuring I had done the previous day had caused Maven to lose track of things, and issuing this command fixed everything.At the top right corner of the problems window (next to minimize) there is a small arrow-icon. Click it  and select \"Configure filters\". There is a severity filter that might have been activated.On Ganymede, check the configuration of the Problem view:('Configure content') It can be set on 'any element in the same project' and you might currently select an element from the project.Or it might be set on a working set, and this working set has been modifiedMake sure that 'Match any configuration' is selected.I have also faced the same problem.After installing m2eclipse plugin, i was not getting any Java compilation errors. My solution was to enable dependency management by Select Project -> Right Click (to get context menu) -> m2 Maven -> Enable dependency management. Now i am able to view Java Compilation Errors. In my case Eclipse wasn't properly picking up a Java project that a current project was dependent on. You can go to Project > BuildPath > Configure BuildPath and then delete and re-add the project. There are obviously several reasons why this might occur, and I thought I'd add the solution to my issue. (I have a java project into which I have imported files with virtual links)If you have a situation like mine, you will have another folder on the same level as your 'src' folder. If you do, right-click on that other folder, then select 'Build Path' > 'Add to Build Path' (if you see 'Build Path' > 'Remove from Build Path', then it had already been added.)To further configure the Build Path, right click on your top level project dir, and select 'Build Path' > 'Configure Build Path'. Your folders should show up in the 'Source' tab.To configure what errors you see, Click on Java Compiler > Errors/Warnings and then click 'Configure Workspace Settings'. That is the same as going to Window > Preferences > Java > Compiler > Errors/Warnings. If you don't want Eclipse to ignore something, then just change it to Warning.I could reproduce this issue by creating an enumeration with a non-static member class and a static block enumerating its values:This class breaks the Ganymede compiler. If you delete the line in the static initializer block, the code compiles correctly again, and you get the error that there is no enclosing instance for the new Bar() call, as expected.-- correction: The above holds only if the project has gaeNature from Google Appengine. However, if you get an error similar as mentioned in the original question, you might be encountering another java compiler bug ...I have the same issue with Eclipse Helios and the m2eclipse plugin. They just can't seem to get this thing to work with WTP or WPT or whatever the blasted acronym is. If I do a clean on the project and watch the Maven console then I can see the compilation issues in the console but eclipse won't touch it. It seems eclipse or WTP/WPT and m2eclipse are busy playing slap hands.I experienced that problem with a MapReduce project. I closed the error window and never came back after doing what the other answers suggested.Click on the bottom left -> Kepler SP2, Java Project (Web Driver), and we use Gradle instead of MavenNone of the above helped, what did fix the problem for me was to select my projects (r-Click) > Gradle > Refresh AllIn my case I setted a old workspace and it was the problem.Try to set a new folder for workspaceI had same problem. In my case, I enable project specific setting the workspace setting. \nProject \u2192 Validation \u2192 mark \"Enabled project setting\"Edit: If \"Debug\" has been recently activated then check the top right of the program (under the Minimise button) and click back onto Java.
Java

I have an ArrayList with values like \"abcd#xyz\" and \"mnop#qrs\". I want to convert it into an Array and then split it with # as delimiter and have abcd,mnop in an array and xyz,qrs in another array. I tried the following code:But it failed saying \"Ljava.lang.String;@57ba57ba\"Can you help me please. You don't need to reinvent the wheel, 's the  method:if you see the last line (new String[0]), you don't have to give the size, there are time when we don't know the length of the list, so to start with giving it as 0 , the constructed array will resize.What you did with the iteration is not wrong from what I can make of it based on the question. It gives you a valid array of String objects. Like mentioned in another answer it is however easier to use the toArray() method available for the ArrayList object => Just a side note. If you would iterate your dsf array properly and print each element on its own you would get valid output. Like this:What you probably tried to do was print the complete Array object at once since that would give an object memory address like you got in your question. If you see that kind of output you need to provide a toString() method for the object you're printing.Here is the solution for you given scenario - 
Java

I am working in Windows Environment. And I am getting this error everytime as I am working with tomcat-I tried adding  in System Variables, still I am getting the same error  again and again. Any help will be appreciated. I have also read other post in stackoverflow also but it didn't worked out.The PermGen space is what Tomcat uses to store class definitions (definitions only, no instantiations) and string pools that have been interned. From experience, the PermGen space issues tend to happen frequently in dev environments really since Tomcat has to load new classes every time it deploys a WAR or does a jspc (when you edit a jsp file). Personally, I tend to deploy and redeploy wars a lot when I\u2019m in dev testing so I know I\u2019m bound to run out sooner or later (primarily because Java\u2019s GC cycles are still kinda crap so if you redeploy your wars quickly and frequently enough, the space fills up faster than they can manage).This should theoretically be less of an issue in production environments since you (hopefully) don\u2019t change the codebase on a 10 minute basis. If it still occurs, that just means your codebase (and corresponding library dependencies) are too large for the default memory allocation and you\u2019ll just need to mess around with stack and heap allocation. I think the standards are stuff like: I\u2019ve found however the best way to take care of that for good is to allow classes to be unloaded so your PermGen never runs out:Stuff like that worked magic for me in the past. One thing tho, there\u2019s a significant performance tradeoff in using those, since permgen sweeps will make like an extra 2 requests for every request you make or something along those lines. You\u2019ll need to balance your use with the tradeoffs.You have to allocate more space to the PermGenSpace of the tomcat JVM.This can be done with the JVM argument : By default, the PermGen space is 64M (and it contains all compiled classes, so if you have a lot of jar (classes) in your classpath, you may indeed fill this space).On a side note, you can monitor the size of the PermGen space with  and you can even inspect its content with To complement Michael's answer, and according to , a safe way to deal with the problem is to use the following arguments:If tomcat is running as Windows Service neither CATALINA_OPTS nor JAVA_OPTS seems to have any effect.You need to set it in Java options in GUI.The below link explains it wellIn Tomcat 7.0 Windows Service Installer Version.There is not catalina.bat in /bin .\nSo you need open Tomcat7w.exe in /bin and add blow JVM argumenton Java Option in Java Tab, like this. You also add other options.Another, if you use IntellijIDEA you need add JVM argument in Server Configurations,like this.@AndreSmiley 's code of line worked for me.only modification required is.-XX:MaxPermSize=256\"m\" means MB.Actually my application is kinda huge so i was advised to make it 1024m for performance.This one worked for me, in  the following line needs to be added if it doesn't exist  with the value . The full line:I'm running tomcat7 on CentOS 6.6. I tried creating a new /usr/share/tomcat/bin/setenv.sh file and setting both  and . But tomcat wouldn't pick up the values on restart. When I put the following line into /etc/tomcat/tomcat.conf:tomcat did pick up the new environment variable. I verified this by runningand seeing the new settings in the output. This took a long time to diagnose and I didn't see anyone else suggesting this, so I thought I'd throw it out to the internet community.Killing the tomcat process(forcefully, kill -9 for Linux) and starting it again solves the issue. My guess is, the tomcat instance doesn't get killed properly using shutdown.bat. So, we need to forcefully kill the process and start again.
Java

I am relatively new to matchers. I am toying around with  in combination with JUnit and I kinda like it.Is there a way, to state that one of multiple choices is correct?Something likeThe method I am testing returns one element of a collection. The list may contain multiple candidates. My current implementation returns the first hit, but that is not a requirement. I would like my testcase to succeed, if any of the possible candidates is returned. How would you express this in Java?(I am open to hamcrest-alternatives)From : See also .Moreover, you could write your own Matcher, what is quite easy to do.marcos is right, but you have a couple other options as well. First of all, there  an either/or:but if you have more than two items it would probably get unwieldy. Plus, the typechecker gets weird on stuff like that sometimes. For your case, you could do:or if you already have your options in an array/Collection:See also .
Java

I'm quite confused about the basic concepts of a Hash table. If I were to code a hash how would I even begin? What is the difference between a Hash table and just a normal array? Basically if someone answered this question I think all my questions would be answered:\nIf I had 100 randomly generated numbers (as keys), how would I implement a hash table and why would that be advantageous over an array?Psuedo-code or Java would be appreciated as a learning tool...The answers so far have helped to define hash tables and explain some theory, but I think an example may help you get a better feeling for them.A hash table and an array are both structures that allow you to store and retrieve data.  Both allow you to specify an  and retrieve a value associated with it.  The difference, as Daniel Spiewak noted, is that the indices of an array are , while those of a hash table are based on the  associated with them.A hash table can provide a very efficient way to search for items in large amounts of data, particularly data that is not otherwise easily searchable.  (\"Large\" here means , in the sense that it would take a long time to perform a sequential search).No problem.  The simplest way is to invent an arbitrary mathematical operation that you can perform on the data, that returns a number  (usually an integer).  Then use that number as the index into an array of \"buckets\" and store your data in bucket #.  The trick is in selecting an operation that tends to place values in different buckets in a way that makes it easy for your to find them later.  A large mall keeps a database of its patrons' cars and parking locations, to help shoppers remember where they parked.  The database stores , , , and .  On leaving the store a shopper finds his car by entering the its make and color.  The database returns a (relatively short) list of license plates and parking spaces.  A quick scan locates the shopper's car.You could implement this with an SQL query:If the data were stored in an array, which is essentially just a list, you can imagine implementing the query by scanning an array for all matching entries.On the other hand, imagine a hash rule:This rule will convert each item to a number between 0 and 99, essentially  the data into 100 buckets.  Each time a customer needs to locate a car, you can hash the make and color to find the  bucket out of 100 that contains the information.  You've immediately reduced the search by a factor of 100!Now scale the example to huge amounts of data, say a database with millions of entries that is searched based on tens of criteria.  A \"good\" hash function will distribute the data into buckets in a way that minimizes any additional searching, saving a significant amount of time.First, you have to understand a what a hash function is.\nA hash function is a function that takes a key (for example, an string of arbritrary length) and returns a number . The same key must always return the same hash. A really simple string hashing function in java might look likeYou can study a good hash function at Now, the hash map uses this hash value to place the value into an array. Simplistic java method:(This map enforces unique keys. Not all maps do.)It is possible for two different keys to hash to the same value, or two different hashes to map to the same array index. There exists many techniques for dealing with this. The simplest is to use a linked list (or binary tree) for each array index. If the hash function is good enough, you will never need a linear search.Now to look up a key:Hashtables are .  This is a huge difference from arrays, which are just linear data structures.  With an array, you might do something like this:Notice how you are getting an element out of the array by specifying an exact memory offset ().  This contrasts with hashtables, which allow you to store key/value pairs, later retrieving the value based on the key:With the above table, we can make the following call:...and be assured that  will be valued at .I think this will probably answer most of your questions.  The implementation of a hashtable is a fairly interesting topic, one .\"I'm more interested in the way Hash Tables look up the key and how the key is generated.\"That's the general solution.  Two numeric calculations and you've gone from arbitrary object as key to arbitrary object as value.  Few things can be as fast.The transformation from object to hash value happens in one of these common ways.The slot in the hash table is mod( number, size of table ).If that slot has the desired value, you're done.  If that's not the desired value, you need to look somewhere else. There are several popular probing algorithms to look for a free spot in the table.  Linear is a simple search for the next free spot.  Quadratic is a non-linear hopping around looking for a free slot.  A random number generator (with a fixed seed) can be used to generate a series of probes that will spread data evenly but arbitrarily.The probing algorithms are not (1).  If the table's big enough, the odds of collision are low, and probes don't matter.  If the table's too small, then collisions happen and probing happens.  At that point, it becomes a matter of \"tuning and tweaking\" to balance probing and table size to optimize performance.  Usually we just make the table bigger.See .Something I didn't see specifically noted yet:The point of using a hash table over an array is performance. Iterating through an array would typically take anywhere from O(1) to O(x) where x is the number of items in the array. However the time to find your item will be extremely , expecially if we are talking about hundreds of thousands of items in the array.A properly weighted hash table typically has an almost  access time of just over O(1), no matter how many items are in the hash table.You wouldn't want to use a hash table for 100 randomly generated numbers.A good way to think about hash tables is to think about value pairs.  Let's use students, and say everyone has a student ID number.  In your program you store information on students (names, phone numbers, bills, etc).  You want to find all of the information about a student using only basic information (name or student ID, for example).Let's say you have 10,000 students.  If you store them all in an array, then you have to loop through the entire array comparing each entry's student ID with the one you are looking for.If, instead, you \"hash\" (see below) their student ID number to a position in the array, then you only have to search student's who's numbers have the same hash.  Much less work to find what you wanted.In this example, let's say student IDs are just 6 digit numbers.  Our hash function could be use only the bottom 3 digits of the number as the \"hash key\".  Thus 232145 is hashed to array location 145.  So then you only need an array of 999 element (each element being a list of students).That should be a good start for you.  You should, of course, read a text book or wikipedia for this kind of info.  But I assume you've already done that and are tired of reading.Here is, in short, how a hash table works.Imagine you have a library, full of books.  If you were to store the books in an array, you would put each book on a spot on a shelf, and then when someone asked you to find a book, you'd look through all the shelves -- pretty slow.  If someone said \"book #12345\", you could find it pretty easily, though. Let's say instead you say, if the book title starts with 'A', it goes in row 1. If the second letter is 'B', it goes in row 1, rack 2.  If the third letter is 'C', it goes in row 1, rack 2, shelf 3... and so on until you identify the book position.  Then, based on the title of the book, you could know exactly where it should be.Now, there are some problems in the simplistic \"hashing\" algorithm I described -- some shelves are going to be way overloaded while others stand empty, some books will be assigned to the same slot.. so the real hash functions are carefully constructed to try to avoid such problems.  But this is the basic idea.I'll answer that part about the difference between a hash table and an array... but since I've never implemented a hashing algorithm of any import before, I'll leave that to somebody more knowledgeable :)An array is just an ordered list of objects. The object itself doesn't really matter... what's important is that if you want to list the objects in order of insertion, it is always the same (meaning that the first element  has an index of 0).As for a hashtable, that's indexed by keys, not order... I think that a basic search on hashing algorithms will give you a lot more insight than I can... Wikipedia has a very decent one... that determines \"bucket\" that the keys go into for quick retrieval on arbitrary objects used as keys.As for advantages: If order of insertion is important, an array or some kind of ordered list is necessary. If fast look-up by arbitrary key (keyed by various hash functions) is important, then a hash table makes sense.That depends on your hash function. Lets suppose that your hash function hashes a word as per the length of your word, the key for chris will be 5. Similarly, key for yahoo will also be 5. Now, both values (chris and yahoo) will go under 5 (i.e. in a 'bucket' keyed by 5). This way you don't have to make an array equal to the size of your data.The question, I believe, is answered quite clearly and in many different ways by now.I would just like to add another perspective (which may confuse a new reader as well)At a level of least abstraction, arrays are just contiguous block of memory. Given the starting address (), size () and the  of a single element, the address of element is computed as:The interesting thing to note here is that arrays can be abstracted/viewed as hash tables with  as key and the above function as a hash function which calculates the location of a value in Hash table is a data structure that is created for quick look up.The hash tables are not effective when the number of entries are very small.Some examples:Output:The hash algorithm is used to generate an index into that array based on the values of the item that will be stored in the array. The maximum size of this array is typically smaller than the number of items in the set of possible values for the type of data being stored in the hashtable. When an element is added to the Hashtable , the element is placed into a bucket based on the hash code of the key. Each bucket can have multiple records which are organized in a particular order. Subsequent lookups of the key use the hash code of the key to search in only one particular bucket, thus substantially reducing the number of key comparisons required to find an element. The load factor of a Hashtable determines the maximum ratio of elements to buckets. Smaller load factors cause faster average lookup times at the cost of increased memory consumption. An instance of Hashtable has two parameters that affect its performance: initial capacity and load factor . More about...Rj
Java

after some days of trying and waitin' for answers on the springsource forums I'll try it here.\nRunning my application results in these exception:Here's the relevant codeapplication context:com.example.my.entities.user:service:Multiple things can cause this, I didn't bother to check your entire repository, so I'm going out on a limb here.First off, you could be missing an annotation (@Service or @Component) from the implementation of , if you're using annotations for configuration. If you're using (only) xml, you're probably missing the  -definition for the UserService-implementation.If you're using annotations and the implementation is annotated correctly, check that the package where the implementation is located in is scanned (check your  -value).Add this to you applicationContext:Add annotation @Repository to the head of userDao Class.If userDao is a interface,add this annotation to the implements of the interface.I have similar trouble in test config, because of using AOP.\nI added this line of code in spring-config.xmlAnd it works !I had a similar issue but I was missing the (@Service or @Component) from the implementation of com.example.my.services.myUser.MyUserServiceImplIF this is only occurring on deployments, be sure that you have the dependency of the package you are referencing in the .war.  For instance, this was working locally on my machine, with debug configurations working fine, but after deploying to Amazon's Elastic Beanstalk , I received this error and noticed one of the dependencies was not bundled in the .war package.  I had the same issue but in my case, implemented class was accidently become 'abstract' as a result autowiring was failing.In my case it was the wrong dependecy for CrudRepository. My IDE added also follwing:But I just needed:I removed the first one and everything was fine.
Java

I am trying to keep a temporary container of a class that contains member :A class called myobjectsListThen I do then: Add some hashmap items to A (like2)thenthen: Add hashmap items to A; (like 4 more)then return A to the items stored in B;but when I do this B grows with A while I am adding hashmap items to A.\nA now has 6 items in it because B had 6.I want A to have original 2 still at end after last assingment\nin C++ i would use copy with objects, what is the java equivalent?Added: OK I left something out explaining this.MyObjectsList does not contain the HashMap, it is derived from a class MyBaseOjbectsList which has the HashMap member and MyObjectsList extends MyBaseOjbectsList. Does this make a difference.?If you want a copy of the HashMap you need to construct a new one with.This will create a (shallow) copy of the map.You can also useMethod to copy all elements from one hashmap to another hashmap Program for copy all elements from one hashmap to anothersource :  The difference is that in C++ your object is on the stack, whereas in Java, your object is in the heap. If A and B are Objects, anytime in java you doB = AA and B point to the SAME object. So anything you do to A you do to B and vice versause new HashMap() if you want two different objectsAnd you can use Map.putAll(...) to copy data between two MapsHere is small (HUGE) understatement. Because if you want to copy  that is more structured  will cope the value, because it doesn't know how to exactly copy you object. For example So basicaly you will need to copy all by yourself like hereIn Java, when you write: and  are the same and point to the same reference. Changing one will change the other. So if you change the state of  (not its reference)  will reflect that change too.However, if you write:Then  is still pointing to the first object you created (original ) while  is now pointing to a new Object.Since this question is still unanswered and I had a similar problem, I will try to answer this. The problem (as others already mentioned) is that you just copy references to the same object and thus a modify on the copy will also modify the origin object. So what you have to to is to copy the object (your map value) itself. The far easiest way to do so is to make all your objects implementing the serializeable interface. Then serialize and deserialize your map to get a real copy. You can do this by yourself or use the apache commons SerializationUtils#clone() which you can find here:   But be aware this is the simplest approach but it is an expensive task to serialize and deserialize a lot of objects.What you assign one object to another, all you're doing is copying the  to the object, not the contents of it. What you need to do is take your object B and manually copy the contents of object A into it. If you do this often, you might consider implementing a  method on the class that will create a new object of the same type, and copy all of it's contents into the new object.
Java

I have the following code snippet:Here, how do I call the  method for the thread without creating an instance of the thread class?You're already creating an instance of the Thread class - you're just not doing anything with it. You  call  without even using a local variable:... but personally I'd normally assign it to a local variable, do anything else you want (e.g. setting the name etc) and then start it:Since anonymous classes extend the given class you can store them in a variable.eg.Alternatively, you can just call the start method on the object you have immediately created.Though personally, I would always advise creating an anonymous instance of Runnable rather than Thread as the compiler will warn you if you accidentally get the method signature wrong (for an anonymous class it will warn you anyway I think, as anonymous classes can't define new non-private methods).egNot exactly sure this is what you are asking but you can do something like:Notice the  method at the end of the anonymous class.  You create the thread object but you need to start it to actually get another running thread.Better than creating an anonymous  class is to create an anonymous  class:Instead overriding the  method in the  you inject a target  to be run by the new thread.  This is a better pattern.Just call start()The entire  expression is an object reference, so methods can be invoked on it:
Java

Ive got the following if statement:I want it to include startsWith  'Mon' 'Tues' 'Weds' 'Thrus' 'Friday' etc. Is there a simple way to this when using strings? I tried '||' but it didn't work...Thanks!Do you mean:or you could use regular expression:Besides the solutions presented already, you could use the Apache Commons Lang library:A simple solution is:A fancier solution would be:No one mentioned  so far, so here it is:Of course, be mindful that your program will only be useful in english speaking countries if you detect dates this way.  You might want to consider:  From there you can use .startsWith or .matches or whatever other method that others have mentioned above.  This way you get the default locale for the jvm.  You could always pass in the locale (and maybe default it to the system locale if it's null) as well to be more robust.You need to include the whole  for each item, since  only works with boolean expressions (true or false).There are other options if you have a lot of things to check, like , but they tend to be slower and more complicated regular expressions are generally harder to read.An example regular expression for detecting day name abbreviations would be:When you say you tried to use OR, how exactly did you try and use it? In your case, what you will need to do would be something like so:
Java

I am learning Java EE and I downloaded the eclipse with glassfish for the same. I saw some examples and also read the Oracle docs to know all about Java EE 5. Connecting to a database was very simple. I opened a dynamic web project, created a session EJB and  I used EntityManager and with the get methods could access the stored data table.For my next project I had create a simple class and then access some DB table. The very first problem I encuntered was, that the PersistenceUnit attribute would only be recognised by EJB,Servlet etc and not a simple java class. So then I could not use the EntityManager way(or can I?) I was asked to go via the \"JDBC\" way. The very first problem I encountered was to get the connection to the DB. It seems all this must be hardcoded. I had a persistence.xml with which I could easily configure the data base connection. Even setting up a driver for the DB was easy. Also there no get/set methods in the JDBC for accessing table entities.How do I understand JPA and persistence in relation to JDBC? What was JPA thought for? Why is there set/get methods? Can someone throw some light on the essence of these two and what are the pros/cons without \"jargons\"?? Please also suggest some links. A simple google search for JPA and JDBC differences led me to some sites full of \"terminology\" I couldn't follow :(Layman's terms:  is a standard for connecting to a DB directly and running SQL against it - e.g SELECT * FROM USERS, etc.  Datasets can be returned which you can handle in your app, and you can do all the usual things like INSERTS, DELETES, run stored procedures, etc.  It is one of the underlying technologies behind most java database access (including  providers).One of the issues with traditional  apps is that you can often have some crappy code where lots of mapping between datasets and objects occur, logic is mixed in with SQL, etc. is a standard for Object Relational Mapping. This is a technology which allows you to map between objects in code and database tables.  This can \"hide\" the SQL from the developer so that all they deal with are java classes, and the provider allows you to save them and load them magically.  Mostly, XML mapping files or annotations on getters, setters can be used to tell the JPA provider which fields on your object map to which fields in the DB.  The most famous JPA provider is Hibernate, so is a good place to start for concrete examples. Other examples include OpenJPA, toplink, etc.Under the hood, Hibernate and most other providers for JPA write SQL and use JDBC to read and write to the DB.  Main difference between JPA and JDBC is level of abstraction.JDBC is a low level standard for interaction with databases. JPA is higher level standard for the same purpose. JPA allows you to use an object model in your application which can make your life much easier. JDBC allows you to do more things with the Database directly, but it requires more attention. Some tasks can not be solved efficiently using JPA, but may be solved more efficiently with JDBC. JDBC is a much lower-level (and older) specification than JPA. In it's bare essentials, JDBC is an API for interacting with a database using pure SQL - sending queries and retrieving results. It has no notion of objects or hierarchies. When using JDBC, it's up to you to translate a result set (essentially a row/column matrix of values from one or more database tables, returned by your SQL query) into Java objects.Now, to understand and use JDBC it's essential that you have some understanding and working knowledge of SQL. With that also comes a required insight into what a relational database is, how you work with it and concepts such as tables, columns, keys and relationships. Unless you have at least a basic understanding of databases, SQL and data modelling you will not be able to make much use of JDBC since it's really only a thin abstraction on top of these things.JDBC is the predecessor of JPA. JDBC is a bridge between the Java world and the databases world. In JDBC you need to expose all dirty details needed for CRUD operations, such as table names, column names, while in JPA (which is using JDBC underneath), you also specify those details of database metadata, but with the use of Java annotations. So JPA creates update queries for you and manages the entities that you looked up or created/updated (it does more as well).If you want to do JPA without a Java EE container, then Spring and its libraries may be used with the very same Java annotations.
Java

I am using the JSON library provided here  to convert a json string I have to CSV.\nBut the problem I have is, the order of the keys is lost after conversion.This is the conversion code:This is the content of \"someString\":This is the result:While what I expect is to keep the order of the keys:Is there any way I can have this result using this library? If not, is there any other library that will provide the capability to keep the order of keys in the result?There are (hacky) ways to do it ... but you shouldn't.In JSON, an object is defined thus:See .Most implementations of JSON make no effort to preserve the order of an object's name/value pairs, since it is (by definition) not significant.If you want order to be preserved, you need to redefine your data structure; e.g.or more simply:You need to have a hard conversation with whoever designed that file structure and won't let you change it.  It is / they are plain wrong.  You  to convince them.If they  won't let you change it:This kind of thing as really bad.  On the one hand, your software will be violating a well established / long standing specification that is designed to promote interoperability.  On the other hand, the nit-wits who designed this lame (not JSON!) file format are probably slagging off other people's systems etc 'cos the systems cannot cope with  nonsense.It is also worth reading what the  says on this subject.  Here are some excerpts:It is quite simple to maintain order. I had the same problem with maintaining the order from DB layer to UI Layer.Open JSONObject.java file. It internally uses HashMap which doesn't maintain the order.Change it to LinkedHashMap:This worked for me. Let me know in the comments. I suggest the JSON library itself should have another JSONObject class which maintains order, like JSONOrderdObject.java. I am very poor in choosing the names.  takes whatever map you pass. It may be  or  and  it will take  only when the map is null .Here is the constructor of  class that will do the checking of map.So before building a json object construct  and then pass it to the constructor like this ,A more verbose, but broadly applicable solution to this sort of problem is to use a pair of data structures: a list to contain the ordering, and a map to contain the relations.For Example:You iterate the itemOrder list, and use those to look up the map values.  Ordering is preserved, with no kludges.I have used this method many times.Another hacky solution using reflect:Apache Wink has . It keeps the order while parsing the String.Solved.I used the JSON.simple library from here  to read the JSON string to keep the order of keys and use JavaCSV library from here  to convert to CSV format.I know this is solved and the question was asked long time ago, but as I'm dealing with a similar problem, I would like to give a totally different approach to this:For arrays it says \"An array is an ordered collection of values.\" at  - but objects (\"An object is an unordered set of name/value pairs.\") aren't ordered.I wonder why that object is in an array - that implies an order that's not there.So a solution would be to put the keys in a \"real\" array and add the data as objects to each key like this:So this is an approach that tries to rethink the original modelling and its intent. But I haven't tested (and I wonder) if all involved tools would preserve the order of that original JSON array.Just stumbled upon the same problem, I believe the final solution used by the author consisted in using a custom ContainerFactory:see \nThe most safe way is probably overriding keys method that is used to generate output:patchFor(answer @gary) : You can use the following code to do custom ORDERED serialization and deserialization of JSON Array (This example assumes you are ordering Strings but can be applied to all types):Your example:add an element \"itemorder\"This code generates the desired output without the column title line:In the real world, an application will almost always have java bean or domain that is to be serialized/de-serialized to/from JSON. Its already mentioned that JSON Object specification does not guarantee order and any manipulation to that behavior does not justify the requirement. \nI had the same scenario in my application where I needed to preserve order just for the sack of readability purpose. I used standard jackson way to serialize my java bean to JSON:In order to make the json with an ordered set of elements I just use JSON property annotation in the the Java bean I used for conversion. An example below:the getObject() used above:The output shows as per Json property order annotation:Tested the wink solution, and working fine:
Java

I want to change server location but I can't it's greyed (I cannot select last radio button) how can I do it then:On the  view, delete all the webapps published under your server (right click on the server >  or right click on the server >  and  then remove manually the webapps) and finally right click on the server >  (the 'empty' content). This way you would un-gray the  area.As the dialog says : \"Server must be published with no modules present to make changes.\" \nStop the server remove any modules. After that the options will be enabled.If you are still dont see the option enabled, start the tomcat and then it will be enabled.
Java

Suppose I create a temporary file in Java with the methodIf I do not explicity call the  method, when will the file be deleted?As an intuition, it might be when the JVM terminates, or  (by the Garbage Collector), or  (by some Operating System sweeping process).The file won't be deleted automatically, from the :So you have to explicitly call :As the other answers note, temporary files created with  will  be deleted automatically unless you explicitly request it.The generic, portable way to do this is to call  on the  object, which will schedule the file for deletion when the JVM terminates.  A slight disadvantage of this method, however, is that it only works if the VM terminates normally; on an abnormal termination (i.e. a VM crash or forced termination of the VM process), the file might remain undeleted.On Unixish systems (such as Linux), it's actually possible to obtain a somewhat more reliable solution by deleting the temporary file .  This works because Unix filesystems allow a file to be deleted (, to be precise) while it's still held open by one or more processes.  Such files can be accessed normally through the open filehandle, and the space they occupy on disk will only be reclaimed by the OS after the last process holding an open handle to the file exits.So here's the most reliable and portable way I know to ensure that a temporary file will be properly deleted after the program exits:On a Unixish system, running this should produce something like the following output:whereas on Windows, the output looks slightly different:In either case, however, the temp file should not remain on the disk after the program has ended. While testing this code on Windows, I observed a rather surprising fact: apparently, merely .  Of course, this also means that any crash that happens while the temp file is in use will cause it to be left undeleted, which is exactly what we're trying to  here.AFAIK, the only way to avoid this is to ensure that the temp file  gets closed using a  block.  Of course, then you could just as well delete the file in the same  block too.  I'm not sure what, if anything, using  would actually gain you over that.It won't, at least not by Java.  If you want the file to be deleted when the JVM terminates then you need to call .from: For example,The above example will create a temporary file named \u201cabc.tmp\u201d and .If you want , you can still use the File.delete().Temporary file is used to store the less important and temporary data, which should always be deleted when your system is terminated. The best practice is use the File.deleteOnExit() to do it.For example,The above example will create a temporary file named \u201cabc.tmp\u201d and delete it when the program is terminated or exited.You can manually delete the file before terminating the process if you want to, however when the process is terminated the file will be deleted as well.
Java

I have a JUnit test that fails because the milliseconds are different.  In this case I don't care about the milliseconds.  How can I change the precision of the assert to ignore milliseconds (or any precision I would like it set to)?Example of a failing assert that I would like to pass:Use a  object with a format that shows only the parts you want to match and do an  on the resulting Strings. You can also easily wrap that in your own  method.Yet another workaround, I'd do it like this:There are libraries that help with this:If you have  on your classpath, you can use  to truncate the dates to some field.There is a shorthand for this:Note that 12:00:00.001 and 11:59:00.999 would truncate to different values, so this might not be ideal. For that, there is round:Starting with version 3.7.0,  added an  assertions, if you are using the Java 8 Date / Time API.It also works with legacy java Dates as well:You could do something like this:No String comparisons needed.I don't know if there is support in JUnit, but one way to do it:In JUnit you can program two assert methods, like this:This is actually a harder problem than it appears because of the boundary cases where the variance that you don't care about crosses a threshold for a value you are checking.  e.g. the millisecond difference is less than a second but the two timestamps cross the second threshold, or the minute threshold, or the hour threshold.  This makes any DateFormat approach inherently error-prone.Instead, I would suggest comparing the actual millisecond timestamps and provide a variance delta indicating what you consider an acceptable difference between the two date objects.  An overly verbose example follows:Using JUnit 4 you could also implement a  for testing dates according to your chosen precision. In this example the matcher takes a string format expression as a parameter. The code is not any shorter for this example. However the matcher class may be reused; and if you give it a describing name you can document the intention with the test in an elegant way. use AssertJ assertions for Joda-Time ()the test failing message is more readableIf you were using Joda you could use .Just compare the date parts you're interested in comparing:JUnit has a built in assertion for comparing doubles, and specifying how close they need to be.  In this case, the delta is within how many milliseconds you consider dates equivalent.  This solution has no boundary conditions, measures absolute variance, can easily specify precision, and requires no additional libraries or code to be written. It must be 100.0 instead of 100 (or a cast to double is needed) to force it to compare them as doubles.Something like this might work:Instead of using  directly, you can create a small collaborator, which you can mock out in your test:Create a DateBuilder member and change calls from  to The main method will produce:In the test you can inject a stub of  and let it return any value you like. For example with Mockito or an anonymous class which overrides :Convert the dates to String using SimpleDateFromat, specify in the constructor the required date/time fields and compare the string values:I did a small class that might be useful for some googlers that end up here : i cast the objects to java.util.Date and compare
Java

We know that quick sort is the best sorting algorithm.The collections.sort used merge sort algorithm instead of quick sort. But Arrays.sort uses quick sort.What is the reason Collections.sort uses merge sort instead of quick sort? Highly likely from Josh Bloch :Also, the  is relevant:Also, see .There isn't a single \"best\" choice. As with many other things, it's about tradeoffs.
Java

Is it possible for a spring controller to handle both kind of requests? If I define a single controller of the kind:the HTTP Request with \"logout\" is not accepted.If I define two controllers to handle each request separately, Spring complains with the exception \"There is already 'Controller' bean method ... mapped\".You need to give  for  and  request parameters as well. That's because, when you provide just the  parameter, it actually expects for  and  as well as they are still mandatory.It worked when you just gave  and  because  wasn't a mandatory parameter thanks to  already given for .Create 2 methods which handle the cases. You can instruct the  annotation to take into account certain parameters whilst mapping the request. That way you can nicely split this into 2 methods. As part of  onwards you now have full support of Java 8  () therefore in your example both requests will go via your single mapping endpoint as long as you replace  with Optional for your 3 params logout, name, password:
Java

I am trying to convert a string encoded in java in UTF-8 to ISO-8859-1. Say for example, in the string '\u00e2abcd'  '\u00e2' is represented in ISO-8859-1 as E2. In UTF-8 it is represented as two bytes. C3 A2 I believe. When I do a getbytes(encoding) and then create a new string with the bytes in ISO-8859-1 encoding, I get a two different chars. \u00c3\u00a2.  Is there any other way to do this so as to keep the character the same i.e. \u00e2abcd?If you're dealing with character encodings other than UTF-16, you shouldn't be using  or the  primitive -- you should only be using  arrays or  objects.  Then, you can use  to convert between encodings:Will do the trick. From your description it seems as if you're trying to \"store an ISO-8859-1 String\". String objects in Java are  implicitely encoded in UTF-16. There's no way to change that encoding.What you can do, 'though is to get the bytes that constitute some other encoding of it (using the .getBytes() method as shown above).Starting with a set of bytes which encode a string using UTF-8, creates a string from that data, then get some bytes encoding the string in a different encoding:this outputs strings and the iso88591 bytes correctly:So your byte array wasn't paired with the correct encoding: Outputs(either that, or you just wrote the utf8 bytes to a file and read them elsewhere as iso88591)This is what I needed:If you have the correct encoding in the string, you need not do more to get the bytes for another encoding.Output:For files encoding...In addition to Adam Rosenfield's answer, I would like to add that  returns the buffer's underlying byte array, which is not necessarily \"trimmed\" up to the last character. Extra manipulation will be needed, such as the ones mentioned in  answer; in particular:evict non ISO-8859-1 characters, will be replace by '?'\n(before send to a ISO-8859-1 DB by example):utf8String = new String ( utf8String.getBytes(), \"ISO-8859-1\" );
Java

How can one make a Java class immutable, what is the need of immutability and is there any advantage to using this?An immutable object is one that will not change state after it is instantiated.In general, an immutable object can be made by defining a class which does not have any of its members exposed, and does not have any setters.The following class will create an immutable object:As can be seen in the above example, the value of the  can only be set when the object is instantiated, and by having only a getter () the object's state cannot be changed after instantiation.However, there must be care taken that all objects that are referenced by the object must be immutable as well, or it could be possible to change the state of the object. For example, allowing an reference to an array or  to be obtained through an getter will allow the internal state to change by changing the array or collection:The problem with the above code is, that the  can be obtained through  and be manipulated, leading to the state of the object itself to be altered, therefore, not immutable.One way to get around this problem is to return a copy of an array or collection when called from a getter:The advantage of immutability comes with concurrency. It is difficult to maintain correctness in mutable objects, as multiple threads could be trying to change the state of the same object, leading to some threads seeing a different state of the same object, depending on the timing of the reads and writes to the said object.By having an immutable object, one can ensure that all threads that are looking at the object will be seeing the same state, as the state of an immutable object will not change.In addition to the answers already given, I'd recommend reading about immutability in Effective Java, 2nd Ed., as there are some details that are easy to miss (e.g. defensive copies). Plus, Effective Java 2nd Ed. is a must-read for every Java developer.You make a class immutable like this: Immutable classes are useful because they're thread-safe.  They also express something deep about your design: \"Can't change this.\"  When it applies, it's exactly what you need.Ans) Immutable class is a class which once created, it\u2019s contents can not be changed. Immutable objects are the objects whose state can not be changed once constructed. e.g. String classAns) To create an immutable class following steps should be followed:Immutability can be achieved mainly in two ways:Advantages of immutability are the assumptions that you can make on these object:Immutable classes cannot reassign values after it is instantiated.The constructor assign values to its private variables. Until the object becomes null, values cannot be changed due to unavailability of setter methods.to be immutable should satisfy following,Advanteges:\nImmutable objects contains its initialized values until it dies.In short, an Immutable class is a class whose instances cannot be modified. The information contained in each immutable object is provided when it is created and is frozen for its lifetime.  Once an Immutable object has been created, it is read only, forever fixed, like a fossil.As a good programming practice in Java one should try to use immutable objects as far as possible. Immutability can have a performance cost, since when an object cannot be mutated we need to copy it if we want to write to it. When you care a lot about performance (e.g. programming a game) it may be necessary to use a mutable object. Even then it is often better to try to limit the mutability of objects.Since immutable object can not be reused and they are just a use and throw. String being a prime example, which can create lot of garbage and can potentially slow down application due to heavy garbage collection. are those whose objects cannot be changed after creation.Immutable classes is useful forString Class
Java

I'm using Spring Security 3 and Spring MVC 3.05.I would like to print username of currently logged in user,how can I fetch UserDetails in my Controller?If you already know for sure that the user is logged in (in your example if  is protected):To first check if the user is logged in, check that the current  is not a .Let Spring 3 injection take care of this.Thanks to  the easiest way is:If you just want to print user name on the pages, maybe you'll like this solution. It's free from object castings and works without Spring Security too:Note \"\" parameter added.Works fine because Spring injects it's own objects (wrappers) for HttpServletRequest, Principal etc., so you can use standard java methods to retrieve user information.if you are using spring security then you can get the current logged in user byThat's another solution (Spring Security 3):
Java

I am still quite new to java programming and I am trying to update existing value of Array list by using this codeI want to print  instead of  but I got  as the result, I still have \"Two\". I want to print . How do I do this?\nThank You..Use the  method to replace the old value with a new one.Use : To replace the existing element at specified position in Arraylist use the method,in your code block  you are using  This method inserts the specified element at the specified position in this list.Below are the few difference between add and set method,The  replaces the element at the specified position in this list with the specified element.here int index is index of the element to replace and element is element to be stored at the specified position.\nIf the index is out of range then it will throw the  exception.\nThis method returns the element previously at the specified position.method inserts the specified element E at the specified position in this list.It shifts the element currently at that position (if any) and any subsequent elements to the right (will add one to their indices).This method does not return any value.and it will also throw the  exception if the index is out of range.U must use  first.Your elements will become like this.then add this Your elements will become like this. 
Java

My web server would be overloaded quickly if all the work were done there.  I'm going to stand up a second server behind it, to process data.What's the advantage of EJB over RMI, or vice versa?  What about web services (SOAP, REST)?EJBs are built on top of RMI.  Both imply Java clients and beans.  If your clients need to be written in something else (e.g., .NET, PHP, etc.) go with web services or something else that speaks a platform-agnostic wire protocol, like HTTP or XML over HTTP or SOAP.If you choose RMI, you don't need a Java EE EJB app server.  You have to keep client and server JVMs in synch; you can't upgrade the client without upgrading the server.  You have to write all the services that the EJB app server provides for you (e.g., connection pooling, naming and directory services, pooling, request queuing, transactions, etc.).RMI is quite low level when you think about it.  Why would you drop all the way back to CORBA?A better choice is EJB 3.0 versus Spring.  It depends on whether you like POJO development, want a choice of relational technologies besides ORM and JPA, among other things.You can pay for a Java EE app server (e.g., WebLogic, WebSphere) or use an open source one (JBOSS, Glassfish and OpenEJB and ActiveMQ), or you can stick to Spring and deploy on Tomcat, Jetty, Resin or any other servlet/JSP engine.Spring offers a lot of choice by being technology agnostic: persistence (Hibernate, iBatis, JDBC, JDO, JPA, TopLink), remoting (HTTP, Hessian, Burlap, RMI, SOAP web service), etc.  EJB 3.0 is a spec with many vendors; Spring can only be had from Spring Source.I would recommend .  It's very solid, has lots of traction, isn't going anywhere.    It leaves all your options open.  Web services are great in theory, but there are some gotchas that you need to watch out for: Spring's web service module is very good, but do be careful about choosing to deploy this way. Write in terms of POJO service interfaces.  These will allow you to get the conceptual isolation you want, defer the deployment choice until the last moment, and let you change your mind if the first thought doesn't perform well.Between EJB and RMI, EJB would certainly be better - it has everything RMI has and much more via the container (object pooling, transaction management, etc.)Between EJB and web services, web services would give you more portability if you want to be able to call them from non-java apps in the future.  EJB again gives you things like transaction management and pooling that you might not get \"out of the box\" with web services.Personally, if I were doing it, I would probably use EJB or some similar remote object framework (spring remoting comes to mind as well).  If you need the ability to call the objects from a non-java app, you can always front your EJBs with simple web service proxies as needed.Re: web services (SOAP, REST)\nIf your back end servers are not going to be exposed publicly, then you are not getting any benefit from using platform independent web service interfaces such as SOAP/REST.\nIn fact you'll be incurring a penalty with all of the overhead added by the XML tags wrapping the data across a remote call, not to mention the hit you'll take from marshalling and unmarshalling the XML to java objects.\nAlthough any distributed call is going to require some level of serialization - even RMI/EJB, but the price is greater when serializing to human readable XML.  You may not need to code remote calls in java at all, you could front your service with a plain apache httpd instance, which is configured to load balance across multiple java servers using  or .\nThese modules can be used to load balance across servlet containers such as tomcat/jetty, or ejb containers such as jboss/glassfish.
Java

I have a string representing an URL containing spaces and want to convert it to an URI object. If is simple try to doit gives me where index  is the position of the first space in the URL string.How can i parse into a  object?You should in fact  the \"invalid\" characters. Since the string actually contains the complete URL, it's hard to properly URI-encode it. You don't know which slashes  should be taken into account and which not. You cannot predict that on a raw  beforehand. The problem really needs to be solved at a higher level. Where does that  come from? Is it hardcoded? Then just change it yourself accordingly. Does it come in as user input? Validate it and show error, let the user solve itself.At any way, if you can ensure that it are  the spaces in URLs which makes it invalid, then you can also just do a string-by-string replace with :Or if you can ensure that it's  the part after the last slash which needs to be URI-encoded, then you can also just do so with help of  utility class:Do note that  is insuitable for the task as it's designed to encode query string parameter names/values as per  rules (as used in HTML forms). See also .This will  the string. is the part after the last slash - in your case, the name of the song, as it seems.To handle spaces, @, and other unsafe characters in arbitrary locations in the url path, Use Uri.Builder in combination with a local instance of URL as I have described :I wrote this function:
Java

How to transform XML with XSLT processor in Java?Here is sample for using java api for transformer, as @Raedwald said:The Java standard library provides an (XSLT) transformation interface for XML parsing. See the API documentation for the classes  and . For example, Saxon 6.5.5 (for XSLT 1.0) and Saxon 9.1.07 (for XSLT 2.0) are written in Java. The documentation is at , which doesn't require writing a program in order to perform an XSLT transformation. For example, : .:where  is the name of the output file,  is the xml file,  is the primary xslt file and  is a name-value list of external parameters (I almost always leave this empty).JAXP provides a implementation independent way of working with XSLT transformations.  to get you started. If you are working with huge XSLT and/or working with multiple XSLT's then there is also an option of caching the parsed XSLT templates for performance reasons.  explains how to cache xslt's
Java

The  method returns the ordinal of an enum instance.\nHow can I set the ordinal for an enum?You can't set it. It is always the ordinal of the constant definition. See the :And actually - you should not need to. If you want some integer property, define one.You can control the ordinal by changing the order of the enum, but you cannot set it explicitly like in .  One workaround is to provide an extra method in your enum for the number you want:In this situation , but .You can update ordinal using reflection:From If you havethen SUNDAY has an ordinal of 0, MONDAY is 1, and so on...Check out the Java  and The easy answer: just change the order of the constants.  The first defined will be 0, the second will be 1, etc.  However, this may not be practical if you have constantly changing code, or enums will many many values.  You can define a custom method to work around the default ordinal, but MAKE SURE it is well documented to avoid confusion!
Java

I am trying to compile my JasperReports template using an Ant script and Java. I am getting this error:There is nothing complex in the template, but I still can't compile.You will have to set the  value in your template to Java. There are two ways you can do this:Then try to recompile - you should be sorted. :)Another solution is to copy groovy-all-{version}.jar from the groovy binary distribution into the application's.Change the languge to java in JRXML (ex:- language=\"java\") or add groovy*.jar to your project\u2019s classpath.If you are using TIBCOJaspersoftStudio:
Java

I'm trying to make an \"executable\" war file () that will start up a Jetty webserver that hosts the webapp contained in the WAR file I executed.I found  that described how to make what I'm looking for:However, following that advice along with how I think I'm supposed to make an executable jar (war) isn't working.I have an Ant task creating a WAR file with a manifest that looks like:The contents of the WAR file look like:When I try to execute the WAR file, the error is:There appears to be two errors here: one where it seems the JAR files can't be found, and one where the  class can't be found.To fix the first one, I put the Jetty JAR files in the base of the WAR file and tried again -- same error.  I also tried adding the  to the  attribute of the manifest.  That did not work either.Does anyone have any insight as to what I'm doing right/wrong and how I can get this executable WAR file up and running?The  you have in your question provides most of what you need. However, there are a few things that need to be done in addition to that.Any class files that Jetty needs to start up will need to be located at the root of the war file when it's packaged. We can leverage Ant to do that for us before we  the file. The war's manifest file will also need a  attribute to execute the server.Here's a step-by-step:To see what all you can configure here, have a look at the .If everything's set up properly above, you should be able to:This is an adaptation for Maven of @RobHruska's answer.  It just copies the files of the main class and merges the Jetty JAR files into the WAR file, nothing new, just to simplify your life if you are new -like me- to Maven:We have figured this out by using jetty-console-maven-plugin. Whenever you run mvn package it creates another war that can be used with java -jar whateverpackage-runnable.warIt also generates the init.d scripts and everything for you!Hudson solves this exact problem using the Winstone servlet container, which supports this use case directly.  Perhaps this would work for you?Even though this is kind of old another alternative with Jetty 8 is to simply include the Jetty jars as dependencies in your pom and add the following in your pom (versus an ant script that unpackages the war and repackages it):I take it that by \"without maven\" you want a jar that you can run by itself and not with \"mvn jetty:run\"--not that you don't want to use maven at all.It took me way to long to figure this out because I found many options--none of them dirt simple.  Eventually I found .  It works wonderfully.This is my example ANT extract. The idea is to unpackage the Jetty dependencies and then include them locally just like a normal JAR file:\n    \n    The  direcory is for the web applications dependencies. In this case we're packaging the WAR file so that it works like the normal Jetty JAR file on startupSo what to do?I have done a similar thing before but are you launchign the app as \"java -jar xxx.war\" ?. You have only 2 jars and it is not going to be enough I think. Also try using Jetty 7.0.0M1 (which is the latest version). When I added jetty-server and jetty-webapp as two dependencies (they are from org.eclipse.jetty) I get the following jar's in the lib directory. FYI the org.mortbay.jetty.Handler was in the jetty-server*.jar.
Java

I am using Selenium for automating the tests. My application exclusively uses IE, it will not work on other Browsers.Code:And here is the error I am gettingCan someone help me on this?Basically, you have to set this property  you initialize driverYou are setting the path for Chrome not IE. The error message says However you're setting \"\".You must set \"\" to the file location when using InternetExplorerDriver.You can set these properties in your shell/MVN/IDE with the -DpropertyName=ValueYou need to use quotes because of spaces or slashes in your path, alternatively reverse the slashes other wise they are escape prefix.You could also useinside your code.I just put the driver files directly into my project to not get any dependency to my local machine.For spring :You will need have to download InternetExplorer driver executable on your system, download it from the source () after download unzip it and put on the place of somewhere in your computer. In my example, I will place it to D:\\iexploredriver.exeThen you have write below code in your eclipse main class 
Java

My question is related to . When should I use it? Do I have to use each time I need to update the GUI components? What does it exactly do? Is there an alternative to it since it doesn't sound intuitive and adds seemingly unnecessary code?No, not if you're already on the event dispatch thread (EDT) which is always the case when responding to user initiated events such as clicks and selections. (The  methods etc, are always called by the EDT.)If you're  on the EDT however and want to do GUI updates (if you want to update the GUI from some timer thread, or from some network thread etc), you'll have to  the update to be performed by the EDT. That's what this method is for.Swing is basically thread unsafe. I.e., all interaction with that API needs to be performed on a single thread (the EDT). If you need to do GUI updates from another thread (timer thread, networking thread, ...) you need to use methods such as the one you mentioned (SwingUtilities.invokeLater, SwingUtilities.invokeAndWait, ...).usage (basic) for 1) main methods should be always wrapped into 2) delayed (but asynchronously) action/event to the end of , 3) if EDT doesn't exists then you have to create a new EDT by using can you test it with    4) there are exist , but till today I () can't found reason for using   instead of , except hard changes into GUI (JTree & JTable) but just with  (excelent for testing consistency of events on the EDT)5) 6) all output from BackGround Tasks must be wraped into Every Swing application has at least 2 threads:If you want to update the UI you should execute code within the EDT.\nMethods like SwingUtilities.invokeLater, SwingUtilities.invokeAndWait, EventQueue.invokeLater, EventQueue.invokeAndWait allow you to execute code by the EDT.What is key to understand is that Java has a separate thread (EDT) handling Swing related events.You should use  to display the main  of a desktop application (for example), instead of trying to do it in the current thread. It will also create the context for graceful closing of the application later. That's about it for most applications.No. If you modify a GUI component, it will trigger an event which is registered for later dispatching by Swing. If there is a listener for this event, the EDT thread will call it somewhere down the road. You don't need to use , just set your listeners on components properly. Keep in mind that this thread is the same thread drawing frames etc... on your screen. Hence, listeners should not perform complex/long/CPU intensive tasks, otherwise your screen will freeze.You don't need to write more code than displaying your application with  + listeners you are interested in on component. The rest is handled by Swing.Most user-initiated events (clicks, keyboard) will already be on the EDT so you won't have to use SwingUtilities for that.  That covers a lot of cases, except for your main() thread and worker threads that update the EDT.
Java

I'm looking for a library to handle  data in Java.Open source, well-documented implementations with a good object model are preferred.  iCal parsing capabilities are less important to me, but still nice to have.Does anyone have any recommendations?I had limited success with  () on a project last year.It seems to be a fairly popular choice for ical work in the java community. If I remember correctly the API can be slightly confusing at first glance.\nHowever It's pretty solid in the long run.Good luck, \nBrian A challenger appears!  Please give  a try.  I'm looking for lots of feedback on how it can be improved.
Java

I'm trying to build a Servlet that calls a JSP page similar to the following:I need this Servlet to respond to the domain's root (eg: ) so I'm using the following mapping in the web.xml:The problem I'm having is that this matches EVERYTHING, so when the dispatcher forwards to \"/WEB-INF/main.jsp\" this matches the url-pattern so the Servlet gets run again. This results in a loop that runs until it dies with a .How can I match the root without preventing other scripts from being runnable?Use an empty pattern, e.g.The servlet 3.0 spec has clarified this:So it should at least work on a 3.0 container, and I've verified that it works on Jetty 8Using the welcome-file element of web.xml worked for me, . Here's mine:The original question doesn't mention that they're trying to map a root servlet on App Engine - it's easy on Tomcat (and other servlet containers as far as I know) but App Engine isn't a normal servlet container.My normal way of building a web application with servlets is to extend HttpServlet, add a \"page\" object with title, content, errors, messages etc. and for output forward to a JSP template.  This has been an absolute nightmare getting working in App Engine.Here's my web.xml (edited for brevity) which finally worked.I haven't been particularly scientific about validating all this - but it seems to work for me now and I'm pretty happy about that.You can create a welcome file named index.jsp in the root with the following code using JSTL or otherwise.So in the web.xml file you will have this:So anyone requesting the root will be redirected to /main. Now your servlet can be mapped to main.Try just to remove '*' from the pattern, i.e.Have you tried the below?  (Note the missing , which is a wild card and is the reason that your configuration catches everything.)(Edited as per comments from just .)If you want your application (not just a servlet, but the entire application) to be available under the root context (\"/\" of \"\"), then you need to set up a context entry for it - not a servlet mapping. With Tomcat, you add a new  (in one of about 3 different possible places).A solution is mentioned in another thread  using URLrewrite -> 
Java

I have an android project that uses ant to build, is it possible to import this ant project in eclipse IDE?update : There is an option to create project using ant  in eclipse File->New->Project->Java->Java project from existing ant Buildfile. and if the build.xml file is selected it show error I guess javac is declared in this taskFrom :just simply import \"existing projects into workspace\" and import your project. then open 'ant' window from windows-->show/view --> ant drag-drop your ant file from project explorer to the and window.click to expand, and select the target you want to run ->right click -> run as ANTyour setup should be ok with this.Try the following method, got it work for me.
Java

In Java there used to be a subtle but important difference between abstract classes and interfaces: . Abstract classes could have them, interfaces could not. Java 8 though introduces default implementations for interfaces, meaning this is no longer the critical difference between an interface and an abstract class.So what is?As best as I can tell, the only remaining difference (besides perhaps some under the hood efficiency stuff) is that abstract classes follow traditional Java single-inheritance, whereas interfaces can have multiple-inheritance (or multiple-implementation if you will). This leads me to another question - How do the new Java 8 interfaces avoid the ?Interfaces cannot have state associated with them.Abstract classes can have state associated with them.Furthermore, default methods in interfaces need not be implemented. So in this way, it will not break already existing code, as while the interface does receive an update, the implementing class does not need to implement it.\nAs a result you may get suboptimal code, but if you want to have more optimal code, then your job is to override the default implementation.And lastly, in case a diamond problem occurs, then the compiler will warn you, and  will need to choose which interface you want to implement.To show more about the diamond problem, consider the following code:Here I get the compiler error on , that:The fix is:In case I wanted to inherit the  from .\nThe same holds for if  were a .To show even more about the difference between interfaces and abstract classes in Java 8, consider the following :You can in theory provide a default implementation of  such that you can add players to for example a list of players.\nBut wait...?\nHow do I store the list of players?\nThe answer is that you cannot do that in an interface, even if you have default implementations available.There have been some very detailed answers, but they seem to be missing one point that I at least consider as one of the very few justifications to have abstract classes :Abstract classes can have  members (and members with default visibility). Methods in interfaces are implicitly . The definition of the  is a vague. There are all kinds of issues that can occur with multiple inheritance. Fortunately, most of them can be easily detected at compile-time, and the programming languages support simple solutions to work around these issues. Most of these problems are not even specific to the . For example, conflicting definitions of methods can also occur without :The specific problem with  is the question of  vs. . If you have a type hierarchy where  and  derive from , and  derives from  and , then the question is:Well, in Java 8 the type  has to be an . So it makes no difference, because  have no state. It doesn't matter, that  can define , since they also have no state. They can invoke methods that have direct access to state. However, these methods are always implemented based on single inheritance.Now that interfaces can contain executable code, lots of use-cases for abstract classes are taken over by interfaces. But abstract classes can still have member variables, while interfaces can't. The diamond problem is avoided by simply not allowing a class to implement two interfaces when both interfaces provide a default implementation for the same method with the same signature.Still there are few more critical differences. Refer to this post: sAbove example produce below outout:  Above example produce below output:
Java

I would like to modify a file inside my jar. Is it possible to do this without extracting and re jarring, from within my application?File i want to modify are configuration files, mostly xml based.The reason i am interested in not un jarring is that the application is wrapped with launch4j if i unjar it i can't create the .exe file again.You can use the  option for From the Java Tutorials:\"Any files already in the archive having the same pathname as a file being added will be overwritten.\"See .Much better than making the whole jar all over again. Invoking this from within your program sounds possible too. Try Java jar files are the same format as zip files - so if you have a zip file utility that would let you modify an archive, you have your foot in the door. Second problem is, if you want to recompile a class or something, you probably will just have to re-build the jar; but a text file or something (xml, for instance) should be easily enough modified.As many have said, you can't change a file in a JAR without recanning the JAR. It's even worse with Launch4J, you have to rebuild the EXE once you change the JAR. So don't go this route.It's generally bad idea to put configuration files in the JAR. Here is my suggestion. Search for your configuration file in some pre-determined locations (like home directory, \\Program Files\\ etc). If you find a configuration file, use it. Otherwise, use the one in the JAR as fallback. If you do this, you just need to write the configuration file in the pre-determined location and the program will pick it up.Another benefit of this approach is that the modified configuration file doesn't get overwritten if you upgrade your software.You can use Vim:Vim is able to edit compressed text files, given you have  in your environment.This may be more work than you're looking to deal with in the short term, but I suspect in the long term it would be very beneficial for you to look into using  (or , or even ) instead of building jar's manually.  That way you can just click on the ant file (if you use Eclipse) and rebuild the jar.Alternatively, you may want to actually not have these config files in the jar at all - if you're expecting to need to replace these files regularly, or if it's supposed to be distributed to multiple parties, the config file should not be part of the jar at all.To expand on what dfa said, the reason is because the jar file is set up like a zip file.  If you want to modify the file, you must read out all of the entries, modify the one you want to change, and then write the entries back into the jar file.  I have had to do this before, and that was the only way I could find to do it.Note that this is using the internal to Java jar file editors, which are file streams.  I am sure there is a way to do it, you could read the entire jar into memory, modify everything, then write back out to a file stream.  That is what I believe utilities like 7-Zip and others are doing, as I believe the ToC of a zip header has to be defined at write time.  However, I could be wrong.Yes you can, using SQLite you can read from or write to a database from within the jar file, so that you won't have to extract and then re jar it, follow my post using the syntax  \"jdbc:sqlite::resource:\" you would be able to read and write to a database from within the jar fileCheck out .It does exactly what you want (to edit files inline inside a jar file), through a virtual file system API. It also supports nested archives (jar inside a jar) as well.Extract jar file for ex. with winrar and use CAVAJ:here is video tutorial if you need:\nNot sure if this help, but you can edit without extracting:Check the blog post for more details\nAs long as this file isn't .class, i.e. resource file or manifest file - you can.The simplest way I've found to do this in Windows is with :
Java

I would like to know what would be the best way to do unit testing of a servlet. Testing internal methods is not a problem as long as they don't refer to the servlet context, but what about testing the doGet/doPost methods as well as the internal method that refer to the context or make use of session parameters?Is there a way to do this simply using classical tools such as JUnit, or preferrably TestNG? Did I need to embed a tomcat server or something like that?Try , although you are likely to end up writing automated tests that are more 'integration tests' (of a module) than 'unit tests' (of a single class).Most of the time I test Servlets and JSP's via 'Integration Tests' rather than pure Unit Tests. There are a large number of add-ons for JUnit/TestNG available including:This is a JWebUnit test for a simple Order Processing Servlet which processes input from the form 'orderEntry.html'. It expects a customer id, a customer name and one or more order items:I looked at the posted answers and thought that I would post a more complete solution that actually demonstrates how to do the testing using embedded GlassFish and its Apache Maven plugin. I wrote the complete process up on my blog  and placed the complete project for download on Bitbucket here: I was looking at another post on an image servlet for JSP/JSF tags just before I saw this question. So I combined the solution I used from the other post with a complete unit tested version for this post.Apache Maven has a well defined lifecycle that includes . I will use this along with another lifecycle called  to implement my solution.Add this plugin as part of the .Add/modify the plugin as part of the .Add integration tests like the example below.I wrote the complete process up on my blog  and placed the complete project for download on Bitbucket here: If you have any questions, please leave a comment. I think that this is one complete example for you to use as the basis of any testing you are planning for servlets.Are you calling the doPost and doGet methods manually in the unit tests? If so you can override the HttpServletRequest methods to provide mock objects.The  is a convenience Java class. I suggest you to create a utility method in your unit tests to create the mock http requests:It's even better to put the mock creation methods in a base servlet superclass and make all servlets unit tests to extend it.Mockrunner () can do this.  It provides a mock J2EE container that can be used to test Servlets.  It can also be used to unit test other server-side code like EJBs, JDBC, JMS, Struts.  I've only used the JDBC and EJB capabilities myself.This implementation of a JUnit test for servlet doPost() method relies only on the Mockito library for mocking up instances of , , ,  and .  Replace parameter keys and JavaBean instance with those that correspond to values referenced in the associated JSP file from which doPost() is called.Mockito Maven dependency:JUnit test:Another solution is to use my  library, which is specifically designed for unit testing of servlets. It provides complete plain-Java implementations of all the Servlet API classes, and you can configure and inspect these as necessary for your tests.You can indeed use it to directly call doGet/doPost methods from JUnit or TestNG tests, and to test any internal methods even if they refer to the ServletContext or use session parameters (or any other Servlet API features).This doesn't need an external or embedded container, doesn't limit you to broader HTTP-based \"integration\" tests, and unlike general-purpose mocks it has the full Servlet API behaviour \"baked in\", so your tests can be \"state\"-based rather than \"interaction\"-based (e.g. your tests don't have to rely on the precise sequence of Servlet API calls made by your code, nor on your own expectations of how the Servlet API will respond to each call).There's a simple example in my answer to . For full details and a free download see the  website.
Java

I defined my own custom annotationhow, if at all, can I make the attribute optionalYou can  for the attribute:Found it. It can't be optional, but a default can be declared like this:If no default can make sense as \"empty\" value then that is a problem.For Optional attribute you need to provide default value for that attribute you can provide default value using \"default\" keyword.Note : For only one attribute you can use attribute name as .\nIf you use your attribute name as  you can directly pass value like this @MyCustomAnnotation(true) instead of @MyCustomAnnotation(myType = true).
Java

is there an easy way to get the (to-be-generated) sql from a Hibernate Criteria?Ideally I would have something like:The idea would then be to use the sql as part of a huge 'MINUS' query (I need to find the differences between 2 identical schemas - identical in structure, not in data - and the MINUS is not supported by Hibernate)(BTW I know I can check the SQL from the log files)I've done something like this using Spring AOP so I could grab the sql, parameters, errors, and execution time for any query run in the application whether it was HQL, Criteria, or native SQL.This is obviously fragile, insecure, subject to break with changes in Hibernate, etc, but it illustrates that it's possible to get the SQL:Wrap the entire thing in a try/catch and use at your own risk.Here's \"another\" way to get the SQL  :For those using NHibernate, this is a port of [ram]'s codeIf you are using Hibernate 3.6 you can use the code in the accepted answer (provided by Brian Deterling) with slight modification:I like this if you want to get just some parts of the query:For instance something like this:Here is a method I used and worked for meThis answer is based on user3715338's answer (with a small spelling error corrected) and mixed with Michael's answer for Hibernate 3.6 - based on the accepted answer from Brian Deterling. I then extended it (for PostgreSQL) with a couple more types replacing the questionmarks:
Java

I am trying to understand a JMX service URL.It would be great, if someone can help me understand this.ThanksI will reuse an answer I wrote up earlier for this question: It's not complete, but might help:Suppose you have the JMX Server (alias 'JMX Agent' alias 'the JVM you want to connect to') running on 'TARGET MACHINE' with the  at 'RMI REGISTRY PORT' and the  at 'JMX RMI SERVER PORT'.Note:The following URI will lead to successful connection (tested)This looks nasty. Let's cut it apart.This URI is an RFC2609 \"Service Location Protocol URL\" (well, it's really an URI, right?)It is composed of: is decomposed into:A well-informed JMX client connects to the \"ipsite\" to do JMX-over-RMI exchanges; but what of the JMX client that doesn't KNOW that port? Patience... is decomposed into:This is somewhat cart-before-horse, as one has to contact the  given by the  part of the SLP URL first.After scratching head, intuitively, let's try: Yes, that works! The JMX RMI server port is nicely obtained from the registry. On second thoughts, the  should also be obtained from the registry, thus:Even better, that works, too!References:To explain:Previous answers suggest that the 2nd part of the URL is to obtain the server port of the JMX RMI server. That is not correct. The JMX RMI server port is (TCP) 1234 and is part of the URL. What you get from the RMI registry is the RMI stub () which you can use to talk to JMX Agent (MBean Server) over RMI.Hope this helps.According to this url is assembled like this
Java

sorry to be a pain... I have: Yet...I'm guessing that  doesn't accept the standard  ?Am I doing something wrong or will I have to wrap my code in:ThanksIt accepts only a string value of  to represent boolean . Best what you can do isOr if the  actually represents an \"entitiy\", I think a  is way much better. Or if it represents configuration settings, you may want to take a look into .I have a small utility function to convert all possible values into Boolean. According to  (emphasis mine):If you're trying to get C's behavior ( and everything else is ), you could do this:As a note ,\nfor those who need to have null value for things other than \"true\" or \"false\" strings ,  you can use the function belowThomas,  I think your wrapper code, or just the condition itself, is the cleanest way to do what you want to do in java, which is convert \"1\" to the Boolean True value.  Actually, comparing to \"0\" and taking the inverse would match the C behavior of treating 0 as false and everything else as true.  Java is strongly typed. 0 and 1 are numbers, which is a different type than a boolean. A number will never be equal to a boolean.I know this is an old thread, but what about borrowing from C syntax:Returns true if comes 'y', '1', 'true', 'on'or whatever you add in similar wayHow about this?Very simple way: if valTest has the string \"true\", the boolean result will be true, otherwise, false;\nYou may use it for 0 or 1 values:
Java

Why it was always \"GC (Allocation Failure)\"?Java HotSpot(TM) 64-Bit Server VM (25.25-b02) for linux-amd64 JRE (-b17), \"Allocation Failure\" is a cause of GC cycle to kick.\"Allocation Failure\" means that no more space left in Eden to allocate object. So, it is normal cause of young GC.Older JVM were not printing GC cause for minor GC cycles.\"Allocation Failure\" is almost only possible cause for minor GC. Another reason for minor GC to kick could be CMS remark phase (if  is enabled).
Java

In java, what does the private static method  of the Object class do?The other answers are technically correct, but not very useful for someone with no JNI experience. :-)Normally, in order for the JVM to find your native functions, they have to be named a certain way. e.g., for , the corresponding C function is named . By using  (or rather, the JNI function ), you can name your C functions whatever you want.Here's the associated C code (from OpenJDK 6):(Notice that  is not in the list; it will still be called by the \"standard\" name of .) For the functions listed, the associated C functions are as listed in that table, which is handier than writing a bunch of forwarding functions.Registering native functions is also useful if you are embedding Java in your C program and want to link to functions within the application itself (as opposed to within a shared library), or the functions being used aren't otherwise \"exported\", since these would not normally be found by the standard method lookup mechanism. Registering native functions can also be used to \"rebind\" a native method to another C function (useful if your program supports dynamically loading and unloading modules, for example).I encourage everybody to read the , which talks about this and much more. :-)What might be slightly confusing is that the code shown for  in a previous answer is just an  of how to register native functions.  This is the code that (in the implementation of OpenJDK) registers native functions for class Object.  To register native functions for your own class, you must call the JNI function  from the native code in your own library.  This might sound a bit circular, but there are a couple ways to break the loop.ORSince you looked at the source code to find it, it's pretty easy to guess isn't?It's a native method, and it's called registerNatives, so I guess it registers objects with the underlying platform.It's also private, so it's probably nothing to be concerned about.
Java

There are many ways to initialize a mock object using MockIto.\nWhat is best way among these ?1.2.[EDIT]\n3.suggest me if there are any other ways better than these... , using the runner or the  are strictly equivalent solutions. From the javadoc of the  :The first solution (with the ) could be used when you have already configured a specific runner ( for example) on your test case.The second solution (with the ) is the more classic and my favorite. The code is simpler. Using a runner provides the great advantage of  (described by  in ).Both the solutions allows to share the mocks (and spies) between the test methods. Coupled with the , they allows to write unit tests very quickly. The boilerplate mocking code is reduced, the tests are easier to read. For example :Pros : The code is minimal Cons : Black magic. IMO it iss mainly due to the @InjectMocks annotation. With this annotation   (see the great comments of )The third solution is to create your mock un each test method. \nIt allow as explained by  in its answer to have \"\".Pros : You clearly demonstrate how the your api works (BDD...)Cons : there is more boilerplate code. (The mocks creation) recommandation is a compromise. Use the  annotation with the , but do not use the  :Pros : You clearly demonstrate how the your api works (How my  is instantiated). No boilerplate code.Cons : The test is not self contains, less pain of codeThere is now (as of v1.10.7) a fourth way to instantiate mocks, which is using a JUnit4  called .JUnit looks for , and uses them to . The upshot of this is that you can extract @Before methods, @After methods, and even try...catch wrappers into rules. You can even interact with these from within your test, the way that  does.MockitoRule behaves , except that you can use any other runner, such as  (which allows your test constructors to take arguments so your tests can be run multiple times), or Robolectric's test runner (so its classloader can provide Java replacements for Android native classes). This makes it strictly more flexible to use in recent JUnit and Mockito versions.In summary:See also: There is a neat way of doing this.MockitoAnnotations & the runner have been well discussed above, so I'm going to throw in my tuppence for the unloved:I use this because I find it a little bit more descriptive and I prefer (not out right ban) unit tests not to use member variables as I like my tests to be (as much as they can be) self contained.
Java

Can you overlay a view on top of everything in android?In iPhone I would get the new view set its  to (0,0) and its width and height to the width and height of . Adding it to  would then cause it to act as an overlay, covering the content behind (or if it had a transparent background then showing the view behind).Is there a similar technique in android? I realise that the views are slightly different (there are three types (or more...) relativelayout, linearlayout and framelayout) but is there any way to just overlay a view on top of everything indiscriminately?Simply use  or . The last child view will overlay everything else.Android supports a pattern which Cocoa Touch SDK doesn't: Layout management.\n for iPhone means to position everything absolute (besides some strech factors). Layout in android means that children will be placed in relation to eachother.Example (second EditText will completely cover the first one): is some kind of view stack. Made for special cases. is pretty powerful. You can define rules like , , etcUsually you set the content with  in  (it will inflate the layout for you). You can do that manually and call , there's no difference.The view itself might be a single view (like ) or a complex layout hierarchy (nested layouts, since all layouts are views themselves).After calling  your activity knows what its content looks like and you can use  to retrieve any view int this hierarchy (General pattern ).Now any view you add under LinearLayout with  will appear as overlay with  on Linear Layout with You can use :The best way is  , You can add any drawable as overlay to any view as its overlay since Android JellyBeanMR2(Api 18).Add  to  as its overlay:
Java

Is there a way to set heap size from a running Java program?  No. What you can do with an app that has very variable heap requirements is to set your max heap size very high with  and tune  and  so that the app will not hang on to a lot of memory when the heap shrinks (it does that with default settings). But note that this may cause performance problems when the memory actually used by the app varies both strongly and quickly - in that case you're better off having it hang on to all the memory rather than give it back to the OS only to claim it again a second later. You might also want to fiddle with the  to ensure that the GC doesn't leave too much unclaimed objects lying around, which it tends to do when there's a lot of room for the heap to grow, and which would defeat the goal of wanting the heap size to adjust to the app's needs.According to , you can't do this at runtime, but you can spawn another process with a different heap size.You can tweak those settings when you start your application but once the JVM is up and running those values cannot be changed.  Something like this:will set the minimum heap size to 32MB and the maximum heap size to 512MB.  Once these are set, you cannot change them within the running program.The consensus may indeed be that this is not possible, but we should be looking at the JVM source to see how it can be ergonomically controlled.  It would be very nice to be able to have a JVMTI agent be able to adjust the heap/perm/tenured/new/&c sizing online/at runtime.What would this do? it would allow agents to infer sizing adjustments based upon performance or footprint goals which will be important when moving JVMs into the Cloud.You can use the  option on startup (also known as )  This is maximum size you should ever need in which cause you shouldn't need to set it to more than the maximum size you will ever need.However, a work around is to have the main() check the maximum size and restart the java if the maximum size is not as desired. i.e. start another java program and die. on startup onlyI asked same question to myself. And unlike answers above there is something I can do about  app increasing max heap JVM size. If app is a web server in cluster mode, I could start a new instance with changed min/max heap size and than shutdown initial instance. That shall be especially simple in GlassFish where you have management instance separated from nodeAgent(app server clustered instance) JVM.Since many JVM applications are web apps, I think it worth to preserve in this blog.If I understand your question correctly, you're trying to change the heap size at . I don't see any reason why this should be possible. Set the heap size at  using the  JVM option. I also advise you to set the  option only if you absolutely need to. This option sets the initial amount of head memory that is allocated for the JVM. You should know how your application behaves in terms of memory. Set the the value of  wisely. If your app is some kind of a server app you can set a higher value, otherwise compromise your choice with other possible apps running in client machines and of course available memory.
Java

I have 2 jars, let's call them a.jar and b.jar.b.jar depends on a.jar.In a.jar, I defined a class, let's call it StaticClass. In the StaticClass, I defined a static block, calling a method named \"init\" : in b.jar, I have a main, so in the main, I expect that the init() method has been called, but actually not. I suspect that is because the StaticClass has not been loaded by the jvm, could anyone tell meThanksYes, you are right. Static initialization blocks are run when the JVM (class loader - to be specific) loads  (which occurs the first time it is referenced in code).You could force this method to be invoked by explicitly calling  which is preferable to relying on the JVM.You could also try using  to force the JVM to load the class and invoke its static blocks.Yes you are right, since you are not using your  it is not loaded by the vm and therefore  is never executed.For your second question, you probably have to go the hard way and scan all available classes and load them. You are right, the easiest way is to access the class, for instance do a Or something to that respect in your main method. This will ensure the class is loaded by the classloader.The static code is executed when your class ( I guess) is referenced.Thus, it should be executed if you create a  of  or if you .Yes, the static initializer will be executed when the class is loaded. This normally occurs when you access the class in the class loading context for the first time.Static block is executed when a loaded class is initialized or referenced first. Loading class doesnt mean that class is to initialized. JVM Class Loading is separate things to concern.in b.jar main method class should extend that StaticClass then automatically that static block and init() will be invokedAdding some more:   static block will be executed when jvm load class.Here in your example you can call  method of your  by intantiating  classlike \n    StaticClass staticClass=new StaticClass();or     
Java

I'm new to Spring and I'm wondering if its possible to use numerous transaction managers in the same application?I have two data access layers - one for both of the databases. I'm wondering, how do you go about using one transaction managers for one layer and different transaction manager for the other layer. I don't need to perform transactions across both databases - yet. But I do need perform transactions on each database individually. I've created an image to help outline my problem:Here is my application context configuration:Here is an example that uses this configuration:So for the account repository, I want to use an entity manager factory with the persistence unit set to accounts. However, with my BusinessData Repository, I want to use an entity manager factory with a different persistence unit. Since I can only define one transaction manager bean, how can I go about using different transaction managers for the different repositories?Thanks for any help.Where you use a  annotation, you can  by adding an attribute set to a bean name or qualifier.  For example, if your application context defines multiple transaction managers with qualifiers:You can use the qualifier to specify the transaction manager to use:This Spring Jira entry discusses the issue a bit: I think it could be one transaction manager per connection if you're not using two-phase commit.  You just need to create two transaction managers and inject them with the appropriate connection.But I must ask the question: why do you think you need two transaction managers?  You can have more than one database connection.  The DAOs that use the connections can and should be instantiated by different services, each of which can be annotated with their own transactional settings.  One manager can accommodate both.  Why do you think you need two?
Java

I have learned basics of Java but want to practice more. I was looking via Google and couldn't find many beginner level problems that I can solve using Java. Any suggestions?I recommend reading through the  for code examples and practice in  areas of Java programming, especially the areas you wish to improve in.Depending on how much of beginner examples you were looking for, check out  for some good beginner exercises.  is another good site, but depending on your skill level now, this may be too much, but it's worth trying anyways.Most importantly, Its also worth noting that  are a great way to start to learn a new language. I would also recommend starting a project that is benefical to you and get cracking right away, no time is better than the present!When learning a new language, there are some nice problem sets you can use to learn the language better.I highly recommend reading the book  from You could try the problems at , many of which lack Java solutions at the moment. The problems are of many different difficulties, but each has a solution already in another language which should help with the algorithmic side.If you wanted to learn some GUI, may be tic tac toe is good. Even for console, I still find that is a fun problem. Not challenging but a little bit fun. Later you can advance some other games or port that game to GUI, client server or java applet for the web. I think if you want to learn something and get fun as well, game is a good choice:)My recommendation is to solve problems that you're interested in, writing code that might be useful to you.Java is a huge box.  It's got a lot of computer science inside: graphics, scientific computing, relational databases, user interfaces for desktop and web, messaging and queuing, multi-threading, security, and more.  Each area has their own \"beginner problem\".  Which one do you mean?How do you define \"beginner problem\"?  Maybe you're having trouble because you aren't narrowing your search enough.  If your imagination is lacking, your best bet is to  and investigate what you get back.Or start with  and work you way all the way through it.  You'll know a fair amount about Java when you're done.Once you are quite good in Java SE (lets say you are able to pass SCJP), I'd suggest you get junior Java programmer job and improve yourself on real world problemsGo and buy the book titled \"Java examples in a nutshell\". In the book you will find most of practical examples. 
Java

I created a CircularImageView with this question: Download project on 1) This is the CircularImageView class :2) I use in my layout like this :3) Current result in picture :Objectif result :You can used or download my   with  by using  :I modified the  to achieve what you want.To create a shadow around the border, I simply used these two lines:You need  due to hardware acceleration on HoneyComb and up. It didn't work without it when I tried it.Here is the full code:I hope it helps! .I forked your CircularImageView and added support for selector overlays. I also improved drawing performance significantly...to add a border by making imageview as a circle, i've done a simple thing,\nI used this class to  make my image as a circleand by using this on Oncreate i have call the image for setting it,to add a border i created a circle shape XML like this,then using layouts i added a relativeLayout with imageview inside of it, by using padding and background drawable with wrapcontent i set my relative layout like thisnow it show like this, i don't know to add the shadow, sorry for that tooHope it helps.Maybe a better solution .Create a custom drawable, and use that to define your the background attribute of your ImageView.  You can use a LayeredDrawable, to create as many different components for the component as you would like.Checkout this answer, which creates a custom Rectangle (but is exactly the same with an Oval\\Circle):  just use drawCircle() method  with more width and height before drawing the actual image. Increase the width and height of in that new method call according to your wish, and set some another color of you want on paintI found a library that doing exactly what you wish, worked fine for me.\nCheck it out.\n
Java

This is probably a newbie question, but hope you can help me. :) I have something like this:I am using NetBeans IDE and for some reason the printStackTrace is underlined in a squiggly line.  When I press Alt+Enter, it says Throwable.printStackTrace() should be removed.  What does this mean?  Could anyone give more insight as what this may mean? Or can I ignore this?Thanks!It is just a recommendation. In eclipse it is fine - I believe it is just the IDE telling you that there are more conventional methods of doing it, like some of the other answers.\nI find that it is useful for debugging, and that you should tell users when a fatal error is going to occur, to use a debug mode (like a console switch -d) to collect these logs.Try:It's probably because  doesn't really handle the error as much as it just dumps the stack in the console. It acts as a placeholder until you replace it with proper error handling (if it is needed at all) and replace the output with a logger of some sort.Is not good practice because it prints in the default ErrorStream, which most of the times is the console!NetBeans should be warning you about that. The good practice about it, is logging the message. Follow same reference:\nSee first comment bellow to more info.
Java

I have read books on , saying that it is good to create setters and getters for variables such as  and .  For example:But what is the difference from that andandIf setters and getters are better, could you explain to me what practical problems would arise?Multiple reasons:then you cannot add any logic in future to validate the data.say if x cannot be less than 100 you cannot do it, however if you had setters likeThough for constants likeyou will allow field access as they cannot be changed, for instance variable you will place them with getters, setters.Though in such cases you have to be careful in getter method to ensure you don't give out reference of objects(in case your class have object as instances).We can use the private variables in any package using getters and setters.Using getter and setter functions allow for constraints and encapsulation. Lets say x is the radius. shape.x = -10 would not make much sense. Also, if someone tries to set an illegal value, you can print an error, set a default value, or do nothing.It is good practice to make member variables private so they cannot be modified directly by programs using them.\nAnother good reason to user getter and setter can be understand by the following exampleThe point of getters and setters is that only they are meant to be used to access the private varialble, which they are getting or setting. This way you provide encapsulation and it will be much easier to refactor or modify your code later.Imagine you use name instead of its getter. Then if you want to add something like a default (say the default name is 'Guest' if it wasn't set before), then you'll have to modify both the getter and the sayName function.There is no requirement for getters and setter to start with get and set - they are just normal member functions. However it's a convention to do that. (especially if you use Java Beans)A lot of people have mentioned encapsulating the specifics of the implementation, which to me is the biggest reason to use getters and setters in a class. With this, you also get a lot of other benefits, including the ability to throw out and replace the implementation on a whim without needing to touch every piece of code that uses your class. In a small project, that's not a big benefit, but if your code ends up as a well-used (internal or public) library, it can be a  benefit.One specific example: . Some languages have them as a language or framework feature, others don't. I will use a mutable class as an example here, but it could just as easily be immutable.A complex number can be written on the form  with real and imaginary parts, lending itself well to  and .However, in some cases it's easier to reason about complex numbers on polar form , giving  (r) and  (\u03b8).You can also expose methods like  and . Depending on the argument types these may or may not need different names, but then the class' consumer can use either as fits its needs.The two forms are interchangeable; you can fairly easily convert from one to the other, so which form the class uses for internal storage is irrelevant to consumers of that class. However, consumers may use either form. If you choose the form a+bi for internal representation, and , not only do you force the class consumers to use that form, you also cannot later easily change your mind and replace the internal representation with re^(i\u03b8) because that turns out to be easier to implement in your particular scenario. You're stuck with the public API you have defined, which mandates that specifically the real and imaginary parts are exposed using specific field names.One of the best reasons I can think of for getters and setters is the permanence of a class's API. In languages like python you can access members by their name and switch them to methods later. Because functions behave differently than members in java once you access a property thats it. Restricting its scope later breaks the client. By providing getters and setters a programmer has the flexibility to modify members and behavior freely as long as the adhere to the contract described by the public API.Let's say, hypothetically, you find a library that does a better job of what you have been doing in your own class (YourClass). The natural thing to do at this point is to make YourClass a wrapper interface to that library. It still has a concept of \"X\" which your client code needs to get or set. Naturally, at this point you pretty much have to write the accessor functions.If you neglected to use accessor functions and let your client code access YourClass.x directly, you would now have to rewrite all of your client code that ever touched YourClass.x. But if you were using YourClass.getX() and YourClass.setX() from the beginning, you will only need to rewrite YourClass.One of the key concepts of programming, and especially object oriented programming, is hiding implementation details so that they're not used directly by code in other classes or modules. This way, if you ever change the implementation details (as in the example above), the client code doesn't know the difference and doesn't have to be modified. For all your client code knows, \"x\" might be a variable, or it might be a value that is calculated on the fly.This is an oversimplification and doesn't cover all the scenarios where hiding implementation is beneficial, but it is the most obvious example. The concept of hiding implementation details is pretty strongly tied to OOP now, but you can find discussions of it going back decades before OOP was dreamed up. It goes back to one of the core concepts of software development, which is to take a big nebulous problem, and divide it into small well-defined problems which can be solved easily. Accessor functions help keep your small sub-tasks separate and well-defined: The less your classes know about each other's internals, the better.Originally, getter/setter pattern was created to promote good object-oriented design by  the internals of a  from its external .    this is the best answer of your question There are lots of reasons.  Here are just a few.Before get into the answer, we gotta know something prior...! \"\".\n. For our purpose, think of properties as private instance variables. since they're private, the only way they can be accessed \nfrom outside of their class is through 'methods'in the class.\n The methods that change a propertiy's value are called , and the methods that retrieve a property's value are called .I would say that neither the getters/setters nor the public members are good Object Oriented design.  They both break OOP Encapsulation by exposing an objects data to the world that probably shouldn't be accessing the properties of the object in the first place.This is done by applying the  principle of OOP.This means, you must define the visibility for the attributes and methods of your classes. There are 3 common visibilities:When you declare private/protected attributes, you are encouraged to create methods to obtain the value (get) and change the value (set). One example about visibility is the  class: it has a  property to know the actual size of the inner array. Only the class  change its value, so the code is something likeIn this example, you can see that the size value can change only inside the class methods, and you can get the actual size by calling it in your code (not mutating it):Getters and setters encapsulate the fields of a class by making them accessible only through its public methods and keep the values themselves private. That is considered a good OO principle.Granted, it often seems like redundant code if it does nothing more than setting or returning a value. However, setters also allow you to do input validation or cleanup. Having that in one place improves data integrity for your objects,Because we are using Object oriented programming language. \nHere we are using Data hiding and encapsulation.\nThe variable should not directly accessible from out side world (for achiving data hiding) so we will create it private so is not correct.\nGetter and setter method are used to get and set the value of x which is the way to achive encapsulation.
Java

What are the advantages of  over compressed strings in JDK9?Compressed strings (Java 6) and compact strings (Java 9) both have the same motivation (strings are often effectively Latin-1, so half the space is wasted) and goal (make those strings small) but the implementations differ a lot.In  Aleksey Shipil\u00ebv (who was in charge of implementing the Java 9 feature) had this to say about compressed strings:In Java 9 on the other hand, compact strings are fully integrated into the JDK source.  is  backed by , where characters use one byte if they are Latin-1 and otherwise two. Most operations do a check to see which is the case, e.g. :Compact strings are enabled by default and can be partially disabled - \"partially\" because they are still backed by a  and operations returning s must still put them together from two separate bytes (due to intrinsics it is hard to say whether this has a performance impact).If you're interested in more background on compact strings I recommend to read  I linked to above and/or watch  (which also explains the new string concatenation). and  are different things.  meant that Strings that are ASCII only could be converted to , but this was off by-default. In jdk-9 this optimization is always on, but not via the flag itself, but build-in. Until java-9 Strings are stored internally as a  in UTF-16 encoding. From java-9 and up they will be store as . Why?Because in  each character can be encoded in a single byte (8 bits) vs what it is used to be until now (16 bits, 8 of each where never used). This works  for , but that is the majority of Strings used anyway.So that is done for space usage. Here is a small example that should make things more clear:In the first case we are going to get zeroes only, meaning that the most significant 8 bits are zeroes; in the second case there is going to be a non-zero value, meaning that at least one bit from the most significant 8, is present.That means that if internally we store Strings as an array of chars, there are string literals that actually waste half of each char. It turns out there are multiple applications that actually waste a lot of space because of this.You have a String made from 10 Latin1 characters? You just lost 80 bits, or 10 bytes. To mitigate this String compression was made. And now, there will be no space loss for these Strings. Internally this also means some very nice things. To distinguish between String that are  and  there's a field :Now based on this  is computed differently:If our String is Latin1 only, coder is going to be zero, so length of value (the byte array) is the size of chars. For non-Latin1 divide by two. will have best of both worlds.As can be seen in the definition provided in OpenJDK documentation: As mentioned by @Eugene, most of the strings are encoded in Latin-1 format and require one byte per character and hence do not require the whole 2-byte space provide in current String class implementation.The new String class implementation will shift from  to  . The additional  will show whether the characters are stored using UTF-16 or Latin-1 format.This also concludes that we will also be able to store strings in UTF-16 format if required. And this also becomes the main point of difference between the  and  as in Compressed String  was used for storage which was then representated as . 
Java

I create a web application (WAR) and deploy it on Tomcat. In the  there is a page with a form where an administrator can enter some configuration data. I don't want to store this data in an DBMS, but just in an XML file on the file system. Where to put it?I would like to put the file somewhere in the directory tree where the application itself is deployed. Should my configuration file be in the  directory? Or put it somewhere else? And what is the Java code to use in a servlet to find the absolute path of the directory? Or can it be accessed with a relative path?What we do is to put it in a separate directory on the server (you could use something like /config, /opt/config, /root/config, /home/username/config, or anything you want). When our servlets start up, they read the XML file, get a few things out of it (most importantly DB connection information), and that's it.I asked about why we did this once.It would be nice to store everything in the DB, but obviously you can't store DB connection information in the DB.You could hardcode things in the code, but that's ugly for many reasons. If the info ever has to change you have to rebuild the code and redeploy. If someone gets a copy of your code or your WAR file they would then get that information.Putting things in the WAR file seems nice, but if you want to change things much it could be a bad idea. The problem is that if you have to change the information, then next time you redeploy it will overwrite the file so anything you didn't remember to change in the version getting built into the WAR gets forgotten.The file in a special place on the file system thing works quite well for us. It doesn't have any big downsides. You know where it is, it's stored seperatly, makes deploying to multiple machines easy if they all need different config values (since it's not part of the WAR).The only other solution I can think of that would work well would be keeping everything in the DB except the DB login info. That would come from Java system properties that are retrieved through the JVM. This the Preferences API thing mentioned by Hans Doggen above. I don't think it was around when our application was first developed, if it was it wasn't used.As for the path for accessing the configuration file, it's just a file on the filesystem. You don't need to worry about the web path. So when your servlet starts up it just opens the file at \"/config/myapp/config.xml\" (or whatever) and it will find the right thing. Just hardcodeing the path in for this one seems pretty harmless to me.WEB-INF is a good place to put your config file.  Here's some code to get the absolute path of the directory from a servlet.Putting it in  will hide the XML file from users who try to access it directly through a URL, so yes, I'd say put it in .I would not store it in the application folder, because that would override the configuration with a new deployment of the application.I suggest you have a look at the Preferences API, or write something in the users folder (the user that is running Tomcat).The answer to this depends on how you intend to read and write that config file.For example, the Spring framework gives you the ability to  (or Java property files); these can be stored in your classpath (e.g., in the WEB-INF directory), anywhere else on the filesystem, or even in memory.  If you were to use Spring for this, then the easiest place to store the config file is in your WEB-INF directory, and then use Spring's  class to access your configuration file.But again, it all depends on how you plan to access that file.If it is your custom config WEB-INF is a good place for it. But some libraries may require configs to reside in WEB-INF/classes.
Java

I need to download a web page on an android app and I am having a hard time deciding whether to use the android apache http client or java's URLConnection.Any thoughts?For most things I'd say that  is the way to go.  However there are some situations and edge cases where I'd fall back to a .  Examples of edge cases  and  \nA similar question has been asked before: .   I would find  code much quicker and easier to write and maintain.  According to a comments below, the core elements of  have been performance optimised.  If performance is a major concern your best bet is to write two clients, one using each method, then benchmark them both.  If you do this, please let us know the results.Google has silently deprecated Apache HTTP client usage since Gingerbread: . And while they didn't mark it with deprecated annotation, they suggest you to use HttpURLConnection for new applications as: .Personally I don't like that decision and would rather stick to HttpClient 4.1+, as it is faster, have fewer bugs and is updated regularly. And while you can not upgrade system library to version 4.1, you can include HttpClient jar to your Android project (as the additional benefit this would allow you to not depend on Google bug fixes and vendor updates). There is one pitfall however: to prevent possible collisions with built-in library you should rename httpclient packages using JarJar tool. Turned out someone already did this (repackaged jar and Android library projects are available for download):  in Gingerbread and later, HttpURLConnection is the way to go. consider Apache HttpClient deprecated. (also note that Android doesn't use HttpClient 4.1, mentioned in another comment.)if you have a case where Apache HttpClient is faster, report it as a bug here: 
Java

I found the following Java code.where  and  are .I know basic operations on primitive types are thread-safe, but I am not sure about . If the above  is necessary, is there maybe a better class to handle such operation?No.  The  operation is not thread-safe.  It requires locking and / or a proper chain of \"happens-before\" relationships for any expression involving assignment to a shared field or array element to be thread-safe.  (With a field declared as , the \"happens-before\" relationships exist ... but only on read and write operations.  The  operation consists of a read and a write.  These are individually atomic, but the sequence isn't.  And most assignment expressions using  involve both one or more reads (on the right hand side) and a write.  That  is not atomic either.)For the complete story, read JLS  ... or the relevant chapter of \"Java Concurrency in Action\" by Brian Goetz et al.Actually, that is an incorrect premise:There is an additional issue for the  type.  The JLS () says this:In a comment, you asked:In this case (where you are updating a , there is no alternative to synchronization with locks or primitive mutexes.If you had an  or a  you could replace them with  or  and make use of those classes' lock-free update.  However there is no  class, or even an  class.  ( - someone pointed out that Guava provides an  class, so that  be an option.  A good one actually.)One way of avoiding a \"global lock\" and massive contention problems might be to divide the array into notional regions, each with its own lock.  That way, one thread only needs to block another thread if they are using the same region of the array.  (Single writer / multiple reader locks could help too ... if the vast majority of accesses are reads.)Despite of the fact that there is no  or  in java, you can easily create your own based on .As you can see, I use  and  to store  as  in . They both have the same size in bits, so precision is not lost (except for -NaN, but I don't think it is important).In Java 8 the implementation of  can be even easier, as you can use  method of  that was added in java 1.8.: It appears that I virtually re-implemented guava's .Even the normal 'double' data type is not thread-safe (because it is not atomic) in 32-bit JVMs as it takes eight bytes in Java (which involves 2*32 bit operations).As it's already explained, this code is not thread safe. One possible solution to avoid synchronization in Java-8 is to use new  class which is capable to maintain the sum of double numbers in thread-safe manner.Create array of  objects before parallelizing:Then accumulate the sum in parallel threads like this:Finally get the result after parallel subtasks finished:
Java

If I write this line in Java:Which method will be called?I can test it. But in other cases similar to this, I want to know what happens.The  method will be called - in this caseThis generally comes under the  step of overload resolution in the spec (15.12.2), and in particular .Without getting into the details (which you can read just as well in the spec as here), the introduction gives a good summary:In your particular case the more specific method will be called.  In general, though, there are some cases where the method signature can be ambiguous.  Consider the following:In this case, the compiler can't decide between the method that takes an Integer and the method that takes a String.  When I try to compile that, I getor I should have known - never doubt Jon Skeet. The problem I've referred to above only occurs when it's impossible to determine which method is more specific. Here's a test case:The above will give a compiler error.
Java

I need a data structure to store string-int value pairs in an 1:1 relationship, and being able too look up from either way their counterpart.I wrote a class with a Hashtable and a String array and stored the data 2 times and used the built in functions for lookup.My question is that is there a nicer way to accomplish this? And by nicer I mean being efficient and not storing the data 2 times, and preferably without writing a ton of code either :P.It seems like you may be looking for a bimap.The Google Collections (now a part of ) contains an  interface with a few implementations.From the  documentation:The  method appears to return a  with the values as the keys, and the keys as the values, so that  can be used to call  on the value and retrieve a key.In addition the  returned by  is a view of the underlying data, so it does not have to make extra copies of the original data.From the  method documentation:You can do a simple implementation like this. Please note that the data is not copied in this implementation. Only the references are ! I have added implementation for add and get. remove and other required method are left as exercise :)And ofcourse its applications responsibility to ensue even the 'values' are unique. Example usage:Apache Commons also includes the  (Bi Directional Map).The  has a  that does what you want.Using , read complete tutorial Create a hashmap that maps Object to Object - then you can use the same map to store String -> Integer and Integer -> String.When you add a string/int pair just add it both ways to the same map.
Java

I have two packages,  and :I am writing the JavaDoc for  and need to provide an  to .I have tried all of the following, and none of them work:I've been able to find documentation for linking to: (a) classes within the same package, or (b) externals URLs, but not classes in another package.Any ideas what the correct syntax should be? Thanks!The  variants areYou were missing a complete package. The following example should be correctFor another package use this syntax:  In your case this should be:   If you want to show only the class name then use the label, if complete path is desired then label is not required.Reference:\n
Java

Is there a way to download dependencies from a pom.xml file to a specified folder in java? I'm able to run maven command from java and I got download messages, but I don't know where maven stores these libraries? How can I download these dependencies to a specific folder? Take a look at maven's dependency plugin, specifically the  goal. The  describes how to do exactly what you want.To do it from the command line just do:Maven stores all of these in it's local Maven2 repository.  By default, it will store them in your user home directory under a directory called repository.You can use the maven-dependency-plugin's goal called copy to take all of your project's dependencies and put them in a folder.Add something similar to the following to pom.xml:Then run  to perform the copy.\nCombine this with the  and you can package everything into a self contained archive for distribution.
Java

How can I see the number of threads in a Java process? Useful tool for debugging java programs, it gives the number of threads and other relevant info on them:It will return the number of active threads in the .docs:  doesn't limit itself to thread groups as  does.There is a static method on the  Class that will return the number of active threads controlled by the JVM:Additionally, external debuggers should list all active threads (and allow you to suspend any number of them) if you wish to monitor them in real-time.I have written a program to iterate all  created and printing  of each Output:If you remove below conditionYou will get below threads in output too, which have been started by system.. Generic solution that doesn't require a GUI like jconsole (doesn't work on remote terminals), ps works for non-java processes, doesn't require a JVM installed. 
Java

I would like to convert cal to a Date type to insert into table.There is a  method (unsure why it's not called getDate).Edit: Just realised you need a java.sql.Date. One of the answers which use  is what you need.Did you try ? This gets the date representation.You might also want to look at the javadoc.Use Converting is easy, setting date and time is a little tricky. Here's an example:Here is a simple way to convert  values into  instances.I found this code works:   you can find the rest in this tutorial:\n
Java

orI don't need to use 's' outside the loop ever again. \nThe 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.Use your second option:If you disassemble code the compiled from each (with the JDK's  tool), you will see that the loop compiles to the exact same JVM instructions in both cases. Note also that  \"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.The only difference between the two cases is that, in the first example, the variable  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 , and a good JIT compiler will probably elide it at runtime. You could fix this simply by using an empty declaration (i.e., ), but this is considered bad practice and has another side-effect discussed below. Often a bogus value like  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.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:The variables  and  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.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.In , it's a waste of resources to declare the string inside the loop. \nIn , however, both of the snippets you presented will compile down to the same code (declaration outside the loop).  So, if your compiler does any amount of optimization, there's no difference.In general I would choose the second one, because the scope of the 's' variable is limited to the loop. Benefits:If you want to speed up for loops, I prefer declaring a max variable next to the counter so that  no repeated lookups for the condidtion are needed:instead ofI preferAny other things that should be considered have already been mentioned, so just my two cents (see ericksons post)Greetz, GHadTo add on a bit to @, they will both require the creation of a new string each time through the loop (as the return value of the  expression). Those strings need to be garbage collected either way.I know this is an old question, but I thought I'd add a bit that is  related.I've noticed while browsing the Java source code that some methods, like String.contentEquals (duplicated below) makes redundant local variables that are merely copies of class variables.  I believe that there was a comment somewhere, that implied that accessing local variables is faster than accessing class variables.In this case \"v1\" and \"v2\" are seemingly unnecessary and could be eliminated to simplify the code, but were added to improve performance.It seems to me that we need more specification of the problem.The is not specified as to what kind of assignment this is.  If the assignment is then a new sting needs to be allocated.but if it is s will merely point to the constants memory location, and thus the first version would be more memory efficient.Seems i little silly to worry about to much optimization of a for loop for an interpreted lang IMHO.When I'm using multiple threads (50+) then i found this to be a very effective way of handling ghost thread issues with not being able to close a process correctly ....if I'm wrong, please let me know why I'm wrong:
Java

I am simply trying to see the H2 database content for an embedded H2 database which spring-boot creates when I don't specify anything in my application.properties and start with mvn spring:run. I can see hibernate JPA creating the tables but if I try to access the h2 console at the URL below the database has no tables.I see suggestions like this one:\nBut I don't know where to put the suggested XML in spring-boot and even if I did, I don't want the h2console to be available anymore when an external database is configured so it is more likely that I need to handle this with some kind of conditional code (or maybe just allow spring to automatically handle it in the most ideal case where I only include H2 when a maven profile is activated).Does anyone have some sample code showing how to get the H2 console working in boot (and also the way to find out what the jdbc connection string that spring is using is)?This is how I got the H2 console working in spring-boot with H2. I am not sure if this is right but since no one else has offered a solution then I am going to suggest this is the best way to do it.In my case, I chose a specific name for the database so that I would have something to enter when starting the H2 console (in this case, \"AZ\"). I think all of these are required though it seems like leaving out the spring.jpa.database-platform does not hurt anything. In application.properties:In Application.java (or some configuration):Then you can access the H2 console at {server}/console/. Enter this as the JDBC URL: jdbc:h2:mem:AZAs of Spring Boot , the H2 console can be auto-configured. The prerequisites are:Even if you don't use Spring Boot Dev Tools, you can still auto-configure the console by setting  to Check out  part of the documentation for all the details.I have found a nice tutorial about this topic: Basically the correct JDBC URL for me was: A similar answer with Step by Step guide.I had only below properties in /resources/application.properties. After running spring boot, using this URL(), the table in H2 console was visible and read to view the table data, also you can run simple SQL commands. One thing, in your java code, while fetching data, the column names are upper-case, even though schema.sql is using lower-case names :)From  H2 Web Console (H2ConsoleProperties):Adding the above two lines to my application.properties file was enough to access the H2 database web console, using the default username (sa) and password (empty).In order to get the tables all you need to do is create 2 sql files schema.sql(for table creation) and data.sql(data for the created tables). These files to be put in src/main/resources folder. Spring boot auto detects them and takes care of the rest during runtime.If your using more than 2 DB in your project ensure to use specific files like (schema-h2.sql -- for h2 DB , schema-oracle.sql -- for oracle DB). The same to be followed for data.sql too.Also ensure that you drop tables by adding drop table statement in your schema.sql as first statement. To avoid appending of duplicate records.The link for spring boot is here.My application.properties is as follows.You can follow the steps in the below link.If you use Spring Boot's developer tools, it comes with H2 Console enabled by default. It can be accessed from /. On the login interface, for input  use value . Pay attention to  string.If you don't use Spring Boot's developer tools, you can enable the console in  using . This will enable console under . If you want to change the URL then you can add another entry with .The default schema name is .More details in .
Java

I would like to concatenate a string within a ternary operator in EL(Expression Language).Suppose there is a variable named value. If it's empty, I want to use some default text. Otherwise, I need to append it with some static text.This will not compile however. What would be a correct way to write this? Or is this even possible?This answer is obsolete. Technology has moved on. Unless you're working with legacy systems see .There is no string concatenation operator in EL. If you don't need the concatenated string to pass into some other operation, just put these expressions next to each other:With EL 2 you can do the following:If you're already on EL 3.0 (Java EE 7; WildFly, Tomcat 8, GlassFish 4, etc), then you could use the new  operator for this:If you're however not on EL 3.0 yet, and the  is a genuine  instance (and thus not e.g. ), then use EL 2.2 (Java EE 7; JBoss AS 6/7, Tomcat 7, GlassFish 3, etc) capability of invoking direct methods with arguments, which you then apply on :Or if you're even not on EL 2.2 yet, then use JSTL  to create a new EL variable with the concatenated values just inlined in value:Since Expression Language 3.0, it is valid to use += operator for string concatenation.Quoting . is right. I just want to add an improvement if in case you may need to return the variable's value as:1.The +(operator) has not effect to that in using EL.\n2.so this is the way,to use that is this helpful to You ?it also can be a great idea using concat for EL + MAP + JSON problem like in this example :#{myMap[''.concat(myid)].content}
Java

Is it better to writeor I think the second one is better, should be faster and more memory optimized. But aren't they equal?For performance, it usually best to make the code as simple and clear as possible and this will often perform well (as the JIT will optimise this code best).  In your case, the simplest examples are also likely to be the fastest.I would do eitheror a longer versionorIts best not to create an object if you don't need to.Performance wise, the first is best.If you know for sure that you won't get an overflow you can useyou won't get faster than this.Use . And don'try to micro-optimize your code unless you can prove that you have a performance issue.May I propose a thirdWrapping int primitive into Integer object will cost you some memory, but the difference will be only significant in very rare(memory demand) cases (array with 1000+ elements). I will not recommend using new Integer(int a) constructor this way. This will suffice :About comparision there is Math.signum(double d).They're already ints. Why not just use subtraction?Note that Integer.compareTo() doesn't necessarily return only -1, 0 or 1 either.For pre 1.7 i would say an equivalent to Integer.compare(x, y) is:You can do this via the bit manipulation, something like this:If you are using java 8, you can create Comparator by this method:if you would like to compare with reversed order:
Java

I have a thick client, java swing application with a schema of 25 tables and ~15 JInternalFrames (data entry forms for the tables).  I need to make a design choice of straight JDBC or ORM (hibernate with spring framework in this case) for DBMS interaction.  Build out of the application will occur in the future.Would hibernate be overkill for a project of this size?  An explanation of either yes or no answer would be much appreciated (or even a different approach if warranted).TIA.Good question with no single simple answer.I used to be a big fan of Hibernate after using it in multiple projects over multiple years. \nI used to believe that any project should default to hibernate.Today I am not so sure.Hibernate (and JPA) is great for some things, especially early in the development cycle.\nIt is much faster to get to something working with Hibernate than it is with JDBC.\nYou get a lot of features for free - caching, optimistic locking and so on.On the other hand it has some hidden costs. . Follow some tutorial, put some annotations on your class - and you've got yourself persistence. But it's not simple and to be able to write good code in it requires good understanding of both it's internal workings and database design. If you are just starting you may not be aware of some issues that may bite you later on, so here is an incomplete list.The runtime performance is good enough, I have yet to see a situation where hibernate was the reason for poor performance in . The problem is the startup performance and how it affects your unit tests time and development performance. When hibernate loads it analyzes all entities and does a lot of pre-caching - it can take about 5-10-15 seconds for a not very big application. So your 1 second unit test is going to take 11 secods now. Not fun.It is very cool as long as you don't need to do some fine tuning on the database.For every transaction Hibernate will store an object in memory for every database row it \"touches\". It's a nice optimization when you are doing some simple data entry. If you need to process lots of objects for some reason though, it can seriously affect performance, unless you explicitly and carefully clean up the in-memory session on your own.Cascades allow you to simplify working with object graphs. For example if you have a root object and some children and you save root object, you can configure hibernate to save children as well. The problem starts when your object graph grow complex. Unless you are extremely careful and have a good understanding of what goes on internally, it's easy to mess this up. And when you do it is very hard to debug those problems.Lazy Loading means that every time you load an object, hibernate will not load all it's related objects but instead will provide place holders which will be resolved as soon as you try to access them. Great optimization right? It is, except you need to be aware of this behaviour otherwise you will get cryptic errors. Google \"LazyInitializationException\" for an example. And be careful with performance. Depending on the order of how you load your objects and your object graph you may hit \"n+1 selects problem\". Google it for more information.Hibernate allows easy schema changes by just refactoring java code and restarting. It's great when you start. But then you release version one. And unless you want to lose your customers you need to provide them schema upgrade scripts. Which means no more simple refactoring as all schema changes must be done in SQL. Hibernate requires exclusive write access to the data it works with. Which means you can't really use views, stored procedures and triggers as those can cause changes to data with hibernate not aware of them. You can have some external processes writing data to the database in a separate transactions. But if you do, your cache will have invalid data. Which is one more thing to care about.Hibernate sessions are single threaded. Any object loaded through a session can only be accessed (including reading) from the same thread. This is acceptable for server side applications but might complicate things unnecessary if you are doing GUI based application.I guess my point is that Hibernate is a good tool, but it's a complex tool, and it requires time to understand it properly. If you or your team members don't have such knowledge it might be simpler and faster to go with pure JDBC (or Spring JDBC) for a single application. On the other hand if you are willing to invest time into learning it (including learning by doing and debugging) than in the future you will be able to understand the tradeoffs better.Hibernate can be good but it and other JPA ORMs tend to dictate your database structure to a degree. For example, composite primary keys can be done in Hibernate/JPA but they're a little awkward. There are other examples.If you're comfortable with SQL I would strongly suggest you take a look at . It can do 90%+ of what Hibernate can but is far simpler in implementation.I can't think of a single reason why I'd ever choose straight JDBC (or even Spring JDBC) over Ibatis. Hibernate is a more complex choice.Take a look at the .No doubt Hibernate has its complexity.But what I really like about the Hibernate approach (some others too) is the conceptual model you can get in Java is better. Although I don't think of OO as a panacea, and I don't look for theoritical purity of the design, I found so many times that OO does in fact simplify my code. As you asked specifically for details, here are some examples :For all these reasons, I would choose Hibernate :-)I think either is a fine choice, but personally I would use hibernate.  I don't think hibernate is overkill for a project of that size.Where Hibernate really shines for me is dealing with relationships between entities/tables.  Doing JDBC by hand can take a lot of code if you deal with modifying parent and children (grandchildren, siblings, etc) at the same time.  Hibernate can make this a breeze (often a single save of the parent entity is enough).There are certainly complexities when dealing with Hibernate though, such as understanding how the Session flushing works, and dealing with lazy loading.Hibernate best suits for the middleware applications. Assume that we build a middle ware on top of the data base, The middelware is accessed by around 20 applications in that case we can have a hibernate which satisfies the requirement of all 20 applications.Straight JDBC would fit the simplest cases at best. If you want to stay within Java and OOD  then going Hibernate or Hibernate/JPA or any-other-JPA-provider/JPA should be your choice. If you are more comfortable with SQL then having Spring for JDBC templates and other SQL-oriented frameworks won't hurt. In contrast, besides transactional control, there is not much help from having Spring when working with JPA.You could look at  which doesn't use session objects ... and where lazy loading just works. Certainly an option, not overkill, and will be simpler to understand.
Java

The idea is to have a String read and to verify that it does not contain any numeric characters. So something like \"smith23\" would not be acceptable. What do you want? Speed or simplicity? For speed, go for a loop based approach. For simplicity, go for a one liner RegEx based approach.Java 8 lambda expressions. Both fast and simple.Or if you are using Apache Commons, .I used this regex expression . With  statement it will avoid all expressions that have a letter before, at the end or between any type of other character.A  way to do it is by:Because you don't have to run the whole  to check if it isn't an .I know it's a bit crowded. I was using it with my program and felt the desire to share it with people. It can tell if any character in a string is not a letter or not. Use it if you want something easy to clarify and look back on.Faster way is below. Considering letters are only a-z,A-Z.Runtime is calculated in nano seconds. It may vary system to system.Check this,i guess this is help you because it's work in my project so once you check this codeTry using regular expressions: 
Java

Have Googled extensively on this error, but I can't seem to fix the problem. I've written a basic java program in Eclipse Juno, as follows:After clicking Run, I get: \"Error: Could not find or load main class HelloWorld\". This error message applies to all my other projects in the same workspace. I've tried switching workspaces but the error still appears.I'm on Windows 7 64-bit. Any help would be appreciated!I just ran into that problem. The cause... not sure. However, only happened after I added a new jvm.\nMy solution: In the Classpath tab:I hope it helps someone out there. It took me time to figure this out.This just happened to me today after updating my JRE. I cleaned the project and it started working again. will remove any existing class files and completely rebuild the project. There's more information on Eclipse's clean function .I deleted a jar file from the bin directory.  Right click on your project - Properties then Libraries tab.  There was a red flag in there.  I removed the jar file from the Libraries and it worked.It seems that the class is not compiled by Eclipse.Few pointers could be-Same Problem occur with me.I went to project > properties > javaBuildPath.There In order of export , I moved up my java/main to the top preoritythat's because you guys created the class one time with the main method & after that may be you have been deleted that form or workplace & still some of the files exist ,i will suggest you to create that form or workspace again & then delete it by clicking on it completely,then after that if you created the some class like Runner class try to run it again.This happened to me. I noticed that someone said I have to create an entire new WORKSHOP! Why? Because I installed a newer JRE version and that won't allow other previous versions to run on it. So all those old files I have become useless in a way. Not really, Just copy and paste it to new class and change it to an unused class name.if your package name is same with your class name this problem will occur.
Java

I use RegexBuddy while working with regular expressions. From its library I copied the regular expression to match URLs. I tested successfully within RegexBuddy. However, when I copied it as Java  flavor and pasted it into Java code, it does not work. The following class prints : Does anyone know what I am doing wrong?Try the following regex string instead. Your test was probably done in a case-sensitive manner. I have added the lowercase alphas as well as a proper string beginning placeholder.This works too:Note:The best way to do it now is:EDIT: Code of  from  :I'll try a standard \"Why are you doing it this way?\" answer...  Do you know about ?The above will throw a  if it can't parse the URL.The problem with all suggested approaches: all RegEx is All RegEx -based code is over-engineered: it will find only valid URLs! As a sample, it will ignore anything starting with \"http://\" and having non-ASCII characters inside.Even more: I have encountered 1-2-seconds processing times (single-threaded, dedicated) with Java RegEx package (filtering Email addresses from text) for very small and simple sentences, nothing specific; possibly bug in Java 6 RegEx...Simplest/Fastest solution would be to use StringTokenizer to split text into tokens, to remove tokens starting with \"http://\" etc., and to concatenate tokens into text again.If you want to filter Emails from text (because later on you will do NLP staff etc) - just remove all tokens containing \"@\" inside.This is simple text where RegEx of Java 6 fails. Try it in divverent variants of Java. It takes about 1000 milliseconds per RegEx call, in a long running single threaded test application:Do not rely on regular expressions if you only need to filter words with \"@\", \"http://\", \"ftp://\", \"mailto:\"; it is huge engineering overhead. If you really want to use RegEx with Java, try This works too:Note: So probably the first one is more useful for general use. In line with billjamesdev answer, here is another approach to validate an URL without using a RegEx:From  lib, look at class . Some example code:Construct a UrlValidator with valid schemes of \"http\", and \"https\".If instead the default constructor is used.prints out \"url is valid\"When using regular expressions from RegexBuddy's library, make sure to use the same matching modes in your own code as the regex from the library.  If you generate a source code snippet on the Use tab, RegexBuddy will automatically set the correct matching options in the source code snippet.  If you copy/paste the regex, you have to do that yourself.In this case, as others pointed out, you missed the case insensitivity option.
Java

I've developed a simple demo application with a splash screen a map and some regular screens.I have an action bar at the top that contains a logo. It all looks fine on my phone (Galaxy s1 I9000 V2.3) but when i test it on Galaxy s2 v4 the action bar appears also in the splash screen and in the map screen.The spalsh and map activity are not even inheriting from ActionBarActivity so how is that possible and how can i make it go away?Manifest:MapActivity definition (it's a long one so i included just the definition):Splash Activity:Apply the following in your Theme for the Activity in :That should do the trick.As you are asking about how to hide in a certain activity ; I  think .hide(); is what you need or 1.Go to your  file.2. the  for which you want to hide your ActionBar and then  ,The  usually exists along  so from the  you can hide itand from the  you can do it    If you want to get full screen without actionBar and Title.Add it in style.xmland use the style at activity of manifest.xml.If you were using Theme.AppCompat.Light, a better equivalent would be Theme.AppCompat.Light.NoActionBar.I found that using Theme.AppCompat.NoTitleBar caused my button text to be invisible so I am using Theme.AppCompat.Light.NoActionBar.You can use Low Profile mode\nJust search for  that also dims the navigation buttons if they are present of screen.The above answers would help with the ActionBar thing. To add to it, use the following code in case you are using the Splash Screen:\nUse this before you set the content view:Just to clarify, here's how you do it:This would make your screen a full screen, i.e remove the top bar where you see the network bar, etc
Java

Since I implented app compat my searchview doesn't work anymore:So nullpointer for searchview while I have it:And in my menu I have this:I have no idea why it doesn't work anymore but it happened since I started using app compat 21.Regards,Try using the custom  namespace for your  too:This could also happen if you have proguard enabled and it is striping aways  class. You would need to modify proguard settings to keep the class.See  question for more details.after a while of playing \"run & error\" I found a solution.. Looks like the UI-element isn't the reason what causes the error. After setting the search to the QueryListener it is working well. Here is some code: which contains the SearchBar:And the \"SearchBar\" in And last, but not least, the  (but this should be clear)... more information -> Add the following line to  file located inside  folder:It\u00b4s an additional information to Simas answer. I found this in another answer () and it was very important for solving my exception:After you've clicked on a result, your app is expecting that an operation has not completed and is trying to go further into an Intent argument. and return  which notifies your app that the click operation has completed.
Java

I've been trying to convert a value of seconds (in a BigDecimal variable) to a string in an editText like \"1 hour 22 minutes 33 seconds\" or something of the kind. I've tried this:(I have a roundThreeCalc which is the value in seconds so I try to convert it here.)Then I set the editText to sequnceCaptureTime String.\nBut that didn't work. It force closed the app every time. I am totally out of my depth here, any help is greatly appreciated. Happy coding! You should have more luck withThis will drop the decimal values after each division.Edit: If that didn't work, try this.  (I just wrote and tested it)Is it necessary to use a BigDecimal? If you don't have to, I'd use an int or long for seconds, and it would simplify things a little bit:You might want to pad each to make sure they're two digit values(or whatever) in the string, though., formats an elapsed time in the form \"\" or \"\" . It returns the String you are looking for. You can find the documentation Here is the working code:Here's my function to address the problem:I use this:know this is pretty old but in java 8:LocalTime.MIN.plusSeconds(120).format(DateTimeFormatter.ISO_LOCAL_TIME)I prefer java's built in  libraryIf you want the units ,  and  for a duration you can use this:That's a lot of conditional operators. The method will return those strings:This is my simple solution:
Java

Is Python slower than Java/C#?Here is a project that optimizes CPython:  Don't conflate Language and Run-Time.Python (the language) has many run-time implementations.Note that Python (the language) is not slow.  Some Python run-times (CPython, for example) will be slower than native-code C++.It is not really correct to ask why Python is slower than Java/C#. How fast is Java? Well, naive interpreters are around ten times slower than optimised compilers. I believe there is a Java bytcode interpreter written in JavaScript - that probably isn't very fast. So, the intended question appears to be \"Why is the CPython language system slower than the equivalent Sun, IBM and Oracle JRE and Microsoft .NET runtime?\"I believe the correct answer is non-technical. The fastest Java and .NET runtime are faster because they have large full time technical teams developing them in performance-competitive environment.Dynamic language systems are easy to implement. Any idiot can do it. I have. Static language systems are more complex to design and implement. A simple static system will tend to run much faster than the equivalent just-working dynamic equivalent. However, it is possible for highly optimised dynamic systems to run almost as fast. I understand some Smalltalk implementation were quite good. An often quoted example of a developed dynamic system is the .In addition if the real grunt is being done by library code, then the language system may not matter. Alternatively, the language may encourage (or give time(!)) to develop more efficient algorithms which can easily wipe out constant factor performance differences.As mentioned in the other answers this depends on the run-time system as well as the task at hand. So the standard (C)Python is not necessarily slower than Java or C#. Some of its modules are implemented in C. Thus combining speed of a  implementation with Python's language.We did a small experiment: We compared the execution time of a Factorial computation in different languages. The test was actually intended to evaluate the performance of arbitrary-precision integers implementations.The bar chart shows the results. Python is the clear winner. As far as I know Python uses the  to multiply large integers, which explains the speed.Besides, Python's \"arbitrary-precision integers\"-type is the built-in . Hence you don't even need special type handling which is required for Java's BigInteger-class.As suggested in comments, you should really provide a test case to reason about. Reasons behind performance differences will change depending on the test being executed.However, I'd suggest that the static vs dynamic nature may well have a lot to do with it. For non-virtual calls, the JIT-compiled C#/Java is extremely cheap as it can be determined accurately at JIT-time. Even virtual calls just involve a single level of redirection. When binding becomes dynamic, there's a wider range of things to consider.I don't know enough details about Python to claim to understand its exact runtime behaviour, which I suspect may vary with version and implementation too. There is such a thing as \"python byte code\" which is then executed by a virtual machine - whether this virtual machine actually performs JIT-compilation or not is another matter.It boils down to the fact that the compilation phase has lesser information to work with and hence the runtime needs to do more work in case of duck typed (dynamically typed) languages. Thus if I am making the method invocation foo.bar(), in case of Java or C++ the invocation to bar can be optimized in the compilation process by discovering the type of \"foo\" and then directly invoking the method at the memory location where the compiler knows it will be found. Since a python or any other dynamically typed language compiler does not know what type the object foo belongs to, it has to do a type check at runtime and then look up the address of the bar method and then invoke it. There are other difficulties a python compiler writer struggles with as well, though the one above hopefully adequately gives an indication. So even with the best compiler writers, statically typed languages are likely to perform much better at runtime.Where dynamically typed languages score are typically in the development time. Due to fewer lines of code to write and maintain, and no compile wait times for developers, the development often goes through much faster.Simply - . No matter what interpreter (currently available) you use, it is slower than Java and C. In various benchmarks, its slower than Ruby and PHP.\nDo not depend on other's answers, check and verify yourself. Personally I do not think, there is much serious contribution and development done on getting python faster. Since the productivity is good in python and it solves some of problem straight forward, speed/performance is not taken seriously. There are some architecture issues too preventing Python getting performance tweaks. - This answer probably will hurt Python lovers. I too am Python developer, loves developing webapps in Django/Flask/Pyramid rather than Spring (Java). But I see practically in my work and experience, how Python is slower. The speed is not always my priority. But I do stand with them, who says Python Interpreter should get oiling and greasing or total engine change to at least stand in marathon. It's a mainstream programming language.What you got there is clear example of writing Java in Python:A bit more pythonic:I think it's ultimately that Python doesn't go as far as it can with optimizations.  Most of the optimization techniques that are common are for static languages.  There  optimization techniques for dynamic languages, but the modern ones don't seem to make as much use of them as they could.  Steve Yegge has an excellent .:  I just wanted to point out that I'm not necessarily stating this to be critical of Python.  I prefer simplicity over unnecessary speed any day. It doesn't have anything to do with the languages themselves, it's just the fact that java  and  (JVM) are very high quality, and that lots of resources have been invested in stability, scalability and performance improvements over the years.Contrast that to the fact that CPython implementation just recently implemented eg threaded dispatch in its interpreter which gave it performance boost of up to 20% for certain problems. It's not a good thing as it sounds, it is bad because that kind of basic optimization should be there from the day one.This type of question can't be answered just by qualitative reasoning, you need good benchmarks to back it up.  Here's one set that compare  and find Python to be 3 to 300 times slower.  The Python vs. Java results are similar.  (The usual cautions about interpreting benchmarks apply.)These benchmarks also report the source code size, and Python was significantly more concise than Java and C#.I think opposite. I can do simple program in Python faster than in Java,\nand those Python scripts work really fast.Of course your question without examples is hard to answer. Maybe you have found slow library, bug etc. Give us more details please.I would argue that the ease and simplicity of writing Python code makes it possible to write more complex code; for example, code that takes advantage of multi-core processors.  Since per-core performance has been mostly stagnant for the past 5-10 years, I don't think it's clear that Python programs (whether they're running on CPython or something else) are slower in the long run.Since it's interpreted and not compiled.. it should be slower in execution time. As a table mentioned in  book, page 600, C# equals C++ in  (1:1). And Python is slower above hundred times than C++ in  (>100:1).And Java is slower than C++ by one time and a half (1.5:1). These statistics are on average. I don't know who made this study, but seems interesting.   
Java

my  do not call ,  even  constructor, therefore, does not appear anything in .\nI put logs for debugging, and no log is shown.\nWhat can be?\nMy adapter:My custom row XML:and my Fragment:Your  method . So  never tries to instantiate a view. Make it return something .Another one is make sure you set layout manager to RecyclerView:FWIW, I observed it when I set the recycler view adapter  the adapter was actually initialized. Solution was to make sure  was called with a non-null adapter This happened when my  was inside a  and I was using Android Support Library 23.0. To fix, I updated to Android Support Library 23.2:In build.gradle:This does not apply for your particular case. But this might help someone else.This reason could be careless usage of the following methodIf not used with caution, this might cause the  and  to not be called at all, with no error in the logs.Setting the height of the  in the  or . If height is , the  will not be visible.Please set layout manager to RecyclerView like below code:RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view_right);\nNavigationAdapter adapter = new NavigationAdapter(this, FragmentDrawer.getData());\nrecyclerView.setAdapter(adapter);\nrecyclerView.setLayoutManager(new LinearLayoutManager(this));In my case I set the ID of my RecyclerView to \"recyclerView\". It seems that this ID was already defined somewhere, because when I changed that to different ID, the methods from the adapter were called properly.Other option is if you send this list objetc using get,verify if you have correct reference,for exampleIf using a custom adapter do not forget to set the ItemCount to the size of your collection.
Java

I get connection failures that appear randomly when connecting to an HAProxy server using SSL. I have confirmed that these failures happen on JDK versions 1.7.0_21 and 1.7.0_25 but not with 1.7.0_04 or with 1.6.0_38.The exception is These failures only happen when using the TLS SSL context and not with the default context. The following code is run in a loop a thousand times and failures happen before the loop completes (about 2% of the connections fail):If, however, I create the SSL context this way I have no connections failures on any of the Java versions I mentioned:The first way uses  and the later uses . Looking at the code, I don't see any differences that would cause the exception to occur.Why would I be getting the failures and what are the advantages/disadvantages of using the  call?Note: The exceptions were first seen using the Apache HttpClient (version 4). This code is the smallest subset that reproduces the problem seen with HttpClient.Another piece of information is that the errors do not occur if I turn off Diffie-Hellman on the proxy server.Judging by the symptoms, I'm  this is related to browsers using , which is a client-side trick Google introduced to :From the : (emphasis mine)javax.net.ssl.SSLPeerUnverifiedException arise only because of http security you have to configure your connection as https else follow this code..use this. i hope it will help you
Java

I wonder if anyone could tell me how casting works? I understand  I should do it, but not really how it works. On primitive data types I understand partially but when it comes to casting objects I don't understand how it works.How can a object with the type Object just suddenly be cast to, let's say,  (just an example) and then get all the methods?Casting in Java isn't magic, it's you telling the compiler that an Object of type A is actually of more specific type B, and thus gaining access to all the methods on B that you wouldn't have had otherwise. You're not performing any kind of magic or conversion when performing casting, you're essentially telling the compiler \"trust me, I know what I'm doing and I can guarantee you that this Object at this line is actually an <Insert cast type here>.\" For example:The above is fine, not magic and all well. The object being stored in o is actually a string, and therefore we can cast to a string without any problems.There's two ways this could go wrong. Firstly, if you're casting between two types in completely different inheritance hierarchies then the compiler will know you're being silly and stop you:Secondly, if they're in the same hierarchy but still an invalid cast then a  will be thrown at runtime:This essentially means that you've violated the compiler's trust. You've told it you can guarantee the object is of a particular type, and it's not.Why do you need casting? Well, to start with you only need it when going from a more general type to a more specific type. For instance,  inherits from , so if you want to store an  as a  then that's ok (since all Integers are Numbers.) However, if you want to go the other way round you need a cast - not all Numbers are Integers (as well as Integer we have , , , , etc.) And even if there's just one subclass in your project or the JDK, someone could easily create another and distribute that, so you've no guarantee even if you think it's a single, obvious choice!Regarding use for casting, you still see the need for it in some libraries. Pre Java-5 it was used heavily in collections and various other classes, since all collections worked on adding objects and then casting the result that you got back out the collection. However, with the advent of generics much of the use for casting has gone away - it has been replaced by generics which provide a much safer alternative, without the potential for ClassCastExceptions (in fact if you use generics cleanly and it compiles with no warnings, you have a guarantee that you'll never get a ClassCastException.)Actually, casting doesn't always work. If the object is not an  the class you're casting it to you will get a  at runtime.Casting a reference will only work if it's an  that type. You can't cast random references. Also, you need to read more on e.g.Suppose you wanted to cast a String to a File (yes it does not make any sense), you cannot cast it directly because the File class is not a child and not a parent of the String class (and the compiler complains). But you could cast your String to Object, because a String is an Object (Object is parent). Then you could cast this object to a File, because a File is an Object. So all you operations are 'legal' from a typing point of view at compile time, but it does not mean that it will work at runtime !The compiler will allow this even if it does not make sense, but it will crash at runtime with this exception:
Java

This is pretty simple, I come from a swing/awt background.I'm just wondering what the proper way to set the background color for a SWT widget is?I've been trying:Except I have no idea how to create the color Object in SWT?To create a color, try this:For standard colors (including common colors and default colors used by the operating system) Use , and pass in the  constant for the color you want.Note that you do not need to dispose these colors because SWT created them.Remember that in SWT you must explicitly dispose any resources that you create when you are done with them.  This includes widgets, fonts, colors, images, displays, printers, and GCs.  If you do not dispose these resources, eventually your application will reach the resource limit of your operating system and the application will cease to run.See also: 
Java

In WebDriver, if I use sendKeys it will append my string to the value that already exists in the field.  I can't clear it by using clear() method because the second I do that, the webpage will throw an error saying that it has to be between 10 and 100.  So I can't clear it or an error will be thrown before I can put in the new value using sendKeys, and if I sendKeys it just appends it to the value already there.Is there anything in WebDriver that lets you overwrite the value in the field?I think you can try to firstly select all the text in the field and then send the new sequence:You can also clear the field before sending it keys.Okay, it is a view days ago...\nIn my current case, the answer from ZloiAdun does not work for me, but brings me very close to my solution...Instead of:the following code makes me happy:So I hope that helps somebody!This worked for me.In case it helps anyone, the C# equivalent of ZloiAdun's answer is:Use this one, it is trusted solution and works well for all browsers:If input has type=\"file\" - do not clear it for IE. It will try to find file by empty path and will throw a bug.More details you could find This solved my problem when I had to deal with HTML page with embedded JavaScript Had issues using most of the mentioned methods since textfield had not accepted keyboard input, and the mouse solution seem not complete.This worked for to simulate a click in the field, selecting the content and replacing it with new.
Java

I was asked the following question in my interview yesterday:Consider a Java or C++ array say  which is sorted and no two elements in it are same. How best can you find an index say  such that element at that index is also . That is .As clarification she also gave me an example:The best I could think was a linear search. After the interview I though a lot on this problem but could not find any better solution. My argument is: the element with the required property can be anywhere in the array. So it could also be at the very end of the array so we need to check every element.I just wanted to confirm from the community here that I'm right. Please tell me I'm right :)ThanksThis can be done in  time and  space by using a slightly modified .Consider a new array  such that Since the elements in  are in  order, the elements in the\nnew array  will be in  order. So a  for  in  will give the answer.But creating  will take  space and  time. So instead of\ncreating the new array you just modify the binary search such that a\nreference to  is replaced by .Algorithm:\nThere are some faster solutions, averaging O(log n) or in some cases O(log log n) instead of O(n). Have a google for  and , you're likely to find very good explanations.If the array is unsorted, then yes, the element is anywhere and you can't get under O(n), but that's not the case with sorted arrays.--Some explanation on interpolation search as requested:While the binary search only concerns with comparing two elements in terms of \"greater / not greater\", the interpolation search tries to also make use of . The point is: You have a sorted range of values from 0 to, say, 20000. You look for 300 - binary search would start at the half of range, at 10000. The interpolation search guesses that 300 would probably be somewhere closer to 0 than 20000, so it would check the element 6000 first instead of 10000. Then again - if it's too high, recurse into lower subrange, and it's too low - recurse into upper subrange.For a big array with +- uniform distribution of values, interpolation search should behave much faster than binary search - code it and see for yourself. Note that it's the thing a human does intuitively when looking up something in a dictionary.I think this would be faster.Start in the middle of the listIf X[i] > i then go to the middle of the remaining left sideif X[i] < i then go the middle of the remaining right Keep doing that and it will reduce the number of possible elements by half for each loopIts not require to think in terms of any array  as suggested in  by @codaddict.Use binary search and check the middle element of given array, if it is lower than its index, than we do not need to check for any lower index because the array is\nsorted and so if we move to the left, subtracting m indexes and (at least) m value, all subsequent elements will also be too small. E.g. if  then  and  and so on. Similar logic can be apply if middle element is greater than its index.Here is simple  implementation:Note that the above solution would work only if all elements are distinct.You can perform a binary search:\nsearch the middle, if the value is lower than the index, than no lower index will contain the same value.Then you search the higher half, and continue till you find the element, or reach one element span.Your linear search idea looks to be correct, yes. I personally can't think of another way to find the value, unless you sorted in such a way that the value you want is always in the first element.EDIT: Ok I'm wrong. Apologies!This is a solution I came up with, and it works if there are duplicates (I mistakenly overlooked that caveat of there being no duplicates).I would guess this takes O(log n) time, but this isn't clear in first glance???If you're unlucky, it'll take O(n log n) time (the height of the stack tree will be log n, and it will be a full tree, with n nodes in the last level, n/2 in next to last, etc.). So, on average it will be between O(log n) and O(n log n). Yes, I believe you are right. No logarathmic search would be possible, as there is no way to halven the data we have. We will need to look at all the index in the array.@Kos, I don't see how sorting the array would make any difference?of the top of my head, doing binary splitting might be faster.look at the middle value, if it is high then what you need, re-search in the lower half.After one comparison, you have already spilt your data set in halfAfter reading the question it seems like there is one scenario that can be used to speed up the lookup.  When comparing the position to the value, if the value is greater then the position then the value can be used as the next position to evaluate.  This will help jump through the array faster.  This can be done because the array is sorted.  The values that we are skipping are conceptually shifted to the left in the array and are in the wrong location.Example:If my current position is 2 and it has a value of 4 they are not equal and conceptually the value 4 is shifted to the left.  I can use the value of 4 as my next position because if the value 4 is out of position then everything less then 4 is out of position as well.  Some example code just for the sake of discussion:Modified version of Binary Search would suffice I guessSuppose the sequence is orFrom both the examples we see that the required result will never lie on the right side if mid < a[mid]... pseudocode would look something like thisJava:C++:
Java

I'm trying to format a date in Java in different ways based on the given locale. For instance I want English users to see \"Nov 1, 2009\" (formatted by \"MMM d, yyyy\") and Norwegian users to see \"1. nov. 2009\" (\"d. MMM. yyyy\").The month part works OK if I add the locale to the SimpleDateFormat constructor, but what about the rest?I was hoping I could add format strings paired with locales to SimpleDateFormat, but I can't find any way to do this. Is it possible or do I need to let my code check the locale and add the corresponding format string?Use  instead of creating your own patterns with .Use the :  Check  Run the following example to see the differences:Localization of date string:Based on redsonic's post:will be like 05-\u4e5d\u6708-2013The troublesome classes of  and  are now legacy, supplanted by the java.time classes.The  class represents a date-only value without time-of-day and without time zone.A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in  is a new day while still \u201cyesterday\u201d in .Use  to generate strings representing only the date-portion or the time-portion.The  class can automatically .To localize, specify:Example:Going the other direction, you can parse a localized string.Note that the locale and time zone are completely orthogonal issues. You can have a Montr\u00e9al moment presented in Japanese language or an Auckland New Zealand moment presented in Hindi language. Another example: Change  (Spanish) to  (standard  format). The java.time classes use ISO 8601 formats by default for parsing/generating strings.The  framework is built into Java 8 and later. These classes supplant the troublesome old  date-time classes such as , , & .The  project, now in , advises migration to java.time.To learn more, see the . And search Stack Overflow for many examples and explanations. Specification is .Where to obtain the java.time classes? The  project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as , , , and .
Java

What is the best way to exit/terminate a while loop in Java?For example, my code is currently as follows:Use :However, if your code looks  like you have specified you can use a normal  loop and change the condition to :Finding a  construct with  in my code would make my eyes bleed. Use a standard  loop instead: And take a look at the link Yacoby provided in his , and this one too. Seriously. Take a look at the  by Oracle.But basically, as , use .If you can it is often clearer to avoid using break and put the check as a condition of the while loop, or using something like a do while loop. This isn't always possible though. is what you're looking for:alternatively, restructure your loop:or:You can do multiple condition logical tests within the while() check using the same rules as within any logical check.works, as doesare valid. The conditionals are checked on each iteration through the loop. As soon as one doesn't match, the while() loop is exited. You can also use break;You can use \"break\", already mentioned in the answers above. If you need to return some values. You can use \"return\" like the code below:                                                        in this case, this while is in under a method which is returning some kind of values. if you write . its means that loop will not stop in any situation for stop this loop you have to use break statement between while block.
Java

I have Spring/Java App that is compiled with .I have a new Linux setup where I downloaded .I downloaded .I set the path in bash as follows:Java -version reports:And set in setnenv.sh (for Tomcat):When I deploy my WAR file I get below error.\nI think Tomcat doesn't seem to use the Java I installed.\nI have followed the setup instructions.\nPS: I also tried JRE instead of JDK and same issue.The class that's throwing the exception is using this code to check for Java version:So, when Spring 2.5 was first released, the code didn't assume it will be run in a Java version that's later than 1.7. For Java 8 and beyond, the code above will assume default 1.4 version. Because of this, the annotations part will complain.I think you either need to upgrade your Spring version or use Java 7.  for quite some time now, anyway.TO =>ORI have the similar problem. Old Spring MVC/Spring Faces application  under spring 2.5.5 doesn't run on Java 8.I spent few days trying to find solution because we need to run Java 8.  First idea was:  to upgrade complete Spring package up to 4.1.6. I used Maven. Problem of this method that after that it is  necessary to rework nearly the whole project.  It is  because for example in Spring 4 were removed JSF implementation and some special taglibs where completely removed, like . And were some more major and minor problems with configuration, adapters, handlers, mappings.... Second approach was to replace Spring JARs partially.One by one. Again no success. Impossible to replace any jar without touching dependencies.I believe that after few weeks or monthes of struggling I can get success on both approaches. But have no so much time. And I gave up.\nMy solution is:I found source file JdkVersion.java from org.springframework.core package. .\nI created org.springframework.core package in my project with only one class JdkVersion. After that made simple change of the code to check Java 8 version. Smth like that: ...Even this code change is not really necessary, only just for fun.It is because this source came from Spring 3.0.0 package where Spring guys already changed the Java version check. Versions higher than 7 are not considered as old java. Now application starts properly. It call JdkVersion class from my project instead of jar.Works so far! Thanks for all from this thread who gave this idea.ThanksI need to support Spring 2.5.5 on Java 8, so I used the approach from  to provide a future-proof drop-in replacement for  with as few side-effects as possible (nobody else posted a complete class, and I didn't want to hijack the other answer). There is no need to check for Java 8, simply default to Java 7, which is the highest version the class cared about:Extract the jar file:Check the Spring version in  (you should see something like ). Look up the  of  and use that as a starting point (the example below is for Spring 2.5.5 and you don't want to change any method signatures from the version you're working with).Check the major and minor version of the  file:We see that the class was original compiled as target  (, we find that is Java 1.4):Create  with the following content:Then compile the new class as Java 1.4:You can check the major.minor version again as above if needed.Create the modified jar file (without overwriting the original manifest):Copy the modified jar file where needed (as  or as appropriate).I happen to be another unfortunate user of a very old project (developed in 2008!) which is still using Spring 2.5. And it is not a Maven project either, so upgrading to later versions of Spring was taking a long time with dependencies failing and giving build errors. I downgraded tomcat JRE to 1.7 and it worked fine. Just documenting how to do that in eclipse in case someone needs help:Migrate your spring version from 2.5 to >=3.2.3.For Spring migration you need to do following changes - 1) In your pom.xml remove dependency for spring 2.5.6 and add dependency for spring new version.2) Update 'xsi:schemaLocation' in beans tag of applicationcontet.xml file of your project.e.g update  to \n for spring 3.2.3 version.3) Clean,build and re-deploy your project.i had the same problem, but i have a solution:in your project file pom.xml replace:for:and say good bye to your problems!!This two dependecies are the replacement for the firts dependency in the most part.I was facing the same issue. But, after trying very hard, I found out that this is because of using Java 1.8. I changed it to 1.6 and it worked.I created a fully automatic version of the answer by valismortis.\nPlease read his post first for the subtleties he addresses.build file contents:
Java

I have some junit tests which create some resources which should also be closed.One way to implement this logic is using the  and  approach.What I did was to encapsulate the creation in some utility class to be reused. For example:The whole point is for the object to close itself, rather than needing to remember to close it in .The usage should be:The problem is that junit's assert keyword throws an  - not .* Couldn't find the answer in the .It does not  anything. But it does  close all resources. blocks .The pseudo-code of a basic  statement is (cf ):As you can see it catches  not  which includes  but  in order to add as suppressed exceptions any exceptions that occurred while closing the resources.You can also notice that your resources are closed in the  block which means that  (except in case of a  of course as it terminates the currently running Java Virtual Machine) even in case an  or any sub class of  is thrown.Try-with-resources don't catch anything in and of themselves.However, you can attach a  block to the end of the try-with-resources block, to catch whatever types of  you like:The idea behind  is to make sure that the resources should be closed.The problem with conventional  statements is that let's suppose your  block throws an exception; now usually you'll handle that exception in  block. Now suppose an exception occurs in finally block as well. In such a case, the exception thrown by try catch is  and the exception generated in  block gets propagated.In  the  method of the resource will get automatically called, and if the  throws any exception, the rest of the  isn't reached, and the original exception is lost.Contrast that with this:in the above code snippet, the  method automatically gets called and if that  method also generated any exception, than that exception will automatically get suppressed.See also: Misconception on your end: try-with-resources does  do a .It does a  , therefore the kind of \"problem\" doesn't matter.See the  for further information!
Java

I'd like to know some cases in Java (or more generally:\nin programming) when it is preferred in boolean expressions to use the unconditional  () instead of the conditional version ().I know how they work, but I cannot think about a case when use the single  is worth it.I have found cases in real life where both sides of the expression were really cheap, so it shaved off a nanosecond or two to avoid the branch and to use the unconditional  instead of .  (These were extremely high-performance math utilities, though; I would almost never use this in other code, and I wouldn't have done it anyway without exhaustive benchmarking to prove it was better.)(To give specific examples,  is going to be super cheap and side-effect-free.  Why bother risking a branch misprediction to avoid a test that's going to be so cheap anyway?  Sure, since it's a  the end result is going to be used in a branch anyway, but  involves two branches, and  involves only one.)The only difference is that  and  stop the evaluation as soon as it is known. So for example:works well with , but with  you could get a NullPointerException if a is null.The only case I can think about where you want to use  is if the second operand has a side effect, for example (probably not the best example but you get the point):However, this looks like smelly code to me (in both cases).The && allows the jvm to do short circuit evaluation. That is, if the first argument is false, then it doesn't need to bother checking the second argument.A single & will run both sides regardless.So, as a contrived example, you might have:In that example, you might always want to log the fact that the owner of the account attempted to do something.I don't think I have ever used a single & in commercial programming though.Wikipedia has nicely described the  From the same link:If there are side effects that must happen, but that's a little ugly. The bitwise AND () is mostly useful for just that - bitwise math.Input validation is one possible case.  You typically want to report all the errors in a form to the user in a single pass instead of stopping after the first one and forcing them to click submit repeatedly and only get a single error each time:Granted, you could trivially avoid the need for short circuit evaluation in  by refactoring the  logic outside of ; but then you'd need to call the extracted code every time validateField() was called; at a minimum adding 10 extra lines for method calls.  As always it's a case of which tradeoff's work best for you.If the expression are trivial, you may get a micro-optimisation by using  or  in that you are preventing a branch. ie.is the same aswhich has two places a branch can occur.    However using an unconditional  or , there can be only one branch.Whetehr this helps or not is highly dependant on what the code is doing.If you use this, I sugegst commenting it to make it very clear why it has been done.There isn't any specific use of single & but you can consider the following situation.Consider that  is doing some operation which will modify instance variables or do something which will impact behavior later in processing.So in this case if you use  operator and the first condition fails it will never go in . In this case single  operator will suffice.Because  is a bit-wise operator, you can do up to 32-checks in a single operation concurrently. This can become a significant speed gain for this very specific use cases. If you need to check a large number of conditions, and do it often and the cost of boxing/unboxing the conditions are amortized by the number of checks, or if you store your data on-disk and on-RAM in that format (it is more space efficient to store 32 conditions in a single bitmask), the  operator can give a huge speed benefit over a series of 32 individual . For example if you want to select all units that can move, is an infantry, has weapon upgrade, and is controlled by player 3, you can do:See  on a related question for more on the topic.The only benefit I can think of is when you need to invoke a method or execute a code, no matter the first expression is evaluated to  or :Although you can do this without :Short-circuiting can lead to errors in branch prediction on modern processors, and dramatically reduce performance (a notable example is highly optimized ray with axis aligned box intersection code in ray tracing)[clarification needed]. 
Java

Is there any simple java web framework like sinatra (for ruby) or web.py (for python)?If you want a strict Java framework  might be an alternative:  . Haven't tried it myself but heard only good things about it and seems to be quite beginner-friendly.I think the simplest thing to do to generate web content via Java is to write a Servlet.  Just like web.py allows you to define a  method, you can implement a Servlet's  method and write data directly back to the client.Here is a  to the Servlets tutorial.  You will also need to know how to package and deploy a web application; for that I usually point people to the  (see the section titled \"First Web Application\").Writing and deploying a Java web application is not going to be as fast as in Ruby or Python, but Java isn't particularly known for its succinctness.If you don't strictly require Java, check out .  It's a web application framework built on Groovy, which is a dynamic language similar to Python and Ruby that compiles to the JVM. Java EE 6 Servers like  bundles it by default.If you use Tomcat, you can use , , or  implementations.Using JAX-RS annotations the web development feels like Sinatra or Merb. BTW you don't have to use Java as the language, you can use Scala, Groovy, JRuby...If you are only looking for a presentation framework in  Java then, for me,   is the closest of the Java MVC frameworks to the RoR philosophy: simple, elegant, and requiring minimal configuration.  Stripes pioneered the  approach for Java web development. And while some other frameworks have adopted some of its principles (like Spring MVC or Struts2 with plugins), I still prefer Stripes because it does one thing, and does it well.It is possible to use  as is with look at this two as well: 1.  and 2. You might want to have a look at those 2 groovy projects:Really light akin to Sinatra. Might be a bit on the bleeding edge though:-) Interesting and promising never the less.Check  :If you have to develop business or database applications  is a good option. OpenXava allows you to develop a complete AJAX web application writing just domain classes, with no code generation and producing an application ready for production. Little code, great result.The smallest \"usable\" web server for Java that support Servlets that I can find is . And honestly there is no reason to run a Java web server that doesn't support Servlets. If you want to do REST,  has a built in HTTP daemon that means you can run it as a . is really simple. Of course, it builds like an API above Servlet API, but deals with page and component instead of request and response. In other words it is truly MVC. is a framework for Scala inspired by Sinatra.I can recommend  to you, because i like the plugin architecture and with the convention plugin it is simple and fast to develop.
Java

If I'm in an interface and pointing to a method name, what can I do to quickly go to the ONLY implementation of that method ?using eclipse 3.6.xHold control, hover over the method name, and select \"Open Implementation\". I just checked this on my Eclipse 3.6 install. You may assign a keyboard shortcut to this action by using Window->Preferences->General->Keys and searching for \"Open Implementation\".  is the typical \"go to implementation\".  For interfaces that go to the  definition.Instead use  +  to see all implementations of the interface definition.  You can then easily go to the one you want with the arrow keys and Enter.  I believe that the first one is automatically selected so that  +  will do what you need. In the keymap (General > Keys) search for \"open implementation\" and map it to whatever you want.  I chose  +  + .  Make sure you select \"Editing Java Source\" in the When box.  I tested it, and having the cursor over the method name and pressing  +  +  took me directly to the implementation instead of showing the hierarchy that you get with  + .Also you can see an answer to a nearly identical question for other options:
Java

What would be the easiest way to calculate Greatest Common Divisor and Least Common Multiple on a set of numbers? What math functions can be used to find this information?I've used  to find the greatest common divisor of two numbers; it can be iterated to obtain the GCD of a larger set of numbers.Least common multiple is a little trickier, but probably the best approach is , which can be similarly iterated:There is an  for GCD,By the way,  and  should be greater or equal , and  = There are no build in function for it. You can find the GCD of two numbers using .For a set of numberApply it recursively.Same for LCM:If you can use Java 8 (and actually want to) you can use lambda expressions to solve this functionally:I oriented myself on , butThis approach is probably slightly slower due to additional function calls, but that probably won't matter at all for the most use cases.More simpler to understand:- See more at: With Java 8, there are more elegant and functional ways to solve this.LCM:GCD:Of course if one argument is 0, both methods will not work.import java.util.Scanner;\npublic class Lcmhcf {
Java

I'm trying to install a plugin in Eclipse Luna. I installed Papyrus and am trying to install SWT designer, but before the download/installation is completed I get an error:After this error I can't install anything and the install manager does not work anymore and shows me the same error all the time only one way I delete the current Eclipse directory and extract it again.This time I install Papyrus, SWT designer and some other, but I get the error between install another plugin again. This is wrong if I get an error on install any of plugin reinstalling Eclipse and the other plugin again.Is this a bug or a problem?Ok finally i find the solution for solve this problem i don't know why Eclipse showing me this error and i don't know is this a best solution but anyway i solve my problem with delete the  file in Eclipse root directory\nAfter delete this file try to install that plugin again but this time after few second everything done and work perfectly\nIf you get that's error again just go to Eclipse root directory and search for \"artifacts.xml\" and delete all the files is in the result ;)Run Eclipse as an administrator, then try to install the plugin again via help->Install New Software. it worked for meI installed E4 RCP Patch(bugzillas 445122)(Install new software -> Eclipse 4.4.1 Patches for bug 445122) and this helped me.I ran across this problem while updating eclipse's internal software. I discovered that the jar file org.eclipse.epp.mpc.help.ui_1.5.2.v20161004-1655.jar (found in the error details) in the eclipse plugins directory was corrupted (7-Zip was unable to inspect its contents). I redownloaded and manually replaced this file with one downloaded from , and I was then able to install the software without an issue. Hope this helps :)(If it was a different JAR file for you, you can click \"show directory contents\" on  and download the one you need.)Try this from the Eclipse marketplace\n1. Click Help>Eclipse marketPlace (Eclipse marketPlace dialog box will open)\n2. Type the name of your plugin (ex: type SWT Designer) in the find edit box, make sure to keep default values for All markets and all categories, and click go button.\n3. The page will refresh and display all plugins that have swt designer in their name.\n4. Click intsall or update button on the one that fits your needs.\n5. The installation or update will be done successfully.\n6. Restart your eclipse\n7. The installation will be fine.It's a failure in Eclipse.Try to uninstall it then download it from:  and install it.
Java

I have a byte[] and would like to copy it into another byte[].  Maybe I am showing my simple 'C' background here, but is there an equivalent to memcpy() on byte arrays in Java?You might try  or make use of array functions in the  class like . Both should give you native performance under the hood.Arrays.copyOf is probably favourable for readability, but was only introduced in java 1.6.Use Example,\nor use \nExample, was added in JDK 1.6.\n The  method uses  to make a copy of the array, but is more flexible than  since you can make copies of parts of an array.If you just want an exact copy of a one-dimensional array, use .For other array copy operations, use / as .You can use . It copies elements from a source array to a destination array. The Sun implementation uses hand-optimized assembler, so this is fast.Java actually does have something just like memcpy(). The Unsafe class has a copyMemory() method that is essentially identical to memcpy(). Of course, like memcpy(), it provides no protection from memory overlays, data destruction, etc. It is not clear if it is really a memcpy() or a memmove(). It can be used to copy from actual addresses to actual addresses or from references to references. Note that if references are used, you must provide an offset (or the JVM will die ASAP). Unsafe.copyMemory() works (up to 2 GB per second on my old tired PC). Use at your own risk. Note that the Unsafe class does not exist for all JVM implementations.You can use 
Java

How can I create a list out of all of the files in a specific directory in Clojure? Do I have to resort to calling Java or can Clojure handle this natively?Use  function. Usage example: Clojure was designed to embrace the Java platform, and this is one area where Clojure does not provide its own API. This means that you probably have to dive into Java, but the classes you have to work with are perfectly usable directly from Clojure.The one class you should read about in the javadocs is , which represents a .The  instance method returns an array (which you can use as a seq) of  objects \u2013 one for each entry in the directory identified by the  instance. There are other useful methods for determining whether a  exists, is a directory, and so on.The constructor of  can sometimes be a bit inconvenient to use (especially when merging many path segments in one go) and in this case Clojure provides a useful helper function: . As its arguments it accepts path segments as strings or files. The segments are joined with the correct path separator of the platform.Note: Clojure also provides the  function which returns a preorder walk (as a seq) though the file hierarchy starting at the given file.Also check out the . It may not be worth pulling in the extra dependency if you just need a list of files in a directory, but there are many useful utility functions there, for example for:The latter expression is an array of File-objects returned from the method listFiles, called on the file-object created from the path \"/tmp\". This is a fancy way to write:To make the modified code match the functionality of original sample code you should add the call to get the file names, like this.Usually, when we say that we want to list directory, we mean that we want to get file names or paths, so ->Simplest way to list directory:If you want to list it recursive, then:
Java

Optional is used to represent nullable object, Some uses of this class includeFor the first case, do I need to return Optional in all nullable return method?  The question we face is: will JDK 8 Optional objects get rid of null references? And the answer is an emphatic no! So, detractors immediately question its value asking: then what is it good for that we couldn't already do by other means?Unlike functional languages like SML or Haskell which never had the concept of null references, in Java we cannot simply get rid of the null references that have historically existed. This will continue to exist, and they arguably have their proper uses (just to mention an example: ).I doubt that the intention with the Optional class is to replace every single nullable reference, but to help in the creation of more robust APIs in which just by reading the signature of a method we could tell if we can expect an optional value or not  and force the programmer to use this value accordingly. But ultimately, Optional will be just another reference and subject to the same weaknesses of every other reference in the language (e.g. you could return a null Optional). It is quite evident that Optional is not going to save the day.How these optional objects are supposed to be used or whether they are valuable or not in Java has been the matter of a  in the project lambda mailing list. From the detractors we hear interesting arguments like:So, it would appear that the benefits of Optional are really questionable and are probably constrained to improving readability and enforcing public interface contracts. I do believe that the adoption of this Optional functional idiom is likely to make our code safer, less prompt to null dereferencing problems and as a result more robust and less error prone. Of course, it is not a perfect solution because, after all, Optional references can also be erroneously set to null references, but  I would expect that programmers stick to the convention of not passing null references where an optional object is expected, pretty much as we today consider a good practice not to pass a null reference where a collection or an array is expected, in these cases the correct is to pass an empty array or collection. The point here is that now we have a mechanism in the API that we can use to make explicit that for a given reference we may not have a value to assign it and the user is forced, by the API, to verify that.Quoting  about the use of optional objects: So, I guess it's up to every API designer to choose how far they want to go in the use of Optional.Some influential developers like Stephen Colebourne and Brian Goetz have published a few interesting articles more recently on the proper use of optional. I particularly found useful the following:As an observation, I think one of the most important aspects that have to be considered when architecting an application is to decide how to treat the \"null problem\". \nIn this respect, the first step would be to identify possible \"sources\" of nulls. For example, the database or external libraries used in the project. The next step would be to 'contain' the problem, namely, to wrap problematic code(using Optional) and thus block the propagation of null throughout the system, where unsuspecting code might trigger NPEs.\nTo answer your question, it depends...Most of the times I would say that's unnecessary, since it creates a lot of work with no value (for example, I wouldn't use optional for methods that call other private methods inside classes, or for methods that call methods of package-private classes), but code that exists at the thin  of different 'concerns' (or layers) in your application, (the signature of the interfaces/classes that you use to query the datastore, for example, or pojos used for 'transporting' data that might have null properties - DTOs, or, a more general description,  APIs of different modules) should avoid 'leaking' nulls into some other areas with different concerns. Compared with Guava, one annoying problem with  is that it does not provide a method like  which is, on the other hand, defined in  as The lack of this specific feature limits monadic applications of Java 8's Optional.Guava's  can be replicated as in with Java 8 Optional asorIn  (finally!) you'll be able to use :That's neat!
Java

Say I have a   relationship like the following:If I have a parent P and children C...C referencing back to P, is there a clean and pretty way in JPA to automatically remove the children C...C when P is removed (i.e. )? What I'm looking for is a functionality similar to  in SQL.This is essentially the same question as , and from what I can gather from that, the answer is \"no\"?Relationships in JPA are always unidirectional, unless you associate the parent with the child in both directions. Cascading REMOVE operations from the parent to the child will require a relation from the parent to the child (not just the opposite).You'll therefore need to do this:If you are using hibernate as your JPA provider you can use the annotation @OnDelete. This annotation will add to the relation the trigger , which delegates the deletion of the children to the database.Example:With this solution a unidirectional relationship from the child to the parent is enough to automatically remove all children. This solution does not need any listeners etc. Also a query like  will remove the children.Create a bi-directional relationship, like this:@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)Given annotation worked for me.For Example :-
Java

I want to draw circle by canvas. Here is my code:[MyActivity.java]:[View.java]:So i have just black screen without circle.\nWhy it does not work? How to fix it?You can override the onDraw method of your view and draw the circle.For a better reference on drawing custom views check out the official Android documentation.\nif you want to draw circle at centre. You could also translate your entire canvas to center then draw circle at center.using These two link also helpXml example: will produce a circle of 5dpAbove is the code to render a circle. Tweak the parameters to your suiting.Try this The entire code for drawing a circle or download project source code and test it on your android studio.  
Java

Is there any convenient way to read and parse data from incoming request.E.g client initiate post requestI\u2019m not able to get param using . The following codehowever displays the content for me What is the best way to parse incoming request? I don\u2019t want to write my own parser, probably there is a  ready solution. encoded requests are indeed not by default supported by the Servlet API prior to version 3.0. The Servlet API parses the parameters by default using  encoding. When using a different encoding, the  calls will all return . When you're already on Servlet 3.0 (, , etc), then you can use  instead. Also see  for extended examples.Prior to Servlet 3.0, a  standard to parse  requests would be using . Just carefully read its  and  sections to learn how to use it. I've posted an answer with a code example before  (it also contains an example targeting Servlet 3.0).Solutions:Solution A:Solution B:Solution C:Solution D:Use Struts. Struts 1.1 handles this automatically.Reference: Not always there's a servlet before of an upload (I could use a filter for example).\nOr could be that the same controller ( again a filter or also a servelt ) can serve many actions, so I think that rely on that servlet configuration to use the getPart method (only for Servlet API >= 3.0), I don't know, I don't like. In general, I prefer independent solutions, able to live alone, and in this case   is one of that. 
Java

Suppose I have a Java class with multiple constructors:How can I extend it in Scala and still provide access to all three of Base's constructors? In Scala, a subclass can only call one of it's superclass's constructors. How can I work around this rule?Assume the Java class is legacy code that I can't change.It's easy to forget that a trait may extend a class. If you use a trait, you can postpone the decision of which constructor to call, like this:Traits may not themselves have constructor parameters, but you can work around that by using abstract members instead. - Assuming that each of your constructors ultimately create the   of the object, create a companion object with \"static\" methods to create this stateThen create a private constructor taking the state and (public) overloaded constructors which defer to the primary constructorThis is a silly answer that would probably work somewhat but might be too much effort if the Java class has way too many constructors, but:Write a subclass in Java that implements a constructor that takes all the inputs the various other constructors would and calls the proper constructor of its superclass based on the presence or absence of inputs (via usage of \"null\" or some sort of sentinel values), then subclass that Java class in Scala and assign the sentinel values as default parameters.I would pick the most generic one (in this case, String) and do the internal conversion yourself if it meets the other criteria.Although I admit this is not the best solution and something strikes me as wrong about it. :-(
Java

I've been interviewed recently and the interviewer wanted me to do a technical test to see my knowledge. After I finished it he gave me feedback about how I did it, which I didn't expect and I appreciated, since few interviewers do it if they don't want to hire you.One of the things he told me that he saw bad about my code was that I used more than one try-catch block inside each method I wrote. This calls my attention since I see it interesting. I believe at the moment that I should make try-catch blocks where there is a semantically distinguishable block of code which has one or more methods that can throw exceptions needed to be caught. The only exception to this that I followed was that if two methods throw the same exception type, I better put them in different try-catch blocks to clearly distinguish when debugging where and why an exception was thrown. This strongly differs from what the interviewer wanted me to do. So is using just one try-catch block per method a known good practice? If it is a known good practice what are the benefits of doing it?For me, two try-catch blocks makes most methods too long. It obfuscates the intention if the method is doing many things.With two try-catch blocks, it's doing at least four things, to be preciseI would rather make short and clear methods out of each try-catch block- likeRobert C. Martin in 'Clean Code' takes it to next level, suggesting:I would definitely refactor the method with two separate try/catch blocks into smaller methods.I'd say that if you find yourself wrapping two separate blocks of code with  you should consider refactoring those blocks into separate methods. If this is a pattern you used in your interview than perhaps you misunderstood your interviewer.It is perfectly fine to use two  blocks if the algorithm requires it. I have often used a new  in a catch block to ensure a safe cleanup so a blanket statement is not possible.To answer your question, when we talk about modern day JVMs which are actually applying a lot of optimizations in the code, when you write some code which is inefficient then the JVM will automatically introduce optimizations.Please refer the answer in ().So the good practice thing is not of much importance. On a personal note, I believe that one must not encapsulate anything in a , ,  etc blocks un-necessarily.Let us make our code more readable to the ones who will be working on this. If an exception is caught, it is better to explicitly make it prominent that which piece of code is throwing it. No guessing for the reader, that is why JVMs are smart, write as you want , make it better for humans and JVM takes care of the optimization part. I have read plenty of books and I didn't find it any place which says that one big try catch is better than multiple small ones. Moreover, many in the developer community believe the opposite. I try to avoid duplication in catch blocks. If all the exceptions in a method receive the same treatment in the catch block, then go ahead and catch them all together. If you need to do different things with them, then catch them separately.For example, here we can catch all exceptions together, because any kind of exception means the whole method fails:Whereas here, we have different fallback behaviour for each group of calls, so we catch separately:(This code exists purely to illustrate this point about catching exceptions; i beg you to disregard the fact that it is utterly horrible in other ways)As for me, it's clearer to have just one  block wrapping all the 'hazardous' code in a method. Regarding who to blame when two lines throw the same exception, you'll always have the stacktrace. Besides, having more than one  inside a method usually means having more than one  lines (which can also make hard to follow code execution at a sight), as chances are that if something goes wrong in the first , it won't make sense to keep running the rest of the code.Here you can find some 'standard' best practices, just in case you may find them useful.-It's also important to consider the context of the code.  If you're writing code with heavy IO then you may need to know which parts of the code are failing.  I didn't see anywhere yet a point that try...catch is meant to give you a chance to recover from a problem.So if you get an IO exception in reading from one file, you may want to retry reading. Same with writing. But if you had one large try...catch you wouldn't know which to retry.This is another thing that often starts Java-flamewar... ;-)Basically, for the performance matters only throwing exceptions. So using few  blocks shouldn't affect a performance at all.\nIn some opinion writing code that way obfuscates the code and does not even recall \"clean code\", in others opinion it's better to use  only for lines which can actually throw any exception.It's up to you decide (or the team convention).
Java

I'm looking for a way to rename a Hashmap key, but i don't know if it's possible in Java.Try to remove the element and put it again with the new name. Assuming the keys in your map are , it could be achieved that way:Assign the value of the key, which need to be renamed, to an new key. And remove the old key.You don't rename a hashmap key, you have to insert a new entry with the new key and delete the old one.This will do what you want but, you will notice that the location of the key has changed.You cannot rename/modify the hashmap  once added.Only way is to delete/remove the key and insert the new key and value pair. : In hashmap internal implementation the Hashmap key modifier marked as final.For Reference : 
Java

I'm using  to convert a  string to a Java-Object.\nThe value of  is exactly the same as the value of . (Copied from debugger; Backslashs added)The following exception is thrown while converting result1:\nConverting  works fine.The json string is valid according to jsonlint.com.I suspect that result1 has some characters at the end of it that you can't see in the debugger that follow the closing  character. What's the length of  versus ? I'll note that  as you've quoted it has 169 characters.GSON throws that particular error when there's extra characters after the end of the object that aren't whitespace, and it defines whitespace  narrowly (as the JSON spec does) - only , , , and space count as whitespace. .If you can't easily figure out what's causing the extra characters at the end and eliminate them, another option is to tell GSON to parse in lenient mode:From my recent experience,  basically makes the parser very tolerant, even to allow malformed JSON data.But for certain data retrieved from your trusted RESTful API(s), this error might be caused by trailing white spaces. In such cases, simply  the data would avoid the error:Then  should work as expected.In the debugger you don't need to add back slashes, the input field understands the special chars.In java code you need to escape the special chars
Java

In Java, is there any difference between  and ?\nIs there a specific code convention for these?According to ,  returns:So there shouldn't really be a difference except for an additional method invocation.Also, in case of , if the instance is , a  will be thrown, so, arguably, it's less .  2) The signature or syntax of string's valueOf() method is given below:The signature or syntax of string's  method is given below:Yes.  As the  explains,  will be treated as a special case, whereas  will just give you an NPE.No.  Use which ever is most appropriate to the requirements of the context in which you are using it.  (Do you  the formatting to work for ?)Note: that isn't a code convention.  It is just common sense programming.  It is more important that your code is  than it is to follow some stylistic convention or \"best practice\" dogma.Personal opinion:Some developers acquire the (IMO) bad habit of \"defending\" against nulls.  So you see lots of tests for nulls, and treating nulls as special cases.  The idea seems to be prevent NPE from happening.I think this is a bad idea.  In particular, I think it is a bad idea if what you do when you find a  is to try to \"make good\" ... without consideration of why there was a  there.In general, it is better to avoid the  being there in the first place ... unless it has a very specific meaning in your application or API design.  So, rather than avoiding the NPE with lots of defensive coding, it is better to let the NPE happen, and then track down and fix the source of the unexpected  that triggered the NPE.So how does this apply here?Well, if you think about it, using   be a way of \"making good\".  That is to be avoided.  If it is unexpected for  to be  in the context, it is better to use . and  are literally the same thing.If you take a look at the implementation of , you'll see that  is basically just a null-safe invocation of  of the appropriate object:The most important difference is the way they handle null String references.The below shows the implementation for java.lang.String.valueOf as described in the source for jdk8u25. So as per my comment, there's no difference. It calls \"Object.toString\". For primitive types, it wraps it in its object form and calls \"toString\" on it.See below:When argument is , the  returns , but  throws , that's the only difference.I can't say exactly what the difference is but there appears to be a difference when operating at the byte level. In the following encryption scenario Object.toString() produced a value that couldn't be decrypted whereas String.valueOf() worked as intended ...There is one more major difference between the two methods is when the object we are converting is an array.When you convert an array using Object.toString() you will get some kind of garbage value(@ followed by hashcode of array).To get a human-readable toString(), you must use String.valueOf(char[]); plz note that this method works only for Array of type char. I would recommend using Arrays.toString(Object[]) for converting arrays to String.Second difference is when the object is null, ValueOf() returns a String \"null\", while toString() will return null pointer exception.
Java

So my 2009 new years resolution is to learn Java.  I recently acquired \"Java for Dummies\" and have been following along with the demo code in the book by re-writing it using Eclipse.  Anyway, every example in the book that uses a relative path does not seem to read the .txt file it's supposed to read from.Here is the sample code:And you can see in the below screen shot I have included this file.Also, I have verified that when I build the application that a copy of Hankees.txt is placed in the bin folder with the compiled .class files.Lastly, if I change line 12 to the following and place Hankees.txt in the root of my C:\\ drive the program compiles and runs fine.So basically, my question is what am I doing wrong?  Or is Eclipse responsible for this in some way?Thanks for any and all help!You need Your file is in the source folder which is not counted as the working directory.\\Or you can move the file up to the root directory of your project and just use A project's build path defines which resources from your source folders are copied to your output folders. Usually this is set to Include all files.New run configurations default to using the project directory for the working directory, though this can also be changed.This code shows the difference between the working directory, and the location of where the class was loaded from:The output is likely to be something like:This is really similar to another question.\nHow should I load my files into my Java Application?You  want to load your files in by:this is You should use getResourceAsStream.And also you should use ; which is the system-dependent name-separator character, represented as a string for convenience.Yeah, eclipse sees the top directory as the working/root directory, for the purposes of paths....just thought I'd add some extra info. I'm new here! I'd like to help.Paraphrasing from :The classes under  resolve relative pathnames against the current user directory, which is typically the directory in which the virtual machine was started.Eclipse sets the working directory to the top-level project folder.i has the same problem. If YourClass and Hankees.txt have one directory in your Project then, i find following - not so bad.
Java

I have seen different approaches to define a static array in Java.  Either:...or onlyor as a Is there a difference (except for the List definition of course)?What is the better way (performance wise)?If you are creating an array then there is no difference, however, the following is neater:But, if you want to pass an array into a method you have to call it like this:Nope, no difference. It's just .  creates an additional list.
Java

I have to store UTC dateTime in DB.\nI have converted the dateTime given in specific timezone to UTC. for that I followed the below code.\nMy input dateTime is \"20121225 10:00:00 Z\" timezone is \"Asia/Calcutta\" \nMy Server/DB(oracle) is running in the same timezone(IST) \"Asia/Calcutta\" DB (oracle) has stored the same given  not in UTC.I have confirmed from the below sql.My DB server also running on the same timezone \"Asia/Calcutta\"It gives me the below appearances Will  print in local timezone like  does? Not UTC?Although it is not explicitly specified for  drivers have to follow the rules established by the :When you call with  the JDBC driver uses the time zone of the virtual machine to calculate the date and time of the timestamp in that time zone. This date and time is what is stored in the database, and if the database column does not store time zone information, then any information about the zone is lost (which means it is up to the application(s) using the database to use the same time zone consistently or come up with another scheme to discern timezone (ie store in a separate column).For example: Your local time zone is GMT+2. You store \"2012-12-25 10:00:00 UTC\". The actual value stored in the database is \"2012-12-25 12:00:00\". You retrieve it again: you get it back again as \"2012-12-25 10:00:00 UTC\" (but only if you retrieve it using ), but when another application accesses the database in time zone GMT+0, it will retrieve the timestamp as \"2012-12-25 12:00:00 UTC\".If you want to store it in a different timezone, then you need to use the  with a Calendar instance in the required timezone. Just make sure you also use the equivalent getter with the same time zone when retrieving values (if you use a  without timezone information in your database).So, assuming you want to store the actual GMT timezone, you need to use:With JDBC 4.2 a compliant driver should support  (and ) for  (and ) through . The  classes are without time zones, so no conversion needs to be applied (although that might open a new set of problems if your code did assume a specific time zone).I think the correct answer should be java.sql.Timestamp is NOT timezone specific. Timestamp is a composite of java.util.Date and a separate nanoseconds value. There is no timezone information in this class. Thus just as Date this class simply holds the number of milliseconds since January 1, 1970, 00:00:00 GMT + nanos. In PreparedStatement.setTimestamp(int parameterIndex, Timestamp x, Calendar cal)\nCalendar is used by the driver to change the default timezone. But Timestamp still holds milliseconds in GMT. API is unclear about how exactly JDBC driver is supposed to use Calendar. Providers seem to feel free about how to interpret it, e.g. last time I worked with MySQL 5.5 Calendar the driver simply ignored Calendar in both PreparedStatement.setTimestamp and ResultSet.getTimestamp.It is specific from your driver.  You need to supply a parameter in your Java program to tell it the time zone you want to use.Further this:  May also be of value in handling the conversion properly.  Taken from For Mysql, we have a limitation.\nIn the , we have :So, when we do not use this parameters and we call  with calendar or without calendar, we have the timestamp in the jvm timezone.Example :The jvm timezone is GMT+2.\nIn the database, we have a timestamp : The first method returns  : The second method returns : The third method returns  : Instead of Oracle, when we use the same calls, we have :The first method returns  : The second method returns : The third method returns  : \nIt is not necessary to specify the parameters for Oracle.
Java

Is there a way to exclude code from inclusion into Cobertura coverage reports? We have some methods that should not be included in the coverage report and therefore not drive down the coverage numbers.I know that Clover has such a functionality, but I have not found anything similar for Cobertura.You can exclude classes from instrumentation. Then they should not appear on reports. See  statements below.You can also ignore calls to some methods. See  statement below.If you are using maven, see . And for ant see .This has been breaking my head for some time now.My problem was that I had the cobertura maven plugin setup in the reporting section instead of the build section.The instrumentation settings, and hence the excluding of classes or packages, won't be applied if you don't set it up on build section, so watch out for this.Remember to exclude inner classes too.It took me ages to notice I was missing an asterisk!Cobertura doesn't currently provide such a feature, and neither does Emma (which we use) although it is listed as a forthcoming enhancement - although in the form of an extension to the exclusion rules I believe rather than as an annotation.Would be handy to cover off those few inaccessible corners cleanly so that you can strive for 100% without being ridiculous.I think annotations would probably be a friendlier way to do it, but they ought to be fairly explicitly named and based on a list of acceptable scenarios as I fear otherwise something like '@ExcludeFromCoverage' would get added over generously.
Java

What is the difference between compile time and run time dependencies in Java?\nIt is related to class path, but how do they differ?Although compile-time dependency usually implies run-time dependency, you can have a compile-time only dependency. This is based on the fact that Java only links class dependencies on first access to that class, so if you never access a particular class at run-time because a code path is never traversed, Java will ignore both the class and its dependencies.Example of thisIn C.java (generates C.class):In A.java (generates A.class):In this case,  has a compile-time dependency on  through , but it will only have a run-time dependency on C if you pass some parameters when executing , as the JVM will only try to solve 's dependency on  when it gets to execute . This feature allows you to provide at runtime only the dependencies of the classes that you use in your code paths, and ignore the dependencies of the rest of the classes in the artifact.An easy example is to look at an api like the servlet api. To make your servlets compile, you need the servlet-api.jar, but at runtime the servlet container provides a servlet api implementation so you do not need to add servlet-api.jar to your runtime class path.The compiler needs the right classpath in order to compile calls to a library (compile time dependencies)The JVM needs the right classpath in order to load the classes in the library you are calling (runtime dependencies).They may be different in a couple of ways:1) if your class C1 calls library class L1, and L1 calls library class L2, then C1 has a runtime dependency on L1 and L2, but only a compile time dependency on L1.2) if your class C1 dynamically instantiates an interface I1 using Class.forName() or some other mechanism, and the implementing class for interface I1 is class L1, then C1 has a runtime dependency on I1 and L1, but only a compile time dependency on I1.Other \"indirect\" dependencies which are the same for compile-time and run-time:3) your class C1 extends library class L1, and L1 implements interface I1 and extends library class L2: C1 has a compile-time dependency on L1, L2, and I1.4) your class C1 has a method  and a method  where I1 is an interface and L1 is a class that takes a parameter which is interface I1: C1 has a compile-time dependency on I1 and L1. Note that the run-time dependency chain is run-time dependent or fail-slow: if the implementation of L1 sometimes depends on instantiating an object of class L2, and that class only gets instantiated in one particular scenario, then there's no dependency except in that scenario.Java doesn't actually link anything at compile time.  It only verifies the syntax using the matching classes it finds in the CLASSPATH.  It's not until runtime that everything gets put together and executed based on the CLASSPATH at that time.Compiletime dependencies are only the dependencies (other classes) which you use  in the class you're compiling. Runtime dependencies covers both the direct and indirect dependencies of the class you're running. Thus, runtime dependencies includes dependencies of dependencies and any reflection dependencies like classnames which you have in a , but are used in .For Java, compile time dependency is your source code's dependency. For instance, if class A calls a method from class B, then A is dependent to B at the compile time since A has to know about B (type of B) to be compiled. The trick here should be this: Compiled code is not a complete and executable code yet. It includes replaceable addresses (symbols, metadata) for the sources which are not yet compiled or existing in external jars. During linking, those addresses must be replaced by actual adresses in the memory. To do it properly, correct symbols/adresses should be created. And this can be done with the type of the class (B). I believe that's the main dependency at the compile time.Runtime dependency is more related with the actual flow-of-control. It involes actual memory addresses. It's a dependency that you have when your program is running. You need class B details here like implementations, not only the type info. If the class not exists, then you will get RuntimeException and JVM will exit.Both dependencies, generally and shouldn't, flow the same direction. This is a matter of OO design though.In C++, compilation is a bit different (not just-in-time) but it has a linker too. So the process might be thought similar to Java I guess.
Java

I have a blank Spring MVC project, and I've installed Hibernate and the PostgreSQL drivers using Maven.I'm running short on complete tutorials that show how to connect PostgreSQL with Hibernate.Any help here?This is a hibernate.cfg.xml for posgresql and it will help you with basic hibernate configurations for posgresql.If the project is maven placed it in , in the package phase it will copy it in Make sure File Location should be under 
Java

I am implementing a  for the apache HttpClient package, like so:but I'd like for the  function to return nothing, i.e. . Is this possible? The following does not compile, since  is not a valid Java type:I suppose I could replace  with  to return a  object, but that's not really what I want. : is it possible to organize this callback situation in such a way that I can return  from ?Generics only handles object classes.  void and primitive types are not supported by Generics and you cannot use these as a parameterized type.  You have to use Void instead.Can you say why you don't want to use ?The  type was created for this exact situation: to create a method with a generic return type where a subtype can be \"void\".  was designed in such a way that no objects of that type can possibly be created. Thus a method of type  will always return  (or complete abnormally), which is as close to nothing as you are going to get. You do have to put  in the method, but this should only be a minor inconvenience.In short: Do use . You can set the code to return  as you say, however you can never instanciate a  so you can't actually write a function which conforms to this specification.Think of it as: The generic function says \"this function returns something, of type X\", and you can specify X but you can't change the sentence to \"this function returns nothing\". (I'm not sure if I agree with these semantics, but that's the way they are.)In this case, what I always do, is just make the function return type , and in fact always return .You can't have primitives in generics so that  is actually an . The object  is analogous with the keyword  for generics.When you need to return java.lang.Void, just return null.This java.lang.Void implementation in Java kind of speaks for itself. Also, I wrote an article that ties this into generics. It took a bit of thought before I started understanding this: . Notice TYPE = Class.getPrimitiveClass(\"void\");package java.lang;
Java

When creating a 2D array, how does one remember whether rows or columns are specified first?Java is considered \"row major\", meaning that it does rows first. This is because a 2D array is an \"array of arrays\".For example:  It can also be visualized more like this:The second illustration shows the \"array of arrays\" aspect. The first array contains , and each of those is an array containing four elements, .TL;DR summary:For more explanations, see also .While Matt B's may be true in one sense, it may help to think of Java multidimensional array without thinking about geometeric matrices at all.  Java multi-dim arrays are simply arrays of arrays, and each element of the first-\"dimension\" can be of different size from the other elements, or in fact can actually store a null \"sub\"-array.  See comments under  Instinctively one thinks geometrically: horizontal (X) axis and then vertical (Y) axis. This is not, however, the case with a 2D array, rows come first and then columns.Consider the following analogy: in geometry one walks to the ladder (X axis) and climbs it (Y axis). Conversely, in Java one descends the ladder (rows) and walks away (columns).In Java, there are no multi-dimension arrays. There are arrays of arrays. So:It actually consists of two arrays, each has three elements.All depends on your visualization of the array. Rows and Columns are properties of  (probably in your imagination) of the array, not the array itself. I could draw it red, I could draw it greed right? Color is not an integral property of a number. In the same way representing 2D array as a grid of rows and columns is not necessary for existence of this array. 2D array has just  and , everything related to visualizing those is purely your flavour.When I have char array , I may like to print it on console rotated so that I have 25 rows of 80 characters that fits the screen without scroll. I'll try to provide viable : Let's say I need an array of 1 000 000 000 integers. My machine has 8GB of RAM, so I have enough memory for this, but if you try executing , you'll most likely get OutOfMemory exception. That's because of memory fragmentation - there is no consecutive block of memory of this size. Instead you you can create 2D array 10 000 x 100 000 with your values. Logically it is 1D array, so you'd like to draw and imagine it as a single sequence of values, but due to technical implementation it is 2D.In java the rows are done first, because a 2 dimension array is considered two separate arrays. Starts with the first row 1 dimension array.
Java

I have a class as below:The logic in the constructor  and  are the things I am trying to mock. I want any calls like:  returns a dummy string \"test\".I tried:But it doesn't seem to be working.  is still going through the constructor logic instead of fetch the mocked object of A.The code you posted works for me with the latest version of Mockito and Powermockito. Maybe you haven't prepared A?\nTry this:A.javaMockA.javaBoth tests should pass with mockito 1.9.0, powermockito 1.4.12 and junit 4.8.2To my knowledge, you can't mock constructors with mockito, only methods.  But according to the wiki on the Mockito google code page there is a way to mock the constructor behavior by creating a method in your class which return a new instance of that class.  then you can mock out that method.  Below is an :If you're just wanting to return a mocked object of your class I think this should work for you.  In any case you can read more about mocking object creation here:Without Using Powermock .... See the example below based on Ben Glasser answer since it took me some time to figure it out ..hope that saves some times ... Mockito has limitations testing final, static, and private methods.with jMockit testing library, you can do few stuff very easy and straight-forward as below:Mock constructor of a java.io.File class:Mock a static method:
Java

Assuming that I'm trying to pull from a RESTful api that uses basic authentication / basic certificates, what would be the best way to store that user name and password in my program?   Right now it's just sitting there in plaintext.Is there some way of doing this that is more security minded?ThanksWith an inner-to-outer mindset, here are some steps to protect your process:First step, you should change your password-handling from  to .The reason for this is that a  object's data will not be cleansed immediately even if the object is set to ; The data is set for garbage-collection instead, and this poses security problems because malicious programs might gain access to that  (password) data before it is cleaned.This is the main reason why  method is deprecated, and why .The second step is to encrypt your credentials, only decrypting them temporarily during the authentication process.This, similarly to the first step, makes sure your vulnerability-time is as small as possible.It is recommended that your credentials are not hard-coded, and that instead, you store them in a centralized, configurable and easily-maintainable manner, such as a configuration or properties file.You should encrypt your credentials before saving the file, and additionally, you can apply a second encryption to the file itself (2-layer encryption to the credentials, and 1-layer to other file contents).Note that each of the two encryption processes mentioned above can be multiple-layered themselves. Each encryption can be an individual application of , as a conceptual example.After your local environment is properly protected (but remember, it's never ever \"safe\"!), the third step is apply basic protection to your transmission process, by using .The forth step is to apply other protection methods.For example, applying obfuscation techniques to your \"to-use\" compile, to avoid (even if shortly) the exposure of your security measures in case your program is obtained by  and decompiled.By @Damien.Bell 's request, here is an example that covers the first and second steps:A full example, addressing every protection step, would far exceed what I think is reasonable for this question, since it's about , not .It would far over-size my answer (at last the sampling), while other questions here on S.O. are already directed on the  of those steps, being far more appropriate, and offering far better explanation and sampling on the implementation of each individual step.If you are using basic auth, you should couple that with SSL to avoid passing your credentials in base64 encoded plain text. You don't want to make it easy for someone sniffing your packets to get your credentials. Also, don't hard code your credentials in your source code. Make them configurable. read them from a config file. You should encrypt the credentials before storing them in a config file and your app should decrypt the credentials once it reads them from the config file.plus probably thousand things i forgot about :)It's generally not good advice to encrypt credentials. Something that is encrypted can be decrypted. Common best practice is to store passwords as a .A hash cannot be decrypted. The salt is added to defeat brute force guessing with . As long as every userId has its own random salt, an attacker would have to generate a set of tables for every possible value of the salt, quickly making this attack impossible within the lifespan of the universe. This is the reason why websites generally can't send you your password if you have forgotten it, but they can only 'reset' it. They don't have your password stored, only a hash of it. Password hashing is not very difficult to implement yourself, but it's such a common problem to solve that countless others have done it for you. I've found  easy to use. As an extra protection against brute force guessing of passwords, it is common best practice to force a userId or remote IP to wait a few seconds after a certain number of login attempts with the wrong password. Without this, a brute force attacker can guess as many passwords per second as your server can handle. There is a huge difference between being able to guess 100 passwords per 10 second period or a million. I get the impression that you have included the username/password combination in your source code. This means that if you ever want to change the password, you'll have to recompile, stop and restart your service, and it also means that anyone who gets a hold of your source code, also has your passwords. Common best practice is never to do this, but to store the credentials (username, password hash, password salt) in your datastoreIf you cannot trust the environment your program is running in, but need to authenticate via plain passwords or certificates, there is nothing you can do to secure your credentials. The most you can do is obfuscate them with the methods described in the other answers.As a workaround, I'd run all requests to the RESTful api through a proxy that you can trust and do the cleartext password authentication from there.
Java

I know that '==' doesn't work with values outside the range of [-128,127] as there is a cache maintained of Integer objects within this range and the same reference is returned if value is within the range. But why does '>', '<', '>=', '<=' give correct answers even outside the range ?Why is this happening ?The , ,  and  operators are only defined for primitive types. Therefore using them on wrapper types causes the compiler to unbox the objects into primitives.This meansis equivalent toHowever, the  and  operators exist for both primitive types and reference types, so using them to compare two objects of primitive wrapper types compares the references instead of the primitive values they wrap.As Holger commented, comparison of object references with  and  existed in the Java language before auto-boxing and auto-unboxing were introduced, but comparison with , ,  and  was not supported for any reference types before auto-unboxing was introduced.This means that in the early days of Java, the  of your code snippet would not pass compilation (since  and  are not primitive numeric types). On the other hand your  snippet would still pass compilation and return .Changing the behavior of  and  for reference types that happen to be wrappers of numeric primitives would change the behavior of existing code, thus breaking backwards compatibility, which is probably the reason it wasn't done.
Java

I was asked this question in interview: \"How to detect the loop in linked list?\", I solved this but immediately the interviewer asked me how do I remove the loop in a linked list.  I fumbled.So any pointers on how to solve this, may be pseudo code, or method definition?I'm comfortable with Java so I have tagged this question under java.For Instance this linked list has a loopThere are two parts to this problem:Once you know where the loop starts, it's easy to identify the last element in the list since it's the element in the list following the start of the loop that ends up pointing back to the start of the loop. It is then trivial to set the next pointer/reference of this element to  to correct the cyclic link list (not circular linked list which is where the last elements points back to the first - this would be a specific instance of cyclic lists).Here's some quick and dirty Java code assuming a linked list of s where a  has a  reference. This could be optimized but it should give you the basic idea: might help the why behind Part II: - courtesy of :The explanation for this solution is straight from the book: - courtesy of me :)I hope this helps.\nHristoThis response is not meant to compete for the answer, but rather to explain a little more on the meeting of the two nodes in the tortoise and the hare algorithm.It's a bit late here so I hope I've articulated effectively. Let me know otherwise and I'll try and update my response.If using an identity hash map (such as ) is permissible this is terribly easy to solve. It does use more space, though.Traverse the nodes list. For each node encountered, add it to the identity map. If the node already existed in the identity map then the list has a circular link and the node which was prior to this conflict is known (either check before moving or keep the \"last node\") -- simply set \"next\" as appropriate to break the cycle.Following this simple approach should be a fun exercise: code is left as an exercise for the reader.Happy coding.Insert dummy node after every node of link list and before inserting check that node next to next is dummy or not. If next to next is dummy, insert null in next of that node.  
Java

Is there any good and free Date AND Time Picker available for Java Swing?There are a lot date pickers available but no date AND time picker. This is the closest I came across so far: Anybody?For a time picker you can use a JSpinner and set a JSpinner.DateEditor that only shows the time value.You can extend the swingx JXDatePicker component:EDIT: This article disappeared from the web, but as SingleShot discovered, it is still available in an internet archive. Just to be sure, here is the full working example:Use the both combined.. that's what i did:There is the  component with a combined Date and Time Picker.As you said Date picker is easy, there are many out there.As for a Time picker, check out how Google Calendar does it when creating a new entry.  It allows you to type in anything while at the same time it has a drop down in 30 mins increments.  The drop down changes when you change the minutes.If you need to allow the user to pick seconds, then the best you can do is a typable/drop down comboThe best of the best, JCalendar:\n\nLGPL licensed.
Java

Can someone explain to me why  returns type  just returns type I'm don't understand why the map would ever map to more then one value. TIA.It returns all parameter values for controls with the  name. For example:orAny checked/selected values will come in as:It's also useful for multiple selections in tables:in combination with\"biff\" now maps to The real function to get all parameter values is is just a shortcut to get first one.In the case with multi-value controls (checkbox, multi-select, etc), the  is used to fetch the values.If you have a multi-value control like a multi-selectable list or a set of buttons mapped to the same name multiple selections will map to an array.
Java

So I have a program that spawns threads (~5-150) which perform a bunch of tasks. Originally I used a FixedThreadPool because  suggested they were better suited for longer lived tasks and with my very limited knowledge of multithreading, I considered the average life of the threads (several minutes) \"long lived\". However, I recently added the capability to spawn additional threads and doing so takes me above the thread limit I set. In this case, would it be better to guess and increase the number threads I can allow or to switch to a CachedThreadPool so I have no wasted threads?Trying them both out preliminarily, there doesn't  to be a difference so I'm inclined to go with the CachedThreadPool just to avoid the waste. However, does the life span of the threads mean I should instead picked a FixedThreadPool and just deal with the unused threads?  makes it seem like those extra threads aren't wasted but I would appreciate the clarification.A CachedThreadPool is exactly what you should use for your situation as there are no negative consequence to using one for long running threads.  The comment in the java doc about CachedThreadPools being suitable for short tasks merely suggest that they are particularly appropriate for such cases, not that they cannot or should not be used for tasks involving long running tasks.To elaborate further,  and  are both backed by the same thread pool implementation (at least in the open JDK) just with different parameters.  The differences just being their thread minimum, maximum, thread kill time, and queue type.A FixedThreadPool does have its advantages when you do in fact want to work with a fixed number of threads, since then you can submit any number of tasks to the executor service while knowing that the number of threads will be maintained at the level you specified.  If you explicitly want to grow the number of threads, then this is not the appropriate choice.This does however mean that the one issue that you may have with the CachedThreadPool is in regards to limiting the number of threads that are running concurrently.  The CachedThreadPool will not limit them for you, so you may need to write your own code to ensure that you do not run too many threads.  This really depends on the design of your application and how tasks are submitted to the executor service.In my opinion, both  and  are evils in highly loaded applications.  is more dangerous than If your application is highly loaded & demands low latency, better to get rid of both options due to below drawbacksSince you know that both are evils, lesser evil does n't do good. Prefer , which provides granular control on many parameters. Are you sure you understand how threads are actually processed by your OS and hardware of choice? How Java maps threads to OS threads, how that maps threads to CPU threads etc.? I'm asking because creating 150 threads within in ONE JRE only makes sense if you have massive CPU cores/threads underneath, which most likely is not the case. Depending on the OS and RAM in use, creating more than n threads might even result in your JRE being terminated because of OOM errors.  So you should really distinguish between threads and work to do by those threads, how many work you are even able to process etc.And that's the problem with CachedThreadPool: It doesn't make sense to queue up long running work in threads which actually can't run because you only have 2 CPU cores able to process those threads. If you end up with 150 scheduled threads you might create a lot of unnecessary overhead for the schedulers used within Java and the OS to concurrently process them. This is simply impossible if you only have 2 CPU cores, unless your threads are waiting for I/O or such all the time. But even in that case a lot of threads would create a lot of I/O...And that problem doesn't occur with FixedThreadPool, created with e.g. 2+n threads, where n is reasonable low of course, because with that hardware and OS resources are used with far less overhead for managing threads which can't run anyway.
Java

How can I create a barcode image in Java?  I need something that will allow me to enter a number and produce the corresponding barcode image.  Is there a free library available for this type of task? is a great Java PDF library. They also have an API for creating barcodes. You don't need to be creating a PDF to use it.This page has the details on . Here is an example from that site:The biggest thing you will need to determine is what type of barcode you need. There are many different barcode formats and iText does support a lot of them. You will need to know what format you need before you can determine if this API will work for you.There is also this free API that you can use to make free barcodes in java.There is a free library called  is a free open source Java library to read and generate barcode images. You need to get the source code and build the jars yourself. Here's a  that I wrote for building with ZXing jars and writing your first program with ZXing.[I use \n\n, it's great, and supports a very wide range of different barcode formats.\nSee if you like \n\n.Sample API:
Java

I'm using IntelliJ 9 and I'm curious if there is any IntelliJ equivalent of the Visual Studio 'immediate' debug window.  There is - to evaluate an expression, but what I'd like to be able to write code in a window that interacts with what I am currently debugging (if that's even possible).Having breakpoints that log messages to the console is helpful, but I'd like to do more than that if I can.Intellij IDEA's Expression Evaluation dialog has a button to enable , which permits multi-statement evaluations. (I'm using version 9.0.2 of the Ultimate Edition.)Same as @Noel answer, but some more details. First of all,  ( + ) can be enabled .  Community Edition, Windows:You can write code in alt-f8.. but you have to do it only 1 line at a time. If you do a return, your code will return when you hit next (I think).  It isn't ideal though...
Java

Is there any performance penalty for the following code snippet?Or does this code actually make more sense?If in byte code these two are totally equivalent then obviously the first method looks better in terms of style, but I want to make sure this is the case.In today's compilers, no.  I declare objects in the smallest scope I can, because it's a lot more readable for the next guy.  :Whether the compiler will produce marginally faster code by defining the variable outside the loop is debatable, and I imagine it won't. I would  it'll produce identical bytecode.Compare this with the number of errors you'll likely prevent by correctly-scoping your variable using in-loop declaration...There's no performance penalty for declaring the Object o within the loop.\nThe compiler generates very similar bytecode and makes the correct optimizations.See the article  for a similar example.You can disassemble the code with javap -c and check what the compiler actually emits.  On my setup (java 1.5/mac compiled with eclipse), the bytecode for the loop is identical.The first code is better as it restricts scope of  variable to the  block. From a performance perspective, it might not have any effects in Java, but it might have in lower level compilers. They might put the variable in a register if you do the first.In fact, some people might think that if the compiler is dumb, the second snippet is better in terms of performance. This is what some instructor told me at the college and I laughed at him for this suggestion! Basically, compilers allocate memory on the stack for the local variables of a method just once at the start of the method (by adjusting the stack pointer) and release it at the end of method (again by adjusting the stack pointer, assuming it's not C++ or it doesn't have any destructors to be called). So all stack-based local variables in a method are allocated at once, no matter where they are declared and how much memory they require. Actually, if the compiler is dumb, there is no difference in terms of performance, but if it's smart enough, the first code can actually be better as it'll help the compiler understand the scope and the lifetime of the variable! By the way, if it's really smart, there should no absolutely no difference in performance as it infers the actual scope.Construction of a object using  is totally different from just declaring it, of course.I think readability is more important that performance and from a readability standpoint, the first code is definitely better.I've got to admit I don't know java.  But are these two equivalent?  Are the object lifetimes the same? In the first example, I assume (not knowing java) that o will be eligible for garbage collection immediately the loop terminates.  But in the second example surely o won't be eligible for garbage collection until the outer scope (not shown) is exited?Don't prematurely optimize. Better than either of these is:because it eliminates boilerplate and clarifies intent.Unless you are working on embedded systems, in which case all bets are off. Otherwise, don't try to outsmart the JVM.I've always thought that most compilers these days are smart enough to do the latter option. Assuming that's the case, I would say the first one does look nicer as well. If the loop gets very large, there's no need to look all around for where o is declared.These have different semantics.  Which is more meaningful?Reusing an object for \"performance reasons\" is often wrong.The question is what does the object \"mean\"?  WHy are you creating it?  What does it represent?  Objects must parallel real-world things.  Things are created, undergo state changes, and report their states for reasons.What are those reasons?  How does your object model and reflect those reasons?To get at the heart of this question... [Note that non-JVM implementations may do things differently if allowed by the JLS...]First, keep in mind that the local variable \"o\" in the example is a pointer, not an actual object.All local variables are allocated on the runtime stack in 4-byte slots. doubles and longs require two slots; other primitives and pointers take one. (Even booleans take a full slot)A fixed runtime-stack size must be created for each method invocation. This size is determined by the maximum local variable \"slots\" needed at any given spot in the method.In the above example, both versions of the code require the same maximum number of local variables for the method.In both cases, the same bytecode will be generated, updating the same slot in the runtime stack.In other words, no performance penalty at all.HOWEVER, depending on the rest of the code in the method, the \"declaration outside the loop\" version might actually require a larger runtime stack allocation. For example, comparewithIn the first example, both loops require the same runtime stack allocation.In the second example, because \"o\" lives past the loop, \"x\" requires an additional runtime stack slot.Hope this helps,\n-- ScottIn both cases the type info for the object o is determined at compile time.In the second instance, o is seen as being global to the for loop and in the first instance, the clever Java compiler knows that o will have to be available for as long as the loop lasts and hence will optimise the code in such a way that there wont be any respecification of o's type in each iteration. \nHence, in both cases, specification of o's type will be done once which means the only performance difference would be in the scope of o. Obviously, a narrower scope always enhances performance, therefore to answer your question: no, there is no performance penalty for the first code snip; actually, this code snip is more optimised than the second.In the second snip, o is being given unnecessary scope which, besides being a performance issue, can be also a security issue.The first makes far more sense. It keeps the variable in the scope that it is used in. and prevents values assigned in one iteration being used in a later iteration, this is more defensive.The former is sometimes said to be more efficient but any reasonable compiler should be able to optimise it to be exactly the same as the latter.As someone who maintains more code than writes code.Version 1 is much preferred - keeping scope as local as possible is essential for understanding. Its also easier to refactor this sort of code.As discussed above - I doubt this would make any difference in efficiency. In fact I would argue that if the scope is more local a compiler may be able to do more with it!When using multiple threads (if your doing 50+) then i found this to be a very effective way of handling ghost thread problems:The answer depends partly on what the constructor does and what happens with the object after the loop, since that determines to a large extent how the code is optimized.If the object is large or complex, absolutely declare it outside the loop.  Otherwise, the people telling you not to prematurely optimize are right.I've actually in front of me a code which looks like this:So, relying on compiler abilities, I can assume there would be only one stack allocation for  and one for . Then everything would be fine except the duplicated code.As a side note, java applications are known to be slow. I never tried to do profiling in java but I guess the performance hit comes mostly from memory allocation management.
Java

What are Java's equivalents of  and ?I mean, instead of writing this on my own:In Java 8, the equivalents are the  and  interfaces respectively. Similarly,  is equivalent to . As mentioned elsewhere, these are interfaces instead of delegates.Related aside: I'm currently leaning heavily on the following utility class to do LINQ-like extension method stuff:Unlike  and  the LINQ-like methods I present here are not lazy and fully traverse the source collections before returning the result collections to the caller. Still, I find them useful for purely syntactic purposes and could be made lazy if necessary. GivenOne can do the following:Which I prefer to the following: interface is similar to Func. interface is similar to Action. In general, Java uses anonymous inner classes as a replacement for C# delegates. \nFor example this is how you add code to react to button press in GUI:The elegance of the overloaded Func delegates (besides the delegate vs anonymous class issue) is that they support from 0 to 16 arguments (, , , etc.)Unfortunately, this is impossible in Java because of type erasure. Classes cannot differ by generic type parameters alone. Java 8 now brings in a zoo of names like  for  and, because Java does not allow primitive type arguments, . The \"zoo\", though, is not very big, and I am not aware of a library that expands it. There was a wonderful proposal for function type literals like  but it was not adopted.There really are no equivalents for those.  You can create anonymous inner classes in Java, but there tends to be specific interfaces rather than such generic ones like Func and Action.Java doesn't have the concept of delegates.  For a workaround approach, please see :For  use: java.util.function.Supplier\n
Java

I have a process A that contains a table in memory with a set of records (recordA, recordB, etc...)Now, this process can launch many threads that affect the records, and sometimes we can have 2 threads trying to access the same record - this situation must be denied. Specifically if a record is LOCKED by one thread I want the other thread to abort (I do not want to BLOCK or WAIT).Currently I do something like this:But this is causing me problems ... because while Process1 is performing the operation, if Process2 comes in it blocks/waits on the synchronized statement and when Process1 is finished it performs the operation. Instead I want something like this:Any clues on how this can be accomplished?\nAny help would be much appreciated.\nThanks,One thing to note is that the  you receive such information, it's stale. In other words, you could be told that no-one has the lock, but then when you try to acquire it, you block because another thread took out the lock between the check and you trying to acquire it.Brian is right to point at , but I think what you really want is its  method:You can also call  with an amount of time to wait - so you could try to acquire it for a tenth of a second, then abort if you can't get it (for example).(I think it's a pity that the Java API doesn't - as far as I'm aware - provide the same functionality for the \"built-in\" locking, as the  class does in .NET. Then again, there are plenty of other things I dislike in both platforms when it comes to threading - every object potentially having a monitor, for example!)Take a look at the  objects introduced in the Java 5 concurrency packages.e.g. The  object is essentially doing the same thing as the traditional  mechanism, but with more functionality.EDIT: As Jon has noted, the  method tells you at , and thereafter that information is out of date. The  method will give more reliable operation (note you can use this with a timeout as well)EDIT #2: Example now includes  for clarity.Whilst the above approach using a Lock object is the best way to do it, if you have to be able to check for locking using a monitor, it can be done. However, it does come with a health warning as the technique isn't portable to non Oracle Java VMs and it may break in future VM versions as it isn't a supported public API.Here is how to do it:My advice would be to use this approach only if you cannot refactor your code to use java.util.concurrent Lock objects for this and if you are running on an Oracle VM.While the Lock answers are very good, I thought I'd post an alternative using a different data structure.  Essentially, your various threads want to know which records are locked and which aren't.  One way to do this is to keep track of the locked records and make sure that data structure has the right atomic operations for adding records to the locked set.I will use CopyOnWriteArrayList as an example because it's less \"magic\" for illustration.  CopyOnWriteArraySet is a more appropriate structure.  If you have lots and lots of records locked at the same time on average then there may be performance implications with these implementations.  A properly synchronized HashSet would work too and locks are brief.Basically, usage code would look like this:It keeps you from having to manage a lock per record and provides a single place should clearing all locks be necessary for some reason.  On the other hand, if you ever have more than a handful of records then a real HashSet with synchronization may do better since the add/remove look-ups will be O(1) instead of linear.Just a different way of looking at things.  Just depends on what your actual threading requirements are.  Personally, I would use a Collections.synchronizedSet( new HashSet() ) because it will be really fast... the only implication is that threads may yield when they otherwise wouldn't have.I found this, we can use Thread.holdsLock(Object obj) to check if that object is lockedAnother workaround is (in case of you didnt have chance with the answers given here )is using timeouts. i.e. below one will return null after 1 second hanging:Thanks for this, it helped me out solving a race condition. I changed it a little to wear both belt and suspenders.You can ensure that you get safe access to the  method by doing something like this:This would avoid the situation where you might get two calling  at the almost same time, causing the return to be potentially doubt full. I'd like to now if I'm wrong, I might be over cautios here. But hey! My gig is stable now :-)..Read more on my development issues at my .
Java

My team is working with a third party CMS that uses Solr as a search index.  I've noticed that it seems like the authors are using Solr as a database of sorts in that each document returned contains two fields:So basically it runs a search against Solr, download the XML representation of the object, and then instantiate the object from the XML rather than looking it up in the database using the id.My gut feeling tells me this is a bad practice.  Solr is a search index, not a database... so it makes more sense to me to execute our complex searches against Solr, get the document ids, and then pull the corresponding rows out of the database.Is the current implementation perfectly sound, or is there data to support the idea that this is ripe for refactoring? When I say \"XML representation\" - I mean one stored field that contains an XML string of all of the object's properties, not multiple stored fields.It's perfectly reasonable to use Solr as a database, depending on  application. In fact, that's pretty much what .It's definitely  bad practice per se. It's only bad if you use it the wrong way, just like any other tool at any level, even GOTOs.When you say \"An XML representation...\" I assume you're talking about having multiple stored Solr fields and retrieving this using Solr's XML format, and not just one big XML-content field (which would be a terrible use of Solr). The fact that Solr uses XML as default response format is largely irrelevant, you can also use a , so it's quite comparable to traditional relational databases in that regard.Ultimately, it's up to your application's needs. Solr  primarily a text search engine, but can also act as a NoSQL database for many applications.Yes, you can use SOLR as a database but there are some really serious caveats : That said - there are plenty of obvious advantages to SOLR for certain tasks : (see ) -- loose queries are much easier to run and return meaningful results.  Indexing is done as a matter of default, so most arbitrary queries run pretty effectively (unlike a RDBMS, where you often have to optimize and de-normalize after the fact).   Even though you CAN use SOLR as an RDBMS, you may find (as I have) that there is ultimately \"no free lunch\" - and the cost savings of super-cool lucene text-searches and high-performance, in-memory indexing, are often paid for by less flexibility and adoption of new data access workflows.This was probably done for performance reasons, if it doesn't cause any problems I would leave it alone. There is a big grey area of what should be in a traditional database vs a solr index. Ive seem people do similar things  to this (usually key value pairs or json instead of xml) for UI presentation and only get the real object from the database if needed for updates/deletes. But all reads just go to Solr.I've seen similar things done because it allows for very fast lookup.  We're moving data out of our Lucene indexes into a fast key-value store to follow DRY principles and also decrease the size of the index.  There's not a hard-and-fast rule for this sort of thing.
Java

I needed something similar to waitForElementPresent to check whether element is displayed before I click it. I thought the implicitWait should cover this. So I used the following:and then click byUnfortunately sometimes it waits for the element and sometimes not. I looked for a while and found this solution :And it waited all right, but before timing out it had to wait 10 times 5, 50 seconds. A bit much. So I set the implicitly wait to 1sec and all seemed fine until now. Because now some things wait 10s before timeout but some other things time out after 1s.How do you cover the waiting for element present/visible in your code? Any hint is appreciable.This is how I do it in my code.orto be precise.See also:You can use Explicit wait or Fluent WaitExample of Explicit Wait -Example of Fluent Wait -Check this  for more details.Above wait statement is a nice example of Explicit wait. As Explicit waits are intelligent waits that are confined to a particular web element(as mentioned in above x-path). By Using explicit waits you are basically telling WebDriver at the max it is to wait for X units(whatever you have given as timeoutInSeconds) of time before it gives up.
Java

I want to connect Java class file with SQL server 2012. I have logged in with SQL server authentication. But i am receiving error in connectivity.My code ---If there are any more questions, please let me know.Thanks.Got to Start->All Programs-> Microsoft SQL Server 2012-> Configuration Tool -> Click SQL Server Configuration Manager ->Expand SQL Server Network Configuration-> Protocol ->Enable TCP/IP Right boxDouble Click on TCP/IP and go to IP Adresses Tap and Put port 1433 under TCP port.The error is self explanatory:A good check I often use is to use telnet, eg on a windows command prompt run:If you get a blank screen it indicates network connection established successfully, and it's not a network problem. If you get 'Could not open connection to the host' then this is network problemAs the error says, you need to make sure that your sql server is running and listening on port 1433. If server is running then you need to check whether there is some firewall rule rejecting the connection on port 1433.Here are the commands that can be useful to troubleshoot:Go to Start->All Programs-> Microsoft SQL Server 2012-> Configuration Tool -> Click SQL Server Configuration Manager.  If you see that SQL Server/ SQL Server Browser State is 'stopped'.Right click on SQL Server/SQL Server Browser and click start.\nIn some cases above state can stop though TCP connection to port 1433 is assigned.  
Java

When the code above is run, it produces an error on the line . Why? cannot be represented as a 32-bit integer (type ). It can be represented as a 64-bit integer (type ). long literals in Java end with an \"L\": Append suffix : .By default, java interpret all numeral literals as 32-bit integer values. If you want to explicitely specify that this is something bigger then 32-bit integer you should use suffix  for long values.You need to use a long literal: But I would expect that function to run out of memory (or time) ...The java compiler tries to interpret 600851475143 as a constant value of type int by default. This causes an error since 600851475143 can not be represented with an int.To tell the compiler that you want the number interpretet as a long you have to add either  or  after it. Your number should then look like this .Since some Fonts make it hard to distinguish \"1\" and lower case \"l\" from each other you should always use the upper case \"L\".You need 40 bits to represent the integer literal 600851475143. In Java, the maximum integer value is 2^31-1 however (i.e. integers are 32 bit, see ).This has nothing to do with . Try using a long integer literal instead (as suggested in the other answers).At compile time the number \"600851475143\" is represented in 32-bit integer, try long literal instead at the end of your number to get over from this problem.Apart from all the other answers, what you can do is : for example : 
Java

I'm trying to open a file in android like this :, but in case the file does not exists a file not found exception is thrown . I'd like to know how could I test if the file exists before attempting to open it. I think the best way to know if a file exists, without actually trying to open it, is as follows:Hope that helps, bye!The documentation says Context.openFileInput either returns an inputStream (file found) or throws a FileNotFoundException (not found)So it looks like the exception is your \"test\".You could also try using standard But that is not recommended. Context.openFileInput() and Context.openFileOutput() make sure you stay in your applications storage context on the device, and that all of your files get\ndeleted when your app gets uninstalled.With the standard  this is the function I have created, and works correctly:why dont you just catch the FileNotFound exception and take that as the file not being present.If you want to ensure a file exists (i.e. if it doesn't exist create a new one, if it does then don't erase it) then use File.createNewFile:e.g.If you want to open a file in any case (i.e. if it doesn't exist create a new one, if it does append to the old one) you can use this, no testing necessary:My suggestion is to check length of the file.  that means file doesn't exist.
Java

I have problem with starting Apache Tomcat 6 from Netbeans IDE 7.4 (on 7.3 version I had the same troubles. Other people mentioned that this problem exist also in other versions, like 8.0 etc). What did I do: When I now click \"start\", I got \"\". My suspicions: It affects at least NetBeans versions 7.4 through 8.0.2. It was first reported from version 8.0 and fixed in NetBeans 8.1. It would have had the problem for any tomcat version (confirmed for versions 7.0.56 through 8.0.28).Specifics are described as . This problem is also related to postings mentioning the following error output:For a tomcat installed from the zip file, I fixed it by changing the  file in the tomcat  directory.Find the bellow configuration in your  file.And change it as in below by :Now save your changes, and start your tomcat from within NetBeans.This affects:This is because Netbeans does not 'see' that tomcat is started, although it started just fine.I have filed .In the  file, in the  element for HTTP/1.1, add the following attribute: . Example:The reason for that is that prior to 8.5.3, the default was to set the server header as , while since 8.5.3 this default has now been changed to blank. Apparently Netbeans checks on this header.Maybe in the future we can expect a fix in netbeans addressing this issue.I was able to trace it back to a change in documentation.::That explains the need for explicitly adding the server attribute since version 8.5.3.For NetBeans to be able to interact with tomcat, it needs the user as setup in netbeans to be properly configured in the  file. NetBeans can do so automatically.That is, within the , which you can find in , or ,Example, changeToAddActually the netbeans online-help incorrectly states:The role should be , and not .For a more complete  file:There is another nice posting on Also, it is very likely, that problem with proxy settings.Any who didn't overcome Tomact starting problrem, - try in NetBeans choose  in the Tools -> Options -> General tab.It helped me.
Java

I was working with numbers recently and I had a situation where I want to set the precision of a double value say to 6 digits or 4 digits, depending on the value stored in the database.For example, If in the database the precision is set as 4 digits then the output must look as,. I tried with  and using the string , but it is annoying to use symbols everytime. Is there any better approach, say something like below:You can't set the precision of a double (or Double) to a specified number of decimal digits, because floating-point values don't have decimal digits. They have binary digits.You will have to convert into a decimal radix, either via  or , depending on what you want to do with the value later.See also my answer to  for a refutation of the inevitable *100/100 answers.You can try  for this purpose this is a easy way to do it.it set the presition to 2 digit o any.if you only want to print it use this way.The precision of  and  is fixed by their size and the way the  are implemented.The number of decimal digits in the output, on the other hand, is a matter of formatting. You are correct that typing the same constant over and over is a bad idea. You should declare a string constant instead, and use its symbolic representation.Using a symbolic representation would let you change precision in all places the constant is used without searching through your code.Here's an efficient way of achieving the result with two caveats.See sample test cases here.Here's the code. The two caveats I mentioned above can be addressed pretty easily, however, speed mattered more to me than accuracy, so i left it here.\nString manipulations like  are computationally costly compared to mathematical operations. In my tests, the below code (without the sysout) took 1/30th the time compared to String manipulations.To expand on @EJP, the concept of 'precision' when dealing with doubles is extremely fraught. As discussed in  you can't even represent 0.1 as a double regardless of the precision, for the same reason you can't represent 1/3 in base 10 with finite precision.You need to consider the problem you are trying to solve, and consider:a) Should I be using doubles in the first place; if precision is a relevant concept, then using doubles may well be a mistake.b) If doubles are appropriate, what do I mean by precision? If you are only talking about display, wrap the logic in a display function and you will only need to deal with it in one place; ie. apply the DRY principle.I saw the answer at top:which i think is not the perfect answer. Because answer will change when you call .doubleValue() in many cases.\nExample:\noutput of BigDecimal.valueOf(toBeTruncated)\n    .setScale(3, RoundingMode.HALF_UP) is 12.500then after .doubleValue(), the output will be 12.5 i.e. precision is lost.Solution either use BigDecimal type  without .doubleValue() method to display or use string formatting after the final answerThis worked for me:Maybe this method would help you for precising double values.This method will allow to set the precision level.To set precision for double values DecimalFormate is good technique, to use this class import  and create object of it for example So it will print two digits after decimal point here it will print 12.79
Java

I've been trying to compare CSV parser libraries for my Java application.\nMy post will aim to capture most of the popular ones talked about.The popular ones I looked into are:\nReviewing the different Stackoverflow votes from other posts, OpenCSV seems to be the most popular. But it hasn't been updated in a long time. The last release been 3 years ago in 2011 ().  \nThis project came as a result of 'authors of the [OpenCSV] project do not respond'. Which gave me for reason not to use 'OpenCSV'. I haven't heard much about it, hence I'm reluctant to use it.\nHas good documentation, and the last release was about a year ago (2013).\nI really like this because of it's support for annotations, and looks really easy. And it's last updated only a few month ago. See an example of it's usage here, the first answer - . The only problem is I'm not able to find the Maven upload for the latest version, the version on maven is 0.9.3 which is 4 years old (Request for Maven Upload - ). Which demonstrates their lack of support.\nThis project aims incorporate / make redundant OpenCSV, Skif CSV and GenJavaCSV. It seems all incorporating. But it is still not released, and is unknown when it will be released (currently in sandbox).I'm interested in your personal recommendations on top of what I have already commented about these CSV libraries? Or if you know the release date, etc for these libraries. Especially JSefa, since it's annotations looks so easy to use? And Apache Commons, the all encapsulating, but not yet released?============================= 23/09/2014 (thanks Kane)14/10/2014
Java

I have successfully set up an Apache Juddi v3 installation (tomcat version) on my computer. What I want now is to publish a service whose WSDL is found at To achieve this, I created a standalone Java application (starting from the Juddi documentation) that publishes the service found at the above location.The publish part looks ok, but then I want to query the juddi database for the service but a field that should contain the found services is always  (). I really don't know what is wrong and I didn't find any good documentation or tutorial about this on the internet. you can find the sources of the program. Just unarchive it and go to the  folder. The application is found there.With out much Apache knowledge, It sounds as if  function is trying to retrieve information from the wrong sub folder when you do a query.  Try changing the location of the search Function so that it will search all folders/locations or a specific folder/location where the database is located. I could be wrong ( I have limited skills with Apache ).Good luck, sorry if this confused you or did not help.Edit: Sorry, I misread the question. I'm not sure what search criteria you've specified, but the server didn't return any results. When using the \"approximateMatch\" find qualifier, you really need to specify a wildcard character, such as % (any number of characters) or _ (a single character).Long story short, this is probably a bug that has since been fixed. Try a newer version
Java

I'm trying to send a request to an existing webservice. This webservice is not governed by me. The security policy of this webservice requires me to send my complete certificate chain in my SOAP request. My certificate chain contains 3 certificates. There are no issues with the setup of the certificate chain, as I'm able to test it's validity (and have done so).The security configuration for this setup (= sending the complete certificate chain in the request), is:I'm trying to achieve this through . Spring-WS uses spring-ws-security for security. Spring-ws-security delegates to xws-security. Xws-security comes in 2 flavors:andThe first one is used by Spring WS Security. The second is legacy.Applying my XWSS configuration in xws-security is done in a class called BinarySecurityToken. BinarySecurityToken has a field calledThe JavaDoc of valueType says it has support for X509PKIPathv1 (among others). However, it does not, as stated by this setter:The class MessageConstants does not (even) have a static for X509PKIPathv1. When I run my code, I get the expected result:I was able to look at the source code of the legacy . Despite my efforts, I have not found the source code of . However I believe the code is the same. I tried both libraries and both give me the same exception. I tried it, using the default spring-ws-security and using explicit dependency declarations to both libraries (one at a time).My questions: I have considered re-writing BinarySecurityToken, but that would probably also imply rewriting the X509 signing of SignatureProcessor in DSIG.Interesting problem you got there.As far as I could tell with my Google-fu, there exists support for #X509PKIPathv1 in some projects (e.g.,  or ), however it is not widespread and even application like Soap UI  for SOAP-WS.Not only that, but other languages/frameworks have the same lack of support, like  and , .What you could do, based on  and especially  is implementing your own WebServiceTemplate / WebServiceMessageSender.That is found here\n\nHave you tried those values specifically instead of a URL?
Java

I am creating a Blackberry application to display a full screen web view of a certain site. I have a working browserfield that displays properly but navigation from page to page is slower than that of the native browser. The browserfield does not seem to have a built in cache causing the load time to be slow. When I add the following code to manage the cache the site no longer displays properly.BrowserFieldScreen.java:CacheProtocolController.java:CacheManager.java:CacheManagerImpl.java:CacheItem.java:Any help that can be giving towards this will be greatly appreciated. This really has me stumped. Thanks. It looks like the caching only works at a certain level of the Blackberry libraries. I have added logic to check the current Software level and turn on the caching if it is supported by the device's current software level. This provides me with a good work around, but i would still like to know if there is a better way for the caching to work with all devices. Based on comments: The site no longer displaying properly pertains to site not displaying the proper layout, images and text. It basically give a white background with links and text displaying as a bulleted list, all formatting removed.I've been looking at your code, and the only thing I've found there's wrong with it, is you are completely ignoring the possibility of  returning less than zero (in ). Although this didn't happen to me at the stackoverflow.com page, some pages use , which means  is not present. This is, however, well handled, and should not cause the cache to fail (it would only be less effective).I suggest testing your code on smaller problems, one step at a time. First, create cacheable page that only contains some text (like \"hello\") without any HTML tags. That should work pretty well, and in case it does not, it shouldn't be hard to determine where the data are getting lost. Or try to manually create cache item that does not expire and contains a webpage with no (external) stylesheet nor images, and see if it's even possible to pass it to  the way you do it. Then build on, add an image, add a style sheet so you can corner the problem.The code is written very nicely, but at this point, it is not possible to help you because there are no evident flaws in the code and you are not explaining yourself very well, it is not clear how the error manifests itself, if it is every time or random, ... If I had a Blackberry device, I could probably try running the code for myself, but i don't.
Java

Just recently I have had a problem with a key store. I know there are plenty of questions about this problem already. I have read them all and Googled furiously.If I type in the password very quickly it works, sometimes.It seems that opening up Eclipse and entering the password the first time lets me use the keystore.Obviously, if all else fails, I will have to create a new key store. I really would like to get this resolved, I am just not sure what to do now besides republish with a new key.If the key cannot be recovered properly, I might open source it on Github.A special thanks to user Erhannis!Here is what I did:The command would error out on me each time: Since you told me we could extract private keys from the Java Keystore(.jks), I dug deeper and ended up using a variation of the command. I followed the links you posted  and :After extracting the private key and storing as PKCS12, I think extracted my private key and put it back into a brand new Java Keystore:I may have had the same problem.  I never did figure out why it was failing (though I wonder if it was because the keystore password was shorter than 6 digits), but I was able to copy my key into a new keystore, which I then renamed to replace the old one, and it mysteriously worked after that (using the new passwords).  Needed the key password, by the way.  Working off , I did the following:After double-checking that the new one worked, I just copied it over the old one.  Hope it works for you; good luck.Try to remove  folder in your workspace and clear all temp folders. If your keystore file isn't damaged and you have tried to reinstall Eclipse, ADT, Android SDK and Java SDK correctly, I don't see other possibly causes for this strange issue excluding .metadata cache files and\\or some temp corruption.Try to use  an utility for managing and examining keystores, keys, certificates, certificate requests, certificate revocation lists etc.I will suggest couple of more heat and trials.Have patience to apply these,Hopes this will help you.I had the same problem and I tried everything that is suggested in this thread but nothing was able to save my alias password. The point is that I was  about the password, since I had updated the app four times already. I was getting the  message.It appears that at the creation of the keystore using eclipse, This nasty bug was apparently fixed at a later version rendering me unable to sign my app with the password I thought was the correct one.Based on this SO link:  I would suggest that you .Are you storing values such as key.store.password or key.alias.password in your local.properties file?  Are either of those incorrect?I'm curious if there's some bug that occurs for keys created with JDK6 and verified in JDK7 - It would explain why the new keys you created for testing work, but the old one doesn't.  Try downgrading to JDK6 and see if that fixes it- Others have had jarsigner trouble in JDK7 that went away when they downgraded to 6.  If that works, file a bug report and demand a patch so you can safely upgrade to Java 7 :)I battled this issue as well recently, and tried all suggestions listed here and elsewhere. Finally identified a silly mistake that was causing this error at my end - I wanted to share this here in case it helps any of you.This is more likely to be the case if you, like me, have multiple Java versions on your machine and had upgraded JRE / JDK between the time you originally created the keystore and now when you're trying to sign the APK.For some reason, our compile instructions were referencing the full Java path like this:C:\\Progra~1\\Java\\jdk1.6.0_45\\bin\\jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore cre80ve.keystore unsigned.apk cre80veOne of the suggestions above got me thinking that it might not be a password issue at all, and it could be version incompatibilities causing the issue. So I ran the below command :keytool -list -keystore cre80ve.keystoreUsing the password that I knew was correct, and lo and behold, it confirmed that it was the right password.I then dropped the explicit reference in the path to the (older) Java version. This made it automatically pick up the latest version of Java (jdk1.8.0_31 in my case):jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore cre80ve.keystore unsigned.apk cre80veAnd everything started working fine! Bottomline: it may not be a password issue at all, but different versions of Java or the Android SDK causing the issue, so remember to check that out. And once it starts working, remember to backup your keystore and password in a safe place :-)My key alias stoped working sudenly. (Ok, after few updates of Android Studio and Java).I tried all solutions from this thread as well as from others. In my case the solution was surprising.\nI have the keystore with few aliases. None was working except one, which had password the same as keystore. But unfortunately it wasn't the one I needed. This made me thinking with no logic involved.\nI copied single alias to new keystore withAnd then I changed alias password to the same as keystore's password with:Finally I was able to sign my apk.\nIt looks like silly bug which can waste a day of development.
Java

Is it possible to do  a \"C like\" fork in java, using an new independent jvm process ?How?Funnily, I am just working on this: a Java process running other Java processes. I used the article  as a solid base, and  as a good advice how to gobble the output streams.PS.: For those wondering, I had to do that (instead of spawning new threads) because yet another Java process is checking the presence of these processes which are, normally, ran separately with shell commands.This answer is probably a little late but:seems to be exactly what your looking forThe  introduces  which addresses this use case.
Java

I wanted to find unused dependencies in my project. Is there any feature for this in gradle like in maven?In  Gradle has implemented  for finding and removing unwanted dependencyThis plugin has various rules.  is one of them. It has 3 specific characteristics.To apply the rule, add:Details of  is given in the last part.For an enterprise build, we recommend defining the lint rules in a init.gradle script or in a gradle script that is included via the Gradle apply from mechanism.For multimodule projects, we recommend applying the plugin in an allprojects block:To apply the rule, add:The rule inspects compiled binaries emanating from your project's  looking for class references, and matches those references to the dependencies that you have declared in your  block.For your kind information, I want to share about previous pluginsBut . After that there is no update.The project mentioned in the earlier answers seem to be dead. I use . Setup is simple:Then do:I've had a lot of luck using the .  To get started with it, add the following two things to your Gradle build script.andOnce those are in place, run .  If there are unused dependencies, you'll get a build failure that shows output similar to the text below, plus a list of the unused dependencies (both declared and transitive).  The build failure is really handy if you want to enforce that there should be no unused dependencies via a CI build.The projects on most of the historical answers are dead, but  appears to  be alive at the time of this writing (last commit was two days ago).It's not a built-in feature, and I'm not aware of a third-party plugin (but perhaps there is one).You can try  gragle pluginAlso, there is a thread () in gradle forum about this.
Java

I am looking for a high-performance, concurrent, MultiMap. I have searched everywhere but I simply cannot find a solution that uses the same approach as ConcurrentHashMap (Only locking a segment of the hash array).The multimap will be both read, added to and removed from often.The multimap key will be a String and it's value will be arbitrary.I need O(1) to find all values for a given key, O(N) is OK for removal, but O(logN) would be preferred.It is crucial that removal of the last value for a given key will remove the container of values from the key, as to not leak memory.HERE'S THE SOLUTION I BUILT, availbable under ApacheV2:\nWhy not wrap ConcurrentHashMap[T,ConcurrentLinkedQueue[U]] with some nice Scala-like methods (e.g. implicit conversion to Iterable or whatever it is that you need, and an update method)?Have you tried Google Collections?  They have various  implementations.There is  although I haven't used it.I made a  mixin which extends the mutable.MultiMap mixin and has a concurrent.Map[A, Set[B]] self type.  It locks per key, which has O(n) space complexity, but its time complexity is pretty good, if you aren't particularly write-heavy.you should give  a try. here is the .I had a requirement where I had to have a  where insertion on the Map be concurrent and also on the corresponding Set, but once a Key was consumed from the Map, it had to be deleted, think if as a Job running every two seconds which is consuming the whole  from an specific Key but insertion be totally concurrent so that most values be buffered when the Job kicks in, here is my implementation: I use Guava's helper class Maps to create the concurrent Maps, also, this solution emulates :I am a bit late on this topic but I think, nowadays, you can use Guava like this:Have you taken a look to  which is intended for Real time etc. and of course high performance.It's late for the discussion, yet...When it comes to high performance concurrent stuff, one should be prepared to code the solution. \nWith Concurrent the statement  has a complete meaning. \nIt's possible to implement the structure fully concurrent and lock-free. Starting base would be the NonBlocking Hashtable  and then depending how many values per key and how often need to add/remove some copy on write Object[] for values or an array based Set with semaphore/spin lock.
Java

While writing an answer to , I noticed a strange border case for JIT optimization. The following program is  a \"Microbenchmark\" and  intended to reliably measure an execution time (as pointed out in the answers to the other question). It is solely intended as an  to reproduce the issue:It basically runs the same loop, , where the limit  is once set to , and once to . When executing this on Win7/64 with JDK 1.7.0_21 and the timing results are as follows:Obviously, for the case of , the JIT does what one could expect: It detects that the loop is useless, and completely eliminates it. However, it does  remove the loop when it is running up to . This observation is confirmed by a look at the JIT assembly output when starting with The log contains the following assembly for the method that runs up to :One can clearly see the loop, with the comparison to  and the jump back to . In contrast to that, the assembly for the case where it is running up to :So my question is: What is so special about the  that prevents the JIT from optimizing it in the same way as it does for ? My guess would be that has to do with the  instruction, which is intended for  arithmetic, but that alone is not really a convincing reason. Can anybody explain this, and maybe even give a pointer to the OpenJDK HotSpot code where this case is treated?(An aside: I hope that the answer will also explain the different behavior between  and  that was asked for in the other question, assuming that the reason for the missing optimization is (obviously)  caused by the  loop limit)I have not dug up the Java Language Specification, but I'd guess that it has to do with this difference:I assume that the JIT compiler is \"reluctant\" to optimize-out loops with such corner conditions - there was a  w.r.t. loop optimization in integer overflow conditions, so that reluctance is probably quite warranted.There may also be some hard requirement that does not allow integer overflows to be optimized-out, although I somehow doubt that since integer overflows are not directly detectable or otherwise handled in Java.
Java

I am new to Scala started learning the language for fun and I am still trying to get my head around it. My understanding of Scala traits is that they are like java interfaces except that some methods can have an implementation.Java 8 is adding interfaces that can have default methods where an implementation can be provided. What are the similarities and differences between Java 8 interfaces and Scala traits?Motivations for  and  differ.The former was introduced to support safe API evolution and a limited form of multiple inheritance. With leveraging functional programming idioms in Project Lambda it's been beneficial to add, for example, a  method to  interface without altering all possible implementers (which is actually impossible to do without breaking backward compatibility). As a side effect this also offered a form of . were designed from scratch as building blocks for modular components composition. They are multiple inheritance friendly and don't have  by having strict rules on evaluation order of mix-ins due to linearization. They also support state, can reference the implementing class and place restrictions on which type can mix-in them. Look at Scala collections library where traits are used thoroughly.Note that with ,  now compiles to an interface.\nScala 2.12 is all about making optimal use of Java 8\u2019s new featuresSee  more the difference of implementation.
Java

What is the fastest-track set of resources for a C# developer wishing to hit the ground running in an enterprise-class Java team?I would suggest the following books:Java really is a different kettle of fish - there's a lot more to developing enterprise apps than there is to C#. You have all kinds of different things to worry about - EJB's, Enterprise vs. \"Personal\" runtimes, etc etc..The best advice I can give you is to use the NetBeans IDE. It is big, slow and cumbersome, but it does guide you for most of the way.The language itself should be simple to understand.  There are not as many language constructs, everything possible is done in libraries.The libraries will take some getting used to.  The two most critical things you can do to hit the ground running is:1: Use NetBeans or Eclipse and hit ctrl-space ALL THE TIME.  It's like the god key.2: bookmark this page: \n(or the one appropriate for your version of java--but the version doesn't matter all that much)  Each box in the graphic represents a library package, click one ones that you want to have an overview of. Try to get a handle on what each package does.  Browse the packages that are of interest and scan the classes.  This page also links to a lot of tutorials.After that it's just a matter of learning what other libraries you'll need to do your job.   there is a lot to J2EE if your group uses that, you'll probably end up using Hibernate, and you should look into messaging & maybe RMI (you may not be using it directly, but nearly all intra-java communications are based on RMI).remember ctrl-space.  It will give you parameters, lists of functions that match what you've typed so far, it fills in import declarations, it expands macros, ...Oh, and two other Eclipse tricks:\nctrl-shift-T.  \"Lookup Type\" (in eclipse, there is one in NetBeans but I can't remember the key sequence, ctrl-shift-O maybe).  Anyway, you type in a partial classname and it will give you a list of ALL matching classes in your project.  Click one to open it.ctrl-click.  Jumps to the declaration/definition of whatever you click on.Be prepared for abstractions. Lots and lots of abstractions ;)Read the API documentation for packages , , and . Seriously. The mark of an amateur, in java, is someone writing a loop when there is a method in java.util.Collections that already does what they want.It's good to read:Love it or Hate it! :-)
Java

I'm studying for the OCPJP exam, and so I have to understand every little strange detail of Java. This includes the order in which the pre- and post-increment operators apply to variables. The following code is giving me strange results:Shouldn't the answer be 11? Or maybe 13? But not 12!What is the result of the following code? the first   becomes 4. So you have .( becomes 5 after the 2nd , but that is discarded, because the assignment  overrides it)Your statement:is equivalent to any of those:Use any of those instead. means 'the value of a, and a is then incremented by 1'. So when you runthe first  is evaluated first, and produces the value 3.  is then incremented by 1. The second  is then evaluated.  produces the value of 4, and is then incremented again (but this doesn't matter now)So this turns into which equals 12.First build the syntax tree:To evaluate it start with the outer most element and descent recursively. For each element do:The  operator is special: It gets expanded to something like , but only evaluating the expression  once. Still the left side gets evaluated to a value(and not just a variable) before the right side gets evaluated to a value.This leads to:One thing to note here is that operator precedence has no direct influence on evaluation order. It only affects the form of the tree, and thus indirectly the order. But among siblings in the tree the evaluation is always left-to right, regardless of operator precedence. is a post increment, so value of expression is 3. is post increment, so value of expression is now 4.Expression evaluation is happening from left to right.Each time the you use a++, you're post-incrementing a. That means the first a++ evaluates to 3 and the second evaluates to 4. 3 * 4 = 12.There is a general lack of understanding about how operators work. Honestly, every operator is syntactic sugar.All you have to do is understand what is actually happening behind every operator. Assume the following:Compound operators can then be rewritten using these generalizations (please ignore the return types for the sake of simplicity):You can rewrite your example:asWhich can be split out using multiple variables:It's certainly more verbose that way, but it immediately becomes apparent that you never want to perform more than two operations on a single line.In case of :In case of :Main point to note here is that in this case compiler is solving from left to right and\nin case of post increment, value before increment is used in calculation and as we move from left to right incremented value is used. means return  and increment, so\n means 3 * 4Here is the java code:Here is the bytecode:Here is what happens:Pushes 3 into the stack then pops 3 from the stack and stores it at a.\nNow a = 3 and the stack is empty.Now it pushes the value from \"a\" (3) into the stack, and then increments a(3 -> 4). So now \"a\" equals \"4\" the stack equals {3}.Then it loads \"a\" again (4), pushes into the stack and increments \"a\".Now \"a\" equals 5 and the stack equals {4,3}So it finally pops the fisrt two values from the stack (4 and 3), multiplies and stores it back into the stack (12).Now \"a\" equals 5 and the stack equals 12.Finally is pops 12 from the stack and stores at a.TADA!It is 12.\nThe expression starts evaluating from left. So it does:Once the first part (3++) is evaluated, a is 4, so in the next part, it does a = 3*4 = 12. \nNote that the last post-increment (4++) is executed but has no effect since a is assigned with the value 12 after this.Just to make sure where to put  expression which changes the value based on the location.Everyone has clearly explained the first expression, and why the value of a is 12.For the follow on question, the answer is totally obvious to the casual observer:Pre & post-prefix increments have a higher precedence than the multiplication operator. hence the expression is evaluated as 3*4.If you use a++ the next time you use a it is incremented by one. So your doing
Java

What would be the easiest way to tell  the following:Managing Maven and Ivy repositories is sort of new to me - I tried the following steps and they result in :Maybe I misunderstand something - why would getting the  version of the dependency be such a hard task that?Gradle currently neither supports Maven's  (which is rarely used and deprecated) nor Ivy's . The general recommendation is to build against exact versions. Otherwise, the build can become a lottery.It can be quite useful sometimes to get the latest release - if for example you release often your own dependencies.You can get the latest version likeor better specify at least the major version likeCheck out the Gradle-Versions-Plugin. It does exactly what you want: For the installation, see the github page. Basically you need to add these two lines to your build.gradle - project file:Then you can use the plugin, by running this command in terminal in your project dir:And it will show you which dependencies are outdated!Latest Gradle User Guide mentions and explains plus sign in versions:From :From :
Java

I have been implementing an LLRB package that should be able to operate in either of the two modes, Bottom-Up 2-3 or Top-Down 2-3-4  ( - improved code, though dealing only with 2-3 trees , thanks to RS for pointer).Sedgewick provides a very clear description of tree operations for the 2-3 mode, although he spends a lot of time talking about the 2-3-4 mode. He also shows how a simple alteration of the order of color flipping during insertion can alter the behaviour of the tree (either split on the way down for 2-3-4 or split on the way up for 2-3):However, he glosses over deletion in 2-3-4 LLRBs with the following:His delete() function:My implementation correctly maintains LLRB 2-3 invariants for all tree operations on 2-3 trees, but fails for a subclass of right-sided deletions on 2-3-4 trees (these failing deletions result in right leaning red nodes, but snowball to tree imbalance and finally null pointer dereferencing). From a survey of example code that discusses LLRB trees and includes options for construction of trees in either mode, it seems that none correctly implements the deletion from a 2-3-4 LLRB (i.e. none has the extra rotation alluded to, e.g. Sedgewick's java above and ).I'm having trouble figuring out exactly what he means by \"extra rotation when the right node off the search path is a 4-node\"; presumably this is a rotate left, but where and when?If I rotate left passing upwards past a 4-node equivalent (i.e. RR node) or a right leaning 3-node equivalent (BR node) either before calling fixUp() or at the end of the fixUp function I still get the same invariant contradiction.Here are the tree states of the smallest failing examples I have found (generated by sequential insertion of elements from 0 to the respective maximum value).The first pair of trees shows the transition from invariant-conforming state prior to deletion of element 15 to obviously broken state after.The second is essentially the same as above, but with deletion of 16 of 0..16 (deletion of 15 results in the same topology). Note that the invariant contradiction manages to cross the root node.The key is going to be understanding how to revert the violations generated during the walk down the tree to the target node. The following two trees show how the first tree above looks after a walk down the left and right respectively (without deletion and before walking back up with fixUp()).After attempt to delete '-1' without fixUp:\nAfter attempt to delete '16' without fixUp:\nTrying rotate left on the walk back up when the node has only a red right child seems to be part of the solution, but it does not deal correctly with two red right children in a row, preceding this with a flipColor when both children are red seems to improve the situation further, but still leaves some invariants violated.If I further check whether the right child of a right child is red when its sibling is black and rotate left if this is true I only fail once, but at this point I feel like I'm needing a new theory rather than a new epicycle.Any ideas?For reference, my implementation is available  (No, it's not Java).Follow-up:Part of the reason I was interested in this was to confirm the claim by many that 2-3 LLRB trees are more efficient than 2-3-4 LLRB trees. My benchmarking has confirmed this for insertion and deletion (2-3 are about 9% faster), but I find that retrieval is very slightly faster for 2-3-4 trees.The following times are representative and consistent across runs:First column is bench name, second is number of operations, third is result. Benchmark on i5M 2.27.I have had a look at branch lengths for 2-3 tree and 2-3-4 trees and there is little in that to explain the retrieval difference (mean distance from root to node and S.D. of 1000 trees each with 10000 random inserts):Of key importance to testing this is that the implementation doesn't support deleting a nonexistent or previously deleted node! I spent way too long trying to figure out why my working solution was \"broken\". This can be fixed by doing a preliminary search for the key and returning false if it's not in the tree at all, and that solution was employed in the linked code at the bottom.It doesn't appear Sedgewick wrote a deletion for 2-3-4 deletion that is publicly available. His results specifically deal with 2-3 trees (he only makes cursory mention of 2-3-4 trees in that their average path length (and thus search cost), as well as that of other red-black trees, is indistinguishable from the 2-3 case). Nobody else seems to have one easily found, either, so here's what I found after debugging the problem:To begin, take Sedgewick's code and fix the out of date bits. In the slides  (pg 31) you can see that his code still uses the old representation of 4 nodes where it was done by having two left reds in a row, rather than balance. The first bit to write a 2-3-4 deletion routine, then, is to fix this so that we can do a sanity check which will help us verify our fixes later:Once we have this, we know a couple things. One, from the paper we see that 4 nodes should not be broken on the way up when using a 2-3-4 tree. Two, there's a special case for a right 4-node on the search path. There's a third special case that isn't mentioned, and that is when you are going back up a tree, you may end up where you have  be red, which would leave you invalid with just a rotate left. This is the mirror of the case described for insert on page 4 of the paper.The rotation fix for a 4-node you need is as follows:And this removes the splitting on 2-3-4, as well as adds the fix for the third special caseFinally, we need to test this and make sure it works. They don't have to be the most efficient, but as I found during the debugging of this, they have to actually work with the expected tree behavior (i.e. not insert/delete duplicate data)! I did this with a test helper methods. The commented lines were there for when I was debugging, I'd break and check the tree for obvious imbalance. I've tried this method with 100000 nodes, and it performed flawlessly:The complete source can be found .
Java

I'm trying to understand how java deals with ambiguities in function calls. In the following code, the call to  is ambiguous, but  is not!!!. I feel both are ambiguous, but why does this compile when I comment out the call to ? Why is  not ambiguous as well?EDIT: \nThis came up in comments: A number of IDEs report both as ambiguous - IntelliJ and Netbeans so far. However, it compiles just fine from command-line/maven.An intuitive way to test whether  is more specific than  is to see whether  can be implemented by invoking  with the same parametersIf there are varargs, we may need to expand a vararg so that 2 methods have same number of params.Let's check the first two s in your example(return types are not used in determining specificity, so they are omitted)Both compile, therefore each is more specific than the other, hence the ambiguity. Same goes for your s, they are more specific than each other. Therefore the call to  is ambiguous and shouldn't compile; otherwise it's a compiler bug.So that's what the spec says; but is it proper? Certainly,  looks more specific than . Actually if we have a concrete type instead of then only  is more specific than , not vice versa.The discrepancy arises from the magic of type inference. / calls a generic method without explicit type arguments, so the compiler tries to infer the type arguments. The  of type inference algorithm is to find type arguments ! No wonder L1 and L2 compile. L2 is actually infer to be Type inference tries to guess what the programmer wants, but the guess must be wrong sometimes. Our real intention is actually
Java

If one writes two public Java classes with the same case-insensitive name in different directories then both classes are not usable at runtime. (I tested this on Windows, Mac and Linux with several versions of the HotSpot JVM. I would not be surprised if there other JVMs where they are usable simultaneously.) For example, if I create a class named  and one named  like so:Three eclipse projects containing the code above are .If try I calling  on both classes like so:The typechecker succeeds, but when I run the class file generate by the code directly above I get:In Java, names are in general case sensitive. Some file systems (e.g. Windows) are case insensitive, so I'm not surprised the above behavior happens, but it seems . Unfortunately the Java specifications are oddly non-commital about which classes are visible. The  (Section 6.6.1, page 166) says:In Section 7.3, the JLS defines observability of a compilation unit in extremely vague terms:The  is similarly vague (Section 5.3.1):All of this leads to four questions in descending order of importance:The core bits and pieces of the language, plus supporting implementation classes. Not guaranteed to include any class that you write. (The normal JVM loads your classes in a separate classloader from the bootstrap one, and in fact the normal bootstrap loader loads its classes out of a JAR normally, as this makes for more efficient deployment than a big old directory structure full of classes.)Java loads classes by mapping the full name of the class into a filename that is then searched for on the classpath. Thus  goes to  and  goes to . Some filesystems mix these things up, and may serve the other up when one is asked for. Others get it right (in particular, the variant of the ZIP format used in JAR files is fully case-sensitive and portable). There is nothing that Java can do about this (though an IDE could handle it for you by keeping the  files away from the native FS, I don't know if any actually do and the JDK's  most certainly isn't that smart).However that's not the only point to note here: class files know internally what class they are talking about. The absence of the  class from the file just means that the load fails, leading to the  you received. What you got was a problem (a mis-deployment in at least some sense) that was detected and dealt with robustly. Theoretically, you could build a classloader that could handle such things by keeping searching, but  Putting the class files inside a JAR will fix things far more robustly; those are handled correctly.More generally, if you're running into this problem for real a lot, take to doing production builds on a Unix with a case-sensitive filesystem (a CI system like Jenkins is recommended) and Donal's fine explanation leaves little to add, but let me briefly muse on this phrase:  Names and Strings in general are never case-insensitive , it's only there  that can be. And secondly, Java doesn't do such an interpretation. So, a correct phrasing of what you had in mind would be: Don't think just about folders.Use explicit different namespaces (\"packages\") for your classes, and maybe use folders to match your classes.When I mention \"packages\", I don't mean \"*.JAR\" files, but, just the concept of:When you do not specify a package for your code, the java tools (compiler, I.D.E., whatever), assume to use the same global package for all. And, in case of several similar classes, they have a list of folders, where to look for.Packages are like \"virtual\" folders in your code, and apply to all your packages on your classpath, or installation of Java.  You can have several classes, with the same I.D., but, if they are in different package, and you specify which package to look for, you won't have any problem.Just my 2 cents, for your cup of Java coffe
Java

I am learning programming (python and algo\u2019s) and was trying to work on a project that I find interesting.   I have created a few basic python scripts but I\u2019m not sure how to approach a solution to a game I am trying to build.users will be given items with a value. For exampleThey will then get a chance to choose any combo of them they like (i.e. 100 apples, 20 pears, and 1 oranges).  The only output the computer gets is the total value(in this example, its currently $143).  The computer will try to guess what they have. Which obviously it won\u2019t be able to get correctly the first turn.The next turn the user can modify their numbers but no more than 5% of the total quantity (or some other percent we may chose. I\u2019ll use 5% for example.). The prices of fruit can change(at random) so the total value may change based on that also(for simplicity I am not changing fruit prices in this example). Using the above example, on day 2 of the game, the user returns a value of $152 and $164 on day 3. Here's an example.*(I hope the tables show up right, I had to manually space them so hopefully its not just doing it on my screen, if it doesn't work let me know and I'll try to upload a screenshot).I am trying to see if I can figure out what the quantities are over time(assuming the user will have the patience to keep entering numbers). I know right now my only restriction is the total value cannot be more than 5% so I cannot be within 5% accuracy right now so the user will be entering it forever. Here\u2019s my solution so far(not much).  Basically I take all the values and figure out all the possible combos of them(I am done this part).  Then I take all the possible combos and put them in a database as a dictionary(so for example for $143, there could be a dictionary entry {apple:143, Pears:0, Oranges :0}..all the way to  {apple:0, Pears:1, Oranges :47}.  I do this each time I get a new number so I have a list of all possibilities.  Here\u2019s where I\u2019m stuck.  Is using the rules above, how can I figure out the best possible solution? I think I\u2019ll need a fitness function that automatically compares the two days data and removes any possibilities that have more than 5% variance of the previous days data.So my question with user changing the total and me having a list of all the probabilities, how should I approach this? What do I need to learn? Is there any algorithms out there  or theories that I can use that are applicable? Or, to help me understand my mistake, can you suggest what rules I can add to make this goal feasible(if its not in its current state. I was thinking adding more fruits and saying they must pick at least 3,etc..)?  Also, I only have a vague understanding of genetic algorithms but I thought I could use them here, if is there something I can use?I'm very very eager to learn so any advice or tips would be greatly appreciated(just please don't tell me this game is impossible). Thanks in advance.UPDATE: Getting feedback that this is hard to solve.   So I thought I'd add another condition to the game that won't interfere with what the player is doing(game stays the same for them) but everyday the value of the fruits change price(randomly). Would that make it easier to solve? Because within a 5% movement and certain fruit value changes, only a few combo's are probable over time. Day 1, anything is possible and getting a close enough range is almost impossible, but as the prices of fruits change and the user can only choose a 5% change, then shouldn't(over time) the range be narrow and narrow. In the above example, if prices are volatile enough I think I could brute force a solution that gave me a range to guess in, but I'm trying to figure out if there's a more elegant solution or other solutions to keep narrowing this range over time.UPDATE2: After reading and asking around, I believe this is a hidden markov/Viterbi problem that tracks the changes in fruit prices as well as total sum(weighting the last data point the heaviest).  I'm not sure how to apply the relationship though.  I think this is the case and could be wrong but at the least I'm starting to suspect this is a some type of machine learning problem.Update3: I am created a test case(with smaller numbers) and a generator to help automate the user generated data and I am trying to create a graph from it to see what's more likely.\nHere's the code, along with the total values and comments on what the users actually fruit quantities are.We'll combine graph-theory and probability:On the 1st day, build a set of all feasible solutions. Lets denote the solutions set as A1={a1(1), a1(2),...,a1(n)}.On the second day you can again build the solutions set A2.Now, for each element in A2, you'll need to check if it can be reached from each element of A1 (given x% tolerance). If so - connect A2(n) to A1(m). If it can't be reached from any node in A1(m) - you can delete this node.Basically we are building a connected directed acyclic graph.All paths in the graph are equally likely. You can find an exact solution only when there is a single edge from Am to Am+1 (from a node in Am to a node in Am+1).Sure, some nodes appear in more paths than other nodes. The probability for each node can be directly deduced based on the number of paths that contains this node.By assigning a weight to each node, which equals to the number of paths that leads to this node, there is no need to keep all history, but only the previous day.Also, have a look at  - A question I asked a while ago. The accepted answer is a great way to enumarte all combos in each step.This problem is impossible to solve.\nLets say that you know exactly for what ratio number of items was increased, not just what is maximum ratio for this. User has N fruits and you have D days of guessing.In each day you get N new variables and then you have in total D*N variables.For each day you can generate only 2 equations. One equation is sum of  n_item*price and other is based on know ratio.  In total you have at most 2*D equations if they are all independent. 2*D < N*D for all N > 2First, I would like to state what I see two main problems here:Let's lay down some bases for the upcoming examples:In order to solve this more easily , which makes the algorithm converge faster:This rule enables us to rule out solutions more easily. And, with non-tiny ranges, renders  still useless, just like your original problem and rules.In my humble opinion, this rule is not the  of the game but only a facilitator, enabling the computer to solve the problem.For starters,  can be solved using a  to find a set of potential solutions. The technique is simple: Generate random numbers for item values and quantities (within their respective accepted range). Repeat the process for the required number of items. Verify whether or not the solution is acceptable. That means verifying if items have distinct values and the total is equal to our target total (say, 143.)While this technique has the advantage of being easy to implement it has some drawbacks:How to get around these drawback? Well...Note that the more you restrict the ranges, the less useful while be the Monte Carlo algorithm is, since there will be few enough valid solutions to iterate on them all in reasonable time. For constraints { 3, [1-10], [0-100] } there is around 741,000,000 valid solutions (not constrained to a target total value.) Monte Carlo is usable there. For { 3, [1-5], [0-10] }, there is only around 80,000. No need to use Monte Carlo; brute force  loops will do just fine.I believe the  is what you would call a  (or CSP.)Given the fact that  is a CSP, I would go ahead and call , and the problem in general, a  (or DCSP.)One technique used with CSPs that might be useful to this problem is called :For this to work, you need to get a new set of possible solutions every day; Use either brute force or Monte Carlo. Then, compare solutions of D to D and keep only solutions that can succeed to previous days' solutions without violating constraints.You will probably have to keep an history of what solutions lead to what other solutions (probably in a directed graph.) Constraint recording enables you to  possible add-remove quantities and rejects solutions based on that.There is a lot of other steps that could be taken to further improve your solution. Here are some ideas:Given all of this, try and figure out a ranking system based on occurrence of solutions and heuristics to determine a candidate solution.I wrote a program to play the game.  Of course, I had to automate the human side, but I believe I did it all in such a way that I shouldn't invalidate my approach when played against a real human.I approached this from a machine learning perspective and treated the problem as a hidden markov model where the total price was the observation.  My solution is to use a particle filter.  This solution is written in Python 2.7 using NumPy and SciPy.I stated any assumptions I made either explicitly in the comments or implicitly in the code.  I also set some additional constraints for the sake of getting code to run in an automated fashion.  It's not particularly optimized as I tried to err on the side comprehensibility rather than speed.Each iteration outputs the current true quantities and the guess.  I just pipe the output to a file so I can review it easily.  An interesting extension would be to plot the output on a graph either 2D (for 2 fruits) or 3D (for 3 fruits).  Then you would be able to see the particle filter hone in on the solution.Update:Edited the code to include updated parameters after tweaking.  Included plotting calls using matplotlib (via pylab).  Plotting works on Linux-Gnome, your mileage may vary.  Defaulted NUM_FRUITS to 2 for plotting support.  Just comment out all the pylab calls to remove plotting and be able to change NUM_FRUITS to anything.Does a good job estimating the current fxn represented by UnknownQuantities X Prices = TotalPrice.  In 2D (2 Fruits) this is a line, in 3D (3 Fruits) it'd be a plane.  Seems to be too little data for the particle filter to reliably hone in on the correct quantities.  Need a little more smarts on top of the particle filter to really bring together the historical information.  You could try converting the particle filter to 2nd- or 3rd-order.Update 2:I've been playing around with my code, a lot.  I tried a bunch of things and now present the final program that I'll be making (starting to burn out on this idea).Changes:The particles now use floating points rather than integers.  Not sure if this had any meaningful effect, but it is a more general solution.  Rounding to integers is done only when making a guess.Plotting shows true quantities as green square and current guess as red square.  Currently believed particles shown as blue dots (sized by how much we believe them).  This makes it really easy to see how well the algorithm is working.  (Plotting also tested and working on Win 7 64-bit).Added parameters for turning off/on quantity changing and price changing.  Of course, both 'off' is not interesting.  It does a pretty dang good job, but, as has been noted, it's a really tough problem, so getting the exact answer is hard.  Turning off CHANGE_QUANTITIES produces the simplest case.  You can get an appreciation for the difficulty of the problem by running with 2 fruits with CHANGE_QUANTITIES off.  See how quickly it hones in on the correct answer then see how harder it is as you increase the number of fruit.You can also get a perspective on the difficulty by keeping CHANGE_QUANTITIES on, but adjusting the MAX_QUANTITY_CHANGE from very small values (.001) to \"large\" values (.05).One situation where it struggles is if on dimension (one fruit quantity) gets close to zero.  Because it's using an average of particles to guess it will always skew away from a hard boundary like zero.In general this makes a great particle filter tutorial.\nFrom my school years, I would say that if we make abstraction of the 5% changes, we have everyday an equation with 3 unknown values (sorry I don't know the maths vocabulary in english), which are the same values as previous day.\nAt day 3, you have 3 equations, 3 unknown values, the solution should be direct.I guess the 5% change each day may be forgotten if the values of the 3 elements are different enough, because, as you said, we will use approximations and round the numbers.\nToo many unknown - and changing - values in this case, so there is no direct solution I know of. I would trust Lior on this, his approach looks fine! (if you have a limited range for prices and quantities)
Java

Can I move the instruction pointer  to a line of my choice (within the current method) while debugging a Java program in Eclipse (Galileo)?It's straightforward to drag the instruction pointer to the desired line within a method in Visual Studio, but I don't see a way to do that in Eclipse (and don't find anything about it in the docs or on google).This is not possible.If you simply want to execute some code at the current place you can use the  view and enter your code as an expression. The methods called by the expression evaluation will run in the current debugging context.This is possible...I like ankon's answer best, but another option (that will only work for your specific instance -- if that) is to stop at a breakpoint on your  and modify the variable(s) evaluated in the conditional such that it returns false (from the \"Variables\" view, right click on a variable and click \"Change Value...\")I thought that this was totally possible in older versions of eclipse, I thought I had the memory of doing it, but I guess I just implanted that memory when I worked in Visual Studio. From what I'm reading it might come to the jvm and not eclipse itself, there are pages where it's suggested that the jvm cannot handle that.In my opinion Eclipse is many many times better than VS, I worked extensively in both and since I discovered Eclipse I was always in pain when I had to work in VS. But not having this feature is definitely hurting right now hehe.You can jump directly to any other method call inside of the currently debugged method. Select some method call below your current instruction pointer and use \"\" from the context menu.unfortunately not possible to step forward with instruction pointer (program counter), so what you need to do instead is to introduce your own \"debugging\" variables that you can test on - lets say you want to step around a loop that takes too long, then add a variable and test on its increased value and then encapsulate the loop in an if with that variable. I know this is ugly, but it gets it done - or you could just develop in C++ :-) Just right click on desired line and choose run to line.That's it...Put the cursor on the line of your choice and either hit ctrl-R (\"Run to line\") or right-click and select \"Run to line\" from the context menu.
Java

I have recently started working with Cassandra Database. Now I am in the process of evaluating which  we should go forward with. I have seen various post on stackoverflow about which client to use for Cassandra but none has very definitive answer. My team has asked me to do some research on this and come up with certain  for each  in Java.As I mentioned, I recently got involved with  so not have that much idea why certain people choose  and why certain people go with  and some other clients. I know brief things about each of the Cassandra clients, by which I mean I am able to make that work and start reading and writing to Cassandra database.Below is the information I have so far.Below are our priorities in deciding -Can anyone provide some thoughts on this? And also any pros and cons for each  and also which client can fulfill my requirements will be of great help as well.I believe, mainly I will be revolving around  I guess basis on my research so far. But don't have certain information to back my research and present it to my team.Any comparison between Astyanax client and New Datastax client(which uses new Binary protocol) will be of great help.It will be of great help to me in my research and will get lot of knowledge on this from different people who have used different clients in the past.Thrift is becoming more of a legacy API:So I'd avoid Thrift based APIs (thrift is only kept for backwards compatibility).In saying that if you do need to use a thrift based API I'd go for Astyanax.\nAstyanax is very easy to use (compared to other thrift APIs but my personal experience is that Datastax's driver is even easier).So you should have a look at  API ()? I'm not sure if there any compiled versions of the API for download but you can easily build it with Maven. Also if you take a look at the GitHub repo's commit logs it undergoes very frequent updates. The driver works exclusively with CQL3 and is asynchronous but be warned that Cassandra 1.2 is the earliest supported version. \nAstyanax is thrift based and Datastax's drive is the binary protocol. Here are the latest  I could find between thrift and CQL (note these are definitely out of date). But in fairness the small difference in performance shown in these benchmarks will rarely matter. \nDatastax's  support is a definite advantage over Astyanax (Netflix  it but decided not to).  \nI cant really argue against . The documentation is excellent and its updated fairly frequently. Their wiki includes code examples, and you can find tests in the source code if you need to see the code at work. I struggled to find any documentation of the Datastax driver however test are provided in the GitHub repository so that is a starting point.Also have a look at  (well.. not my one anyway) It looks into some advantages/disadvantages of Thrift and CQL.I would recommend Datastax java driver for Cassandra .For JPA like support try my mapping tool.\nAnnotation driven \nNo mapping files, no scripts, no configuration files. \nNo need for DDL scripts.\nSchema automatically synchronized with the entity definition.Usage sample:available on maven centralI would also add decent support as well.  We post answers to playORM all the time on stack overflow ;).  It also is about to start supporting mongodb(work is nearly finished) so any clients can run on mongodb or cassandra.  It has it's own query language such that this port works just fine.  You always have access to the raw astyanax interface too when really need the speed.Also, your note on asynch...thrift previously did not support asynch so no clients did either as they generated the thrift code.  Since that has changed, I don't know of a client that has added the asynch stuff in.I know hbase has an asynch client though.  Anyways, just thought I would add my 2 cents in case it helps a little.EDIT: I was recently in the cassandra-thrift generated source code and it is not a very good api for async development with send and a recv() method but you don't know when to call the recv method.  Aaron morton on cassandra user list has a blog on how you can really do it but it is not clean at all...have to grab the selector from thrift deep down and do some stuff so you know when to call the recv method...pretty nasty stuff.later,\nDeanI've used Hector, Astyanax and Thrift directly.  I've also used the Python client PyCassa.The features that I found important and differentiating were:One of the major issues is getting the types correct.  You want to be able to pass in longs, Strings, byte[], etc..  Both Hector and Astyanax solve this by using Serializer objects.  In Astyanax you specify them higher up the chain so you have to specify them less often.  In Hector the syntax is often very clunky and hard to adapt if you change your schema.Since Python has dynamic types, it is much easier to deal with this in PyCassa.  Since it's not an option for you I won't say much about it, but I found it easiest to use (by far) but also quite slow.Composite column support is very confusing in Hector.  Astyanax has annotations to greatly simplify this.As far as I know, the connection pooling is the same for Hector and Astyanax.  Both will avoid downed hosts and discover new ones added to the ring.  Both of these features a crucial to reliability and maintainability.  Pelops appears to have these features but I've never tried it.A key difference between Astyanax and Hector is the latency optimizations.  Astyanax has the ability to route read and write requests to a replica node, potentially avoiding an extra networking hop.  This can reduce the latency by a few milliseconds.At last look, Astyanax had poor documentation, but it seems much improved now.The only advantage of Hector I can see today is that it is much more widely used so probably less buggy.  But Astyanax has a better feature set.I have a similar recommendation as Valchkou. DataStax java CQL driver, is very good. I tried astyanax, kundera and buffalosw's playorm. Astyanax is very low level and some what complex. Kundara and playorm are generic ORMs for nosql databases, and are complex to setup and to get started.Datastax apis are pretty much similar to a JDBC driver and you have to embed CQL statements in your DAO and write several lines of code to load and save your entities. To solve this problem, I wrote a java object mapper called cassandra-jom, built around datastax cql driver. Cassandra-jom annotations are very similar to JPA/Hibernate annotations and can even create/update your column family schema from your object model. It is easy to use and reliable and used in my other live web applications. Check it out at its github page.
Java

What exactly makes the JVM (in particular, Sun's implementation) slow to get running compared to other runtimes like CPython? My impression was that it mainly has to do with a boatload of libraries getting loaded whether they're needed or not, but that seems like something that shouldn't take 10 years to fix.Come to think of it, how does the JVM start time compare to the CLR on Windows? How about Mono's CLR?UPDATE: I'm particularly concerned with the use case of small utilities chained together as is common in Unix. Is Java now suitable for this style? Whatever startup overhead Java incurs, does it add up for every Java process, or does the overhead only really manifest for the first process?Here is  (with some references).It appears that most of the time is taken just loading data (classes) from disk (i.e. startup time is I/O bound). Just to note some solutions:There are two mechanisms that allow to faster startup JVM.\nThe first one, is the class data sharing mechanism, that is supported since Java 6 Update 21 (only with the HotSpot Client VM, and only with the serial garbage collector as far as I know)To activate it you need to set  (on some implementations:  ) JVM options.To read more about the feature you may visit:\nThe second mechanism is a Java Quick Starter. It allows to preload classes during OS startup, see:\n for more details.Running a trivial Java app with the 1.6 (Java 6) client JVM seems instantaneous on my machine.  Sun has attempted to tune the client JVM for faster startup (and the client JVM is the default),  so if you don't need lots of extra jar files, then startup should be speedy.If you are using Sun's HotSpot for x86_64 (64bit compiled), note that the current implementation only works in server mode, that is, it precompiles every class it loads with full optimization, whereas the 32bit version also supports client mode, which generally postpones optimization and optimizes the most CPU-intensive parts only, but has faster start-up times.See for instance:That being said, at least on my machine (Linux x86_64 with 64bit kernel), the 32bit HotSpot version supports both client and server mode (via the -client and -server flags), but defaults to server mode, while the 64bit version only supports server mode.It really depends on what you are doing during the start up.  If you run Hello World application it takes 0.15 seconds on my machine.  However, Java is better suited to running as a client or a server/service which means the startup time isn't as important as the connection time (about 0.025 ms) or the round trip time response time (<< 0.001 ms).There are a number of reasons:I'm not sure about the CLR, but I think it is often faster because it caches a native version of assemblies for next time (so it doesn't need to JIT). CPython starts faster because it is an interpreter, and IIRC, doesn't do JIT.In addition to things already mentioned (loading classes, esp. from compressed JARs); running in interpreted mode before HotSpot compiles commonly-used bytecode; and HotSpot compilation overhead, there is also quite a bit of one-time initialization done by JDK classes themselves.\nMany optimizations are done in favor of longer-running systems where startup speed is less of a concern.And as to unix style pipelining: you certainly do NOT want to start and re-start JVM multiple times. That is not going to be efficient. Rather chaining of tools should happen within JVM. This can not be easily intermixed with non-Java Unix tools, except by starting such tools from within JVM.All VMs with a rich type system such as Java or CLR will not be instanteous when compared to less rich systems such as those found in C or C++. This is largely because a lot is happening in the VM, a lot of classes get initialized and are required by a running system. Snapshots of an initialized system do help but it still costs to load that image back into memory etc.A simple hello world styled one liner class with a main still requires a lot to be loaded and initialized. Verifying the class requires a lot of dependency checking and validation all which cost time and many CPU instructions to be executed. On the other hand a C program will not do any of these and will amount of a few instructions and then invoke the printer function.
Java

I saw this list of major version numbers for Java in another post:References:\nThese come from the class version.  If you try to load something compiled for java 6 in a java 5 runtime you'll get the error, incompatible class version, got 50, expected 49.  Or something like that.See  in byte offset 7 for more info.Additional info can also be found .I found a list of Java class file versions on the Wikipedia page that describes the class file format:Under byte offset 6 & 7, the versions are listed with which Java VM they correspond to.
Java

I have multiple view resolvers in a Spring configuration and wanted to use different view resolvers for different requests.Example: For URLs starting with , use Birt view resolver, and for ajax calls use Tiles resolver and so on.Tried setting order property, but all views are resolved by .You absolutely can.  has a single method,  which returnsYour  beans are registered. When a view name is returned by a handler, Spring will iterate through each , invoking their  method with the given name. If the method returns non, that  is used. If  is returned, then it continues iterating.So the implementation has to return  if Spring is to skip it.There are some implementations that never return . This seems to be the case with your custom  classes. If the  returns a , even if that  will eventually fail to be rendered, Spring will use it.You either need to fix that or order your  beans. For example, you can order them with the  interface. Have your classes implement that interface and return an appropriate value.
Java

Servlet-3.0 API allows to detach a request/response context and answer to it later.However if I try to write a big amount of data, something like:It may actually block - and it does block in trivial test cases - for both Tomcat 7 and Jetty 8. The tutorials recommend to create a thread pool that would\nhandle such a setup - witch is generally the counter-positive to a traditional 10K architecture.However if I have 10,000 open connections and a thread pool of let's say 10 threads, \nit is enough for even 1% of clients that have low speed connections or just blocked\nconnection to block the thread pool and completely block the comet response or\nslow it down significantly.The expected practice is to get \"write-ready\" notification or I/O completion notification \nand than continue to push the data.How can this be done using Servlet-3.0 API, i.e. how do I get either:If this is not supported by the Servlet-3.0 API, are there any Web Server specific APIs (like Jetty Continuation or Tomcat CometEvent) that allow to handle such events truly asynchronously without faking asynchronous I/O using thread pool.Does anybody know?And if this is not possible can you confirm it with a reference to documentation?I had attached the code below that emulates event-stream.Notes:In such an example I explicitly defined thread pool of size 1 to show the problem:I want to solve such a problem without using thread pool, because with 1000-5000 open\nconnections I can exhaust the thread pool very fast.The sample code below.The sample above uses threads to prevent blocking... However if the number of blocking clients is bigger than the size of the thread pool it would block.How could it be implemented without blocking?I've found the   API tricky to implement correctly and helpful documentation to be sparse. After a lot of trial and error and trying many different approaches, I was able to find a robust solution that I've been very happy with. When I look at my code and compare it to yours, I notice one major difference that may help you with your particular problem. I use a  to write the data and not a . Here my go-to Asynchronous Servlet class adapted slightly for your  case:During my research on this topic, this thread kept popping up, so figured I mention it here:Servlet 3.1 introduced async operations on  and . See .An example can be found at this might be helpfulWe can't quite cause the writes to be asynchronous. We realistically have to live with the limitation that when we do write something out to a client, we expect to be able to do so promptly and are able to treat it as an error if we don't. That is, if our goal is to stream data to the client as fast as possible and use the blocking/non-blocking status of the channel as a way to control the flow, we're out of luck. But, if we're sending data at a low rate that a client should be able to handle, we are able at least to promptly disconnect clients that don't read quickly enough.For example, in your application, we send the keepalives at a slow-ish rate (every few seconds) and expect clients to be able to keep up with all the events they're being sent. We splurge the data to the client, and if it can't keep up, we can disconnect it promptly and cleanly. That's a bit more limited than true asynchronous I/O, but it should meet your need (and incidentally, mine).The trick is that all of the methods for writing out output which just throw IOExceptions actually do a bit more than that: in the implementation, all the calls to things that can be interrupt()ed will be wrapped with something like this (taken from Jetty 9):(I also note that this  happen in Jetty 8, where an InterruptedException is logged and the blocking loop is immediately retried. Presumably you make to make sure your servlet container is well-behaved to use this trick.)That is, when a slow client causes a writing thread to block, we simply force the write to be thrown up as an IOException by calling interrupt() on the thread. Think about it: the non-blocking code would consume a unit of time on one of our processing threads to execute anyway, so using blocking writes that are just aborted (after say one millisecond) is really identical in principle. We're still just chewing up a short amount of time on the thread, only marginally less efficiently.I've modified your code so that the main timer thread runs a job to bound the time in each write just before we start the write, and the job is cancelled if the write completes quickly, which it should.A final note: in a well-implemented servlet container, causing the I/O to throw out  to be safe. It would be nice if we could catch the InterruptedIOException and try the write again later. Perhaps we'd like to give slow clients a subset of the events if they can't keep up with the full stream. As far as I can tell, in Jetty this isn't entirely safe. If a write throws, the internal state of the HttpResponse object might not be consistent enough to handle re-entering the write safely later. I expect it's not wise to try to push a servlet container in this way unless there are specific docs I've missed offering this guarantee. I think the idea is that a connection is designed to be shut down if an IOException happens.Here's the code, with a modified version of RunJob::run() using a grotty simple illustration (in reality, we'd want to use the main timer thread here rather than spin up one per-write which is silly).Is Spring an option for you?  Spring-MVC 3.2 has a class called , which will gracefully handle your \"10,000 open connections/10 server pool threads\" scenario.Example: I've had a quick look at your listing, so I may have missed some points.\nThe advantage of a pool thread is to share thread resources between several tasks over time. Maybe you can solve your problem by spacing keepAlive responses of different http connections, instead of grouping all of them at the same time. 
Java

I am trying to use hibernate annotation for writing a model class for my database tables.I have two tables each having a primary key User and Question. Question Table.And I have one more table, UserAnswer, which has userId and questionId as foreign keys from the above two tables.But I am unable to find how I can reference these constraints in the UserAnswer table.Please help me achieve this?\nThanks in advance. is not the appropriate annotation. You don't want to store a whole User or Question in a column. You want to create an association between the entities. Start by renaming  to , since an instance represents a single question, and not several ones. Then create the association:The  explains that. Read it. And also read the javadoc of the annotations.The  annotation can be used above that property or field  of class that is being referenced from some other entity.
Java

What is the Java 8 functional interface for a method that takes nothing and returns nothing? I.e., the equivalent to to the C# parameterless  with  return type?If I understand correctly you want a functional interface with a method . In which case you can simply use a .
Java

I heard a lot of good things about  and the  Web framework recently, especially from  hence, I might use this technology in my next projects.  Share your experiences on the Scala/Lift Platform.I'm working on my second Lift app at the moment - it's very strongly in Lift's sweet spot - very realtime, lots of concurrency.The first one we wimped out after a few days of wrestling with the DB layer (it's better now, I am led to believe), and went to Play/Scala instead.  That maximized the existing knowledge of our team and made it possible to make deadline.  But the hot code reloading pretty much stopped happening once our project got moderately large (kept running out of PermGen - it's an ongoing problem with Scala compilation pretty much anywhere), and the manual juggling of things like method call parameters and location security in different places in the website got quite cumbersome.  We were glad when it was done - in the same way as I tended to find Rails 1, the speed increases shrank as the project size increased, and by the end it was every bit as tedious and error-prone as working in a Velocity/Spring/XML++ whatever).This time we've been committed to just working out how Lift does what it does, and the right ways to do things.  This has meant a lot of casual browsing through the mailing list (discussions that are several versions old are often still relevant), and most importantly a new ethos for the team.  It's been necessary to internalize very strongly the motto:\"This is feeling hard and repetitive.  I bet they made an easier way to do this.\"So far Lift has never disappointed us.  I'm not talking, by the way, about stuff like the Sitemap and list concatenation syntax - you MUST have a pretty good handle on functional Scala, or you just won't be able to read the source code or even configure your app.That said it's not crazy IO monads or anything, just some common idioms that you'd pick up in a few weeks of Scala anyway.The biggest problem for us has been a slow compile cycle.  It takes about 20 seconds to jetty:run our project, which is a different feeling to Play which (when it's working) hot compiles all your stuff.  On the other hand, we actually timed that the other day when one of our devs complained about it, and it worked out that although Play technically hot compiled it, the page still took 12 seconds to load in Dev mode.  So there's not a huge loss, it just feels a bit slow to have to hop out to the command line.Lift lets you do a great deal, and there are many places in our app where (because it's available), we've said \"Yeah, we really WOULD prefer to have that live updated immediately to all viewers of that page, instead of them discovering later that they're out of date (think of all the times you've posted simultaneously to someone on SO, with the same answer).  COMET is everywhere, it turns out - it's not a specialist use case, it's the way things should work.  And Lift makes it really easy.We also love the strong, programatically configurable, security model - once we switched our mindsets to \"We have to whitelist every location, and specify the necessary entrance conditions\", we never saw another session problem - you know, those ones where you assumed that the user would have traversed a certain path, and thus would know a whole bunch of parameters?  Like, a valid username, and an area of interest or whatever?  (I'm being intentionally vague).  That can be one of the awkward things about a stateful framework, that you're going to want to have usable state when the user hits a page, instead of (for instance) just demanding that all the state gets carried along at each request.My takeaway from this renewed shot at Lift:It's worth it.  Not just to build the app that you're trying to build, but to build the app that you didn't know you needed.There's a lot of head scratching, but not a lot of code.  And when it works it really works.  It's fast, and clean, and for all of the miracles that it's working between the browser and the server, I've never yet seen it get confused.I'm developing enterprise financial application in Lift for more than 6 months and I was JAVA programmer former. I have noticed a few points, which could help you:I can't imagine that I have to return to JAVA code now. But my little advice is to try to code some simple application and you will see.
Java

If I am creating a java class to be generic, such as:  How can one determine internally to that class, what 'T' ended up being? I've poked around the Java API and played with the Reflection stuff, instanceof, getClass, .class, etc, but I can't seem to make heads or tails of them. I feel like I'm close and just need to combine a number of calls, but keep coming up short.To be more specific, I am attempting to determine whether the class was instantiated with one of 3 possible types.I've used a similar solution to what he explains here for a few projects and found it pretty useful.The jist of it is using the following: In contrast to .NET Java generics are implemented by a technique called \"type erasure\".What this means is that the compiler will use the type information when generating the class files, but not transfer this information to the byte code. If you look at the compiled classes with javap or similar tools, you will find that a  is a simple  (of ) in the class file, just as it was in pre-Java-5 code.Code accessing the generic List will be \"rewritten\" by the compiler to include the casts you would have to write yourself in earlier versions. In effect the following two code fragments are identical from a byte code perspective once the compiler is done with them:Java 5:Java 1.4 and before:When reading values from a generic class in Java 5 the necessary cast to the declared type parameter is automatically inserted. When inserting, the compiler will check the value you try to put in and abort with an error if it is not a String.The whole thing was done to keep old libraries and new generified code interoperable without any need to recompile the existing libs. This is  a major advantage over the .NET way where generic classes and non-generic ones live side-by-side but cannot be interchanged freely.Both approaches have their pros and cons, but that's the way it is in Java.To get back to your original question: You will not be able to get at the type information at runtime, because it simply is not there anymore, once the compiler has done its job. This is surely limiting in some ways and there are some cranky ways around it which are usually based on storing a class-instance somewhere, but this is not a standard feature. Because of , there is no way to do this directly. What you could do, though, is pass a  into the constructor and hold onto it inside your class. Then you can check it against the three possible  types that you allow.However, if there are only three possible types, you might want to consider refactoring into an  instead.The Problem is that most of the Generic stuff will disappear during compilation.One common solution is to save the type during the creation of the Object. For a short introduction in the Type Erasure behaviour of java read this  If you know a few specific types that are meaningful, you should create subclasses of your generic type with the implementation.SoAnd thenThe whole point of a generic class is that you dont need to know the type that is being used....It looks like what you want is in fact not a Generic class, but an interface with a number of different implementations. But maybe it would become clearer if you stated your actual, concrete goal.I agree with Visage. Generics is for compile-time validation, not runtime dynamic typing. Sounds like what you need is really just the factory pattern. But if your \"do this\" isn't instantiation, then a simple Enum will probably work just as well. Like what Michael said, if you have a slightly more concrete example, you'll get better answers.
Java

I've compiled a  file and specified the Main-Class in the manifest (I used the Eclipse  function). My dependencies are all in a directory labeled . I can't seem to get a straight answer on how to execute my JAR file while specifying it should use the  as the classpath.I've tried:etc...Each gives an error saying:or gives the  indicating the libraries are not being found.I even tried remaking the JAR file and included the  directory and contents, but still no dice...How can I execute a JAR file from the command line and specify the classpath to use?When you specify  then the  parameter will be ignored. From :You also cannot \"include\" needed jar files into another jar file (you would need to extract their contents and put the .class files into your jar file)You have two options:Run a jar file and specify a class path like this: is the full name of the JAR you want to execute is a path to your dependency JARs is the fully qualified name of the class from the JAR that has the  methodThe jar and dependent jar should have execute permissions.
Java

Is there any way in Gson to map multiple JSON fields to a single Java object member variable?Let's say I have a Java class...I want to use this single class with two different services. However, these two services differ in how they return their data...... and ...... respectively.Is there any way to map both the  and  fields in the JSON string to the  field in the Java object? (Note: I only ever need to convert from JSON string to Java object - never the other way around.)In October 2015,  () added the ability to use alternate/multiple names for  when deserializing. No more custom TypeAdapter needed!It is not supported to define multiple  annotations to a field at Gson.   By default Deserialization is managed with a LinkedHashMap and the keys are defined by incoming json's field names (not the custom class's field names or the serializedNames) and there is a one to one mapping. You can see the implementation(how deserialization works) at  class's inner class 's  method.\nYou can write a custom  which handles ,  and  json tags and maps them to name field of your custom class : As @Mathieu Castets has written at his answer, it is supported now. (That is the correct answer for this question.)
Java

I'm using maven 2.0.9 with Eclipse 3.3.2.I'm used to launching a fresh build once per day by a .\nThen, if I refresh my Eclipse project, it will be \"polluted\" by files from Maven's  directory.That's very annoying while performing searches, getting resources by \"open resource\" and so on.Is there a way to avoid Eclipse looking in this folder?Right click on the folder you want to ignore, open the \"Properties\" dialog, chose the \"Resource\" tab and check the box that says \"Derived\"Reconfigure \"clean\" in Maven not to delete target directory:(found at: )Solution for Indigo [SR2] >  >  > I have been so pissed by this problem that I wrote a plugin to solve it. You get get the source and jar from:Preferences > Team > Ignored ResourcesAdd \"target\", and restart Eclipse.\nTo solve this problem here is what I did:\n\n-----------Cut below here for script--------------Did you try configuring the \"Java Element Filters\" option dialog box, (through the top-right arrow of the project explorer) ?If needed, you can define your own The maven plugin does not hide away the target directory. It does however use the maven target folders to configure eclipse. So target/classes and target/test-classes are used by eclipse, and eclipse filters these folders out. This is done by \"mvn eclipse:eclipse\" as well as by the m2eclipse plugin. What is left visible is everything in the target directory besides these two folders (the generated jar file for example).You can create a filter for the package explorer, but that will not influence the \"open resource\". I had some issues because some solutions here only work for some views, so I made an illustrated summary. \u2192  \u2192  check  and input .Be careful, this will hide all folders and files named , not just the default maven build directory! The  view has a better option without this issue.\nProject Explorer View Menu \u2192  \u2192  search for \"maven\" and check .Checking this option hides the build directory as defined in the projects pom.xml configuration.\nAre you using the Maven plugin for Eclipse?I would imagine it would hide some of the 'pollution' for you.It would also allow you to perform the build within Eclipse - meaning it would refresh the project view for you at the same time.Using Resource filter looks solve issue if you using 'mvn clean install' frequently.Basically it will add 'target' to and sub folders to exclude folder directly to .project file. After run this script, if you import project to eclipse, you can see the setting 'Project'->'Properties'->'Resource'->'Resource Filters'.  Before this whenever I run mvn clean install, eclipse took 50% of my CPU but now it stay under 5% while build project.When Eclipse freezes, looking at the process activity, I can see it browsing all my target, .hg and .git directories. Moreover, those directories are also copied into Eclipse's bin directory. A lot of CPU and disk usage for nothing.Not cleaning the target directory is not an acceptable solution.There was a solution using a Monkey script (http://maven.40175.n5.nabble.com/Eclipse-amp-target-directory-td72354.html) but the project has been closed.I still look for a solution to tell Eclipse to ignore Maven target directories, as well as .hg and .git directories.Eclipse continuously watching those is a pain.I also use m2eclipse but it doesn't solve that issue.
Java

So, I have a class with a constructor like this:and I want to construct a new  object with an empty set. Following Joshua Bloch's advice in his book Effective Java, I don't want to create a new object for the empty set; I'll just use  instead:This gives me an error, complaining that  is not a . OK, how about this:This also gives me an error! Ok, how about this:Hey, it works! But why? After all, Java doesn't have type inference, which is why you get an unchecked conversion warning if you do  instead of . But  works without even a warning. Why is that?The short answer is - that's a limitation of the type inference in Java's generic system.  It can infer generic types against concrete variables, but not against method parameters.I  this is because methods are dispatched dynamically depending on the runtime class of the owning object, so at compile time (when  generic information is resolved) you can't actually know for sure what the class of the method parameter will be and hence can't infer.  Variable declarations are nice and constant, so you can.Someone else might be able to give more detail and/or a nice link. :-)In any case, you can always specify the type parameters explicitly for generic calls like so:or even several parameters at once, e.g.This often looks a little cleaner than having to cast, in cases where inference doesn't kick in.try You can force the type parameter for methods that have them, in cases where the inference isn't good enough, or to allow you to use subtypes; for example:Java does have a type inference, it's just pretty limited. If you are interested in knowing exactly how it works and what its limitations are, this is a really good read:You want to do this:That tells the  method that its generic parameter should explicitly by  instead of the default . And yes, the syntax is completely funky and non-intuitive for this. :)
Java

I'm getting a  when trying to run the following method: The error is on the line I don't understand this error, because monStart is a field of the  class: I'm just learning to use reflection, so I'm sure this is some sort of a syntactical error...The  method will only find the field if it's .  You will need to use the  method instead, which will find any field that is declared  on the class, even if it's not .According to the javadoc,  \"Returns a  object that reflects the specified public member field of the class or interface represented by this  object\".\nUse  if you want to access non-public fields.Best solutions for  problem are:Use () instead of ()2)     Replace  with your class nameIf you want to get the annotation length of the columnI came to this question based on the title. I was getting the same error () in my Android project but for a different reason. So for others who come here, this error can also potentially be caused by the caches getting out of sync in Android Studio. Go to See  also 
Java

How do I count the number of files in a directory using Java ? For simplicity, lets assume that the directory doesn't have any sub-directories.I know the standard method of :But this will effectively go through all the files in the directory, which might take long if the number of files is large. Also, I don't care about the actual files in the directory unless their number is greater than some fixed large number (say 5000). I am guessing, but doesn't the directory (or its i-node in case of Unix) store the number of files contained in it? If I could get that number straight away from the file system, it would be much faster. I need to do this check for every HTTP request on a Tomcat server before the back-end starts doing the real processing. Therefore, speed is of paramount importance.I could run a daemon every once in a while to clear the directory. I know that, so please don't give me that solution.This might not be appropriate for your application, but you could always try a native call (using jni or ), or exec a platform-specific command and read the output before falling back to list().length.  On *nix, you could exec  (note - that's dash-one-a for the first command, and dash-lowercase-L for the second).  Not sure what would be right on windows - perhaps just a  and look for the summary.Before bothering with something like this I'd strongly recommend you create a directory with a very large number of files and just see if list().length really does take too long.  As  suggests, you may not want to sweat this.I'd probably go with Varkhan's answer myself.Ah... the rationale for not having a straightforward method in Java to do that is file storage abstraction: some filesystems may not have the number of files in a directory readily available... that count may not even have any meaning at all (see for example distributed, P2P filesystems, fs that store file lists as a linked list, or database-backed filesystems...).\nSo yes,is probably your best bet.Since Java 8, you can do that in one line:Regarding the 5000 child nodes and inode aspects:This method will iterate over the entries but as Varkhan suggested you probably can't do better besides playing with JNI or direct system commands calls, but even then, you can never be sure these methods don't do the same thing!However, let's dig into this a little:Looking at JDK8 source,  exposes a  that uses an  from  that delegates to .On UNIX systems (decompiled ), it loads an iterator: A  is used (with file locks while iterating through the directory).So, there is an iterator that will loop through the entries here.Now, let's look to the counting mechanism.The actual count is performed by the count/sum reducing API exposed by . In theory, this API can perform parallel operations without much effort (with multihtreading). However the stream is created with parallelism disabled so it's a no go...The  of this approach is that  as the entries will be counted by an iterator as they are read by the underlying (Filesystem) API.Finally, for the information, conceptually in a filesystem, a directory node is not required to hold the  of the files that it contains, it can  contain the list of it's child nodes (list of inodes). I'm not an expert on filesystems, but I believe that UNIX filesystems work just like that. So you can't assume there is a way to have this information directly (i.e: there can always be some list of child nodes hidden somewhere).Unfortunately, I believe that is already the best way (although  is slightly better than , since it doesn't construct  objects).Since you don't really need the total number, and in fact want to perform an action after a certain number (in your case 5000), you can use . The benefit is that you can exit early instead having to go through the entire directory just to get a count.The  for  also has some good examples. If you have directories containing really (>100'000) many files, here is a (non-portable) way to go: Using sigar should help.  has native hooks to get the statsUnfortunately, as mmyers said, File.list() is about as fast as you are going to get using Java. If speed is as important as you say, you may want to consider doing this particular operation using . You can then tailor your code to your particular situation and filesystem.
Java

Question is simple:I have two ListAnd I need to get the intersection of these. Is there a quick way to achieve this?You can use  method:Since retainAll won't touch the argument collection, this would be faster:The intersection will be the values left in columnsNew. Removing already compared values fom columnsOld will reduce the number of comparisons needed.Using Guava: How aboutThere is a nice way with streams which can do this in one line of code and you can two lists which are not from the same type which is not possible with the containsAll method afaik:An example for lists with different types. If you have a realtion between foo and bar and you can get a bar-object from foo than you can modify your stream:If you put the second list in a set say HashSet. And just iterate over the first list checking for presence on the set and removing if not present, your first list will eventually have the intersection you need.\nIt will be way faster than retainAll or contains on a list.\nThe emphasis here is to use a set instead of list. Lookups are O(1).\nfirstList.retainAll (new HashSet (secondList)) will also work.using retainAll if don't care occurrences, otherwise using N.intersectionN is an utility class in 
Java

When I add the configurations for  to my Android project and build the project I get the following error:A little late to the game here but this is  a problem with the dependencies you have listed in your  file for you app. After lots of testing i successfully chased down my problem and believe it could be of help to others.Things I do not recommend:Things to look out for:Google has a comprehensive list of the libraries for selectively compiling With all that said you probably only need to include this one line in gradle for your Google Analytics:Also, you can view the dependency tree by going to the root of your project (or using terminal in Android studio) and running:Good Luck and happy coding!Now as of Android Studio 2.2 you no longer need to trial and error whether you need to use multi-dex in your application. Use the  to see if its really needed! \nThis allows you to refer to all methods of the app. It is as if you have two modules (limit: 2 x 65K) but compacted into one. This entails a cost (time) in the build process. For me it was related to simplexml converter for retrofit 2. And it fixed by:That means your app would working fine on API level 21 or above.So, Firstly making sure you have imported correct dependency, which It seems you did it.In your manifest add the  class from the multidex support library to the application element.Alternative to that, If your app extends the  class, you can override the  method and call  to enable .Finally, you will need to update your build.gradle file as below by adding  :I hope it will help you out.in my case, I had this twice in the build.grade fileOnce I removed the 2nd entry, it worked fine.What i did to fix this is removed the gradle changes from here () then in Android Studio went into 'file/Project Structure' then click into analytics and if the box is checked uncheck it, let gradle sync then check the box again and click the button to sign in. After all this to get your analytics tracker working you just have to copy your actual tracker id into  look at this page for help. Exactly the same problem as I encountered! I found out that it was due to duplicate dependencies. In build.gradle, one dependency may be already included in others, thus generate conflicts. I removed necessary dependencies and solved my problem. Include specific dependencies in the build file. i think you are using google analytic sdk V3  use V4 instead i have also facing the same issue while using sdk V3 of google analytic  see this link for more information.This could happen if you updated Android Studio to the latest version 1.4. Did you update the support libraries to the latest versions? Your  should be 23.I actually found that having too many Android Studio modules was contributing to having this error without multidex enabled. If you are trying to avoid enabling multidex the limit seemed to be around 26 modules. This was with Android Studio 1.5.1The same problem but when using react-native-svg. This helped me:
Java

I'd like to get an id unique to a computer with Java, on Windows, MacOS and, if possible, Linux. It could be a disk UUID, motherboard s/n... can be used (it is not an applet).Ideas?It is common to use the MAC address is associated with the network card.The address is available in Java 6 through through the following API:I haven't used it in Java, but for other network identification applications it has been helpful.The problem with MAC address is that there can be many network adapters connected to the computer. Most of the newest ones have two by default (wi-fi + cable). In such situation one would have to know which adapter's MAC address should be used. I tested MAC solution on my system, but I have 4 adapters (cable, WiFi, TAP adapter for Virtual Box and one for Bluetooth) and I was not able to decide which MAC I should take... If one would decide to use adapter which is currently in use (has addresses assigned) then new problem appears since someone can take his/her laptop and switch from cable adapter to wi-fi. With such condition MAC stored when laptop was connected through cable will now be invalid.For example those are adapters I found in my system:Code I've used to list them:From the options listen on this page, the most acceptable for me, and the one I've used in my solution is the one by @Ozhan Duz, the other one, similar to @finnw answer where he used JACOB, and worth mentioning is  - sample which makes use of WMI is available :This will print some computer information together with computer Serial Number. Please note that all classes required by this example has to be generated by maven-com4j-plugin. Example configuration for maven-com4j-plugin:Above's configuration will tell plugin to generate classes in target/generated-sources/com4j directory in the project folder.For those who would like to see  solution, I'm including links to the three classes I wrote to get machine SN on Windows, Linux and Mac OS:As an alternative way of finnw's solution  command line utility could be used to querying devices serial numbers. Without external dependency most of the WMI things could be established with wmic.What do you want to do with this unique ID? Maybe you can do what you want without this ID.The MAC address maybe is one option but this is not an trusted unique ID because the user can change the MAC address of a computer.To get the motherboard or processor ID check on this .The  project provides  hardware utilities.Maven dependency:For instance, you could use something like the following code to identify a machine uniquely:Output for my machine:Your output will be different since at least the processor serial number will differ.On Windows only, you can get the motherboard ID using , through a COM bridge such as .Example:And if you choose to use the MAC address to identify the machine, you can use WMI to determine whether an interface is connected via USB (if you want to exclude USB adapters.)It's also possible to get a hard drive ID via WMI but this is unreliable.Be careful when using the MAC address as an identifier.  I've experienced several gotchas:Even with the above issues, I still think it's the best pure Java approach to hardware locking a license.Not Knowing all of your requirements. For example, are you trying to uniquely identify a computer from all of the computers in the world, or are you just trying to uniquely identify a computer from a set of users of your application. Also, can you create files on the system?If you are able to create a file. You could create a file and use the creation time of the file as your unique id. If you create it in user space then it would uniquely identify a user of your application on a particular machine. If you created it somewhere global then it could uniquely identify the machine.Again, as most things, How fast is fast enough.. or in this case, how unique is unique enough.I think you should look at this  ... you can make a mixed key using several\nidentifiers such as mac+os+hostname++.The usage of  id is most easier way if the task is about logging the unique id a system.the change of mac id is though possible, even the change of other ids of a system are also possible is that respective device is replaced.so, unless what for a unique id is required is not known, we may not be able to find an appropriate solution.However, the below link is helpful extracting mac addresses.\n In the java programs I have written for release I used the motherboard serial number (which is what I beleive windows use); however, this only works on windows as my function creates a temporary VB script which uses the WMI to retrieve the value.For identifying a windows machine uniquely.\nMake sure when you use wmic to have a strategy of alternative methods. Since \"wmic bios get serialnumber\" might not work on all machines, you might need to have additional methods:Resources:\nThe Best Way To Uniquely Identify A Windows Machine\n
Java

I'm trying to have a default  object in my class, with the default properties it accepts, and let the developer override some of them by specifying another  object, but I couldn't find a nice way for doing that.The intended usage is the following: implements the  interface, and so you  just treat it as such, and use methods like  to add the contents of another .However, if you treat it like a Map, you need to be very careful with this:This often catches people out, because it  like a copy constructor, but it isn't. If you use that constructor, and then call something like  (inherited from its  superclass), you'll get an empty set, because the  methods of  do not take account of the default  object that you passed into the constructor. The defaults are only recognised if you use the methods defined in  itself, such as  and , among others.So if you need to merge two Properties objects, it is safer to do this:This will give you more predictable results, rather than arbitrarily labelling one of them as the \"default\" property set.Normally, I would recommend not treating  as a , because that was (in my opinion) an implementation mistake from the early days of Java (Properties should have contained a , not extended it - that was lazy design), but the anemic interface defined in  itself doesn't give us many options.Assuming you eventually would like to read the properties from a file, I'd go for loading both files in the same properties object like:You're almost good: replaced  by .putAll():\nCopies all of the mappings from the specified map to this hashtable. These mappings will replace any mappings that this hashtable had for any of the keys currently in the specified map. Line 2 has no effect at all. None of the properties from the first file will be in the merged properties object.Yea you're right just invoke the putAll method and you're done. 
Java

How can i get the name of the class\nI am only interested in getting last part  ie only String\n\nAny Api can do that?or programmaticaly Social.class.getSimpleName()getSimpleName() :\nReturns the simple name of the underlying class as given in the source code. Returns an empty string if the underlying class is anonymous.\nThe simple name of an array is the simple name of the component type with \"[]\" appended. In particular the simple name of an array whose component type is anonymous is \"[]\".The below both ways works fine.Output as below:You can use following simple technique for print log with class name.Suppose we have to check coming variable value in method then we can use log like bellow : Importance of this line is that, we can check method name along with class name. To write this type of log.write :-   and Enter.will print on console 
Java

I am actually new to REST WS but really I don't get this . I am testing my REST with Poster on Firefox and the  works fine for me, also the  (when it's a ) but when I try  it doesn't not reach the WS at all, the server rejects it.This is my URL: http:// localhost:8081/RestDemo/services/customers/addthis is  I'm sending: this is  I'm sending:and this is my Resource class:I would appreciate your help, Thanks.This is my Customer class:The issue is in the deserialization of the bean Customer. Your programs knows how to do it in XML, with JAXB as Daniel is writing, but most likely doesn't know how to do it in JSON.Here you have an example with Resteasy/Jackson\nThe same with Jersey:\nAdd  and \nin REST Client header sectionJust in case this is helpful to others, here's my anecdote:I found this thread as a result of a problem I encountered while I was using Postman to send test data to my RESTEasy server, where- after a significant code change- I was getting nothing but 415 Unsupported Media Type errors.Long story short, I tore everything out, eventually I tried to run the trivial file upload example I knew worked; it didn't.  That's when I realized that the problem was with my Postman request.  I normally don't send any special headers, but in a previous test I had added a \"Content-Type\": \"application/json\" header.  OF COURSE, I was trying to upload \"multipart/form-data.\" Removing it solved my issue.Moral: Check your headers before you blow up your world. ;)I had the same problem: I resolved it by adding the dependency to pom.xml as follows. Please try it. I had this issue and found that the problem was that I had not registered the JacksonFeature class:Without doing this your application does not know how to convert the JSON to a java object. Don't return Strings in your methods but Customer objects it self and let JAXB take care of the de/serialization.
Java

I'd like to retrieve all table names from a database schema, and, if possible, get all table starting with a specified prefix. I tried using JDBC's  but it didn't work at all.Could someone help me on this?You need to iterate over your ResultSet calling .This is an example from :Column  is the  (see documentation of ).If you want to use a high-level API, that hides a lot of the JDBC complexity around database schema metadata, take a look at this article: In your example problem is passed table name pattern in getTables function of DatabaseMetaData. Some database supports Uppercase identifier, some support lower case identifiers. For example oracle fetches the table name in upper case, while postgreSQL fetch it in lower case. DatabaseMetaDeta provides a method to determine how the database stores identifiers, can be mixed case, uppercase, lowercase see: From below example, you can get all tables and view of providing table name pattern, if you want only tables then remove \"VIEW\" from TYPES array.public static ArrayList getTablesList(Connection conn)\n            throws SQLException {
Java

How to make the RequestMapping to handle GET parameters in the url?\nFor example i have this url(from jqGrid)how should my RequestMapping look like? I want to get the parameters using HttpReqestTried this:but it doesn't work.Use  in your method arguments so Spring can bind them, also use the  array to narrow the method that will be used by spring. Sample code:This way Spring will only execute this method if ALL PARAMETERS are present saving you from null checking and related stuff.You can add  like so:This will get ALL parameters from the request. For Debugging purposes only:If you are willing to change your uri, you could also use . The first foo is part of the path, the second one is the This works in my case:You should write a kind of template into the :Now define your business method like following:So, framework will map  to appropriate . Since sort may be either asc or desc I'd define it as a enum:Spring deals with enums very well. 
Java

I want a list of dates between start date and end date.  The result should be a list of all dates including the start and end date.  I suggest to use  for that. Add one day at a time until reaching the end date.It wouldn't be too hard to implement your own iterator to do this as well, that would be even nicer.Get the number of days between dates, inclusive.If you are using , there is a much cleaner approach. The new  in Java 8 incorporates the features of the  API.Your requirement can be solved using the below code:please find the below code.output:  Here is the Java 8 way, using streams and .You can do the same with the java.time framework built into Java 8 and later, using its  class.Something like this should definitely work:With  it looks like this in Java:and the output is:One solution would be to create a  instance, and start a cycle, increasing it's  field until it reaches the desired date. Also, on each step you should create a  instance (with corresponding parameters), and put it to your list.Some dirty code:You can also look at the  API. That gives a long to which you can add your increment. Then create a new Date.and maybe apache commons has something like this in DateUtils, or perhaps they have a CalendarUtils too :)including the start  enddate may not be possible if your interval is not perfect :)With  , maybe it's better:It's my solution.... very easy :)In  (which will probably be released still in 2017), you can use following new method:The new method  works with an exclusive end date, hence the shown hack to add a day.Once you have obtained a stream you can exploit all the features offered by - or -packages. Or if you look for a stream-based solution which operates on inclusive dates by default but can also be configured otherwise then you might find the class  in my library  interesting because it offers a lot of special features around date streams including a performant spliterator which is faster than in Java-9:Or even simpler in case of full months:Like as @folone, but correctA tail-recursive version:Enhancing one of the above solutions. As adding 1 day to end date sometimes adds an extra day beyond the end date.Here is my method for getting dates between two dates, including / w.o. including business days. It also takes source and desired date format as parameter.And the method call would be like :You can find the demo code : Recursive solution
Java

Why do we need to close a FileInputStream (and streams in general)  before we leave the program? What would happen otherwise? If the program stops before the input stream is closed explicitly in the program, doesn't the stream also close automatically?File handles are scarce, finite resources.  You can run out of them if you don't clean them up properly, just like database connections.If you've written a small program with just one user you can get away with being sloppy and not closing in a finally block.But if you end up using that idiom in an application that has many users and file handles you might have a problem.\"First we make our habits, then they make us.\"  I try to apply best practices even when they aren't necessary.Yes, when the process terminates the unmanaged resources will be released. For InputStreams this is fine. For OutputStreams, you could lose an buffered data, so you should  flush the stream before exiting the program.Dude.  If you don't close your stream, your unit test will fail.  Or at least, it should.  So, that's why you need to close it.  ;)And while the OS will almost certainly clean up if you just exit, they'll generally get freed up faster if you explicitly close them.  Furthermore, what if your code ends up in a long-running program sometime down the road?  Then they'll have problems and curse you.  :(So, it's like washing your hands after using the bathroom.  Eventually someone will pay the price if you don't do it.  You can get away with it for a while, but it's still a good practice.In addition to Jon's answer, it is generally a good idea to close any resource.Think of a database connection. Your database cannot have infinite connections opened, in this case when you don't need it, it's better you close it as soon as you're done with it.It is also good to make this a habit. \"finally\" block is your friend. In case of C++, you can also use .Sort of. The stream is backed by a \"real\" operating system file descriptor, and when the process terminates the OS will clean up any open file descriptors.Anyway, it's good practice to always close your resources when you're done, so close the streams :)If you don't close streams, you may have problems opening them back up again. This is especially true if they're hanging off the end of sockets.Closing a stream also makes sure that data is flushed through the stream if there is any data left to send. 
Java

I am getting an exception and I can't find the reason of it.The exception I get is :The method is public.i am using apache tomcat 5.5.12\nand JAVA 1.6You are almost certainly using a different version of the class at runtime to the one you expect.  In particular, the runtime class would be different to the one you've compiled against (else this would have caused a compile-time error) - has that method  been ?  Do you have old versions of the classes/jars on your system anywhere?As the javadocs for  state,I'd definitely look at your classpath and check whether it holds any surprises.This happens when accessing a package scoped method of a class that is in the same package but is in a different jar and classloader.  If  is protected then try making it public. The problem could exist in JAVA 1.6 and be absent in 1.5x  I got this for your problem. This happened to me when I had a class in one jar trying to access a private method in a class from another jar.  I simply changed the private method to public, recompiled and deployed, and it worked ok afterwards.\nI was getting this Issue primarily because i was using some thing that is not available/deprecated in that Android versionWrong way:Right way:here Notification.Action is not available prior to  and my min version was Just an addition to the solved answer: be a problem with Android Studio's Instant Run feature, for example, if you realized you forgot to add the line of code:  to your activity after opening another one, and you already re-opened the activity you shouldn't have reopened (which the  solved), then you add  and Instant Run occurs, then the app will crash since the logic has been broken. This is not necessarily a code problem, just an Instant Run problemI was getting this error on a Spring Boot application where a  had a nested class . It seems the  was using a different class loader. I moved the nested class  to a separate .java file and got rid of the problem.
Java

How can I enable the  keyword in Eclipse?To be specific: If anyone wants to  (in contrast to enabling them for just a single run configuration), it is possible with the following steps:You need to go to run configurations and add vm arguments as \"-enableassertion\" (or) \"-ea\"After that when you run code with assert statement, you will see assert in action. Java introduced the  keyword, so the way to enable source-level support is to make sure that Eclipse's Java compliance level is 1.4 or higher.  (The chances are that the compliance level is already higher than that ...)To cause a Java application launched from Eclipsed to run with assertion checking enabled, add the \"-ea\" argument to the VM arguments in the launcher configuration's \"Arguments\" tab.
Java

I am new to using JAX-RS and wrote a sample application that outputs a json object. but I am getting an exception. Here is my code:}My data is simply a POJO class:I get an exception:What am i doing wrong ?I finally found my answer. I added to my pom.xml file. Then I added to my web.xml file, and everything works fine. No change was required to my code above.I added following jars and it worked for meJust a small addition. In case if you do not use the web.xml descriptor file, you may enable the POJOMappingFeatire programatically as shown belowXML output is supported by default. So no dependency needed for it.Working with Jersey 1.8, I was getting the same error while creating a JSON object and hitting a REST API from client side.If you are facing issue at server side then, make sure that you have correctly included jersey-json.jar in classpath and mapped correct init-param in web.xml as mentioned in other answers.As per , the following snippet shows how to use the POJO JSON mapping feature on the client side:I had the same issue:\n A message body writer for Java type, class java.lang.String, and MIME media type, application/json, was not foundThe problem was that the class\njavax.ws.rs.ext.MessageBodyWriter was taken from Was colliding with the same class from:
Java

 I do not really understand how the substring method works. Does the index start at 0? If I start with 0,  is at index 4 but char  is at 7 so the output would be .0: U1: n2: i3: v7: i8: t9: yStart index is inclusiveEnd index is exclusivesee , it's an inclusive index for the 1st arg and exclusive for the 2ndBoth are 0-based, but the start is inclusive and the end is exclusive. This ensures the resulting string is of length . Think of them as positions in the string rather than actual characters.Quoting the :Like you I didn't find it came naturally. I normally still have to remind myself thatso returns the 4-character string \" even though there is no character at position 10.Yes the index starts at zero (0). The two arguments are startIndex and endIndex, where per the docs:\"The substring begins at the specified beginIndex and extends to the character at index endIndex - 1\"See  for more info.For substring(startIndex, endIndex), startIndex is inclusive and endIndex are exclusive. The startIndex and endIndex are very confusing.\nI would understand substring(startIndex, length) to remember that. The Substring starts at, and includes the character at the location of the first number given and goes to but does not include the character at the last number givenThe endIndex is very confusing term. I guess the motive was to keep the length of the new string to endIndex - startIndex. But so what? I guess it was easier to remember both are inclusive, rather than remembering start is inclusive and end is exclusive. \u2014the begin index, inclusive.\u2014the end index, exclusive.Example:Output: \"lo Wo\" from 3 to 7 indexAlso there is another kind of  method.\u2014the begin index, inclusive.\nReturns a sub string starting from  to the end of the main String.example:Output: \"lo World\" from 3 to last index
Java

Is there a way to obtain the post data itself? I know spring handles binding post data to java objects. But if I had two fields that I want to process manually, how do I obtain that data?Assuming I had two fields in my formHow would I go about retrieving those values in my controller? If you are using one of the built-in controller instances, then one of the parameters to your controller method will be the Request object.  You can call  to get the Post data value.If you are using Spring MVC annotations, you can add an annotated parameter to your method's parameters:Spring MVC runs on top of the Servlet API. So, you can use  for this:The  should already be available to you inside Spring MVC as one of the method arguments of the  method.Another answer to the OP's exact question is to set the  content type to  and then declare a  input parameter. This will pass the text of the POST data in as the declared  variable ( in the following example).Of course, this presumes your POST payload is text data (as the OP stated was the case).Example:
Java

I have heard that Java must use a JIT to be fast. This makes perfect sense when comparing to interpretation, but why can't someone make an ahead-of-time compiler that generates fast Java code? I know about , but I don't think its output is typically faster than Hotspot for example.Are there things about the language that make this difficult? I think it comes down to just these things:What am I missing? If I avoid these features, would it be possible to compile Java code once to native machine code and be done?The real killer for any AOT compiler is:This means that you cannot write a AOT compiler which covers  Java programs as there is information available only at runtime about the characteristics of the program.  You can, however, do it on a subset of Java which is what I believe that gcj does.Another typical example is the ability of a JIT to inline methods like getX() directly in the calling methods if it is found that it is safe to do so, and undoing it if appropriate, even if not explicitly helped by the programmer by telling that a method is final.  The JIT can see that in the running program a given method is not overriden and is therefore in this instance can be treated as final.  This might be different in the next invocation.A JIT compiler can be faster because the machine code is being generated on the exact machine that it will also execute on.  This means that the JIT has the best possible information available to it to emit optimized code.If you pre-compile bytecode into machine code, the compiler cannot optimize for the target machine(s), only the build machine.I will paste an interesting answer given by the  in the Book .Java's JIT compiler is also lazy and adaptive.Being lazy it only compiles methods when it gets to them instead of compiling the whole program (very useful if you don't use part of a program). Class loading actually helps make the JIT faster by allowing it to ignore classes it hasn't come across yet.Being adaptive it emits a quick and dirty version of the machine code first and then only goes back and does a through job if that method is used frequently.In the end it boils down to the fact that having more information enables better optimizations. In this case, the JIT has more information about the actual machine the code is running on (as Andrew mentioned) and it also has a lot of runtime information that is not available during compilation.Java's ability to inline across virtual method boundaries and perform efficient interface dispatch requires runtime analysis before compiling - in other words it requires a JIT. Since all methods are virtual and interfaces are used \"everywhere\", it makes a big difference.In theory, a JIT compiler has an advantage over AOT . For instance, if you have an enterprise app running for days and months on a multiprocessor server with plenty of RAM, the JIT compiler  produce better code than any AOT compiler.Now, if you have a desktop app, things like fast startup and initial response time (where AOT shines) become more important, plus the computer may not have sufficient resources for the most advanced optimizations.And if you have an embedded system with scarce resources, JIT has no chance against AOT.However, the above was all theory. In practice, creating such an advanced JIT compiler is way more complicated than a decent AOT one. How about some ?JITs can identify and eliminate some conditions which can only be known at runtime. A prime example is the elimination of virtual calls modern VMs use - e.g., when the JVM finds an  or  instruction, if only one class overriding the invoked method has been loaded, the VM can actually make that virtual call static and is thus able to inline it. To a C program, on the other hand, a function pointer is always a function pointer, and a call to it can't be inlined (in the general case, anyway).Here's a situation where the JVM is able to inline a virtual call:Assuming we don't go around creating  or  instances elsewhere and that  is set to , the JVM knows that the call to  always means , and can therefore avoid the method table lookup, and then inline the call. A similar construct in a non-JITted environment would not be inlinable.I think the fact that the official Java compiler is a JIT compiler is a large part of this. How much time has been spent optimizing the JVM vs. a machine code compiler for Java?
Java

When I executing the following code: I'm facing the following error: \nCould someone help me to find the solution or reason for this?I had the same problem, and finally I found that I forgot to add the . I had only added the client jar, .Hope this helps.A  is thrown when the JRE can't find a class. In your case, it can't find the class , which you most probably did not add to your classpath.After downloading the following libraries:and unzipping them and putting all JAR files in a folder called , the test class:ran without any problems.You can compile and run the class as follows:you don't have the  library on your .There are a number of , so please provide more info regarding how you are executing your program.if from the command line, you can add libraries to the classpath via I had the same error and after the investigation i found that library selenium-api 2.41.0 requires guava 15.0 but it was overridden by an older version so i declared guava 15.0 as direct dependency by adding following configuration in pom.xml:For me, in addition to selecting the jar - selenium-java-2.45.0.jar, I had to select all the jars in the \"libs\" folder under selenium root folder.It looks like you're trying to import some google code:And it's not finding it the class Function.  Check to make sure all the required libraries are in your build path, and that you typed the package correctly.I met the same problem and fail even after installing the 'selenium-server-standalone-version.jar', I think you need to install the guava and guava-gwt jar () as well. I added all of these jar, and finally it worked in my PC. Hope it works for others meeting this issue.I had the same issue. I found that I forgot to add selenium-2.53.0/selenium-java-2.53.0-srcs.jar file to my project's Reference library.I got the same error, but it was resolved if you add the libraries of selenium (again if you haven't), if you are using INTELIJSame needs to be done for other IDE's as well, like eclipse.When I caught the exception  it was caused by errors in Project Libraries. Please check it in your project settings. For Intellij IDEA go to  and select  tab. All I needed to do to resolve this exception was re-adding the selenium libraryPlease include all the jar files of selenium stand-alone and lib folder, then this error will resolvedAfter you extract your \"selenium-java-.zip\" file you need to configure your build path from your IDE. Import all the jar files under \"lib\" folder and both selenium standalone server & Selenium java version jar files.I wanted to try a simple class outside IDE and stuff. So downloaded selenium zip from website and run the class like this:I had the issue that I initially used  instead of . I  need to add selenium standalone jar. This is Java 8 that understands wildcards in classpath. I think java 7 would also do.I had the same problem, and finally I found that I forgot to add the selenium-server-standalone-version.jar. I had only added the client jar, selenium-java-version.jar.
Java

I googled a lot and read about  and  a lot, know purpose of each method, but still have a question. Is it good practice to call  method by hand? As said in  docs, Could you explain me purpose of calling  by hand if  will call it automatically?Thanks!In the Hibernate Manual you can see this exampleWithout the call to the flush method, your first-level cache would throw an OutOfMemoryException One common case for explicitly flushing is when you create a new persistent entity and you want it to have an artificial primary key generated and assigned to it, so that you can use it later on in the same transaction. In that case calling flush would result in your entity being given an id. Another case is if there are a lot of things in the 1st-level cache and you'd like to clear it out periodically (in order to reduce the amount of memory used by the cache) but you still want to commit the whole thing together. This is the case that  covers (+1 from me). will synchronize your database with the current state of object/objects held in the memory but it does not commit the transaction. So, if you get any exception after  is called, then the transaction will be rolled back.\nYou can synchronize your database with small chunks of data using  instead of committing a large data at once using  and face the risk of getting an . will make data stored in the database permanent. There is no way you can rollback your transaction once the  succeeds. Flushing is the process of synchronizing the underlying persistent store with persistable state held in memory.it will update or insert into your tables in the running transaction, but it may not commit those changes.  Commit will make the database commit.When you have a persisted object and you change a value on it, it becomes dirty and hibernate needs to flush these changes to your persistence layer.So You should commit but it also ends the unit of work.By default flush mode is AUTO which means that: \"The Session is sometimes flushed before query execution in order to ensure that queries never return stale state\", but most of the time session is flushed when you commit your changes. Manual calling of the flush method is usefull when you use FlushMode=MANUAL or you want to do some kind of optimization. But I have never done this so I can't give you practical advice.session.flush() is synchronise method means to insert data in to database sequentially.if we use this method data will not store in database but it will store in cache,if any exception will rise in middle we can handle it.\nBut commit() it will store data in database,if we are storing more amount of data then ,there may be chance to get out Of Memory Exception,As like in JDBC program in Save point topic 
Java

I am aware that it is better to call the  method over using the  operator (see ). I want two strings to compare as equal if they are both null or if they represent the same string. Unfortunately the  method will throw an  if the strings are . My code is currently:This is inelegant. What is the correct way to perform this test?If Java 7+, use ; its documentation explicitly specifies that:which is what you want.If you don't, your method can be rewritten to:This works because the  contract guarantees that for any object ,  is always false.From :Very simple, self-explaining and elegant.If you can't use Java 7+ solution, but you have Guava or Commons Lang in classpath, then you can use the following:::or
Java

I have a very simple question. I am brand new to Mac and I am trying to get my Java project moved over to my new Mac. The project has a Gradlew file that I thought I could run from the command line to build and run on any machine. When I do gradlew from the command line (in the location of the gradlew file) it says gradlew not found. Am I missing something on how to run a command from a bash shell?Your directory with gradlew is not included in the PATH, so you must specify path to the gradlew.   means \"current directory\". Also, if you don't have the  file in your current directory:You can install gradle with  with the following command:As mentioned in . Then, you are not going to need to include it in your path (homebrew will take care of that) and you can just run (from any directory):
Java

I am using retrofit 2.0.0-beta1 with SimpleXml. I want the retrieve a Simple (XML) resource from a REST service.\nMarshalling/Unmarshalling the Simple object with SimpleXML works fine.When using this code (converted form pre 2.0.0 code):Service:I get this exception:What am i missing? I know that wrapping the return type by a  works. But I want the service to return business objects as type (and working in sync mode).After added the extra dependancies and  as suggested by different answers, I still get this error:Short answer: return  in your service interface.It looks like Retrofit 2.0 is trying to find a way of creating the proxy object for your service interface. It expects you to write this:However, it still wants to play nice and be flexible when you don't want to return a . To support this, it has the concept of a , which is supposed to know how to adapt a  into a .The use of  is only useful if you are trying to return .The simplest solution is to return a  as Retrofit expects. You could also write a  if you really need it.add dependencies:create your adapter this way: and  both need to be called.Service:Modify  to .With the new Retrofit(2.+) you need to add addCallAdapterFactory which can be a normal one or a RxJavaCallAdapterFactory(for Observables). I think you can add more than both too. It automatically checks which one to use. See a working example below. You can also check  for more details. Add the following dependencies for retrofit 2for GSONfor observablesIn your case for XML , you would have to include the following dependenciesUpdate the service call as below If you want use  and you don't want always return , you have to create your own  which return simple type as you expected. The simple code can look like this:Then simple register the  in Retrofit should solved your problem.After that you can return simple type without .in my case using this with this solved the problem when nothing else workedYou can implement a Callback, get the Simple from onResponse function.The way I fixed this issue was adding this to the application gradle file, if the configuration is not set there will be conflicts, maybe this will be fixed in the stable release of the library:and create your adapter this way:Hope it helps!
Java

This is referring to  ..wasnt able to reply or comment to any so created a new one. Why are my giving warnings-The static field MyUnits.MILLSECONDS should be accessed in a static way ?\nThanks.Because when you access a static field, you should do so on the class (or in this case the enum).  As inNot on an instance as in To address the question of : In Java, when you declare something as , you are saying that it is a member of the class, not the object (hence why there is only one).  Therefore it doesn't make sense to access it on the object, because that particular data member is associated with the class.There's actually a good reason: \n.Suppose we have two classes, A and B, the latter being a subclass of A, with static fields with the same name:Direct access to the static variable:Indirect access using an instance (gives a compiler warning that VALUE should be statically accessed):So far, so good, the compiler can guess which static variable to use, the one on the superclass is somehow farther away, seems somehow logical.Let's remove the static variable from B, and observe following situations:The statement  is now , as the . And that's exactly the reason why static variables should be accessed in a static way.Because ... it () is a static field (hiding in an enumeration, but that's what it is) ... however it is being invoked upon an  of the given type (but see below as this isn't  true).javac will \"accept\" that, but it should really be  (or non-prefixed in the applicable scope). Actually, javac \"rewrites\" the code to the preferred form -- if  happened to be  it would not throw an NPE at run-time -- it is never actually invoked upon the instance).Happy coding.I'm not really seeing how the question title fits in with the rest :-) More accurate and specialized titles increase the likely hood the question/answers can benefit other programmers.
Java

I'm using the  (and parser) in an Android app to parse a JSON feed. Which is the best way to determine if a property exists or not in one of the objects returned?Say I have a JSON feed including \"News\". Some of the news have a property called \"UnpublishDate\" (which is the date the news in question is no longer active), while some of the news don't have this property.The best solution I've come up with (though not implemented yet) is to simply have a \"try-catch\" around the  - do you know of any better solution (that is more graceful when the class scales to several \"optional\" properties in the JSON feed)?You might use the  function :
Java

I'm using a progress bar (in bar form). I wish to make the bar increase and decrease smoothly using an interpolator, but It's not working. This is what I have at the moment:Am I doing something really wrong?The Interpolator have to be attached to an animation and this will work only on Honeycomb or higher :If your minimum SDK is Gingerbread or lower, add to your function/class.I used a DecelerateInterpolator, but this is optional and there are others possibilities.Here is a self-contained drop in solution:replace  with  in your layoutYou many also change the type to AnimatingProgressBar to utilize  to disable animation (could be useful when restoring activity state)If you change progress value each time by 1 (for example from 45 to 46) you'll not see animation. Better to change progress by 100 points, for this you just need to multiply your max value to 100 and each progress value to 100 too. For example:I worked out how to do it, by using a runnable I was able to update the progress bar several times a second and so give the sliding effect. The code is below:Here, 'track' keeps track of how many increments have been done, and increase is the total number of increments that should be done. I can dynamically increase the number of increments from the UI thread to give a smooth effect. The code only works for progress bars that won't need to decrease.To run it, simply use this code:Above link is my library.\nJust use it if you want.According to documentation interpolator applies to indeterminate progress.\nSince you set progress I think you intend to use regular one with values. \nI think the best for you would be to increase maximum value of progress and \ngo in smaller increments.I used android Animation for this:and call it like so:Note: if from and to value are too low to produce smooth animation just multiply them by a 100 or so. If you do so, don't forget to multiply setMax(..) as well.I am not sure but please check it:Bounce is probably not the best animation if you want it to look smooth. Try easein or easeout.
Java

Are there named parameters in JDBC instead of positional ones, like the ,  in the ADO.NET query below?JDBC does not support named parameters. Unless you are bound to using plain JDBC (which causes pain, let me tell you that) I would suggest to use Springs Excellent JDBCTemplate which can be used without the whole IoC Container. supports named parameters, you can use them like that:To avoid including a large framework, I think a simple homemade class can do the trick.Example of class to handle named parameters:Example of calling the class:Please note that the above simple example does not handle using named parameter twice. Nor does it handle using the : sign inside quotes.Vanilla JDBC only supports named parameters in a  (e.g. ), and even then, I suspect the underlying stored procedure implementation has to support it.An example of how to use named parameters:You can't use named parameters in JDBC itself. You could try using Spring framework, as it has some extensions that allow the use of named parameters in queries.I ended up just creating my own wrapper meothod.The biggest downfall is that you have to ensure that the variable is indeed safe for binding. I now just use Spring's Hibernate, much betterPlain vanilla JDBC does not support named parameters.If you are using DB2 then using DB2 classes directly:
Java

In the work that I do on a day to day in Java, I use builders quite a lot for fluent interfaces, e.g.: With a quick-and-dirty Java approach, each method call mutates the builder instance and returns . Immutably, it involves more typing, cloning the builder first before modifying it. The build method eventually does the heavy lifting over the builder state.What's a nice way of achieving the same in Scala?If I wanted to ensure that  was called only once, and then subsequently only  and  could be called, a-la a directed builder, how would I go about approaching this?Another alternative to the Builder pattern in Scala 2.8 is to use immutable case classes with default arguments and named parameters. Its a little different but the effect is smart defaults, all values specified and things only specified once with syntax checking...The following uses Strings for the values for brevity/speed...You can then also use existing immutable instances as kinda builders too...You have three main alternatives here.It's the same exact pattern.  Scala allows for mutation and side effects.  That said, if you'd like to be more of a purest, have each method return a new instance of the object that you're constructing with the element(s) changed.  You could even put the functions within the Object of a class so that there's a higher level of separation within your code.so that your code might look like(Note: I've probably screwed up some syntax here.)Case classes solve the problem as shown in previous answers, but the resulting api is difficult to use from java when You have scala collections in your objects. To provide a fluent api to java users try this:Then in java code the api is really easy to useusing Scala partial applies are feasible if you are building a smallish object that you don't need to pass over method signatures. If any of those assumptions don't apply, I recommend using a mutable builder to build an immutable object. With this being scala you could implement the builder pattern with a case class for the object to build with a companion as the builder.Given that the end result is a constructed immutable object I don't see that it defeats any of the Scala principles.  I think scala's Stackable Modification could be used here. Check this out : \nIt works for me, but I think it is write Java for Scala compiler. I`m still learning the scala way, functionnaly way.The usage is:The structure is:
Java

I have a java project written using eclipse ide and I want to run it through ssh on a different machine, but I have to do this using the command line and I don't know exactly how.I am a beginner at both shell commands and java.Could you please give me a useful link with answers regarding this question, or perhaps a set instructions of how to do this?Maven or Ant are the best option but for an  solution\nyou can choose  and select \nthen transfer the  to your other machine and run this from the command line:Running java applications using command line is very easy.\nThe simplified syntax looks like this:where: - list of directories and/or JAR-files where needed classes reside separated by \";\" for Windows or \":\" for linux (default classpath is \".\" - the current directory); - fully qualified name of the class containig main() method (for example, org.myself.HelloWorld) - various arguments for application if any.So, if you find the directory where Eclipse stored compiled classes (usually it's bin) you may use the command, likeOr, if you use some libraries and classes in other directories, it could be:To build and run a Java project, Its good to use an ant or maven tool. you can find many tutorials on google for the same.a good tutorial on ant is here This is what I did and it worked for me. Hope it could help. \n
Java

Probably a repeat! I am using Tomcat as my server and want to know what is best way to spawn threads in the servlet with deterministic outcomes. I am running some long running updates from a servlet action and would like for the request to complete and the updates to happen in the background. Instead of adding a messaging middleware like RabbitMQ, I thought I could spawn a thread that could run in the background and finish in its own time.  I read in other SO threads that the server terminates threads spawned by the server in order for it to manage resources well. Is there a recommended way of spawning threads, background jobs when using Tomcat. I also use Spring MVC for the application. Your safest bet is using an applicaton wide  with a max amount of threads, so that the tasks will be queued whenever necessary. The  is very helpful in this.Upon application startup or servlet initialization use the  class:Then during servlet's service (you could ignore the result for the case that you aren't interested):Finally, during application's shutdown or servlet's destroy: You could maybe use a CommonJ WorkManager (JSR 237) implementation like : Just to clarify, here is what the  (looks like this is the successor of JSR-236 & JSR-237) writes about unmanaged threads:So nothing new IMO, the \"old\" problem is the same, unmanaged thread are still unmanaged threads: Spring supports asynchronous task (in your case long running) through spring-scheduling. Instead of using Java threads direct I suggest to use it with Quartz. Strictly speaking, you're not allowed to spawn threads according to the Java EE spec. I would also consider the possibility of a denial of service attack (deliberate or otherwise) if multiple requests come in at once.A middleware solution would definitely be more robust and standards-compliant.I know it is an old question, but people keep asking it, trying to do this kind of thing (explicitly spawning threads while processing a servlet request) all the time... It is a very flawed approach - for more than one reason... Simply stating that Java EE containers frown upon such practice is not enough, although generally true...Most importantly, one can never predict how many concurrent requests the servlet will be receiving at any given time. A web application, a servlet, by definition, is meant to be capable of processing multiple requests on the given endpoint at a time. If you are programming you request processing logic to explicitly launch a certain number of concurrent threads, you are risking to face an all but inevitable situation of running out of available threads and choking your application. Your task executor is always configured to work with a thread pool that is limited to a finite reasonable size. Most often, it is not larger than 10-20 (you don't want too many threads executing your logic - depending on the nature of the task, resources they compete for, the number of processors on your server, etc.) Let's say, your request handler (e.g. MVC controller method) invokes one or more @Async-annotated methods (in which case Spring abstracts the task executor and makes things easy for you) or uses the task executor explicitly. As your code executes it starts grabbing the available threads from the pool. That's fine if you are always processing one request at a time with no immediate follow-up requests. (In that case, you are probably trying to use the wrong technology to solve your problem.) However, if it is a web application that is exposed to arbitrary (or even known) clients who may be hammering the endpoint with requests, you will quickly deplete the thread pool, and the requests will start piling up, waiting for threads to be available. For that reason alone, you should realize that you may be on a wrong path - if you are considering such design. A better solution may be to  the data to be processed asynchronously (that could be a queue, or any other type of a temporary/staging data store) and return the response. Have an external, independent application or even multiple instances of it (deployed outside your web container) poll the staging endpoint(s) and process the data in the background, possibly using a finite number of concurrent threads. Not only such solution will give you the advantage of asynchronous/concurrent processing, but will also scale because you will be able to run as many instances of such poller as you need, and they can be distributed, pointing to the staging endpoint.\nHTH Since Spring 3, you can use @Async annotations:with  and  in the context filePlease refer to this tutorial: Works great for me on Tomcat7 and you don't have to managed a thread pool.
Java

I want to use the binary search algorithm to search the string which has been entered by the user in a very big sorted file. I can not compare the string which has been entered by the user with the string which has been located in the middle line of the file to continue my binary search.For example, if the user's string is  and the file's string is , it is obvious that the user's string is smaller than the file's string. How is it implemented in java? it will be great if you can help me with a sample code.You can useIf  is lexicographically less than ,  will be returned,  if equal or  if  is greater. E.g., If you would like to ignore case you could use the following:Haven't you heard about the  interface being implemented by  ? If no, try to useAnd it will output a good root for a solution to your problem.
Java

Findbug told me that I use incorrect lazy initialization.I don't see anything wrong here. Is it wrong behaviour of findbug, or I missed something?Findbug is referencing a potential threading issue.  In a multi thread environment, there would be potential for your singleton to be created more than once with your current code.There is a lot of reading , but it will help explain.The race condition here is on the .  On the first call, a thread will get into the , and will create the instance and assign it to 'instance'.  But there is potential for another thread to become active between the  and the instance creation/assignment.  This thread could also pass the  because the assignment hasn't happened yet.  Therefore, two (or more, if more threads got in) instances would be created, and your threads would have references to different objects.Your code is slightly more complex than needed which might be why it's confused.Edit: It's definitely the threading issue as the others posted but thought I'd post the double lock check implementation here for reference below:: JohnKlehm's double lock checking solution is better. Leaving this answer here for historical reasons.It should actually be You need to put a lock around instantiation to make this correctThanks to John Klehm for posted samplealso may try to assign object instance in sychronised block directlyi.e.You missed multi threading issue, your static object is not  synchronized. Moreover your method is not a lazy initialization. Normally what you do is you keep a Map of object,and you initialize the desired one on demand. So you do not initialize all of them at the beginning rather than calling them when it is needed(called).
Java

Actually i trying to extract code of an .apk file called cloudfilz.apk and wanted to manipulate in its source code so i followed the steps given below:-make a new folder and put .apk file (which you want to decode) now rename this .apk file with extension .zip (eg:rename from filename.apk to filename.apk.zip) and save it..now you get classes.dex files etc...at this stage you are able to see drawable but not xml and java file...so continue...step 2:now extract this zip apk file in the same folder(in this eg or case NEW FOLDER). now dowmload dex2jar from this link  and extract it to the same folder (in this case NEW FOLDER).....now open command prompt and reach to that folder (in this case NEW FOLDER)....after reaching write \"dex2jar classes.dex\" and press enter.....now you get classes.dex.dex2jar file in the same folder......=>Question:-I was successfull to achieve step 1 but in step2 when i am executing dex2jar classes.dex i am getting an error on command prompt  ,I know this is due incompability between my installed jdk version and classes.dex jdk version number so stuck here and dnt have way out...As we now know that apk file is just a zip file containing all program resource file, we can now get java code from apk files with ease. Following are steps to get java code from apk files.Above steps will generate  but to get  files perform following steps.or Visit .... It will definitely help you to extract XML and source Java files from a APK file. It worked for me.Any .apk file from market or unsignedstep 1:step 2: Download java decompiler    this is a good tutorial for both window/ubuntu.Procedure:it will become .zip.\u2013 cd \n\u2013 sh dex2jar.sh classes.dex (result of this command \u201cclasses.dex.dex2jar.jar\u201d will be in your   itself).
Java

I'm trying to build a  in eclipse using Java 8 (and Wildfly appServer if that matters) but I'm unable to make Eclipse Luna M5 use Java 8 (I do have Java 8 BETA support installed and it works on JavaSE projects). In my POM I set the level to Java 8:But after I do  I get the following error:And indeed there is no java 1.8 project facet under Can I manually create such  and add It to to eclipse or I'll have to wait until java 8 is released and the eclipse guys decide to add it ?There are additional patches available for Kepler SR2 officially.\nIn ecliplse, go to \"Help\" --> \"Market Place\" --> Search for java 8 kepler.\nThen choose and install the following.Reference: After this, my multi-module maven project with java 8 is building fine without any error in eclipse kepler SR2.: If you are using Spring Tool Suite (STS), then version 3.5.1 has included these features.There is an official bug report/patch for Kepler SR2. It also works with Spring Tool Suite 3.5.0.RC4 (which is based on Kepler). It should work for Luna too.Bug report :  (see comment #12)Update site for the Java 8 facet : While we await official Java 1.8 support, I've made a github fork that contains what I believe are the required changes - these require the Java 8 patches from here first:  To install the 1.8 facet support (assuming that you're running 4.3.1 or 4.3.2, and have write access to the main .../eclipse/plugins dir):After restarting Eclipse, you should find that 1.8 is now selectable as a Java facet :) (and it also works with M2E enabled projects that specify source/target of 1.8). Note the instruction from the standard 1.8 patch instructions that the installed JDK /must/ be called \"JavaSE-1.8\" within the Eclipse properties.Also note that if/when you update Eclipse (e.g. to upgrade to 4.3.2), you will probably need to re-install the patched version again as the update will put the \"official\" version of the plugin back in.I hit exactly the same problem a few days ago. Looks like this will be included into the next release of Eclipse Luna.Eclipse Luna M6 is scheduled for release on March 14th so hopefully it will be included then.Recently Java updated to Java 8 so you need to update to the new Eclipse for it to work. I was running Eclipse 4.3 (Kepler) and I had to upgrade to Eclipse 4.4 (Luna)Go to Your  search for  and change java version
Java

Sometimes, I'll run a program that accidentally contains an infinite loop or something. Eclipse will let me continue editing the program, but be super slow. How can I stop it? (Do I want to restart the JVM?) Restarting eclipse itself always works, but that breaks my workflow.Open the Console view, locate the console for your running app and hit the Big Red Button.Alternatively if you open the Debug perspective you will see all running apps in (by default) the top left. You can select the one that's causing you grief and once again hit the Big Red Button.For newer versions of Eclipse:I have a .bat file on my quick task bar (windows) with:It's very quick, but it may not be good in many situations!The easiest way to do this is to click on the Terminate button(red square) in the console:For Eclipse:\nmenu bar-> window -> show view then find \"debug\" option if not in list then select other ... new window will open and then search using keyword \"debug\" -> select debug from listit will added near console tab.\nuse debug tab to terminate and remove previous executions. ( right clicking on executing process will show you many option including terminate)
Java

I don't know much regex, but I need to match a simple pattern. The following should return true,when inputLine isHowever, I'm getting this exception:What am I doing wrong?The  and  are special in Java's regex dialect (and most other dialects for that matter): they are the opening and closing tokens for the repetition quantifier  where  and  are integers. Hence the error message: \"Illegal repetition\".You should escape them: .And since you seem to be trying to parse JSON, I suggest you have a look at .There should be plus operator:Double apostrophes only when the string has to contain it.When the string including curly brackets use:
Java

My Eclipse javadoc view has a black background which makes it look  and partly unreadable (e.g. links are dark blue on black). Even worse, the javadoc popup has black background, too. I can't find the corresponding setting.The answer by Sumit Singh showed me how to change the background for the javadoc view. However, I still see no way how to change the foreground. Even worse, the javadoc popup background color didn't change.I don't think it's caused by a plugin, as it happens with a fresh install, too. This happens on Ubuntu 10.4. In Windows the colors can't be changed either, but there are fine.You need to change the 'Tooltip' color in Ubuntu at the OS level.  None of the answers here worked for me (I have Eclipse Mars and Ubuntu 14.04). I had to edit . I've changed  to  and  to . After restarting eclipse, the change took effect.As a KDE user you have to change the tooltip background color with .\nNavigate to and adjust the  and  colors.On ubuntu 12.10 (quantal) you can use the following two commands:(Thanks to the other answers and  that helped me to figure this out)Install the \"GNOME Color Chooser\" in Ubuntu (worked also on Xubuntu)There you can set the Tooltip colors under the tab \"Specific\"Had same issue with Neon on Ubuntu 16.04 Mate edition.To fix it, I have created a small, user-specific GTK3 CSS settings file. \nIt is stored as you HOMEDIR/.config/gtk-3.0/gtk.cssIn my case, I compressed the spacing a bit, specified default font and also, set the appearance for the tooltip windows:Please note, this issue has been resolved in Eclipse as of 8th November 2016.\nTo have this fixed, please download one of the latest  builds: \n\n(The maintenance builds don't have the patch at the time of writing 2016-11Nov-09Wed).I wrote a patch that introduced a new preference in Eclipse \"Information Background/Text\" under General -> Appearance -> Colors and Fonts.\nThis preference generates the correct color on Linux/Gtk (White background, black text).\nSee:\nBug 505738 \u2013 Define a information hover color which JDT, CDT or others can use \nSubsequently I made Javadoc colors inherit it's color from that preference. See:\nBug 501742 \u2013 Default Javadoc text and background color should use colors consistent with Java editor background/foreground. \nAs an added bonus, it also works on the Dark Theme:\nBug 505851 \u2013 [Dark Theme] Style the HOVER_ colors for the dark theme \nAlso try this  after I installed the lib the javadoc looks so much bettersource: I think the answer here to have a properly formattet tooltip (at least for people who use ubuntu and want to have a nice hover tooltip) with html elements like links working is to install libwebkitgtk as it is used by eclipse to show javadoc. It is not preinstalled on e.g. Ubuntu and does not come with eclipse.. use:and restart eclipse to have good looking tooltips.You can change the color in\n .
Java

I'm trying to find a way to iterate through an enum's values while using generics.  Not sure how to do this or if it is possible.  The following code illustrates what I want to do. Note that the code  is not valid in the following code.Here is how I would instantiate a Filter object:The enum is defined as follows:I realize it might not make sense to copy a enum's values to a list, but I'm using a library that needs a list of values as input and won't work with enums.EDIT 2/5/2010:Most of the answers proposed are very similar and suggest doing something like this:This would work great if I can be sure that selectedOption has a non-null value.  Unfortunately, in my use case, this value is often null, as there is a  no-arg constructor as well. This means I can't do a selectedOption.getClass() without getting an NPE.  This filter class manages a list of available options which of the options is selected. When nothing is selected, selectedOption is null.The only thing I can think to solve this is to actually pass in a Class in the constructor.  So something like this:Any ideas how to do this without needing an extra Class parameter in the constructors?This is a hard problem indeed. One of the things you need to do is tell java that you are using an enum. This is by stating that you extend the Enum class for your generics. However this class doesn't have the values() function. So you have to take the class for which you can get the values.The following example should help you fix your problem:Another option is to use EnumSet:Using an unsafe cast:For completeness, JDK8 gives us a relatively clean and more concise way of achieving this without the need to use the synthethic  in Enum class:Given a simple enum:And a test client:This will print :Code can be trivially adapted to retrieve different elements or to collect in a different way. If you are sure that  of the constructor  is not null. You can use reflection. Like this.Hope this helps.The root problem is that you need to convert an array to a list, right? You can do this, by using a specific type (TimePeriod instead of T), and the following code.So use something like this:Now you can pass list into any method that wants a list.If you declare Filter asthenAnd usage is quite easy:Here below an example of a wrapper class around an Enum.\nIs a little bit weird bu is what i need :}To get the  of the generic enumeration:Note in the above method the call to the toString() method.And then define the enumeration with such a toString() method.
Java

I have my class  with subclasses.I will get value of object  from parse :I try use .When I run my application without  app run success.\nWhen I run my app with  my app crash.I think problem is:  rename attribute  of my class to short . I try keep the names of the methods and attributes is constant, but  rename its:What is right way to keep names of the methods and attributes of the my one (static) class?If you dont want your class members to be obfuscated then use  annotation provided by Gson. For example:Moreover, make sure you do add proper proguard configuration for Gson library too. For example:For more info read .Thanks Waqas!I find solution for my case:Also I don't use  in my class, aboved config work fine without serialization.I also found I need to  when using Dexguard's optimise option. Without this several of my model objects failed to deserialise  If you use the  annotation like I do, you can tell ProGuard to keep any field annotated with it:To exclude your class from obfuscation, Keep the attributes of InnerClasses, keep your class and keep the class members of the class eg.For more information 
Java

I need to write an application with which I can do complex queries using spring-data and mongodb. I have been starting by using the MongoRepository but struggled with complex queries to find examples or to actually understand the Syntax. I'm talking about queries like this:or the use of JSON based queries which I tried by trial and error because I don't get the syntax right. Even after reading the mongodb documentation (non-working example due to wrong syntax).After reading through all the documentation it seems that  is far better documented then . I'm referring to following documentation: Can you tell me what is more convenient and powerful to use?  or ? Are both same mature or does one of them lack more features then the other?\"Convenient\" and \"powerful to use\" are contradicting goals to some degree. Repositories are by far more convenient that the templates but the latter of course give you more fine-grained control over what to execute.As the repository programming model is available for multiple Spring Data modules you find more in-depth documentation of it in the general section of the Spring Data MongoDB .We generally recommend the following approach:For your example this would look something like this:This way you essentially get the choice: everything that just easy to declare goes into , everything that's better implemented manually goes into . The customization options are documented .This answer may be a bit delayed, but I would recommend avoiding the whole repository route. You get very little implemented methods of any great practical value. In order to make it work you run into the Java configuration nonsense which you can spend days and weeks on without much help in the documentation. Instead, go with the  route and create your own Data access layer which frees you from the configuration nightmares faced by Spring programmers.  is really the savior for engineers who are comfortable architecting their own classes and interactions since there is lot of flexibility. The structure can be something like this:
Java

I ran the following code in my Android appIn  (Lollipop), it  throw any exception as  is an integer. But in  (KitKat) and lower versions it throws:How is the version of Android causing this difference?Support for explicit  was added in :which has been included starting with . If you have fetched the Git repository, you can verify with:which gives youEven though documentation can give insights into  the change was made (to achieve Java 7 behavior as other answers point out), analyzing the history of the source code gives the most accurate answer to  the behavior changed, since documentation does not necessarily match implementation.This behaviour is actually part of Java 7, as the  state: , in Java 6 only the  symbol was accepted. The Android SDK 21+ has JDK7 dependencies, which is presumably why you are experiencing this behaviour. It works after Java 7.Android 5 introduces the new parseInt feature like the Java 7 version - So this means that your Lollipop uses a newer sdk based on Java 7  which has the parseInt method with the sign handling part too. KitKat did introduce  into Android sdk 19, but not the new parseInt. Lower versions use an earlier implementation of parseInt (Java 6's version) so they will obviously fail as well.The difference between parseInt implementations : \n  vs This is a Java-specific issue. As you see in the documentation,  allows  and  allows  or . With Android Version 19 (KitKat) Java 7 is supported, so you don't get this error. I recommend not to use , because you only need a sign if you have a negative integer.
Java

I am trying to make a Java tool that will scan the structure of a Java application and provide some meaningful information.   To do this, I need to be able to scan all of the .class files from the project location (JAR/WAR or just a folder) and use reflection to read about their methods.   This is proving to be near impossible.I can find a lot of solutions based on URLClassloader that allow me to load specific classes from a directory/archive, but none that will allow me to load classes without having any information about the class name or package structure.EDIT:\nI think I phrased this poorly.  My issue is not that I can't get all of the class files, I can do that with recursion etc. and locate them properly.  My issue is obtaining a Class object for each class file.   The following code loads all classes from a JAR file. It does not need to know anything about the classes. The names of the classes are extracted from the JarEntry.edit:As suggested in the comments above, javassist would also be a possibility. \nInitialize a ClassPool somewhere before the while loop form the code above, and instead of loading the class with the class loader, you could create a CtClass object:From the ctClass, you can get all methods, fields, nested classes, ....\nTake a look at the javassist api:\nList All the classes inside jar file.Scanning all of the files in a folder is simple.  One option is to call  on the  that denotes the folder, then iterate the resulting array.  To traverse trees of nested folders, use recursion.Scanning the files of a JAR file can be done using the  API ... and you don't need to recurse to traverse nested \"folders\".Neither of these is particularly complicated.  Just read the javadoc and start coding.
Java

Following my previous question, , I decided to use just a single DAO for my data layer (at least at the beginning) in an application using JPA/Hibernate, Spring and Wicket. The use of generic CRUD methods was proposed, but I'm not very sure how to implement this using JPA. Could you please give me an example or share a link regarding this?Here is an example interface:And an implementation:Based on the article  we used this kind of technique for many years. We always struggled with problems with our patterns after we realized that we made a big mistake.By using an ORM tool such as Hibernate or JPA you will not have to think DAO and Service layer separately. You can use EntityManager from your service classes as you know the lifecycle of transactions and the logic of your entity classes there.Do you save any minute if you call  instead of simply ? No. You will have an unnecessary dao class that does nothing else but will be a wrapper around EntityManager. Do not afraid to write selects in your service classes with the help of EntityManager (or session in hibernate).One more note: You should define the borders of your service layer and do not let programmers to return or wait for Entity classes. The UI or WS layer programmers should not know at all about entity classes only about DTO-s. Entity objects have lifecycles that most of the programmers do not know about. You will have really serious issues if you store an entity object in a session data and try to update it back to the database seconds or hours later. Well you may would not do it but a programmer of the UI who knows the parameter types and return types of your service layer only would do to save some lines of code.I was looking for this same thing.  I found what appears to be exactly that- the  JPA project provided by SpringSource.  This is a code port from  and has now (Early 2011) been swallowed by Spring and better integrated.\nIt allows you to use a single dao (SimpleJpaRepository) with a static create, or extend the base JpaRepository class to create any object specific dao with ready made CRUD+ methods.  Also allows grails like queries just by using params names as the name of the method- in the interface (no implementation required!) i.e. \nLooks very promising- being part of Spring projects will certainly ensure some future for it too.\nI have begun implementing this in my upcoming project now.if you are looking for a third party implementation , you can check \n . it is a nnotation based generic DAO framework which supports JPA and hibernateYou may also have a look at The related code can be found on github It has integration with Spring and configuration examples for Hibernate and EclipseLink
Java

What is the difference between Java exception handling and using  conditions?It's known that Assert is of two types. But when should we use  keyword?Use assertions for internal logic checks within your code, and normal exceptions for error conditions outside your immediate code's control.Don't forget that assertions can be turned on and off - if you care about things like argument validation, that should be explicit using exceptions. (You could, however, choose to perform argument validation on  methods using assertions, on the grounds that a violation at that point is due to an internal bug rather than an external error.)Alternatively it's entire reasonable (IMO) to use exceptions for everything. I personally don't use assertions much at all, but it's a matter of personal preference to some extent. (There can certainly be objective arguments for and against assertions, but it's not sufficiently clear cut to remove preference altogether.)Java assertions are built on top of Java exceptions and exception handling.  Indeed, when a Java assertion fails, the result is an AssertionError exception that can be caught like any other Java exception. The key differences between exceptions and assertions are:Note: some people say that you should  run production code with assertion checking turned off.  I tend to disagree with this as a blanket statement.  If your production code is known to be stable AND you need to squeeze that last bit of performance out of it, then turning off assertions is good.  But, if a (say) 10% performance hit is not a real problem, I'd prefer to have an application die with an assertion error if the alternative is continue and corrupt my database.@Mario Orteg\u00f3n commented thus:Whether or not you think it is  to turn off assertions in production, it is definitely  to write assertions that have a significant impact on performance when enabled.  Why?  Because it means that you no longer have the option of enabling assertions in production (to trace a problem) or in your stress / capacity testing.  In my opinion, if you need to do  pre/post-condition testing, you should do it in your unit tests. Exception is a mechanism of checking if the implementation is executing without any expected or unexpected errors or not. So, we see that exceptions are basically used for handling even the unforseen conditions during the execution of an application in a better way and hence using exceptions effectively results into a robust application.Assertions should never be a part of the implementation of some functionality of the application. They should only be used to verify the assumptions - just to be sure that whatever we assumed while desinging the solution is actually valid in practical as well.reference: Example of a good use of Assert:I personally think that Assert should  be used when you know something is outside  limits, but you can be sure it's reasonably safe to continue. In all other circumstances (feel free point out circumstances I haven't thought of) use exceptions to fail hard and fast.The key tradeoff for me is whether you want to bring down a live/production system with an Exception to avoid corruption and make troubleshooting easier, or whether you have encountered a situation that should never be allowed to continue unnoticed in test/debug versions but could be allowed to continue in production (logging a warning of course).cf.  see also my c# copy of this answer: Assertions are very similar to exceptions, in fact just like exceptions they will flag a problem, but unlike exceptions - they won\u2019t suggest any alternative execution path, but will simply fail.\nWhy use assertions, if you can do the same thing, plus more with exceptions ?Use them when the problems should not be fixed, and actually SHOULD NEVER HAPPEN IN THE FIRST PLACE.   This sounds weird at first: don\u2019t we want to safeguard our code from ALL potential problems ?   Usually yes.   But there is a case where we don\u2019t.   This case is called: \u201cDesign by contract\u201d.Let say you are writing an application for a bank.  As a developer you can not possibly support all possible financial conditions.  So before starting to code, you get a spec from the bank which gives you the valid ranges that this application should support.   So your application is designed by a contract (by the spec from the bank).    This contract will define the fundamental principles that should always be true in order for your application to work.   These fundamental principles are called \u201cinvariants\u201d (because they can\u2019t change).  Design by contract simplifies your life as a developer - you are only responsible to support the scope of work defined in the contract.\nIts important to check the values of these invariants in your code, but you shouldn\u2019t check them as if they are exceptions and try to work around them.   If they are wrong - you must fail because the inputs have not fulfilled their contractual obligations.The interesting thing is: if you don\u2019t put an assertion into the critical place and invariants become invalid - your code will fail anyway.  You just won\u2019t know why.   So to summarize - assertions are used for verifying the invariants.  They go hand-in-hand with the \u201cdesign by contract\u201d principle.  Use them to debug a problem, thats why they are turned off in production.Another use case: if you are relying on an external library that you don\u2019t completely trust - you may want to use assert statements when calling it.Some also use assertions as a quick and dirty substitute for an exception (since its so easy to do), but conceptually that is not the proper thing to do.Assert is for debugging purpose only and its trigger condition should not happen (null pointer when there shouldn't be, etc.)Exception is for special system events that may always happen : FileNotFound, ConnectionToServerLost, etc.Assertion is used for debugging of the required assumptions to be checked at runtime only by enabling the assert feature while exception is to check the specific conditions to be checked during execution of the program to prevent the program from terminating.  
Java

I occasionally use a  instance variable in cases where I have two threads reading from / writing to it and don't want the overhead (or potential deadlock risk) of taking out a lock; for example a timer thread periodically updating an int ID that is exposed as a getter on some class:My question: Given that the JLS only guarantees that 32-bit reads will be atomic is there any point in  using a volatile long? (i.e. 64-bit).: Please do not reply saying that using  over  is a case of pre-optimisation; I am well aware of how / when to use  but there are cases where  is preferable.  For example, when defining a Spring bean for use in a single-threaded application I tend to favour  instance variables, as there is no guarantee that the Spring context will initialise each bean's properties in the main thread.Not sure if I understand your question correctly, but the  states:and, perhaps more importantly,  :That is, the \"entire\" variable is protected by the volatile modifier, not just the two parts. This tempts me to claim that it's  to use volatile for s than it is for s since  is atomic for non-volatile longs/doubles.This can be demonstrated by exampleCodeOutputNote this only happens for me when running on a 32 bit VM, on 64 bit VM I couldn't get a single error in several minutes.\"volatile\" serves multiple purposes:Is there more?
Java

Is there a way to get the parameters of a running JVM? Is there a command line tool like jstat which takes as input the pid of the JVM and returns its starting parameters? I am particularly interested in the -Xmx and -Xms values that were given when starting the JVM. Thank you.: To clarify my constraints. The JVM we would like to check is running on a production server. That's why, we prefer the minimum disruption. We are able to monitor the JVM using jstat, and so we hope there's a similar simple solution to access the parameters.: We also tried to get the parameters using jvisualvm. But in order to connect to a remote jvm, we need to run jstatd and modify the security settings of the JVM, which we found to be very disruptive and risky on a production server.You can use jps likeprints something likeAlternatively, you can use On Linux:On Mac OSX:On Windows:Source: JConsole can do it. Also you can use a powerful jvisualVM tool, which also is included in JDK since 1.6.0.8.If you can do this in java, try:You can use the JConsole command (or any other JMX client) to access that information.This technique applies for any java application running local or remote.jvisualvm can be found in any JDK since JDK 6 Update 7.  Video tutorial on jvisualvm is 
Java

I have an object of type X which I want to convert into byte array before sending it to store in S3. Can anybody tell me how to do this? I appreciate your help.What you want to do is called \"\". There are several ways of doing it, but if you don't need anything fancy I think using the  would do just fine. Perhaps you could use something like this?There are several improvements to this that can be done. Not in the least the fact that you can only read/write one object per byte array, which might or might not be what you want. Note that \"Only objects that support the  interface can be written to streams\" (see ).Since you might run into it, the continuous allocation and resizing of the  might turn out to be quite the bottle neck. Depending on your threading model you might want to consider reusing some of the objects.For serialization of objects that do not implement the  interface you either need to write your own serializer, for example using the read*/write* methods of  and the get*/put* methods of  perhaps together with reflection, or pull in a third party dependency. has a list and performance comparison of some serialization frameworks. Looking at the APIs it seems  might fit what you need.As i've mentioned in other, similar questions, you may want to consider compressing the data as the default java serialization is a bit verbose.  you do this by putting a GZIPInput/OutputStream between the Object streams and the Byte streams.Yeah. Just use . You have to have each object use  but it's straightforward from there.Your other option, if you want to avoid implementing the Serializable interface, is to use reflection and read and write data to/from a buffer using a process this one below:.Use  and  methods in  from .To convert the  use the  concept of .The complete  explained in is tutorial. 
Java

I wrote a servlet in Java and I would like to know if the request to that servlet was executed using HTTP or HTTPS.I thought I can use  but it returns HTTP/1.1 on both methods.Any ideas? is the answer. The ServletContainer is responsible for returning true in the following cases:The Container should also make this request attributes available when the request is received on :You can't reliably depend on port numbers.\nBut you can depend on the scheme:  Use:  to see if it is .  If it is then it is secure connection.  I believe this should work regardless of Tomcat version.  Be sure to check the inherited methods.https and http runs on different ports. So you can get the port from the request and know from which port the request came and so that you can know the protocol.\n    int port=request.getServerPort();
Java

I want to merge many PDF files into one using  and this is what I've done:Where  is an  containing all the PDF files.When I'm running the above, I'm always getting:Am I doing something wrong?  Is there any other way of doing it?Why not use the  of pdfbox?A quick Google search returned this bug: .It looks like you need to keep the PDFs to be merged open, until after you have saved and closed the combined PDF.This is a ready to use code, merging four pdf files with itext.jar from , more on If you want to combine two files where one overlays the other (example:  document A is a template and document B has the text you want to put on the template), this works:after creating \"doc\", you want to write your template (templateFile) on top of that -
Java

I want to use Mockito to test the (simplified) code below. I don't know how to tell Mockito to fail the first time, then succeed the second time.I can setup the success test with:And the failure test with:But how can I test that if it fails once (or twice) then succeeds, it's fine?From :So in your case, you'd want:The shortest way to write what you want isWhen you supply mutiple arguments to  like this, each argument will be used at most once, except for the very last argument, which is used as many times as necessary.  For example, in this case, if you make the call 4 times, you'll get \"Success\", \"you failed\", \"you failed\", \"you failed\".Since the comment that relates to this is hard to read.  I'll add a formatted answer.If you are trying to do this with a void function.  Where you might want an exception than no behavior.  Then you would do something like this:
Java

What is \"runnable\" in Java, in layman's terms? I am an AP programming student in high school, whose assignment is to do research, or seek out from others what \"runnable\" is (we are just getting into OOP, and haven't touched threads yet).A Runnable is basically a type of class (Runnable is an Interface) that can be put into a thread, describing what the thread is supposed to do.The  requires of the class to implement the method  like so:And then use it like this:If you did not have the  interface, the Thread class, which is responsible to execute your stuff in the other thread, would not have the promise to find a  method in your class, so you could get errors. That is why you need to implement the interface.Note that you do not need to define a class as usual, you can do all of that inline:This is similar to the above, only you don't create another named class. is an interface defined as so:To make a class which uses it, just define the class as It can be used without even making a new Thread. It's basically your basic interface with a single method, run, that can be called. If you make a new Thread with runnable as it's parameter, it will call the run method in a new Thread. It should also be noted that Threads implement , and that is called when the new Thread is made (in the new thread). The default implementation just calls whatever Runnable you handed in the constructor, which is why you can just do  without overriding Thread's  method. 
Java

I have rather simple HttpClient 4 code that calls HttpGet to get HTML output. The HTML returns with scripts and image locations all set to local (e.g. ) so I need calling URL to make these into absolute () Now comes the problem - during the call there may be one or two 302 redirects so the original URL is no longer reflects the location of HTML. How do I get the latest URL of the returned content given all the redirects I may (or may not) have?I looked at  and  - couldn't find anything.Edited:  returns original calling addressThat would be the current URL, which you can get by calling EDIT: You didn't mention how you are doing redirect. That works for us because we handle the 302 ourselves.Sounds like you are using DefaultRedirectHandler. We used to do that. It's kind of tricky to get the current URL. You need to use your own context. Here are the relevant code snippets,The default redirect didn't work for us so we changed but I forgot what was the problem.In HttpClient 4, if you are using  or any subclass of , this is the recommended way (see source code of ) :Since HttpClient 4.3.x, the above code can be simplified as:An IMHO improved way based upon ZZ Coder's solution is to use a ResponseInterceptor to simply track the last redirect location. That way you don't lose information e.g. after an hashtag. Without the response interceptor you lose the hashtag. Example: use it just like ZZ Coder's solution: I think easier way to find last URL is to use DefaultRedirectHandler.Code to use this handler:  In version 2.3 Android still do not support following redirect (HTTP code 302). I just read location header and download again:No circular redirects protection here so be careful. More on by blog I found this on This is how I managed to get the redirect URL:Or, if you are sure that there is only one redirect location, do this:
Java

What is the difference between return 0, return 1 and return -1 in compareTo() in java?..From the reference docs of :In short:returns where the implementation of this method determines the actual semantics of   and  (I don't mean  in the sense of java's object identity operator)will yield something smaller than 0 as  is alphabetically before .will yield something larger than 0 because 2 is larger than 1. It is good practice for a class that implements Comparable to declare the semantics of it's compareTo() method in the javadocs. you should read at least one of the following: you should never rely on the return values of compareTo being ,  and . You should always test for , , , respectively.I use this mnemonic :You keep the signs and always compare the result of  to 0Answer in short: (search your situation)take example if we want to compare \"a\" and \"b\", i.e (\"a\" == this)It can be used for sorting, and 0 means \"equal\" while -1, and 1 means \"less\" and \"more (greater)\".Any return value that is less than 0 means that left operand is lesser, and if value is bigger than 0 then left operand is bigger.The  method returns an int with the following characteristics:
Java

The following is a simple loop in C++. The timer is using QueryPerformanceCounter() and is quite accurate. I found Java to take 60% of the time C++ takes and this can't be?! What am I doing wrong here? Even strict aliasing (which is not included in the code here) doesn't help at all...This C++ runs through in about 9.5 seconds. I am using the Intel Compiler 12.1 with host processor optimization (specifically for mine) and everything maxed. So this is Intel Compiler at its best! Auto-Parallelization funnily consumes 70% CPU instead of 25% but doesn't get the job done any faster ;)...Now I use the following Java code for comparison:The Java code is invoked with aggressive optimization and the server VM (no debug). It runs in about 7 seconds on my machine (only uses one thread).Is this a failure of the Intel Compiler or am I just too dumb again?[EDIT]: Ok now heres the thing... Seems more like a bug in the Intel compiler ^^. \n[Please note that I am running on the Intel Quadcore Q6600, which is rather old. And it might be that the Intel Compiler performs way better on recent CPUs, like Core i7][EDIT]: Another nice case ;). Consider the following trivial lambda expressionIntel compiler shines again:Uhm?! Well, I guess 90 times slower is not a bad thing...I am not really sure anymore that this applies:\n Here is the x64 output of the Intel Compiler:And this one is the assembly of the MSVC x64 build:Intel Compiler configured without Vectorization, 64-Bit, highest optimizations (this is surprisingly slow, 12 seconds):Intel Compiler without vectorization, 32-Bit and highest optimization (this one clearly is the winner now, runs in about 3 seconds and the assembly looks much better):tl;dr: What you're seeing here seems to be .Here's the critical loop:What you see here is the standard loop unrolling by the compiler. MSVC is unrolling to 4 iterations, and splitting the  variable across four registers: , , , and . Then at the end of the loop, these 4 registers are summed up back together.Here's where the 4 sums are recombined:What you're seeing here is an attempt by ICC to vectorize this loop. This is done in a similar manner as what MSVC did (splitting into multiple sums), but using SSE registers instead and with two sums per register.If we walk these instructions down one-by-one, we can see how ICC tries to vectorize it:So it's doing some very messy unpacking just to vectorize. The mess comes from needing to sign-extend the 32-bit integers to 64-bit using only SSE instructions.SSE4.1 actually provides the  instruction for this purpose. But either the target machine doesn't support SSE4.1, or ICC isn't smart enough to use it in this case.But the point is:You changed the data-type to . So now it's floating-point. There's no more of that ugly sign-fill shifts that were plaguing the integer version.Not much here - standard vectorization + 4x loop-unrolling.No vectorization + only 2x loop-unrolling.All things equal, disabling vectorization will hurt performance in this floating-point case.The example is simple enough that the different languages should not make a difference, and stupid enough not to prove anything. The loop could be optimised away by a compiler into a simple assignment, or left running for the whole number of iterations, or some of the iterations might be unrolled... I am not sure why you decided to write that test program, but it does not test anything regarding the languages, as once the logic optimisations are performed it all boils down to exactly the same assembly.Also, regarding the performance of the intel compiler, it will greatly depend on the exact hardware and the compiler version. The compiler generates different versions of the code, and has a tendency to generate horrible code for AMD processors. Even for intel, if it does not recognise the specific processor it falls back into a safe slow mode.You've got some data in one hand, and an assumption (C++ is always faster than Java) in the other.  Why ask for people to justify your assumption when the data tells you otherwise?If you wish to obtain assembly from the JVM in order to compare what's being run then the commandline option is '-XX:+PrintOptoAssembly', but you'll need to download a debug jvm in order to do so.  Looking at the assembly would at least tell you why one is faster than the other.Just for the record, I ran both codes on my box (x86_64 linux), the C++ with , a plain  and, for completeness also with  instead of . Java (open-jdk 1.6) clocked it at 3.8s, C++ (int) at 3.37s, and C++ (long) at 3.9s. My compiler was g++ 4.5.1. Maybe it's just Intel's compiler that's not as good as thought.I think Java compiler implements JITC (Just in time compilation, or some more recent technology) to approach native compilers speed, and could infer that your array doesn't change, and thus could apply constant folding to the inner loop...I suspect the culprit is simple loop unrolling.  Replacewithand observe how much faster the C++ version runs.i see you are running the following looptwice in the Java code; while once in the c++ code;\nthis might bring a caches warmup which makes the Java code finally execute faster than the C++.
Java

I have learned that the JNI interface pointer (JNIEnv *) is only valid in the current thread. Suppose I started a new thread inside a native method; how it can asynchronously send events to a Java method? As this new thread can't have a reference of (JNIEnv *). Storing a global variable for (JNIEnv *) apparently will not work?This is how I've used it in the past, see my Since the callback is on another thread the VM context must be attached to the current thread. Once attached the method can be called.You can obtain a pointer to the JVM () with . You can safely store that pointer as a global variable. Later, in the new thread, you can either use  to attach the new thread to the JVM if you created it in C/C++ or simply  if you created the thread in java code which I do not assume since JNI would pass you a  then and you wouldn't have this problem.
Java

Here is the question: write a method that swaps two variables. These two variables should be primitives. It doesn't need to be generic e.g. two  variables. Is there a way?!Without using an array or objects, no, it is not possible to do it within a method.While it is not possible to write a function that simply swaps two variables, it is possible to write a  that allows you to:That's how you could do it:This works because the Java language guarantees (Java Language Specification, Java SE 7 Edition, section 15.12.4.2) that all arguments are evaluated from left to right (unlike some other languages, where the order of evaluation is undefined), so the execution order is:If  is too long, you can choose a shorter name to make code more compact (e.g. ). Use this to impress your friends and confuse your enemies :-)Check out this JavaWorld article that explains it in detail:A swap of two primitives will never work because primitives are passed by value in Java. You can't even write a method to swap two objects for that matter.  Like @Thomas said, the only thing you could do is have your primitives contained within other objects/arrays and modify those.You can make a generic version of @marcus's swap method that swaps any number of objects of the same type:The AtomicInteger class (and others) have  atomic methods ..To write a swap method that swaps primitives you'd have to have the concept of \"out\" variables, i.e. variables whose values are passed up to the calling context. C# has those but you must still specify that they're out variables.One-liner for any primitive numbers:This function will swap two intsHere's a method that swaps two primitive variablesIt might not be of much use though ;)Ok seriously, it could be done if the variables are class level:Again though, I fail to see what the use of this could beI have read the above answers seeking an explanation as to why it is said that a swapping program cannot be written in java in the way it is written in c++.\n I did the following way\nAs Thomas Owens said. You could probably do it in C by passing variables by &reference, but afaik not in Java without using objects.Yes it is possible to swap two variable using a method.\n .\nHere is an example that illustrates swapping of two variable using a method.public class Swapping{}By compiling the above code the output comes as follows:Before swappingA= AppleB= BatAfter swappingA= BatB= Apple//In case of call by reference original value is changed if we made changes in the called method
Java

I've created a  and it only has two buttons  .After  pops out , I want to click  to continue opening the  and if I clicked  it should cancel the operation.It seems pretty easy but I'm not sure where is my mistake.Code Snippet:You need to look at the return value of the call to .  I.E.:You were testing against , which you were using to set the buttons that should be displayed by the dialog, and this variable was never updated - so  would never have been anything other than .Per the Javadoc for :Try this,First Take Result (Value) of  to integer variable as it always gives integer result and then compare that variable with  that is Yes or NO, in your case written as.IF you want Help on MessageDialogues or any.... visit link below it will help you.\n
Java

Is there any overhead in Java for using a  block, as opposed to an  (assuming that the enclosed code otherwise does not request so)?For example, take the following two simple implementations of a \"safe trim\" method for strings:If the  input is only rarely ,  between the two methods?Furthermore,  to use the  approach for simplifying the layout of code, especially when many  checking rare error conditions can be avoided by enclosing the code in one try/catch block?For example, it is a common case to have a method with , which uses  of them near its start, failing quickly and deterministically if any such parameter is \"invalid\" (e.g., a null or empty string), without affecting the rest of the code.In such cases, instead of having to write   (where  is the average number of checks per parameter, e.g.  for null or empty strings), a  block would significantly shorten the code and a 1-2 line comment could be used to explicitly note the \"unconventional\" logic.Such a pattern would also speed up the method, especially if the error conditions occur rarely, and it would do so without compromising program safety (assuming that the error conditions are \"normal\", e.g. as in a string processing method where null or empty values are acceptable, albeit seldom in presence).I know you're asking about performance overhead, but you really should not use / and  interchangeably./ is for things that go wrong that are outside of your control and not in the normal program flow.  For example, trying to write to a file and the file system is full?  That situation should typically be handled with /. statements should be normal flow and ordinary error checking.  So, for example, user fails to populate a required input field?  Use  for that, not /.It seems to me that your example code strongly suggests that the correct approach there is an  statement and not a /.To answer your question, I would surmise that there is generally more overhead in a / than an .  To know for sure, get a Java profiler and find out for the specific code you care about.  It's possible that the answer may vary depending on the situation.This question has almost been \"answered to death\", but I think there are a few more points that could usefully be made: There are also issues with the way that you've written the example:... and most of the points in my answer are not about null values!Yes there are situations where  values are expected, and you need deal with them.But I would argue that what  is doing is (typically) the wrong way to deal with .  Compare these three bits of code:Ultimately you have to deal with the  differently from a regular string, and it is  a good idea do this as soon as possible.  The further the  is allowed to propagate from its point origin, the more likely it is that the programmer will  that a  value is a possibility, and write buggy code that assumes a non-null value.  And forgetting that an HTTP request parameter could be missing (i.e. ) is a classic case where this happens.I'm not saying that  is inherently bad.  But the fact that a programmer feels the need write methods like this is  indicative of less than ideal null handling. Use the second version. Never use exceptions for control flow when other alternatives are available, as that is not what they are there for. Exceptions are for exceptional circumstances. While on the topic, do not catch  here, and especially do not swallow it. In your case, you would expect a . If you were to catch something, that is what you would catch (). When you catch (and swallow!) , you are saying \"no matter what goes wrong, I can handle it. I don't care what it is.\" Your program might be in an irrevocable state! Only catch what you are prepared to deal with, let everything else propogate to a layer that  deal with it, even if that layer is the top layer and all it does is log the exception and then hit the eject switch.Otherwise exceptions are fast to throw and catch (though an  is probably still faster), but the slow thing is creating the exception's stack trace, because it needs to walk through all of the current stack. (In general it's bad to use exceptions for control flow, but when that really is needed and the exceptions must be fast, it's possible to skip building the stack trace by overriding the  method, or to save one exception instance and throw it repeatedly instead of always creating a new exception instance.)As far as overhead goes, you can test for yourself:}The numbers I got are:As far as what style - it is a whole separate question. The if statement looks pretty natural, but the try looks  really strange for multiple reason:\n- you caught Exception even though you are checking for NULL value, are you expecting something \"exceptional\" to happen (otherwise catch NullException)?\n- you caught that Exception, are you going to report it or swallow?\netc. etc. etc. Edit: See my comment for why this is an invalid test, but I really didn't want to leave this standing here. Just by swapping tryTrim and ifTrim, we suddenly get the following results (on my machine):Instead of starting to explain all of this, just read  for the beginning - Cliff also has some great slides about the whole topic, but I can't find the link at the moment.Knowing how exception handling works in Hotspot, I'm fairly certain that in a correct test try/catch without an exception) would be the baseline performance (because there's no overhead whatsoever), but the JIT can play some tricks with Nullpointer checks followed by method invocations (no explicit check, but catch the hw exception if the object is null) in which case we'd get the same result. \nAlso don't forget: We're talking about the difference of one easily predictable if which would be ONE CPU cycle! The trim call will cost a million times that.
Java

I have a long text in one of the strings at strings.xml. I want to make bold and change the color of some words in that text.How can I do it?thanks in advanceYou could basically use html tags in your string resource like: And use Html.fromHtml or use spannable, check the link I posted. Old similar question: 
Java

What is the correct way to invoke stored procedures using modern day (circa 2012) Spring JDBC Template?Say, I have a stored procedure that declares both  and  parameters, something like this:I have come across  based approaches where we have to explicitly register  and  parameters. Consider the following method in  class:Of course, I do know that I can use it like so:What is the purpose of  when I am already registering them in my  implementation? In other words, why would I need to pass in a  when spring can simply do  internally? Basically, can't I pass in either one of them instead of both of them?Or, is there a much better way to call stored procedures (using Spring JDBC Template) than what I have come across so far? You may find many questions that appear to have a similar title but they are not the same as this one.There are a number of ways to call stored procedures in Spring.If you use  to declare parameters, you will be using Java's standard interface of , i.e register out parameters and set them separately. Using  abstraction will make your code cleaner.I recommend you looking at . It may be used like this:For simple procedures you may use 's  method:I generally prefer to extend Spring based  class to execute stored procedures.Hope this helps you.Here are the ways to call the stored procedures from javaHere we externally manage the resource closingOne more way to call stored procedure is:In this example 'ClientInvestigateDTO' is the POJO class and 'ClientInvestigateMapper' is the mapper class.'client' stores all the result you get on calling the stored procedure.
Java

Is it no option to exclude some tests in IntelliJ IDEA Ultimate? I want to run unit tests in IntelliJ but exclude the integration tests. I name the integration tests with  so the Maven failsafe plugin can run them seperatly from the unit tests.In the  Run configuration set the  to , specify the following regular expression as the pattern:It matches against the class name, so you don't need to match  extension. Regular expression will not match if the class name ends with  using the .I would split them to that they are in different packages. They are doing different things after all. You can then run your tests per package.  link details how to do this.
Java

Is there a Maven 2 archetype for a simple Servlet (2.5) web application? There  an archetype for :This will generate the following structure:Where the web.xml is a Servlet 2.3 web.xml:For a Servlet 2.5 web application, replace it with something like this:I don't know for NetBeans but Eclipse (more precisely M2Eclipse) relies on the  to set the project facets (so you need to change the  before the import, Eclipse won't update the web facet if you change the  after the facts).I have created simple archetype for creating Servlet 3 based webapps: Just clone it, install and generate project that uses Servlet 3, no XML, Tomcat7 ready (plugin included)you can start with For a list of other archetypes,please refere to \nUpdated archetype number.Refer this link  and follow this link for .Frequently used archetype numbers are:OR just use below handy maven command-command:\nmvn archetype:create -DgroupId=com.lei.webapp.quickstart  -DartifactId=webapp-quick-start   -DarchetypeArtifactId=maven-archetype-webapp I let the IDE (mine is Intellij IDEA) create the basic webapp structure for me.Go to:This will give the basic webapp structure.
Java

MySQL has a handy function:This can be used to create simple, but very specific, name based locks for an application. However, it requires a database connection.I have many situations like:It doesn't make sense to simply synchronize this method, because, for example, if this method is called for user B in the meantime, user B does not need to wait for user A to finish before it starts, only operations for the user A and feature X combination need to wait.With the MySql lock I could do something like:Since Java locking is based on objects, it seems like I would need to create a new object to represent the situation for this lock and then put it in a static cache somewhere so all the threads can see it. Subsequent requests to lock for that situation would then locate the lock object in the cache and acquire its lock. I tried to create something like this, but then the lock cache itself needs synchronization. Also, it is difficult to detect when a lock object is no longer being used so that it can be removed from the cache.I have looked at the Java concurrent packages, but nothing stands out as being able to handle something like this. Is there an easy way to implement this, or am I looking at this from the wrong perspective?To clarify, I am not looking to create a predefined pool of locks ahead of time, I would like to create them on demand. Some pseudo code for what I am thinking is:maybe this is useful for you: Edit:My initial response was probably a bit short. I am the author and was faced with this problem several times and could not find an existing solution. That's why I made this small library on Google Code.All those answers I see are way too complicated. Why not simply use:The key point is the method : it ensures that the String returned is a global unique object, and so it can be used as a vm-instance-wide mutex. All interned Strings are held in a global pool, so that's your static cache you were talking about in your original question. Don't worry about memleaks; those strings will be gc'ed if no other thread references it. Note however, that up to and including Java6 this pool is kept in PermGen space instead of the heap, so you might have to increase it.There's a problem though if some other code in your vm locks on the same string for completely different reasons, but a) this is very unlikely, and b) you can get around it by introducing namespaces, e.g. Can you have a ? Each time you require a lock, you basically call .Here's an example using :Then  will cause a new lock to be created  and returned to you. You can then call  on that lock.  returns a Map that is thread-safe, so you can just share that with all your threads.For locking on something like a user name, in-memory s in a map might be a bit leaky. As an alternative, you could look at using s with  to create mutex objects that can be garbage collected when nothing refers to them. This avoids you having to do any manual reference counting to free up memory.You can find an implementation . Note that if you're doing frequent lookups on the map you may run into contention issues acquiring the mutex.A generic solution using java.util.concurrentBased on the  and his class , I have written the generic class  that uses  to store lock objects.  can be used to retrieve a lock object for a key, which can then be used with the Java  statement to apply a lock. Unused lock objects are automatically freed during garbage collection.Example of how to use the LockMap class:A simple test program for the LockMap class:If anyone knows a better way to automatically test the LockMap class, please write a comment.Maybe a little later but you can use Google Guava Maybe something like that:I didn't test it though.2 years later but I was looking for a simple named locker solution and came across this, was usefull but I needed a simpler answer, so below what I came up with. Simple lock under some name and release again under that same name.Here is the code:After some disappointment that there is no language level support or simple Guava/Commons class for named locks,This is what I settled down to:Here I achieved: little boilerplate code with no library dependency, atomically acquiring the lock object, not polluting the global interned string objects, no low-level notify/wait chaos and no try-catch-finally mess.I'd like to notice that  has built-in locking facility that is enough for simple exclusive multithread lock. No additional  objects needed.Here is an example of such lock map used to enforce at most one active jms processing for single client.Similar to the answer from Lyomi, but uses the more flexible ReentrantLock instead of a synchronized block.Yes this will grow over time - but using the ReentrantLock opens up greater possibilities for removing the lock from the map. Although, removing items from the map doesn't seem all that useful considering removing values from the map will not shrink its size. Some manual map sizing logic would have to be implemented.Often times, synchronization needed for a particular key is short-lived.  Keeping around released keys can lead to excessive memory waste, making it non-viable.Here's an implementation does not internally keep around released keys.If one wants re-entrant lock semantics, they can extend the above by wrapping the mutex object in a class that keeps track of the locking thread and locked count.e.g.:If one wants  to return an object to make releases easier and safer, that's also a possibility.Putting it all together, here's what the class could look like:And here's how one might use it:In response to the suggestion of using new MapMaker().makeComputingMap()...MapMaker().makeComputingMap() is deprecated for safety reasons. The successor is CacheBuilder. With weak keys/values applied to CacheBuilder, we're soooo close to a solution.The problem is a note in CacheBuilder.weakKeys():This makes it impossible to select an existing lock by string value. Erg.(4 years later...)\nMy answer is similar to user2878608's but I think there are some missing edge cases in that logic. I also thought Semaphore was for locking multiple resources at once (though I suppose using it for counting lockers like that is fine too), so I used a generic POJO lock object instead. I ran one test on it which demonstrated each of the edge cases existed IMO and will be using it on my project at work. Hope it helps someone. :) I've created a tokenProvider based on the  of McDowell.\nThe manager uses a  which takes care of cleaning up unused locks.TokenManager:\nUsage:or rather use Integers?Your idea about a shared static repository of lock objects for each situation is correct.\nYou don't need the cache itself to be synchronized ... it can be as simple as a hash map.Threads can simultaneously get a lock object from the map. The actual synchronization logic should be encapsulated within each such object separately (see the java.util.concurrent package for that - )TreeMap because in HashMap size of inner array can only increase 
Java

I have a package in which I import javax.servlet.* and javax.servlet.http.*\nWhen I try to compile it in command prompt I get the errorI use JDK 1.7.0 and Tomcat 6.0.You need to add the path to Tomcat 6's  file to the compile time classpath.The classpath is where Java needs to look for imported dependencies. It will otherwise default to the current folder which is included as  in the above example. The  is the path separator for Windows; if you're using an Unix based OS, then you need to use  instead.If you are working with maven project, then add following dependency to your pom.xmlIs it a JSP or Servlet?Well, these two packages aren\u2019t actually built into Java like java.io is. Instead, they come with the Servlet-capable Web server (e.g. Tomcat). So before the Java compiler will be able to compile our Servlet, we need to let it know where to find the classes in these two packages.The classes required are normally stored in a file called servlet.jar. The exact location of this file will depend on the particular Web server software you use, but in the case of Tomcat you can find it in the lib subdirectory of the main Tomcat installation directory (e.g. d:\\Program Files\\Apache Group\\jakarta-tomcat-3.2.3\\lib\\servlet.jar). For the Java compiler to be able to compile Servlets, you need to add this file to your Java class path. By default, Java looks for classes in the current directory (\".\") only. Thus, \".\" is the default class path. If you change the class path to include the servlet.jar file (\".;d:...\\lib\\servlet.jar\" under Windows, \".:/usr/.../lib/servlet.jar\" in Unix), then the Servlet should compile just fine.You can specify a class path to use when you run javac.exe as follows:Or in Linux javac uses : instead of ;In a linux environment the soft link apparently does not work. you must use the physical path. for instance on my machine I have a softlink at  and using this as my classpath argument led to a failed compile with the same error. instead I had to use  which is the file that the soft link pointed to.This is what solved the problem for me:Add servlet-api.jar into your classpath. It will be available into Tomcat's lib folder.This is what I found. Adding /usr/local/apache-tomcat-7.0.64/lib/servlet-api.jar in my environment variable as CLASSPATH. OS is iOS.if using bash: ~/.bash_profile if using zsh: ~/.zshrc export Force it work right now, run  (or .zshrc)\nor one can restart computer and it works for the current user.JSP and Servlet are Server side Programming. As it comes as an built in package inside a Server like Tomcat. \nThe path may be like wise  Just you want to Do is Add this in the following way 
Java

Let's say I want this query to be a valid string in Java. Do I have to convert it to escape all double quotes with a trailing slash in front?Or is there a faster way to make this whole query a valid string at once? I thought you could use single quotes around the whole string to do that but that doesn't work either.Escaping the double quotes with backslashes is the only way to do this in java. Some IDEs around such as  do this escaping automatically when pasting such a String into a String literal (i.e. between the double quotes surrounding a java String literal)One other option would be to put the String into some kind of text file that you would then read at runtimeUse Java's For example, Use a substitution char for the quotes and then replace that char with or replace all instances of  with For a String constant you have no choice other than escaping via backslash.Maybe you find the  project interesting. It is a thin layer over JDBC where you can externalize your SQL queries in XML configuration files without the need to escape double quotes.Yes you will have to escape all double quotes by a backslash.
Java

Is there a specific rule on how Overriding  &  in  considering  ?? knowing that there is many parameters : super fields are private/public , with/without getter ...For instance, Netbeans generated equals() & hashCode() will not consider the super fields ... andwill return true :(If you want to see the Netbeans generated equals() & hashCode() :But , all significant fields should be taken into account for equality and hashing.Fortunately, you you can easily satisfy both rules.Assuming you're not stuck using the NetBeans-generated equals and hashcode, you can modify Hominidae's equals method to use instanceof comparison rather than class equality, and then use it straightforwardly. Something like this:Of course, hashcode is easy:Seriously, though: what's up with NetBeans not taking superclass fields into account by calling the superclass methods?I prefer to use  (and HashcodeBuilder) from the  to make my equals() and hashcode() methods a lot easier to read.Example:Generally speaking implementing equals across subclasses is hard to keep symmetric and transitive.Consider a superclass that checks for field x and y, and subclass checks for x y and z.So a Subclass == Superclass == Subclass  where z is different between the first instance of Subclass and the second, violating the transitive part of the contract.This why the typical implementation of equals will check for  instead of doing an instanceof. In the above example, if SubClass or Superclass does an instanceof check it would break symmetry.So the upshot is that a subclass can certainly take into account super.equals() but should also do its own getClass() check to avoid the above issues and then check for equals on its own fields in addition. It would be a strange duck of a class that changed its own equals behavior based on specific fields of the superclass rather than just if the superclass returns equals.The rules are:from .  So, use the fields needed to fulfill the rules.Because inheritance breaks encapsulation, subclasses that implement equals() and hashCode() must, necessarily, account for the peculiarities of their superclasses.  I've had success encoding calls to the parent class's equals() and hashCode() methods from the subclass's methods.Regarding the accepted @CPerkins answer, I don't think the given equals() code will work reliably, due to the likelihood that the super.equals() method will also check for class equality. A subclass & superclass will not have equal classes.It sounds like your parent (super) class doesn't override equals. If this is the case then you need to compare the fields from the parent class when you override this method in the sub-class. I agree that using the commons EqualsBuiler is the way to go but you do need to be careful that you don't break the symmetry/transative portions of the equals contract.If your sub-class adds attributes to the parent class and the parent class isn't abstract and overrides equals you're going to get in to trouble. In this scenario you should really look at object composition instead of inheritance.I'd strongly recommend the section in Effective Java by Joshua Block on this. It's comprehensive and really well explained.Well,  will be enough with CPerkins's answer.If you want those parent's fields(, , ) in action, one way is creating an actual instance of parent type and use it. Thank God, it's not an abstract class.I'm adding a way to (I think) solve this. The key point is adding a method loosely checks the equality.And here comes the .public class Child extends Parent {Testing...It's worth noting that the IDE auto generation maybe has taken into consideration super class\uff0cjust provided that the equals() and hashCode() of super class exists yet. That is, should auto generate these two functions of super first, and then auto generate of the child. I got below right example under Intellj Idea:The problem happens just when you don't auto generate super's in first. Please check above under Netbeans.
Java

Is it possible in Java to make a Dictionary with the items already declared inside it? Just like the below C# code:How do I do this and what type do I use? I've read that Dictionary is obsolete.This will do what you want:This statment creates an anonymous subclass of HashMap, where the only difference from the parent class is that the 4 entries are added during instance creation. It's a fairly common idiom in the Java world (although some find it controversial because it creates a new class definition).Bite the bullet and type out the map name!You could also do something like this, which might save some typing with a long list:If you use the , you can use its  class, either by itself (examples 1 and 2), or as an initializer for a HashMap (examples 3 and 4):Java7 almost introduced \"collection literals\" that would allow syntax like that. They'll probably try to shove it in Java8. I have no idea what is wrong with these people.This can be easily achieved by some kind of wrapper APINot too bad. I would prefer something likeThis kind of thing must have been implemented by various people, unfortunately the standard API doesn't inculde such things.
Java

Can somebody explain what the exact difference is between  and ?In what situations would we have to use each Receiver class?There is only one difference between  and .When you receive the broadcast inside  method,Suppose,  : :Example:Here, when you receive broadcast, you are starting a service, as you are using , it will hold  and won't let the CPU sleep until you finish the work inside service and fire Code:
Java

I am aware that you can lock an object in c# using lock but can you give up the lock and wait for something else to notify you that it's changed like you can in java with wait and notify?It seems to me that synchronised and lock in java and c# respectively are synonomous.The equivalent functionality (including the normal locking) is in the  class. The  statement in C# is equivalent to calling  and  with an appropriate try/finally block.See  or  for more details.I think Wait Handles may work for you. See if  helps.
Java

I am trying to use Gson to deserialize a json string returned from my webservice The structure would be returned as .where  is likeand ItemDTO is likeWhen I call the code as followsEverything inside the objects is nullHowever, If I use the  and  to pull them out piece by piece from the org.json jars, it works fine and the fields are populated accordingly.Any ideas as to what I'm doing wrong? is Gson extremely fast?\nOr am I better to stick with what I've got working already?Thanks,\nDavid The example Java data structure in the original question does not match the description of the JSON structure in the comment.The JSON is described as \"an array of {object with an array of {object}}\".In terms of the types described in the question, the JSON translated into a Java data structure that would match the JSON structure for easy deserialization with Gson is \"an array of {TypeDTO object with an array of {ItemDTO object}}\".But the Java data structure provided in the question is not this.  Instead it's \"an array of {TypeDTO object with an array of an array of {ItemDTO object}}\".A two-dimensional array != a single-dimensional array.This first example demonstrates using Gson to simply deserialize and serialize a JSON structure that is \"an array of {object with an array of {object}}\".This second example uses instead a JSON structure that is actually \"an array of {TypeDTO object with an array of an array of {ItemDTO object}}\" to match the originally provided Java data structure.Regarding the remaining two questions:Not compared to other deserialization/serialization APIs.  Gson has traditionally been  the .  The current and next releases of Gson reportedly include significant performance improvements, though I haven't looked for the latest performance test data to support those claims.That said, if Gson is fast enough for your needs, then since it makes JSON deserialization so easy, it probably makes sense to use it.  If better performance is required, then Jackson might be a better choice to use.  It offers much (maybe even all) of the conveniences of Gson.I wouldn't.  I would most always rather have one simple line of code like ...to easily deserialize into a complex data structure, than the thirty lines of code that would otherwise be needed to map the pieces together one component at a time.
Java

I'm confused with Heap,Young,Tenured and Perm generation. Could anyone please explain?The Java garbage collector is referred to as a . Objects in an application live for varying lengths of time depending on where they are created and how they are used. The key insight here is that using different garbage collection strategies for short lived and long lived objects allows the GC to be optimised specifically for each case.Loosely speaking as objects \"survive\" repeated garbage collections in the  they are migrated to the . The  is a special case, it contains objects that are needed by the JVM that are not necessarily represented in your program, for example objects that represent classes and methods.Since the  will usually contain a lot of garbage in it is optimised for getting rid of a lot of unused objects at once. The  since it contains longer lived objects is optimised for speedy garbage collection without wasting a lot of memory.With improvements in garbage collection technology the details have become pretty complex and vary depending on your JVM and how it has been configured. You should read the  for the specific JVM you are using if you need to know exactly what is happening.That said there is a simple historical arrangement this is still useful at a conceptual level. Historically the  would be a  and the  be a . A  pays essentially no CPU cost for getting rid of garbage, most of the cost is in maintaining live objects, the price of this efficiency is heavier memory usage. A  pays some CPU cost for both live and and unused objects but utilizes memory more efficiently. is part of memory allocated to JVM by Operating System. Whenever we create objects they are created inside . is divided into three regions or generation for sake of garbage collection called . Permanent generation is garbage collected during full gc in hotspot JVMThe  is where all new objects are allocated and aged. When the young generation fills up, this causes a minor garbage collection.  A young generation full of dead objects is collected very quickly. Some surviving objects are aged and eventually move to the old generation.The  is used to store long surviving objects. Typically, a threshold is set for young generation object and when that age is met, the object gets moved to the old generation. Eventually the old generation needs to be collected. This event is called a major garbage collection.The  contains metadata required by the JVM to describe the classes and methods used in the application. The permanent generation is populated by the JVM at runtime based on classes in use by the application. has been replaced with  since Java 8 release.  parameters will be ignored now. Have a look this  by .Image source:Refer to same article for more details.All objects in the heap survive will they are being referenced. When they're not more, the garbage collector (GC) will reclaim their memory.PermGen, Young and Tenured are diferent clasifications of objects (or spaces in the heap where they can be). these objects will be always there, they're not garbage collected. Classes objects are there, interned strings, etc. I don't know if there is a GC there (when system UNloads classes... but it's not a normal thing) when an object is created it's here. an object goes to this classification/category when it survives N GC passes (survive = GC passes but this object is referenced so it can't be reclaimed).Depending of GC used and some parametrization, GC passes more or less often.Then garbage collection can have different approaches to maange objects in the heap. This classification of objects helps to do it.Here's another excellent (though long) article on how to tune/size your GC parameters, which may help you understand even more:A very useful read if you're having GC issues and need to know how to read GC logs, or need to understand how your current GC collector works.If you want to hook up remote monitoring of a running system to see realtime memory usage and GC runs check this tool out:
Java

I want to do this:Currently this results in a label that displaysI want it to do this instead:Any suggestions?Thank youEDIT: Implemented solutionIn body of method:Helper method:You can use  in . To use it, your text has to start with .Set your text to  and it should work.See  and  for more information.It totally looks the same for me, but its uglyAnother easy way (but changes the text style a bit) is to use a  html block.This will persist any formatting the user entered if the string you are using came from a user input box.Example:The direct procedure of writing a multi-line text in a jlabel is:The problem with using html in  or any Swing component is that you then have to style it as html, not with the usual , , etc. If you're ok with that, fine.Otherwise you can use something like  from JIDE, which extends . It's part of their open source .JLabel can accept html code. Maybe you can try to use the \"< b r >\" tag. Example:\nJLabel myLabel = new JLabel();\nmyLabel.setText(\" This is a < b r > multi-line string \");I don't have the JDK with me right now, So I am not 100% confirm with the solution, but you can give it a shot.p.s. Please remove the whitespace between the < and b and r and > when you try. 
Java

The heap memory is garbage collected in Java.Is the stack garbage collected as well?How is stack memory reclaimed?The memory on the stack contains method-parameters and local variables (to be precise: the references for objects and variables itself for primitive types). That will be automatically removed if you leave the method. If the variables are references (to objects) the objects itself are on the heap and handled by the garbage collector.So the stack isn't garbage collected in the same way as the heap, but stack is a form of automatic memory-management in it's own (which predates garbage collection).A , look into that for more details.The stack is not garbage collected in Java.The stack allocated for a given method call is freed when the method returns. Since that's a very simple LIFO structure, there's no need for garbage collection.One place where the stack and garbage collection interact is that references on the stack are GC roots (which means that they are the root references from which reachability is decided).The stack  be garbage collected. However, in most JVM implementations, it is handled as, well, a \"stack\", which by definition precludes garbage collection.What we call the stack is the accumulation of : for each invoked method, this is the conceptual structure which contains the method arguments, local variables, a hidden pointer to the context for the calling method, and a slot to save the instruction pointer. The activation context is not accessible as such from the Java language itself. A context becomes useless when the method exits (with a  or because of a thrown exception). It so happens that when a method A calls a method B, it is guaranteed that when A regains control, the context for B has become useless. This implies that the lifetime of the context for B is a subrange of the lifetime of the context for A. Therefore, activation contexts (for a given thread) can be allocated with a LIFO (\"Last In, First Out\") discipline. In simpler words, a stack: a new activation context is pushed on top of the stack of contexts, and the context on top will be the first to be disposed of.In practice, the activation contexts (also called ) are concatenated, in stack order, in a dedicated area. That area is obtained from the operating system when the thread is started, and the operating system gets it back when the thread terminates. The top of the stack is designated by a specific pointer, often contained in a CPU register (this depends on whether the JVM is interpreting or compiling code). The \"pointer to caller's context\" is virtual; the caller's context is necessarily located just below in stack order. The GC does not intervene: the area for the stack is created and reclaimed synchronously, from the thread activity itself. This is also how it works in many languages such as , which do not have a GC at all.Now nothing prevents a JVM implementation from doing otherwise, e.g. allocating activation contexts in the heap and having them collected by the GC. This is not usually done in Java Virtual Machines since stack allocation is faster. But some other languages need to do such things, most notably those which play with  while still using a GC (e.g.  and its  function), because such games break the LIFO rule explained above.The stack part of the memory works just like a \"stack\". I know it sounds bad, but that's exactly how it works. Data is added to the top, on top of each other () and is automatically removed from the top () as your program runs. It is not garbage collected - and it doesn't need to be since that memory is automatically reclaimed once data is popped off the stack. And when I say reclaimed I don't mean it gets de-allocated - it's just that the location in the stack memory where the next data will be stored is decreased, as data is popped off.Of course that's not to say that you don't need to worry at all about the stack. If you run a recursive function many times it will eventually use up all the stack space. The same if you call many functions, especially if they have many parameters and/or local variables.But the bottom line is that the memory of the stack is used and reclaimed as functions enter and leave scope - automatically. So at the end of your program's execution all the stack memory would be free and then released back to the operating system.If you refer to the memory used on the stack, it is not garbage collected.\nThe java virtual machine uses explicit bytecode instructions to reserve and release memory on the stack, these instructions are generated by the compiler and manage the lifetime of primitives like int,boolean,double and object-references on the stack.\nThere have been plans to implement a so called tail call optimisation, which would remove some entries from the stack once it is known that they are no longer used, but I don't know any jvm which already supports this.\nSo no there is no garbage collection for the stack itself, only the compiler generated push and pop instructions to manage the memory use.The stack itself is part of a thread. The stack is allocated when the thread object is created and garbage collected after the thread terminated and the thread object is no longer referenced.All objects in Java are allocated on the heap. (At least as far as the spec goes, the actual implementation may allocate them on the stack if they transparently behave as if they were on the heap.) Exactly what is collectible is a bit subtle. If the only reference to an object is in a single stack frame, and it can be shown that reference will not be used again, then the object may be collected. If the object is only used to read a field, then that field read may be optimised forward and the object collected earlier than you might expect.This doesn't usually matter unless you are using finalisers (or presumably s). In that case you should be careful and use locks/volatile to enforce a  relationship.When threads stop, then typically the entire stack will be deallocated.Everything located on stack is treated as global roots by a garbage collector. So, yes, you definitely can say that stack is \"garbage collected\".No one, data is pushed and popped from stack as you have inner variables in methods, during method calls, etc. You don't need to care about this.No. The stack is not garbage collected in Java. \nEach thread has its own stack and contains :These values are pushed as stack frames to the stack for every method call. Since the stack follows 'Last-in First-out' order, at the end of every method call, each stack frame containing all the method specific data and the references to objects, if any, is popped out.Hence, data in stack are automatically cleaned once the method/program goes out of scope. 
Java

I have two byte arrays and I am wondering how I would go about adding one to the other or combining them to form a new byte array. You're just trying to concatenate the two byte arrays?Or you could use System.arraycopy:Or you could just use a List to do the work:You can do this by using Apace common lang package ( class ). You need to do the followingAssuming your  array is biger than ...you're going to it's length, not . You're trying to copy from beyond the array end.The problem with your code here is that the variable i that is being used to index the arrays is going past both the byteSalt array and the byteData array.  So, Make sure that byteData is dimensioned to be at least the maximum length of the passwordSalt string plus 32.  What will correct it is replacing the following line:with:I've used this code which works quite well just do appendData and either pass a single byte with an array, or two arrays to combine them :I think it is best approach,
Java

This error is just bizarre, my code compiles fine, I can see there are no problems with it, yet this error has just popped up. I have tried re-starting NetBeans and there is no additional exception information.What can cause this?I guess you are using an IDE (like Netbeans) which allows you to run the code even if certain classes are not compilable.  During the application's runtime, if you access this class it would lead to this exception.If it is Netbeans, try to uncheck \"Compile on save\" setting in the project properties (Build -> Compiling). This is the only thing which helped me in a similar situation.Source:\nIt's caused by NetBeans retaining some of the old source and/or compiled code in its cache and not noticing that e.g. some of the code's dependencies (i.e. referenced packages) have changed, and that a proper refresh/recompile of the file would be in order.The solution is to force that refresh by either:a) locating & editing the offending source file to force its recompilation (e.g. add a dummy line, save, remove it, save again),\nb) doing a clean build (sometimes will work, sometimes won't),\nc) disabling \"Compile on save\" (not recommended, since it can make using the IDE a royal PITA), or\nd) simply remove NetBeans cache by hand, forcing the recompilation.As to how to remove the cache:If you're using an old version of NetBeans:If you're using a newer one:The paths may vary a little e.g. on different platforms, but the idea is still the same.I also got the same error and I did clean build and it worked.Add selenium-server-standalone-3.4.0.jar. It works to me. \nDisable Deploy on Save in the Project's Properties/Run screen.  That's what worked for me finally.  Why the hell NetBeans screws this up is beyond me.Note: I was able to compile the file it was complaining about using right-click in NetBeans.  Apparently it wasn't really compiling it when I used Build & Compile since that gave no errors at all.  But then after that, the errors just moved to another java class file.  I couldn't compile then since it was grayed out.  I also tried deleting the build and dist directories in my NetBeans project files but that didn't help either.Organize your code as a maven module.\nOnce done run the command from terminal\n  \n\nto check  if your code builds fine.\nFinally import the project in netbeans or eclipse as maven project.Just check the packaging, the simplest answer I can provide is that your package has been mislabeled (within a class).Also, you may have some weird characters. Try white-flushing the code in a Notepad (or Gedit) and then pasting it into a newly created class with your IDE.change the package of classes, your files are probably in the wrong package, happened to me when I copied the code from a friend, it was the default package and mine was another, hence the netbeans could not compile because of it.I had this problem with NetBeans 8.0.1. Messages about problem in project deleted class. Deleting the ~/.netbeans didn't work. Also I looked for ANY reference to the deleted class in ALL my projects, nothing found. I deleted the build classes, everything. Then, when I started Netbeans again, compile and magically appears the message in Run and into the mother compiled class. I tried the uncheck \"Compile on save\" Dime solution, and works, but it's not practical.\nFinally, my solution was edit and force recompile of the mother class. This way the new .class doesn't contains the message and Run works OK.If you are using Netbeans, try to hit the Clean and Build button, let it do the thing and try again. Worked for me!
Java

this is my log outputI would like a time stamp per log message iehere is my log4j config fileHow do I do it?Use %d in your PatternLayout.Also %d can take a format pattern as in %d{dd MMM yyyy HH:mm:ss,SSS} you can pick and choose the elements that you want.  When the format pattern is omitted the date will be in ISO8601 format.A extract from my properties fileYou can find more conversion characters usage in log4j javadoc.For example, at .
Java

I want to choose a random item from a set, but the chance of choosing any item should be proportional to the associated weightExample inputs:So, if I have 4 possible items, the chance of getting any one item without weights would be 1 in 4.In this case, a user should be 10 times more likely to get the sword of misery than the triple-edged sword.How do I make a weighted random selection in Java?I would use a NavigableMapYou will not find a framework for this kind of problem, as the requested functionality is nothing more then a simple function. Do something like this:There is now a class for this in Apache Commons: where  is a , like (assuming Item interface in Arne's answer):or in Java 8:Note:  here needs to be , not .If you're gonna roll a lot of times (as in a game), you should use an alias method.The code below is rather long implementation of such an alias method, indeed. But this is because of the initialization part. The retrieval of elements is very fast (see the  and the  methods they don't loop).This implementation:Anyways, here's the code. (Note that .)If you need to remove elements after choosing you can use another solution. Add all the elements into a 'LinkedList', each element must be added as many times as it weight is, then use  which, according to Finally, get and remove elements using  or 
Java

How do I set Java's min and max heap size through environment variables?I know that the heap sizes can be set when launching java, but I would like to have this adjusted through environment variables on my server.You can't do it using environment variables directly. You need to use the set of \"non standard\" options that are passed to the java command. Run: java -X for details. The options you're looking for are -Xmx and -Xms (this is \"initial\" heap size, so probably what you're looking for.)Some products like Ant or Tomcat might come with a batch script that looks for the JAVA_OPTS environment variable, but it's not part of the Java runtime.  If you are using one of those products, you may be able to set the variable like:  You can also take this approach with your own command line like:  If you want any  process, not just ant or Tomcat, to pick up options like  use the environment variable .In bash: You can't do it using environment variables. It's done via \"non standard\" options. Run:  for details. The options you're looking for are  and  (this is \"initial\" heap size, so probably what you're looking for.)Actually, there is a way to set global defaults for Sun's JVM via environment variables.See .I think your only option is to wrap java in a script that substitutes the environment variables into the command lineA couple of notes:
Java

We have some code wich sorts a list of addresses based on the distance between their coordinates. this is done through collections.sort with a custom comparator.However from time to time an adress without coordinates is in the list causing a NullPointerException. My initial idea to fix this was to have the comparator return 0 as dististance for addresses where at least one of the coordinates is null. I fear this might lead to corruption of the order the 'valid' elements in the list.so is returning a '0' values for null data in a comparator ok, or is there a cleaner way to resolve this.Handle it like  means infinitely far away. Thus:With this, you get a consistent ordering.Just to expand on Willi Sch\u00f6nborn's answer, I came here to say that  is exactly what you're after here. In the general case, you can just write your own  to ignore nulls (assume non-null, so it can concentrate on the important logic), and then use  to handle the nulls:In your case, though, it's data WITHIN the Address (the Coordinates) that is being used to sort, right? google-collections is even  useful in this case. So you might have something more like:then when you want to sort:and that's where the power of google-collections really starts to pay off.My take on this is that anything you try to do to \"make good\" the  coordinates is just papering over the cracks.  What you really need to do is find and fix the bugs that are injecting the spurious  coordinates.In my experience, infestations of NPE bugs are frequently caused by the following bad coding habits:(Better solutions to the \"no value\" problem typically involve rewriting code so that you don't  to represent this and/or using a non-null value instead; e.g. an empty String, a special instance, a reserved value.  You can't always find a better solution, but you often can.)If this describes your application, you should be spending time to root out the code problems rather than thinking of ways to hide the NPEs.My solution (might be useful for someone looking here) is to do the comparison normal, with null values replaced not by 0, but the maximum value possible (e.g. Integer.MAX_VALUE). Returning 0 is not consistent, if you have values that are themselves 0. Here a correct example:I just wanted to add that you don't necessary need the max value for integer. It depends of what your giveMeSomeMeasure() method can return. If for example you compare Celsius degrees for weather, you can set l and r to -300 or +300, depending where you want to set the null objects - to the head or the tail of the list.You probably dont want to return 0 as that implies the addresses are equidistant and you really dont know. This is quite a classic problem where you are trying to deal with bad input data. I dont think its the responsibility of the comparator to try and determin how far the address is in realtive terms when you  the distance. I would remove those addresses from the list before sorting.The hack would be to move them to the bottom of the list (but thats ugly !)Instead of looking at this like it's a technical problem with the comparator, it's better to take a look at the requirements again: what you're really trying to do here, what are you going to do with this sorted list?As you already realize, always returning 0 when one of them is null is not a good idea here; it can corrupt the result indeed. But what you should do instead depends on what you need, not on what others usually do/need. How your program behaves with addresses that don't have a location (so what the user is going to see) should not depend on some technical detail like what the \"best practice\" for comparators is.\n(To me, asking what the \"best practice\" is here, sounds like asking what the \"best requirements\" are).No, there is no cleaner way. Perhaps:But more importantly - try to get rid of / fill in the missing coordinates, or, better: don't put addresses with missing coordinates in the list.Actually, not putting them in the list is the most logical behaviour. If you put them in the list, the result won't be actually ordered by distance.You may create another list, containing the addresses with missing coordinates, and make it clear to whoever needs that information (end-user, API user), that the first list only contains addresses with the needed data, while the second list contains addresses that lack required information.I personally hate dealing with special null cases everywhere in my comparators so i was looking for a cleaner soluation and finally found google collections. Their Ordering is just awesome. They support compound comparators, offer to sort nulls to the top and to the end and allow to run certain functions before comparing. Writing comparators has never been so easy. You should give it a try.If you are using Java 8, you have 2 new static methods in the Comparator class, which come in handy:The comparison will be null safe and you can choose where to place the null values in the sorted sequence. The following example:will print:\n[null] [null] [] [Chimp] [banana] [eat] [run] [sleep] [smile] [throw banana peel] 
Java

I need for example to pass  argument to Jetty which run as maven-plugin (maven-jetty-plugin) by \"\" command.  is the answer. The string content of MAVEN_OPTS variable is passed to jvm (java.exe).: in shell type \"\"\n: in shell (cmd.exe) type \"\":\n (01.04.2013)Matthew Farwell (please upvote his answer to give him a credit) comes with solution of using forked jvm process to run jetty which is new feature of jetty plugin - see  This is better solution as the former running inside same jvm processs as maven (thus share memory).With more recent versions of the maven-jetty-plugin, you can use . The option jvmArgs will allow you to set -Xmx etc.For more information, see: .I think the original issue was .It seems like your current approach is correct - when running jetty through maven, jetty is a thread inside the maven process.  So increasing maven's heap will increase jetty's heap.How are you setting MAVEN_OPTS?One example I found looks like this:   Note that  is an environment variable here, and not passed to the JVM (who wouldn't know what to do with it).The  param mentioned here :  \ndidn't work for me . Maven version : Apache Maven 3.0.3Jetty Maven plugin version : jetty-maven-plugin:8.1.10.v20130312This worked :How about:  On Linux/Unix will do the trickTo specify vm arguments via the command line (as originally asked) you can do the following:The plugin allows you to specify jvmArgs like this:you can use  to pass -Xmx argument like;There is no way using the commandline. But you could copy the  /  to  and change the line To 
Java

Specifically, I have TabPane, and I would like to know if there is element with specific ID in it.So, I would like to do this with lambda expression in Java:Try to use  of Lambda Expression. It is much better approach.While the accepted answer is correct, I'll add a more elegant version (in my opinion):Don't neglect using  which allows to flatten the data structure before applying the .
Java

First up - yes, I have read the multiple questions & answers on this topic, and can't get any of the solutions within those to help me. I'm not running Tomcat or JBoss and I don't have a web.xml file to change. I'm using Java 6.0 and log4j-1.2.8.jarI am creating a runnable jar file with IDEA IntelliJ with jar libraries packaged separately and linked via the manifest. I am running my code on a linux server thus:My log4j configuration file (which I've placed both in mydir and mydir/code, just in case) is:And I have created the log/ directory in mydir and mydir/code, again, just in case.Any ideas?There are many possible options for specifying your log4j configuration. One is for the file to be named exactly \"log4j.properties\" and be in your classpath. Another is to name it however you want and add a System property to the command line when you start Java, like this:All of them are outlined here I had moved my log4j.properties into the resources folder and it worked fine for me !Man, I had the issue in one of my eclipse projects, amazingly the issue was the order of the jars in my .project file. believe it or not!You will find de  in .If you don't find the file, i put it here:RegardsMove Your log4j.properties file into the src folder.\nOpen Windows explorer, browse to the directory where your project resides in.\nBrowse to bin directory and delete all the  with in it.Now in eclipse click project---->clean---->OKThis would force it to build the project again,all the contents delete from bin directory will be recreated.I took while to figure this out.\nAt times directly clicking clean doesn't workput the folder which has the properties file for log in java build path source. You can add it by right clicking the project ----> build path -----> configure build path ------> add t
Java

I have recently created a library Jar file that I imported in my Android project. I am able to call functions and use classes that are present in this Jar file, but Android Studio keeps telling me that it cannot \"resolve symbol\" of the class I am using. Please see the screenshot below:The code builds and executes successfully. The function  simply returns , and that is just what  gets set to.I have tried pressing the  button and using the  option from Android Studio's  menu, but none of this solved the issue. What can I do to make the Android Studio IDE not display the  error?I have faced this issue when IntelliJ IDEA got closed abruptly due to OS crash.You can do \"File\" -> \"Invalidate Caches...\", and select \"Invalidate and Restart\" option to fix this.I found the issue - my  was not generated correctly. It included  files instead of  files. This explains why the IDE was not able to find the SDK class. The package structure was still correct in the Jar, which is why the package name itself is not a red color. The code worked correctly, because the compiler knew to compile the  files.To solve the issue, I modified my  of my SDK project to include  files, instead of  files, when creating the Jar. Including this new Jar instead of the old Jar  fixed the IDE issue.Try adding the library to the .To do this, on the menu choose  -> . Select the  option and click the green  to add your library.This was always happening to me after switching branches on my current project: a lot of non-sense erros being reported by the IDE.The solution is to modify and  a  .
Java

I have a Java class  that I am interested in deserializing from JSON. I have configured a special MixIn class, , to assist me with the deserialization.  has only  and  instance variables combined with proper getters and setters.  looks something like this:In my test client I do the following, but of course it does not work at compile time because there is a  related to a type mismatch.I am aware that I could alleviate this issue by creating a \"Response\" object that has only an  in it, but then I would have to create these somewhat useless objects for every single type I want to return.I also looked online at  but had a terrible time understanding the stuff about  and how it relates to my issue. If you cannot tell, I'm entirely new to Java and come from an Obj-C background. They specifically mention: How can I deserialize directly to ?You can deserialize directly to a list by using the  wrapper. An example method:And is used thus:.Another way is to use an array as a type, e.g.:This way you avoid all the hassle with the Type object, and if you really need a list you can always convert the array to a list by:IMHO this is much more readable.And to make it be an actual list (that can be modified, see limitations of ) then just do the following:I am also having the same problem. I have a json which is to be converted to ArrayList. Account looks like this.All of the above classes have been annotated properly.\nI have tried TypeReference>() {} \nbut is not working.It gives me Arraylist but ArrayList has a linkedHashMap which contains some more linked hashmaps containing final values.My code is as Follows:I finally solved the problem. I am able to convert the List in Json String directly to ArrayList as follows:This variant looks more simple and elegant.
Java

Every now and again, I make use of the Eclipse refactoring feature. Some techniques are more obvious then others and some I never tried.What refactoring is most useful for you and why?Note: I find this presentation very useful, perhaps because it is example driven therefore easy to understand:\"\"Edit: This article is useful as well (Thanks jitter)It is an interesting question. I know what works for me and it is interesting to see what others use. I decided to take a more scientific approach to determine the most commonly used refactoring commands. Eclipse has a  feature built in. The data is . I took the data and extracted the following graph which shows the most commonly used editing commands (without navigation commands).However, I am a strong believer in \"Save Actions\" for formatting and organizing imports (read ), so I wouldn't count those. I would also remove the commenting actions. The picture looks like this:   - because giving things meaningful names is the best way to write self-documenting code. ++ - whenever a method gets too long. ++ - because magic numbers are bad. ++ (refactoring menu, there's no direct shortcut). - to remove clutter from methods. ++ (inline), ++ (introduce)My favourites (in order of using):My favorites:The most popular refactorings have been stated, and I entirely agree with them. (,  or   ) is one of the features of the IDE I use very often. True, it is not refactoring, but it improves code readability while maintaining your coding style: simply head to , , ,  and tell Eclipse how you want your code to look! is also a feature I find to save time when writing Java beans.Eclipse has perhaps the least refactorings for all the popular IDEs. You might consider Netbeans or IntelliJ (Community edition is free). Conversely Eclipse has possibly the best debugger. ;)I use refactoring as I write the code (which I have found speeds up writing by about 15%) so IntelliJ's ability to refactor code which does not compile very useful for me.  The other IDEs may support this now (does any one know?)\nI find IntelliJ's smart complete is a fair bit smarter as well.I have tested retyping a files from printout (originally written in eclipse) and found I used 30% less keys and 50% less mouse movements when typing the file with IntelliJ (compared with Eclipse) I would estimate Netbeans to be somewhere in the middle.My favorites are:1) Rename - It works on method names, variable names, class names, fields-- really anything with a name.\n2) Convert Anonymous Class to Nested - Helps with debugging, lets you reuse logic (such as a comparator) that you only thought that you'd use in one place. \n3) Convert Member Type to Top Level - Frequently after making an anonymous class into a nested class I discover that the class is useful elsewhere. This refactoring is perfect then.What I use the most is Rename, Extract Method and Change Method Signature, in that order.CTRL + 1 on a red lined section, i.e. quick fix.I like the Extract Method (++), and since , it now handles selections that contain continue statements.  I use :1- Rename  - to correct better method name 2- Move  - to organize my package in better ways, like when I start my project, it was so small so no need of a io package, but now yes.3- Generate Comments -when I create a .class  avoid me to re-copy the GPL license, etc4- Correct Indentation - to keep my code readable.It's also worth reading this research:  by D. Dig and R. Johnson.The authors noticed that 80% of the changes were refactorings and classified them.  Here is the abstract:\"It's also worth reading this research: How do API evolve? A story of refactoring. by D. Dig and R. Johnson.The authors noticed that 80% of the changes were refactorings and classified them. Here is the abstract ... \"80% of the BREAKING changes were observed to be refactorings.\nThe refactorings themselves formed only 20 - 30% of the API changes..
Java

I'm trying to parse a string to a date field in an android application but I can't seem to get it correct. Here is the string I'm trying to convert to a date \"03/26/2012 11:49:00 AM\". The function I'm using is:But I keep getting 3/1/112 11:49AM as the result.. Any help I would really appreciate. thanksYou are wrong in the way you display the data I guess, because for me:Prints:it went OK when i used  parametre in Try thisThis code will help you to make a result like   FEB 17 20:49 .Result :Date  : FEB 17Time  : 20:49Output:
Java

I'm working on some legacy code that has a class that is 10,000+ lines of code and has 100s of methods.  Is there a shortcut for any jetbrains IDE (since the shortcut would likely be shared across all of them) to collapse all the methods / functions so that only the method signatures are shown? something like this: You may take a look at . I guess that ++ is exactly what you need.The above suggestion of ++ code folds all code blocks recursively. I only wanted to fold the methods for my classes. I managed to achieve this by using the menu option . I re-assigned it to + which gives me a quick way to collapse my classes down to their methods.This works at the 'block level' of the file and assumes that you have classes defined at the top level of your file, which works for code such as PHP but not for JavaScript (nested closures etc.)go to menu option  to access all code folding related options and their shortcuts.
Java

I have a LinearLayout and ImageView inside this LinearLayout. There is a translation effect for ImageView.Animation working but it's disappearing when ImageView go outside of LinearLayout. You can see problem here : How can i fix it without modify LinearLayout's height.Find the ViewGroup that the ImageView belongs to and apply .\nBy default, the drawing of the children is limited to the bounds of the parent ViewGroup.Two attributes exist that may cause this to happen: clipChildren and clipToPadding. You'll need to set clipChildren to false for each parent ViewGroup whose bounds the object will animate out of. You also need to set clipToPadding to the immediate parent (and maybe more, but I haven't seen a case for it yet).You can set both attributes in the XMLor in codeMy implementation. It can probably help somebody:call\n to disable the clipping in all the parents.In my case clipChildren did nothing but  fixed the problem. Go figure.
Java

What is the difference between these two declarations?Is generic where you want to hide implementation details while returning it to client, at later point of time you may change implementation from  to  transparently.This mechanism is useful in cases where you design libraries etc., which may change their implementation details at some point of time with minimal changes on client side.This mandates you always need to return . At some point of time if you would like to change implementation details to , there should be changes on client side also to use  instead of . is an interface and  is an implementation of the List interface. The  class has only a few methods in addition to the methods available in the List interface. There is not much difference in this. If you use the first, you will be able to call the methods available in the List interface and you cannot make calls to the new methods available in the  class. Where as, you are free to use all the methods available in the  if you use the second one. I would say the first approach is a better one because, when you are developing java applications, when you are supposed to pass the collection framework objects as arguments to the methods, then it is better to go with first approach. In future due to performance constraints, if you are changing the implementation to use  or someother classes which implements  interface, instead of , you need to  change at one point only(the instantiation part).Else you will be supposed to change at all the places, wherever, you have used the specific class implementation as method arguments.The difference is that variant 1 forces you to use an  while variant 2 only guarantees you have anything that implements .Later on you could change that to  without much hassle. Variant 1 might require you to change not only that line but other parts as well if they rely on working with an .Thus I'd use  in almost any case, except when I'd need to call the additional methods that  provides (which was never the case so far):  and . Basically it allows Java to store several types of objects in one structure implementation, by generic type declaration (like ), which is one of Javas main features. Object-oriented approaches are based in modularity and reusability by separation of concerns - the ability to use a structure with any kind of types of object (as long as it obeys a few rules).You could just instantiate things as followed:instead ofBy declaring and using generic types you are informing a structure of the kind of objects it will manage and the compiler will be able to inform you if you're inserting an illegal type into that structure, for instance. Let's say:If you want to see some examples check the documentation :Then you could instantiate things like:The main thing to draw from this is you're specifying which type of object you want to box.As for using , you're not accessing the  or  implementation so you won't be able to do much with the collection.The first declaration has to be an ArrayList, the second can be easily changed to another List type.  As such, the second is preferred as it make it clear you don't require a specific implementation. (Sometimes you really do need one implementation, but that is rare)It is easy to change the implementation to  to :There are a few situations where you might prefer the first one to (slightly) improve performance, for example on some JVMs .Out of that kind of very specific context, you should use the first one.Possibly you can refer to this link\nList is an interface.ArrayList,LinkedList etc are classes which implement list.Whenyou are using List Interface,you have to itearte elements using ListIterator and can move forward and backward,in the List where as in ArrayList Iterate using Iterator and its elements can be accessed unidirectional way.List is interface and ArrayList is implemented concrete class. \nIt is always recommended to use.Because here list reference is flexible. It can also hold  object.Whenever you have seen coding from open source community like Guava and from Google Developer (Android Library) they used this approachbecause it's hide the implementation detail from user.\nYou precisely it's generic approach and this specialized approach For Reference:\nEffective Java 2nd Edition: Item 52: Refer to objects by their interfaces
Java

This is what I can do in JUnit:and the entire class will be ignored. How can I do the same in TestNG?I believe what you want is:(You can apply the @Test annotation to the class, as well as to methods individually.)The  has a comprehensive list of the supported annotations, and also describes exclusion/inclusion of tests by group if that's of any interest. Here's a quote from the relevant section::\nIgnoring a class by applying  is apparently buggy functionality in some versions of TestNG according to  that was raised against TestNG. 
Java

I'm trying to access an XML file within a jar file, from a separate jar that's running as a desktop application.  I can get the URL to the file I need, but when I pass that to a FileReader (as a String) I get a FileNotFoundException saying \"The file name, directory name, or volume label syntax is incorrect.\"As a point of reference, I have no trouble reading image resources from the same jar, passing the URL to an ImageIcon constructor.  This seems to indicate that the method I'm using to get the URL is correct.Inside the ServicesLoader class I have What's wrong with using this technique to read the XML file?Looks like you want to use , seeYou don't say if this is a desktop or web app.  I would use the  method from an appropriate ClassLoader if it's a desktop or the Context if it's a web app.It looks as if you are using the  result as the argument to the  constructor.  is a bit broken, and instead you should generally use . In any case, the string is not a file path.Instead, you should either:The problem was that I was going a step too far in calling the parse method of XMLReader. The parse method accepts an InputSource, so there was no reason to even use a FileReader. Changing the last line of the code above toworks just fine.I'd like to point out that one issues is what if the same resources are in multiple jar files.\nLet's say you want to read /org/node/foo.txt, but not from one file, but from each and every jar file.I have run into this same issue several times before.\nI was hoping in JDK 7 that someone would write a classpath filesystem, but alas not yet.Spring has the Resource class which allows you to load classpath resources quite nicely.I wrote a little prototype to solve this very problem of reading resources form multiple jar files. The prototype does not handle every edge case, but it does handle looking for resources in directories that are in the jar files.I have used Stack Overflow for quite sometime. This is the second answer that I remember answering a question so forgive me if I go too long (it is my nature).This is a prototype resource reader. The prototype is devoid of robust error checking.I have two prototype jar files that I have setup.The jar files each have a file under /org/node/ called resource.txt.This is just a prototype of what a handler would look like with classpath://\nI also have a resource.foo.txt in my local resources for this project.It picks them all up and prints them out.Outside of your technique, why not use the standard Java  to get the references you want? From there most of your problems should go away.If you use resources extensively, you might consider using \n .Also supports:\n * Local Files\n * FTP, SFTP\n * HTTP and HTTPS\n * Temporary Files \"normal FS backed)\n * Zip, Jar and Tar (uncompressed, tgz or tbz2)\n * gzip and bzip2\n * resources\n * ram - \"ramdrive\"\n * mimeThere's also  - but it's not much documented.I have 2 CSV files that I use to read data. The java program is exported as a runnable jar file. When you export it, you will figure out it doesn't export your resources with it. I added a folder under project called data in eclipse. In that folder i stored my csv files.When I need to reference those files I do it like this...Then when you put the jar in a location so it can be ran via commandline, make sure that you add the data folder with the resources into the same location as the jar file.
Java

Here are the facts:As an example of a Java program that has memory leaks (not for the faint of heart, the question may shake your beliefs), see here about a little Java program called Tomcat that even has a \"find leaks\" button: So I am wondering: will programs written in Go exhibit the same kind of (subtle or not) memory leaks that some programs written in Java exhibit?You are confusing different types of memory leaks here.  The heinous, explicit-memory-management based memory leaks are gone in Java (or any other GC based language).  These leaks are caused by completely losing access to chunks of memory without marking them as unused.The \"memory leaks\" still present in Java and every other language on the face of the planet until the computer can read our minds are still with us, and will be for the foreseeable future.  These leaks are caused by the code/programmer keeping references to objects which are technically no longer needed.  These are fundamentally logic bugs, and cannot be prevented in any language using current technologies.It's very possible that Go programs will exhibit memory leaks.  The current implementation of Go has a simple mark-and-sweep garbage collector.  This is only intended as a temporary solution and is not intended as the long term garbage collector. See this  for more info. Look under the header . That page even has a link to code for the current version if you are so inclined.Garbage collection or not, you can write a program that has memory-leaks in Java, Go, or any other language for the most part.Garbage Collection does take some of the burden off the programmer but it does not prevent leaks entirely.A 'memory leak' is when a piece of memory that the programmer thought would be freed isn't freed. This can happen in any language, garbage collected or not. The usual cause in GC languages is retaining an additional reference to the memory.\"Languages don't cause memory leaks, programmers cause memory leaks\".You are mixing abstraction levels here: the memory leaks are due to bugs in the library (where objects reference each other though chains of 'a holds reference to b' as well as a trade-off in the implementation of the garbage collector between efficiency and accuracy.  How much time do you want to spend on finding out such loops?  If you spend twice as much, you'll be able to detect loops twice as long.So the memory leak issue is not programming language specific, there is no reason that by itself GO should be better or worse than Java.
Java

I am trying to call a web service but facing a strange behavior. we have a web-service running on my server but the code is not open to us so can not see what going on behind the wall\nThe owner of the service have exposed  web based test client UI which take input in a text box and will show the response to testing purpose.This input box is taking the input in the below mentioned formatits working fine on this UI but when i am trying to call this web service through my java code its getting connected as well getting authorized by the service but when i trying to call the above method it giving me the below error messagebelow is the code for generating the required XMLand the generated XML is as belowi even did timing of the generated string something as below but unable to find out whats going wrong,one thing i am sure there is some problem in the input XML as its working find on the test Page UI for the same XMLany help in this regard is much appricatedThis error is probably related to a byte order mark (BOM) prior to the actual XML content.  You need to parse the returned String and discard the BOM, so SAXParser can process the document correctly.  You will find a possible solution .to simply remove it, paste your xml file into notepad, you'll see the extra character before the first tag. Remove it & paste back into your file - bofCheck the XML. It is not a valid xml. Prolog is the first line with xml version info. It ok not to \ninclude it in your xml.  This error is thrown when the parser reads an invalid tag at the start of the document. Normally where the prolog resides.e.g.This error can come if there is validation error either in your wsdl or xsd file. For instance I too got the same issue while running wsdl2java to convert my wsdl file to generate the client.\nIn one of my xsd it was defined as belowWhere the schemaLocation was empty. By providing the proper data in schemaLocation resolved my problem.I faced the same issue. Our application running on four application servers and due to invalid schema location mentioned on one of the web service WSDL, hung threads are generated on the servers . The appliucations got down frequently. After corrected the schema Location , the issue got resolved.   
Java

I'm wondering about best practices when creating Javadocs. I have a project with many files. Code has been created by many developers. Each file has an annotation , so it is obvious who has created a particular class. But when some other developer adds new code to a file, modifies it, etc., how should he inform the rest of the team that he has created some new function or has modified existing code? In other words, how should we \"keep the Javadocs compatible with reality\"? ;)Of course, since we use SVN, it is easy to investigate who has made what, but for keeping things clear this Javadoc stuff should be taken into consideration as well.What's the best way to use these  tags?I would say that for most purposes  is unwanted noise.  The user of your API shouldn't - and probably doesn't - care, or want to know, who wrote which parts.And, as you have already stated, SVN already holds this information in a much more authoritative way than the code can.  So if I was one of the team, I would always prefer SVN's log and ignore the . I'd bet that the code will get out of sync with reality, whatever policy you adopted. Following the Don't Repeat Yourself principle, why hold this information in two places?If, however, there is some bureaucratic or policy reason that this information MUST be included in the code, have you considered automatically updating the  tag in the code on check in?  You could  achieve this with an SVN hook.  You could for example list all the developers who changed a given file in the order they changed it; or who changed it most; or whatever. Or, if the  is mandated in (source) code you release to the outside world, you could consider adding the  automatically as part of the release build (I suspect you could get this information out of SVN somehow).As for adding more than a single class level  tag (or other comment), I'd say you'd be accumulating a lot of unhelpful noise. (Again, you have SVN.)In my experience it is much more useful to identify a historical change (say a change to a line of code, or a method), then to work out which change set this relates to (and which track ticket).  Then you have the full context for the change: you have the ticket, the change set, you can find other change sets on the same ticket, or around the same time, you can find related tickets, and you can see ALL the changes that formed that unit of work.  You are never going to get this from annotation or comments in code.You may want to consider  you want author tags in the source.  The Apache Foundation do not and I agree.To my best understanding this is a cargo cult way of working from when sources were printed on paper.  With modern version control systems this information and more can be found in the history anyway.You can have more than one  tag. In case you make some big changes to a class, just add a new  tag with your own name in it. There's no need to mark the changes you've done or to put your name around the changes, as the revision history should be able to display that clearly.In really big and long-running projects with lots of developers, it is useful to know ho is responsible for given code, who can provide you with extra information and such. In that case it would be handy to have such an informationin the file using @author tag. Not marking who created the file or who made some major contributions, but who is a contact person for that code. Those might be very different people as original author may be already on different project or left the company years ago.I think on huge project that approach may be handy, however there is a caveat. Keeping every single file's author information is very difficult as there is huge amount of files and sooner or later will fail. More and more files will have outdated information and developers will no longer trust this @author as source of information and will just ignore it.Solution, which may work, is not to keep @author on every single file, but only per module (high level packages). Javadoc has a feature, where you can document not only files but whole packages ().This is however a special case and as long as your project is not that big or old, I reccomend ommiting the author information.
Java

Using JAXB to generate XML binding classes.The schema is based on a set of legacy XML files, and includes this snippet:The 'Value' attribute conflicts with the 'value' property of , and the code generation fails with the error:The answer lies in making use of JAXB bindings ():The XPath expressions locate the nodes and renames it, thereby avoiding the naming conflict.Using this bindings XML file, the generated Java class ends up having the desired  (as well as the ).Once after xxxx.xjb file is created for duplicate attribute name \"value\" (duplicate is default 'value' provided by JAXB) as below, run XJC command to create JAXB objects:-:-If you want to avoid creating/changing a JAXB bindings file, and you don't mind annotating your XSD, you can add the  annotation to your attribute's definition, e.g.:with suitable additions to the xs:schema tag:I had a problem using the solution with Eclipse (tried both Helios SR1 and Juno SR1) and CXF 2.6.3. The solution was similar to what Kaitsu says. Namely the New > Web Service wizard of Eclipse copies the wsdl into the foldre WebContent/wsdl. I had to place the wsdl and the binding file there myself. Otherwise the binding file gave the \"is not a part of this compilation\" error.I wasn't able to use an inline schema in the WSDL but it did work with an external schema like in answer #1.I'm using the CXF Servlet endpoint config option. In my WSDL I have:The wizard generated this into my web.xml, which works ok:But it put this into cxf-servlet.xml:I had to change the address into the full URL, like this:This bindings file mentioned in the other answer did not work for me with CXF 3.0.0.\nNotice that jaxb namespace has an element \"bindings\" and so do the namespace jaxws, so we need to declare them:In my case the schema was already inside the WSDL so I did no have to specify the schemaLocation attribute.
Java

I need to determine if a user-supplied String is a valid file path (i.e. if createNewFile() will succeed or throw an Exception) but i don't want to bloat the file system with useless files created just for validation purposes, so is there a way to determine if the String i have is a valid file path without attempting to create the file?I know the definition of \"valid file path\" varies depending on the OS, but i was wondering if there was any quick way of accepting \"C:/foo\" or \"/foo\" and rejecting \"banana\"...a possible approach may be attempting to create the file and eventually deleting it if the creation succeeded, but i hope there is a more elegant way of achieving the same result...This would check for the existance of the directory as well.It seems like file.canWrite() does not give you a clear indication if you have permissions to write to the directory.Path class introduced in Java 7 adds new alternatives, like the following : \n(Does  work properly under  - always returns true)A number of things can go wrong when you try and create a file:More to the point, those can change between when you try and query to see if you can and when you actually can.  In a multithreaded environment this is one of the primary causes of race conditions and can be a real vulnerability of some programs.Basically you just have to try and create it and see if it works.  And that's the correct way to do it.  It's why things like  has a  so the check and insert is an atomic operation and doesn't suffer from race conditions.  Exactly the same principle is in play here.If this is just part of some diagnostic or install process, just do it and see if it works.  Again there's no guarantee that it'll work later however.Basically your program has to be robust enough to die gracefully if it can't write a relevant file. is quite useful for this purpose. IO exceptions are thrown for certain types of invalid filenames (e.g. , ,  in Windows) when resolving against the OS or file system. However, this only serves as a preliminary check; you will still need to handle other failures when actually creating the file (e.g. insufficient permissions, lack of drive space, security restrictions).
Java

I have a need to include  in my JavaDoc comment. The problem is that this is also the same sequence for closing a comment. What the proper way to quote/escape this?Example:: It appears I can use  for the slash. The only downside is that this isn't all that readable when viewing the code directly in a text editor.Use HTML escaping. So in your example: escapes as a \"/\" character. Javadoc should insert the escaped sequence unmolested into the HTML it generates, and that should render as \"*/\" in your browser. If you want to be very careful, you could escape both characters:  translates to So? The point isn't for your code to be readable, the point is for your code  to be readable. Most Javadoc comments embed complex HTML for explaination. Hell, C#'s equivalent offers a complete XML tag library. I've seen some pretty intricate structures in there, let me tell you. \nIf it bothers you too much, you might embed a non-javadoc inline comment that explains the encoding:This is the \u2018right\u2019 solution, but for readability's sake I'd probably go for:Use the entity In your documentation it will show up as a \"*/\"Nobody mentioned . This is another way to go:Unfortunately you cannot escape  at a time. With some drawbacks, this also fixes:I would suggest you also add a line comment somewhere near saying something likeAnother way I stumbled upon, just for completeness: add some HTML markup which doesn't alter the output between the * and /. Compared to the HTML escape solution, this seems something of an ugly hack, but it also yields the right result in HTML output.
Java

What is the best way to create Velocity Template from a String?I'm aware of  method where I can pass String or StringReader, but I'm curios is there a better way to do it (e.g. any advantage of creating an instance of Template).There is some overhead parsing template. You might see some performance gain by pre-parsing the template if your template is large and you use it repeatedly. You can do something like this,Then you can call  over and over again without parsing it everytime.BTW, you can pass String directly to .The above sample code is working for me. It uses Velocity version 1.7 and log4j.  A  so question.
Java

My program that connects to a MySQL database was working fine. Then, without changing any code used to set up the connection, I get this exception:What happened?The code used to get the connection:This is a wrapped exception and not really interesting. It is the  of the exception which actually tells us something about the root cause. Please look a bit further in the stacktrace. The chance is big that you'll then face a  or .If this is true in your case as well, then all the possible causes are:To solve the one or the either, follow the following advices:By the way (and unrelated to the actual problem), you don't necessarily need to load the JDBC driver on   call. Just only once during startup is enough.check your wait timeout set on the DB server.\nSome times it defaults to 10 seconds. This looses the connection in 10 seconds.update it make it something like 28800I've been having this issue also for about 8-9 days.\nHere's some background: I'm developing a simple Java application that runs in bash.Details:The application works fine in Arch Linux, Mac OS X 10.6, and FreeBSD 7.2.\nWhen I moved the jar file to another arch linux in a different host, using the same mysql, a similar my.cnf, and the similar kernel version, the connection died and obtained the same error as the original poster:I tried every possible combination for this that I found on so and the forums ( for example, which is closed now and I can't post .. ), specifically:As it was pointed out (if you look up for the same exception , you will find several so threads about the issue \n for example ).If the link get's removed, just add mysqld:ALL to /etc/hosts.allow, but it may help anybody using GNU/Linux and having this exception and this thread seemed the best place to post my research.Hope it helpsI got the same error\nbut then I figured it out its because the  at that time.So to change the status of the serverHope this will help.We have a piece of software (webapp with Tomcat) using Apache commons connection pooling, and worked great for years. In the last month I had to update the libraries due to an old bug we were encountering. The bug had been fixed in a recent version.Shortly after deploying this, we started getting exactly these messages. Out of the thousands of connections we'd get a day, a handful (under 10, usually) would get this error message. There was no real pattern, except they would sometimes cluster in little groups of 2 to 5.I changed the options to on the pool to validate the connection every time one is taken from or put back in the pool (if one is found bad, a new one is generated instead) and the problem went away.Have you updated your MySQL jar lately? It seems like there may be a new setting that didn't used to be there in our (admittedly very old) jar.I agree with BalusC to try some other options on your config, such as those you're passing to MySQL (in addition to the connection timeout).If this failure is transient like mine was, instead of permanent, then you could use a simple try/catch and a loop to keep trying until things succeed or use a connection pool to handle that detail for you.Other random idea: I don't know what happens why you try to use a closed connection (which exception you get). Could you be accidentally closing the connection somewhere?Ensure skip-networking is commented out in my.cnf/my.iniAs BalusC mentioned, it would be very useful to post the  stacktrace (always post a full stacktrace, it is useless and frustrating to have only the first lines of a stacktrace). Anyway, you mentioned that your code  fine and that this problem started suddenly to occur without any code change so I'm wondering if this could be related to you other question  Actually, if this problem started while debugging, then I think it is (you ran out of connections). In that case, restart you database server (and follow the suggestions of the other question to avoid this situation).I encountered same problem. I am using spring & dbcp & mysql 5.5But If I change  to  then everything works. What make things more weird is  just works fine.update: Finally found a solution. Changing bindaddress to  or  in  will fix the problem. In my case, the local loopback interface wasn't started, so \"localhost\" couldn't be resolved.\nYou can check this by running \"ifconfig\" and you should see an interface called \"lo\". If it is not up, you can activate it by running \"ifup lo\" or \"ifconfig lo up\".In my case, the  whereas the .This happened when building a Google appengine application in Android Studio (gradle, Windows x64), communicating to a Linux MySQL server on the local network/local VM.I see you are connecting to a remote host. Now the question is what type of a network are you using to connect to the internet? If it's a  then get your machines IP address and add it to your hosting server so that your host server can allow connections coming from your machine.[your host might have turned this off due to security reasons].\nNote that every time you use a different network device your IP changes.If you are using a LAN then set a static IP address on your machine then add it to your host. I hope this helps!!  I got the communications failure error when using a java.sql.PreparedStatement with a specific statement.  This was running against MySQL 5.6, Tomcat 7.0.29 and JDK 1.7.0_67 on a Windows 7 x64 machine.  The cause turned out to be setting an integer to a string parameter and a string to an integer parameter then trying to perform executeQuery on the prepared statement.  After I corrected the order of parameter setting the statement performed correctly.This had nothing to do with network issues as the wording of the error message suggested.The escential problem is that Mysql JDBC pool connections is not used, then the Timeout from Mysql, close the Connections.  You need change the pool Parameters to get restart connection when the connection has failures, on this way::       Required    (Check)\n           autocommitYou can change the Validation Method if you cannot get it works!If you use WAMP, make sure it is online. What I did was, first turned my firewall off, then it worked, so after that I allowed connection for all local ports, specially port 80. Than I got rid of this problem. For me it was the Firewall who was blocking the connection.I had the same problem and I used most of the params (autoreconnect etc..), but didn't try the (test_on_idle, or test_on_connect) , I am going to do them next.However, I had this hack that got me through this: I have a cron job called Healthcheck, It wakes up every 10 mins and makes a REST API call to the server. The web / app server picks this up, connects to the db, makes a small change and comes back with a 'yes all quiet on western front' or 'shitshappening'. When the latter, it sends a pager / email to the right people.It has the side effect of always keeping the db connection pool fresh.  So long as this cron is running, I don't have the db connection timeout issues. otherwise, they crop up.
Java

With intent to get m2e 1.0 working correctly I have had to specify the lifecycle mapping:But then I get this warning:if I run some specific maven task for example  (If I run only  then there is no such message)I know that the problem is that this POM does not exists, because it is only defined to hold the mapping information. ()Anyway, I want to keep my build clean, without any warnings, so how can I get rid of this specific one? ()I use Maven 3.0.2 and tried Maven 3.0.3 too, but the same result.My team works around this problem by wrapping the relevant configuration in a profile:This a  with  resolution. The suggested solution is the simplest in my opinion:and  this project.Regards\nMirkoNow there's now better solution (for the error messages in Eclipse only).Press  on the error  and then select this option:This works with  plugin (maybe earlier also)
Java

I need to write a project that's only compatible with Java 1.5. I have Java 1.6 installed. Is there some form of backwards compatibility to get Eclipse to compile with 1.5?Do I have to install Java 1.5 to get it to show here? Or maybe there is another way?.Click on the  button. It brings your  to point to the Java location.Select \"\", button right besides JRE home and point to the installed folder location.Even though you want to just 1.5 compiler project, you can achieve it by changing compiler settings in Eclipse instead of removing 1.6 JRE and add 1.5 JRE.As davidfmatheson suggested,Just be careful, especially if you're setting this up for a team of people to work on. If anyone uses anything that is new or changed in 1.6, it will compile, but not run in an environment with JRE 1.5.Click on the  tab in Eclipse, go to  and when that window comes up, go to  \u2192  \u2192  and choose JavaSE-1.5. You then have to go to  and set the .Right click project -> Properties ->  -> select  click  and select  or  after then click  and select   to   Eclipse - specific Project change JDK Version -If you want to change any jdk version of A specific project than you have to click ---> Project --> JRE System Library --> Properties ---> Inside Classpath Container (JRE System Library) change the Execution Environment to which ever version you want e.g. 1.7 or 1.8.See the page . From the add button you can add a different version of the JDK...The JDK (JAVA_HOME) used to launch Eclipse is not necessarily the one used to compiled your project.To see what JRE  can select for your project, check the preferences: \u2192 By default, if you have not added any JRE, the only one declared will be the one used to launched Eclipse (which can be defined in your ).  You can add any other JRE you want, including one compatible with your project.After that, you will need to check in your project properties (or in the general preferences) what JRE is used, with what compliance level:In the preferences section under Java -> Installed JREs click the Add button and navigate to the 1.5 JDK home folder.  Then check that one in the list and it will become the default for all projects:As I was facing this issue minutes ago, in case you are trying to open an existing project in an environment with a newer JDK, make sure you pdate the JDK version in Project Properties -> Project Facets -> Java.
Java

I'm looking for a book or any other resource that will help me learn how to create RESTful APIs in Java. \nLooking on Amazon, I saw that there are , but I'm looking for the one that is tailored to a novice.Looking forward to getting your advices/opinions, thanks!I don't think I can point to only one resource but I would take a path (which you can customize based on your level of understanding of REST). I'm somebody who would like to get my concepts real clear first and then think about the tools to implement the concepts.Obviously, I haven't provided a single resource, but something in the lines I've provided would serve well, IMO.I found  to be the best book covering different styles of REST architectures.  It's also far more practical in its advice than many other books (I wasn't impressed by RESTful Web Services as I think it lacks focus).My recommendation would be this one:I'd recommend this extensive ,  and maybe having at look at the  framework.I have used  to learn about REST concepts. It's an early access book so only the first few chapters are currently available, but I found the writing to be very clear.
Java

I am wondering when static variables are initialized to their default values.\nIs it correct that when a class is loaded, static vars are created (allocated),\nthen static initializers and initializations in declarations are executed?\nAt what point are the default values are given?  This leads to the problem of forward reference.Also please if you can explain this in reference to the question asked on  and especially the answer given by Kevin Brock on the same site. I can't understand the 3rd point.Instance and class (static) variables are automatically initialized to standard default values if you fail to purposely initialize them.  Although local variables are not automatically initialized, you cannot compile a program that fails to either initialize a local variable or assign a value to that local variable before it is used.What the compiler actually does is to internally produce a single class initialization routine that combines all the static variable initializers and all of the static initializer blocks of code, in the order that they appear in the class declaration.  This single initialization procedure is run automatically, one time only, when the class is first loaded.In case of  classes, they can not have static fieldsSee JLS  fields in Java can be initialized separately from their declaration place this is however can not be applicable to  fields. See the example below.This is because there is just one  of the  variables associated with the type, rather than one associated with each instance of the type as with instance variables and if we try to initialize  of type  within the constructor, it will attempt to reinitialize the  type field  because the constructor is run on each instantiation of the class that must not occur to static  fields.See:The last in particular provides  that spell out when static variables are initialized, and in what order (with the caveat that  class variables and interface fields that are compile-time constants are initialized first.)I'm not sure what your specific question about point 3 (assuming you mean the nested one?) is. The detailed sequence states this would be a recursive initialization request so it will continue initialization.The order of initialization is:The details of the process are explained in the JVM  document.Static fields are initialized when the class is loaded by the class loader.  Default values are assigned at this time.  This is done in the order than they appear in the source code.Starting with the code from the other question:A reference to this class will start initialization.  First, the class will be marked as initialized.  Then the first static field will be initialized with a new instance of MyClass().  Note that myClass is immediately given a reference to a  MyClass instance.  The space is there, but all values are null.  The constructor is now executed and prints , which is null.Now back to initializing the class:   is made a reference to a new real object, and we're done.If this was set off by a statement like:   space for a new MyClass instance is again allocated (and the reference placed in ).  The constructor is again executed and again prints , which  is not null.The real trick here is that when you use , as in   is immediately given a reference to a bit of nulled memory.  The JVM will then go on to initialize values and run the constructor.  But if you somehow reference   it does so--by referencing it from another thread or or by referencing from the class initialization, for instance--you are looking at a class instance filled with null values.The static variable can be intialize in the following three ways as follow choose any one you like*
Java

Does anybody have an example of how to use Google Guice to inject properties from a .properties file.  I was told Guice was able to validate that all needed properties exist when the injector starts up.At this time I cannot find anything on the guice wiki about this.You can bind properties using , where  returns a  object or a  (reading the properties file as a  object is up to you).You can then inject them by name using . If you had a properties file:You could inject the values of those properties anywhere you wanted, like this:Guice can convert values from strings to the type being injected, such as the  above, automatically (assuming the string is an appropriate format). This works for primitive types, enums and class literals. 
Java

I am trying to understand PrintWriter for a small program I'm making, and I cant seem to get java to make the file and then write on it. When I execute the program below it gives me a Filenotfoundexeption error on line 9. It also fails to make the file in the directory that I specified. I am new to this so please try and keep the answers simple. I am using Eclipse.If the directory doesn't exist you need to create it. Java won't create it by itself since the  class is just a link to an entity that can also not exist at all.As you stated the error is that the file cannot be created. If you read the documentation of PrintWriter constructor you can seeYou should try creating a path for the folder it contains before:throw an exception for the file.Pass the File object to the constructor :You should have a clear idea of exceptions in java.\nIn java there are checked exceptions and unchecked exceptions.Checked exceptions are checked (not thrown,just checked) by the compiler at Compile time for the smooth execution of the program at run time.NOTE: And in our program if their is a chance that a checked exception will rise, then we should handle that checked exception either by try catch or by throws key word.Otherwise we will get a compile time Error:CE:Unexpected Exception java.io.FileNotFoundException;must be caught or declared to be thrown.How to resolve:\n1.Put your code in try catch block:2.use throws keyword as shown by other guys above.Advice:Read more about Exceptions.(I personally love this topic)Java doesn't normally accept \"/\" to use in defining a file directory, so try this:If the file doesn't exist do:Need any Java help, just come to me.Well I think firstly keep whole main into try catch(or you can use as  and then also use full path of file in which you are writing asall those directies like users,Me,Desktop,directory should be user made. java wont make directories own its own.\nit should be as}The  can actually create the file for you. For a list of valid encodings, Alternatively, you can just pass the file path to the  class without declaring the encoding.
Java

I would like to know if a  exists for Java. In Perl exists  and there's a port to Ruby called , for JavaScript . Someone know about a  for Java, that can provide random names, phone number, P.O. box number, etc...If you're using Hibernate, try .Also: Try . This is new project in early stage. PS. I'm a contributor.There is a Java port of the Perl Data::Faker - \nHow to use:Output :
Java

Personally I've never understood the idea of factory classes because it seems a whole lot more useful to just instantiate an Object directly. My question is simple, in what situation is the use of a factory class pattern the best option, for what reason, and what does a good factory class look like?The idea here is separation of concerns: If the code that uses the object also has enough information to instantiate it, you don't need a factory. However, if there is some logic or configuration involved that you don't want to have the API user to think about (or mess with), you can hide all that (and encapsulate it for reuse) in a factory.Here is an example: You want to access one of the services provided by Google App Engine. The same code should work at both the development environment (of which there are two versions, master-slave and high-availabilty) and the completely different local development environment. Google does not want to tell you about the inner workings of their internal infrastructure, and you don't really want to know. So what they do is provide interfaces and factories (and several implementations of those interfaces for the factories to choose from that you don't even need to know about).Here is a real live factory from my code base. It's used to generated a sampler class that knows how to sample data from some dataset (it's originally in C#, so excuse any java faux-pas)and here is an example usage:As you see, it's not much code, and it might even be shorter and faster just to dothan to use the factory. So why do I even bother? Well, there are two basic reasons, that build on each other:Personally, I use the factory pattern when the implementation of an interface is unknown at run time or it can be made dynamic.This means that as a developer, I work against a known interface to the instance of the object, but I'm not concerned with how the implementation works.Take, for example.  You could use a factory pattern to provide you with objects from a database.  You don't care if that database is a flat file, local/single user database, server database or web resource, only that the factory can generate and manage those objects.I'd hate to have to write implementations for each of those cases :PFrom Effective Java book by Joshua Bloch, partially rewritten by me:1) Static factory methods (), unlike constructors, have names.2) It is not required to create a new object each time  is/are invoked3)  can return an object of any subtype of their return type.4)  reduce the verbosity of creating parameterized type instances.To complement Thilo's answer, let us suppose that you have an object which only has a boolean as a constructor: it would be a total waste to build one each time, since it only has two possible values.In this case, you can create static factory methods. Java's  class is an example: .Factory by itself does not show its beauty so easily. Is when you combine it with other patterns when you see the real benefits for example, if you want to use the decorator pattern, instantiating an object directly may add some additional coupling to your code. As the OOP teacher says, coupling is bad :) so if you were to instantiate the decorated object and didn't want to increase coupling then you could use a factory.You may refer to the , but basic idea of most design patterns is to introduce some abstraction to achieve better maintainability and/or reusability. Factory method pattern is no exception, what it does is to abstract away the complexity of creation from the code.For simple case it seems unnecessary to use factory pattern, a simply  is enough. But when you need more flexibility or functionality, this pattern may help.For example, unless a new instance is required, the static factory  is generally a better choice than , for it avoids creating unnecessary objects. Factory method pattern is also known as . As we know, polymorphism is one of the key features of OOP, but constructor cannot be polymorphic, this shortcoming can be overcome by factory method pattern.In essence, instantiating an object directly(typically via ) is barely a concrete , while factory method pattern shields a   by a  (not limited to the  in Java), pushing the logic of object-creating behind some abstraction to ensure more maintainable and reusable code.As a final word, to fully understand the benefit of factory method pattern and other design patterns, one need grasp the essence of OOP, including , polymorphic abstraction and  principle.
Java

Suppose, I am doing a full build on my large project which has 7 modules and on the 6th module, the build failed because a test failed. Is there any way by which I can start the build from the point it failed?You can resume the build from the 6th module using  or :See the  for details.you can resume the build from any module you want by using the  command.\nFor example, if your build failed in myproject-proxy, you can use the following command:look at the maven summary and you will see the executed modules and where maven is stopped.\nthen try this: You could run the build of module 6 separately to see if it still fails, but I'm afraid that you need to build all modules from the beginning when you want to run the \"big\" build.Edit: Of course the subsequent builds will be faster because the code of modules 1-5 are already compiled, unless you run clean as part of your build. 
Java

There are number of performance tips made obsolete by Java compiler and especially . For example, these platform-provided optimizations can drastically (according to sources) reduces the cost of virtual function calls. VM is also capable of method inlining, loop unrolling etc.What are other performance optimization techniques you came around still being applied but are actually made obsolete by optimization mechanisms found in more modern JVMs?The final modifier on methods and method parameters doesn't help with the performance at all.Also, the  gives a good overview of the optimizations used by HotSpot and how to efficiently use them in Java code.People replacing  with multiple calls to StringBuilder or StringBuffer.  It actually already uses StringBuilder behind the scenes.It is necessary to define time/memory trade-offs before starting the performance optimization. This is how I do it for my memory/time critical application (repeating some answers above, to be complete):In 2001 I made apps for a J2ME phone.  It was the size of a brick.  And very nearly the computational power of a brick.Making Java apps run acceptably on it required writing them in as procedural fashion as possible.  Furthermore, the very large performance improvement was to catch the  to exit for-loops over all items in a vector.  Think about that!Even on Android there are 'fast' loops through all items in an array and 'slow' ways of writing the same thing, as mentioned in the Google IO videos on dalvik VM internals.However, in answer to your question, I would say that it is most unusual to have to micro-optimise this kind of thing these days, and I'd further expect that on a JIT VM (even the new Android 2.2 VM, which adds JIT) these optimisations are moot.\nIn 2001 the phone ran KVM interpreter at 33MHz.  Now it runs dalvik - a much faster VM than KVM - at 500MHz to 1500MHz, with a much faster ARM architecture (better processor even allowing for clock speed gains) with L1 e.t.c. and JIT arrives.We are not yet in the realms where I'd be comfortable doing direct pixel manipulation in Java - either on-phone or on the desktop with an i7 - so there are still normal every-day code that Java isn't fast enough for.   that claims an expert has said that Java is 80% of C++ speed for some heavy CPU task; I am sceptical, I write image manipulation code and I see an order of magnitude between Java and native for loops over pixels.  Maybe I'm missing some trick...? :D:64bit JVM use 30%-50% more memory in comparision to 32bit JVM because of bigger ordinary object pointers. You can heavily reduce this factor by using JDK6+.From JDK6u6p to JDK6u22 it is optional and can be enabled by adding JVM argument:From JDK6u23 (JDK7 also) it is enabled by default. More info .I found links above outdated. Here is a new one on Java optimization: 
Java

When dealing with real world monetary values, I am advised to use BigDecimal instead of Double.But I have not got a convincing explanation except, \"It is normally done that way\".Can you please throw light on this question?It's called loss of precision and is very noticeable when working with either very big numbers or very small numbers. The binary representation of decimal numbers with a radix is in many cases an approximation and not an absolute value. To understand why you need to read up on floating number representation in binary. Here is a link: . Here is a quick demonstration: \nin bc (An arbitrary precision calculator language) with precision=10:(1/3+1/12+1/8+1/30) = 0.6083333332\n(1/3+1/12+1/8) = 0.541666666666666\n(1/3+1/12) = 0.416666666666666Java double:\n0.6083333333333333\n0.5416666666666666\n0.41666666666666663Java float:0.60833335\n0.5416667\n0.4166667\nIf you are a bank and are responsible for thousands of transactions every day, even though they are not to and from one and same account (or maybe they are) you have to have reliable numbers. Binary floats are not reliable - not unless you understand how they work and their limitations.While BigDecimal can store more precision than double, this is usually not required.  The real reason it used because it makes it clear how rounding is performed, including a number of different rounding strategies.  You can achieve the same results with double in most cases, but unless you know the techniques required, BigDecimal is the way to go in these case.  A common example, is money.  Even though money is not going to be large enough to need the precision of BigDecimal in 99% of use cases, it is often considered best practice to use BigDecimal because the control of rounding is in the software which avoids the risk that the developer will make a mistake in handling rounding. Even if you are confident you can handle rounding with  I suggest you use helper methods to perform the rounding which you test thoroughly.I think this describes solution to your problem:  and the problem with double From the original blog which appears to be down now.Many traps lay before the apprentice programmer as he walks the path of software development. This article illustrates, through a series of practical examples, the main traps of using Java's simple types double and float. Note, however, that to fully embrace precision in numerical calculations you a text book (or two) on the topic is required. Consequently, we can only scratch the surface of the topic. That being said, the knowledge conveyed here, should give you the fundamental knowledge required to spot or identify bugs in your code. It is knowledge I think any professional software developer should be aware of.This is primarily done for reasons of precision. BigDecimal stores floating point numbers with unlimited precision. You can take a look at this page that explains it well. When BigDecimal is used, it can store a lot more data then Double, which makes it more accurate, and just an all around better choice for the real world.Although it is a lot slower and longer, it's worth it.Bet you wouldn't want to give your boss inaccurate info, huh?Another idea: keep track of the number of cents in a . This is simpler, and avoids the cumbersome syntax and slow performance of .Precision in financial calculations is extra important because people get very irate when their money disappears due to rounding errors, which is why  is a terrible choice for dealing with money.
Java

I am trying to install IDEA on Ubuntu 11.10. First, I installed . Then I tried running the  file as instructed. However it complains:Trying to  these three variables prints an empty line to the screen. How (and to what values) do I set these variables and proceed with the installation? Thanks.It's recommended to use OpenJDK 1.7+ or Oracle JDK to run IntelliJ IDEA on Linux, OpenJDK 1.6 is strictly unsupported because of the known performance and visual issues.Starting from IntelliJ IDEA 16, custom JRE is bundled with Linux distributions.The tricky part is that Oracle JDK is no longer distributed via .deb packages and you can't just install it with apt-get or Ubuntu Software Center.Their site is also confusing and you can easily download JRE instead of the JDK (which will not work as IntelliJ IDEA needs tools.jar that is missing from JRE package). for the JDK downloads (version 1.6.0_29). From this URL download the appropriate  file, for example  if you need 32-bit Java or  for 64-bit version.to install in the  directory.Inside  add the following on the second line:Normally resides under . Now IntelliJ IDEA should start fine under Oracle JDK 1.6.0_29. You can verify it in  | .You can set  variable and add to your , by doing the following.  As root open up  and add the following to the end of the file. When you reboot, try running the following:if you had install java ,tryif you see like thisthen you should edit .bash_profile,addthen execute if you not install java,you should install manual or auto.I have had this problem a few times...then run it from the terminal:OR 2: navigate into the IDEA_HOME/bin and run it from there.You install JDK 8 with:Then, sometimes the problem lies on the default version of JAVA you are running. For this, use  to modify it:See how I did it:And now Intellij IDEA 2016.3 is running fine.Here is a bash script for developers that installs IDEA so that you can run it from the shell via It also:i also face a question... in firs day all works without problems, but then...\ni solve a problem: add to file  line with path to JDK add after 46 lineActually, you can configure the JAVA_HOME in bash. But, IDEA use javac and java from standard bin folders. So, you have to configure like this.
Java

I have a simple marker annotation for methods (similar to the first example in Item 35 in  (2nd ed)):Then, in a given package (say ), which has a few subpackages containing some 20 classes, I'd like to find all methods that are annotated with it. (Because I'd like to do some checks regarding all the annotated methods in a unit test.)What (if any) is the easiest way to do this? Preferably without adding new 3rd party libraries or frameworks.: to clarify, obviously  will be the way to check if a method has the annotation - but this problem includes finding all the methods.If you want to implement it yourself, these methods will find all the classes in a given package:Then you can just filter on those classes with the given annotation:You should probably take a look at the open source . With it you can easily achieve what you want with few lines of code:If you're happy to use Spring, then that does something along these lines using it's context:component-scan functionality, where Spring scans for annotated classes in a given package. Under the covers, it's pretty gruesome, and involves grubbing about on the filesystem and in JAR files looking for classes in the package.Even if you can't use Spring directly, having a look through its source code might give you some ideas.Certainly, the Java reflection APi is no use here, it specifically does not provide a means to obtain all classes in a package.
Java

I have a Java class that takes in the latitude/longitude of a location and returns the GMT offset when daylight savings time is on and off.  I am looking for an easy way to determine in Java if the current date is in daylight savings time so I can apply the correct offset.  Currently I am only performing this calculation for U.S. timezones although eventually I would like to expand this to global timezones as well.This is the answer for the machine on which the question is being asked:A server trying to figure this out for a client will need the client's time zone.  See @Powerlord answer for the reason why.For any particular TimeZone Here is the modern  (see ) version of the  by . Example code:Note how in the last line we had to extract an  object from our  object with a simple call to .You're going to have to do a bit more work using those coordinates and figure out which time zone they're in.  Once you know which TimeZone that is, the isDayLight() method would be useful.For example, you have no way of telling whether -0500 is EST (US/Canada Eastern Standard Time), CDT (US/Canada Central Daylight Time), COT (Colombia Time), AST (Brazil Acre Standard Time), ECT (Ecuador Time), etc...Some of these may or may not support daylight saving time. contains handling methods which will calculate the offsets for you. See To supplement this, you will need to look up the current time zone with your latitude/longitude info.   provides a java client for its web service, as well as a simple web-request framework (i.e. )
Java

Confused by java compilation processOK i know this: We write java source code, the compiler which is platform independent translates it into bytecode, then the jvm which is platform dependent translates it into machine code.So from start, we write java source code. The compiler javac.exe is a .exe file. What exactly is this .exe file? Isn't the java compiler written in java, then how come there is .exe file which executes it? If the compiler code is written is java, then how come compiler code is executed at the compilation stage, since its the job of the jvm to execute java code. How can a language itself compile its own language code? It all seems like chicken and egg problem to me.Now what exactly does the .class file contain? Is it a abstract syntax tree in text form, is it tabular information, what is it?can anybody tell me clear and detailed way about how my java source code gets converted in machine code.Actually the compiler itself  as a native executable (hence javac.exe). And true, it transforms source file into bytecode. The bytecode is platform independent, because it's targeted at Java Virtual Machine.Not always. As for Sun's JVM there are two jvms: client and server. They both can, but not certainly have to compile to native code.This  file is a wrapped java bytecode. It's for convenience - to avoid complicated batch scripts. It starts a JVM and executes the compiler.That's exactly what wrapping code does.True, confusing at first glance. Though, it's not only Java's idiom. The Ada's compiler is also written in Ada itself. It may look as a \"chicken and egg problem\", but in truth it's only bootstrapping problem.It's not Abstract Syntax Tree. AST is only used by tokenizer and compiler at compiling time to represent code in memory.  file is like an assembly, but for JVM. JVM in turn is an abstract machine which can run specialized machine language - targeted only at virtual machine. In it's simplest,  file has very similar structure to normal assembly. At the beginning there are declared all static variables, then comes some tables of extern function signatures and lastly the machine code.If You are really curious You can dig into classfile using \"javap\" utility. Here is sample (obfuscated) output of invoking :So You should have an idea already what it really is.I think it should be more clear right now, but here's short summary:Edit: Without the  one would have to invoke compiler using something similar to this:As You can see it's calling Sun's private API so it's bound to Sun JDK implementation. It would make build systems dependent on it. If one switched to any other JDK (wiki lists 5 other than Sun's) then above code should be updated to reflect the change (since it's unlikely the compiler would reside in com.sun.tools.javac package). Other compilers could be written in native code.So the standard way is to ship  wrapper with JDK.Where do you get this information from? The  executable could be written in any programming language, it is irrelevant, all that is important is that it is an executable which turns  files into  files.For details on the binary specification of a .class file you might find these chapters in the  useful (although possibly a bit technical):You can also take a look at the  which covers:The Java compiler (at least the one that comes with the Sun/Oracle JDK) is indeed written in Java.  is just a launcher that processes the command line arguments, some of which are passed on to the JVM that runs the compiler, and others to the compiler itself.Many (if not most) compilers are written in the language they compile. Obviously, at some early stage the compiler itself had to be compiled by something else, but after that \"bootstrapping\", any new version of the compiler can be compiled by an older version.The details of the class file format are described in the .Well, javac and the jvm are typically native binaries. They're written in C or whatever. It's certainly possible to write them in Java, just you need a native version first. This is called \"boot strapping\".Fun fact: Most compilers that compile to native code are written in their own language. However, they all had to have a native version written in another language first (usually C). The first C compiler, by comparison, was written in Assembler. I presume that the first assembler was written in machine code. (Or,  ;).class files are bytecode generated by javac. They're not textual, they're binary code similar to machine code (but, with a different instruction set and architechture).The jvm, at run time, has two options: It can either intepret the byte code (pretending to be a CPU itself), or it can JIT (just-in-time) compile it into native machine code. The latter is faster, of course, but more complex.The .class file contains bytecode which is  like very . The compiler could very well be written in Java, but the JVM would have to be compiled to native code to avoid the chicken/egg problem. I believe it is written in C, as are the lower levels of the standard libraries. When the JVM runs, it performs just-in-time compilation to turn that bytecode into native instructions.Windows doesn't know how to invoke Java programs before installing a Java runtime, and Sun chose to have native commands which collect arguments and then invoke the JVM instead of binding the jar-suffix to the Java engine.Write code on a text editor, save it in a format that compiler understands -  file extension,  (java compiler) converts this to  format file (byte code - class file). JVM executes the .class file on the operating system that it sits on.Always remember java is not the base language that operating system recognizes. Java source code is interpreted to the operating system by a translator called . JVM cant understand the code that you write in a editor, it needs compiled code. This is where a compiler comes into picture.Every computer process indulges in memory manipulation. We cant just write code in a text editor and compile it. We need to put it in the computer's memory, i.e save it before compiling.  - We have a separate text format that the compiler recognizes, i.e  . Save the file in .java extension and the compiler will recognize it and compile it when asked.  Compiler is a second translator(not a technical term) involved in the process, it translates user understood language(java) into JVM understood language(Byte code - .class format). The compiler produces .class file that JVM understands. The program is then executed, i.e the .class file is executed by JVM on the operating system. 1) Java is not  it is .2) JVM is developed using . One of the reason why people call Java a slower language than C/C++3) Java byte code (.class) is in , the only language understood by JVM. Any code that produces .class file on compilation or generated Byte code can be run on the JVM.The compiler was originally written in C with bits of C++ and I assume that it still is (why do you think the compiler is written in Java as well?). javac.exe is just the C/C++ code that is the compiler.As a side point you could write the compiler in java, but you're right, you have to avoid the chicken and egg problem.  To do this you'd would typically write one or more bootstrapping tools in something like C to be able to compile the compiler.The .class file contains the bytecodes, the output of the javac compilation process and these are the instructions that tell the JVM what to do.  At runtime these bytecodes have are translated to native CPU instructions (machine code) so they can execute on the specific hardware under the JVM.  To complicate this a little, the JVM also optimises and caches machine code produced from the bytecodes to avoid repeatedly translating them.  This is known as JIT compilation and occurs  as the program is running and bytecodes are being interpreted.
Java

When we must use a _ to separate digits in a number I don't' understand the\nfollowing case in which I can't use it:Some examples?You don't  to use \"_\", you . And examples given in the proposal are credit card numbers, phone numbers, or simply numbers for witch it makes sense to have a separator in the code.For the \"In positions where a string of digits is expected\" it's simply in places where it's supposed to start (or end) with a digit. Here are some examples.As written in :It looks like someone killed the URL in the original post (OP). Here's the whole nasty URL just in case some formatting feature kills it again:The specific quote from that page to which you are speaking is as follows:I too found the third point rather curious. I mean, for the most part, all of the scenarios are covered by the first three points, so what is this mysterious 'string of digits' for which they speak? Which scenario  doesn't actually get addressed by the first three points that forces them to add this mysterious fourth?Initially I thought they were speaking about hexadecimal notation or binary notation, where a number is expected after the b or the x, as with the following examples that don't work:Still, I think that might technically be the same as the first point, which says an underscore can't be at the beginning of the number; but certainly, a 'string of numbers' is expected after a 'b' or an 'x' when using binary or hex, right? So if I was a betting man, I might put some money behind the binary/hexadecimal scenario. But I have another plausible scenario on which I might hedge my bet. Here it goes.Personally, I wish there was a rule in Java that said you can only use the word 'string' when talking about a java.lang.String. Allowing the term 'string' to retain it's pedestrian meaning causes confusion, and this is a perfect example.Now, if the fourth point said \"In positions where a java.lang.String of digits is expected\" I might come to the conclusion that they're talking about actual java.lang.String objects that represent numbers that need to be parsed. So, take this piece of code:Will that compile? Will that run? It will compile fine, but of course, the parseInt method expects a java.lang.String of numbers, and validation or parsing of that numeric java.lang.String will trigger the following error at runtime:Of course, this is a runtime error, and it appears that the Oracle documentation is really speaking about errors that will be flagged at compile time. But this certainly is a scenario where a 'String of numbers' is expected. Now if only the Oracle documentation was in a Wiki format. It might tempt me to go in and add something like the following:By the way, I just wrote a little article on the topic over at TheServerSide. Feel free to take a look. The article is designed to hit on the Oracle Certified Professional, Java 7 Programmer certification objective, but it's a pretty comprehensive and easy to read article to just generally explain the rules around using underscores.Hope that helps.no idea, but here's the grammar, enjoy. (I don't see \"string of digits\" anywhere)My interpretation of this is that underscores cannot be placed  in positions where a string of digits would normally be expected:I believe the \"In positions where a string of digits is expected\" covers things like escape sequences in string literals.  For example, you can't say \"\\u00_11\".\"In positions where a string of digits is expected\" means where a variable of type String which contains digits is expected, then using an underscore will make the underscore part of the number. For example look at the code below:So if you have a method expecting a String of digits as one of the arguments, DO NOT use underscore to separate the digits because it will be treated as any other String.
Java

I know how to change the font of \"Java editor\" in Eclipse in menu  \u2192  \u2192  \u2192 , but I could not find an option for changing the font of \"layout editor\" for files like myLayout.xml or strings.xml.Where is it?Use menu  \u2192  \u2192  \u2192  \u2192  \u2192 . This is a common text font setting that is applied to XML file editors by default.I also found .For my Eclipse\u00a0v4.4 (Luna) installation, the XML editor font size is changed under: Menu  \u2192  \u2192  \u2192  \u2192  \u2192  \u2192 .I had to expand General to get to Appearance... I figured it out in about 3.2 seconds, but just in case anyone wants to save that 3.2 seconds:This is in Eclipse IDE for Android Developers v23.0.2.  I'm pretty sure this changes all font sizes for everything in the editor.. ?  But I'm assuming if you want XML font to be bigger, you want all files to be that font size.
Java

I have an element with the ID  type of . How can I find and access this object if I have the instance  of ?Try
Java

I have quite a lot spots in my code which do:where  creates a new collector on every use.This leads me to the question if it is allowed and advisable to do something like:for every type I use and then make use of that single Collector like:when a collector is required.As the collectors are stateless and just a collection of functions and characteristics, I should think it should work, but OTOH,  creates a new  on every call.What are the downsides of reusing a Collector?I think this is more of a  question, but lets give some thoughts:What I mean with that: if you are worried of \"wasting\" performance; you would rather look into each and any line of code that uses streams to determine whether that stream is working with \"enough\" objects to justify the usage of streams in the first place. Those streams come with  overhead!Long story short: the java community has yet to find \"standard best practices\" for streams; thus my (personal) two cent at this time: prefer those patterns that \"everybody\" is using - avoid doing your own thing. Especially when it is \"performance related\".Since the  is basically a container for the four functions and characteristics flags, there is no problem reusing it, but also rarely any advantage, as the impact of such a lightweight object on the memory management is negligible, if not removed entirely by the optimizer anyway.The main reason not to reuse s, as seen with the builtin , is, that you can\u2019t do it in a type safe way. When offering a collector for arbitrarily typed s, you\u2019ll need unchecked operations to always hand out the same  instance. If you store a  in a properly typed variable instead, to be used without unchecked operations, you can use it only for one type of s, to stay with that example.In the case of , etc., the JRE developers went a different way, but the constants , ,  already existed before the introduction of Generics, and I\u2019d say they are more versatile than the few cacheable , which are just four special cases out of the other more than thirty builtin collectors, which can\u2019t be cached due to their function parameters. Since function parameters are often implemented via lambda expressions, which generate objects of unspecified identity/equality, a cache mapping them to collector instances would have an unpredictable efficiency, but very likely be far less efficient than the memory manager will deal with the temporary instances.It is a good practice for a library to provide a  for obtaining useful objects. As the library  such a method: , it is again a good practice to  whether to create a new instance each time the object is requested or not, instead of tampering with the library, thus decreasing readability and risking the future problems when the implementation changes.This to be added to the GhostCat's and Holger's answer as a supportive argument :)Just a tiny side-note, what @Holger is saying in his answer about the optimizer being smart and replacing that construct entirely is totally doable and it is called a . When an Object used inside a method is  and its fields are . So that resulting  might not be treated at the JVM level as a Object per-se. That would happen at . The classic issue of using a single static object to stand in for one created on-the-fly is mutability. A quick scan of the Java 8 source highlights the  field as a possible problem.Clearly it would be possible for some code somewhere to do something like:This  globally change the functionality of  use of  which could create very obscure bugs.So IMHO - don't!This would be a case of premature optimization. Object creation is pretty cheap. On a normal laptop I would expect to be able to create between 10M-50M objects per second. With these numbers in mind the whole exercise becomes pointless. 
Java

In  Notepad++ , it has a very nice feature that if I select a word , it will highlight all the same words throughout the text . Added to this , I can set the hot-keys to highlight up to five different  words with different styles (See the effect below) .Is there any ways /plug-ins to get this similar effect in eclipse  ? I know when editing Java   , it will highlight all the same variables ,but it will not work when I highlight the comments and editing other files type (eg  xml , html , js , css and etc).Thanks so much and best regardsI've been working with Eclipse for quite a while and I'm pretty certain that there is no canonical way of doing this.In Eclipse these things are managed on a per-editor basis and the Java editor does not support what your looking for for all I know. At least for the Java editor you can do some minor configuration in what is highlighted and how (), but I guess you already know that.As for plugins, I'm not aware of any plugin that achieves what you're looking for. As a matter of fact I'd be surprised if there really was a plugin which achieves what you're looking for.If something comes up I'd much appreciate you sharing it here, I've been trying to get decent highlighting into Eclipse for years unsuccessfully... :)Here is a plugin for eclipse: It highlights all occurrences as with notepad++ upon hitting Ctrl + Alt + F.If you enable \"Mark Occurrences\" , then all words that are the same as the one you have marked will be highlighted.  Below is what I found works for me but you can also assign a key shortcut to 'Find Text in File':As mentioned by @Kislingk you can modify how the words are highlighted/marked in 'Preferences > General >Editors>Text Editors > Annotations'.Use file search to search selected resource can highlight same word in single file. Another useful eclipse plugin is . It has extensive feature set. This is also available in eclipse marketplace.There are other options needed to enable.(Preferences > General >Editors>Text Editors > Annotations).  Find Occurrences and WriteOccurrences and enable Text as 'Hightlight' Have tried all of the above answer, but all not working. At the end, i found that it's due to i have accidentally remove some of the , after add back, it's work correctlyHere is the closest solution I have found:
Java

I am trying to run a Java application, but getting this error:  After the colon comes the location of the class that is missing. However, I know that that location does not exist since the class is located elsewhere. How can I update the path of that class? Does it have something to do with the class path?Your classpath is broken (which is a  common problem in the Java world).  Depending on how you start your application, you need to revise the argument to , your Class-Path entry in MANIFEST.MF or your disk layout.A classpath is a list of locations to load classes from. These 'locations' can either be directories, or jar files. For directories, the JVM will follow an expected pattern for loading a class. If I have the directory  in my classpath, and I attempt to load a class , it will look under the classes directory for a directory called , then under that a directory called , and finally it will look for a file called  in that directory.In the second instance, for jar files, it will search the jar file for that class. A jar file is in reality just a zipped collection of directories like the above. If you unzip a jar file, you'll get a bunch of directories and class files following the pattern above. So the JVM traverses a classpath from start to finish looking for the definition of the class when it attempts to load the class definition. For example, in the classpath :C:/myproject/classes;C:/myproject/lib/stuff.jar;C:/myproject/lib/otherstuff.jarThe JVM will attempt to look in the directory  first, then in  and finally in .When you get a ClassNotFoundException, it means the JVM has traversed the entire classpath and not found the class you've attempted to reference. The solution, as so often in the Java world, is to check your classpath.You define a classpath on the command line by saying  and then your classpath. In an IDE such as Eclipse, you'll have a menu option to specify your classpath.This is the  I found so far.Suppose we have a package called  containing the classes:and the files defining this package are stored physically under the directory  (on Windows) or  (on Linux).The file structure will look like this:\nWhen we invoke Java, we specify the name of the application to run: . However we must also tell Java where to look for the files and directories defining our package. So to launch the program, we have to use the following command:\nIf you know the path of the class or the jar containing the class then add it to your classpath while running it. You can use the classpath as mentioned here:on Windowson UNIX/LinuxTo add the location of a class to your classpath via command line simply add  or  and the location of the class while running it. I.E.Or if you're running an IDE such as eclipse you can right click on the \nand add the external JAR containing your class to the build path then it should work fine.Use ';' as the separator. If your environment variables are set correctly, you should see your settings. If your PATH and CLASSPATH is correct, windows should recognize those commands. You do NOT need to restart your computer when installing Java.Add the  of jar file to the CLASSPATH.\nIn linux use: . Other way worked (without editing the CLASSPATH) was unzipping the jar in the current project folder.Ways didn't work for me:1) Using  option with full path of jar file.2) Using with only the name of jar when located in the current folder3) Copying the jar to the current project folder4) Copying the jar to standard location of java jars (/usr/share/java)Go up to the top and remove the import statement if there is one, and re import the class.  But if that isn't the case do a clean then build.  Are you using Netbeans or Eclipse?I ran into this as well and tried all of the other solutions. I did not have the .class file in my HTML folder, I only had the .java file. Once I added the .class file the program worked fine.Depends on your project. I use maven for my project and when i do \"mvn clean install\" and try to run a program it throws the exception. So, i clean the project and run it again and it works for me. I use eclipse IDE.For Class Not Found Exception when running Junit testtry running \"mvn clean test\" once it will compile all the test classes (worked for me)If you are using maven \ntry to maven update all projects and force for snapshots.\nIt will clean as well and rebuilt all classpath..\nIt solved my problem..ClassNotFoundException is very often a result of build errors. If you have an IDE, you can rebuild the project. From the command line, you can recompile the java file.Put all the code in try block then catch exception in a catch block
Java

If I have an ArrayList, and I added an object to it, and later I modified this object, will this change reflect in the ArrayList? or when I add the object to the ArrayList, Java creates a copy and add it to the ArrayList?What if I change the reference to this object to null? Does that mean that the object in the ArrayList now null too?Yes, since you added a  to the object in the list. The reference you added will still point to the same object, (which you modified).No, it won't copy the object. (It will copy the reference to the object.)No, since the content of the original reference was  when added to the list. (Keep in mind that it is the  that is copied, not the object.)Any change to the object will be reflected in the list.However, when you deal with objects like Strings that are immutable, a new object will be created on \"change operations\". Than actually your old object is still in the list while you got a new one elsewhere.Wanted to add another demonstration where the ArrayList is inside of a Map as the value. The ArrayList is modified after adding to the Map and the Map reflects the changes.The Map has one element with mother's name as the key and children as the value.
Java

I'm currently trying to stream live microphone audio from an Android device to a Java program. I started off with sending the live audio between two android devices to confirm my method was correct. The audio could be heard perfectly with barely any delay on the receiving device. Next I send the same audio stream to a small Java program and I verified that the data was being sent here correctly too. Now what I want to do is encode this data and somehow play it back on the server running the Java program. I would rather play it in a web browser using HTML5 or JavaScript but I am open to alternative methods such as VLC.Here is the code for the Android app which sends the live microphone audioAnd here is the code for the Java program reading in the data..I know that I should encode the audio on the app side before sending this to the Java program but I'm not to sure how to go about encoding while using AudioRecorder. I would prefer not to use NDK as I have no experience with it and do not really have time to learn how to use it....yet :)So I got my problem fixed. The problem was mainly on the receiving side. The receiver takes in the audio stream and pushes it out to the PC's speakers. The resulting voice is still quite laggy and broken but it works none the less. Playing around with the buffer size may improve this.Edit : you use a thread to read the audio in order the avoid lag. Also, it is better to use a sampling size of 16 000 as it is ok for voice. Android Code:Android XML:Server code:I hope this helps save someone a few hours of pain :)}The voice is broken because of the following line in your android code:You're just adding empty bytes. Also, use  instead of 
Java

I was wondering, whether is there any need for me to close the InputStream, after I close the reader?No, you don't have to.Since the decorator approach used for streams in Java can build up new streams or reader by attaching them on others this will be automatically be handled by  implementation.If you look at its source  you see that:So the close operation actually closes the  underlying the stream reader.EDIT: I wanna be sure that  close works also on input stream, stay tuned.Checked it, in which is called when sd's close is called.Technically, closing the  will close the . However, if there was a failure between opening the  and creating the , you should still close the . If you close the  [the resource] there shouldn't be a good reason to close the  [the decorator]. There are also popular bugs where closing a decorator can throw an exception before closing the decorated. So:There are some complications to watch out for. Some decorators may actually contain native resources due to their implementation. Output decorators will generally need to be flushed, but only in the happy case (so in the  not the  block).You don't have to close stream, if you  the reader.No you don't the reader will close the underlying InputStreamAcordding to source sniffing the reader closes its underlying inputstream. According to javadoc it seams that InputStreamReader \"closes the stream\" when reader.close() is invoked.I'm not sure if ANY Reader must close its sources when you do reader.close(). I think that this is important so your code can use a reader no matter what concrete type it is.Anyway it makes sense that it's enforced.
Java

In Java 8, the Collection interface was extended with two methods that return : , which returns a sequential stream, and , which returns a possibly-parallel stream.  Stream itself also has a  method that returns an equivalent parallel stream (either mutating the current stream to be parallel or creating a new stream).The duplication has obvious disadvantages:Why does Collection.parallelStream() exist when calling Collection.stream().parallel() does the same thing?The Javadocs for  and  itself don't answer the question, so it's off to the mailing lists for the rationale.  I went through the lambda-libs-spec-observers archives and found  and another thread that touched on whether  to match (or actually, whether it should be removed).  There was no once-and-for-all conclusion, so perhaps I've missed something from another list or the matter was settled in private discussion.  (Perhaps , one of the principals of this discussion, can fill in anything missing.)The participants made their points well, so this answer is mostly just an organization of the relevant quotes, with a few clarifications in , presented in order of importance (as I interpret it). in the first thread, explaining why  is valuable enough to keep even after other parallel stream factory methods have been removed: stands by this position in the later discussion about ::In response to Kevin Bourrillion's skepticism about whether the effect is significant, :, but hedges his position:Indeed, the later discussion about  .At the time of the discussion, switching a stream from sequential to parallel and back could be interleaved with other stream operations.  , explains why sequential/parallel mode switching may complicate future development of the Java platform:This mode switching was .  In the current version of the library, a stream pipeline is either sequential or parallel; last call to / wins.  Besides side-stepping the statefulness problem, this change also improved the performance of using  to set up a parallel pipeline from a sequential stream factory., in response to  that  allows programmers to understand streams sequentially before going parallel:
Java

I'm working on rest api with spring boot. I need to log all requests with input params (with methods, eg. GET, POST, etc), request path, query string, corresponding class method of this request, also response of this action, both success and errors.For an example:successful request:Log should be looked something like this:Or request with error:Log should be something like this:I want Request/Response to be a single entity, with custom information related to this entity, both in successful and error cases.What is best practice in spring to achieve this, may be with filters? if yes, can you provide concrete example?(I've played with @ControllerAdvice and @ExceptionHandler, but as I mentioned, I need to handle all success and error requests in single place (and single log)).Don't write any Interceptors, Filters, Components, Aspects, etc., this is a very common problem and has been solved many times over. Spring Boot has a modules called  which provides HTTP request logging out of the box. There's an endpoint mapped to  which will show you last few HTTP requests. You can customize it to log each request, or write to a DB.Also, where will this application run? Will you be using a PaaS? Hosting providers, Heroku for example, provide request logging as part of their service and you don't need to do  coding whatsoever then.You could use  if there wasn't a requirement to log java method that been executed.But with this requirement you have to access information stored in  of . That said, you can override  to accomplish logging of request/response pair.Below is an example of idea that can be further enhanced and adopted to your needs. - contains the information about request handler.You then can register this dispatcher as following:And here's the sample of logs:In case of errors Spring does automatic error handling. Therefore,  is shown as request handler. If you want to preserve original request handler, then you can override this behavior at  before  is called, to cache original handler.If you dont mind trying Spring AOP, this is something I have been exploring for logging purposes and it works pretty well for me. It wont log requests that have not been defined and failed request attempts though.Add these three dependenciesAdd this to your xml config file Create an annotation which can be used as a pointcut Now annotate all your rest API methods which you want to logNow on to the Aspect. component-scan the package which this class is in.If you want to read in detail read through this.\nSpring already provides a filter that does this job. Add following bean to your configDon't forget to change log level of  to . This code works for me in a Spring Boot application - just register it as a filterHere is how I do it in spring data rest\nby using\n  and\n required a bit of modification for it to work for me, but it is by far the most customizable thing I could get.It didn't work for me, probably because I also have a HandlerInterceptorAdapter[??] but I kept getting a bad response from the server in that version. Here's my modification of it.After adding  to the spring boot bassed application you have  endpoint available with latest requests informations. This endpoint is working based on  and default implementation is  that saves last 100 calls. You can change this by implementing this interface by yourself and make it available as a Spring bean. For example to log all requests to log (and still use default implementation as a basic storage for serving info on  endpoint) I'm using this kind of implementation: This  map contains basic informations about request and response in this kind of form:\n. There is NO response content here. Logging POST dataYou can access POST data by overriding , but don't think it is a good idea (e.g. all uploaded file content will go to logs)\nHere is sample code, but  use it:
Java

Is there some event/receiver or something for handling first execution after installation or directly after installation? Or Do I need it emulate with preferences?There is the  Broadcast Intent, but the application being installed doesn't receive this.So checking if a preference is set is probably the easiest solution.See  - you can put whatever you want in there. I believe this is how  works - the app that can send back your phone's location after it's stolen, that you install from the website  it's been stolen.I don't think there is such a thing, and I don't think this would be a good idea : usually you have to handle not only installations but some updates (say : a new version with features) or the proper initialization of some resources.  For the resources, the best way is to check them directly.For the version, I use the database, it's so easy.The SQLiteOpenHelper's OnUpgrade method is called when the database version changed. I suppose this could be used to do other things than just handling the new schema.
Java

As we all know, many Android apps display a white screen very briefly before their first  comes into focus. This problem is observed in the following cases:Setting  obviously does not work here. Nor can I set the parent theme of the splash screen to  as described , because [unfortunately] my splash screen makes use of an .Meanwhile, apps that do not extend the  class  show the white screen at startup.The thing is, ideally the initializations performed in the  object need to occur  the first  is shown. So my question is, how can I perform these initializations on app startup  using an  object? Possibly using a  or , I suppose?This is an interesting problem to think about. I can't bypass it the usual way (by setting the  theme), as tragically my Splash screen actually has an  due to some unrelated reasons.I have already referred to the following questions:The problem with white background is caused because of android's cold start while the app loads to memory, and it can be avoided with this:layoutimg faceAdd this theme to your splashscreen in the manifestwhich will produce efect like thisfor more details and more solutions you can check this\nFirst of all, to remove the white screen read this - But more importantly, optimize your initial load and defer any heavy work to when you have time to run it. Post your application class here if you want us to take a look at it.Within the lifecycle callback methods, you can declare how your activity behaves when the user leaves and re-enters the activity. Remember that the way Android is designed, there is a lifecycle for each and every app. If you put too much load to the  method (which is the method used to load the layout files and initalise any controls you have in it), then the white screen will become more visible, as the layout file will take longer to load.I suggest using several different methods when starting an activity. Such are the  (being called as the first thing once the app is loaded),  (being called after the layout is displayed and useful if you are making any data processing upon starting the activity).To make it easier for you, below is the official activity lifecycle diagram:please add this line into your theme Have you tried setting the attribute in the theme of your launcher activity, to either a color or a drawable?For example this: when added to the Launcher activity theme will show a black color (rather than the white color) on startup. This is an easy trick to hide long initialisation, while showing your users something,  even if you subclass the Application object.Avoid using other constructs (even Threads) for doing long initialisation tasks, because you may end up not being able to control the lifecycle of such constructs. The Application object is the correct place for doing exactly this type of actions. Both properties worksDid you try to put initialization to ?Inside  class :As you are already aware why this white screen is there, as due to background processes or application initialization or large files, so just check below idea for overcome from this.To prevent this white screen on beginning of the app, one way is splash screen, this is just a way not final and you must have to use.When you will show splash screen from your splash.xml file, then also this issue will be remain same,So you have to create ont style in style.xml file for splash screen and there you have to set window background as your splash image and then apply that theme to your splash activity from manifest file. So now when you will run app, first it will set theme and by this way user will be able to see directly splash image instead of white screen.Just write the item in values/styles.xml:For example, in the AppTheme:I had same issue, you have to update your style.Your manifest file should looks like below.Hope this would help you.
Java

What is the difference between  and  in JDK 1.5? Put simply, the main difference is in format string:Just have a look at javadoc of both methods to find out more details.String.format is just a shortcut to , this is a \"printf-style\" formatter. On the other side,  uses a different formatting convention, as described in the linked documentation.Use the first  and the second .
Java

If I have an enum object, is it considered a primitive or a reference?It's a reference type.Unlike many languages, in which an  is a set of integral constansts, Java enums are immutable object instances.  You can get the numeric value of an enum instance by calling .You can even add your own members to the enum class, like this:The way enums work is actually not too different from how they were used before their introduction with Java 5:By instantiating the different suits on class loading it is ensured that these will be mutually exclusive and the private constructor ensures that no further instances will be created.These would be comparable either through == or equals.The Java 5 enum works pretty much the same way, but with some necessary features to support serialization etc.I hope this background sheds some further light. essentially shows you how enums are implemented, and as SLaks says, they are references.Enums are reference types, in that they can have methods and can be executed from command line as well , if they have main method.See following \"Planet\" example from Sun/Oracle 
Java

I'm working on a web site project with a Java component and am currently testing for cross-browser compatibility. Most is fine but the Java part won't load on 64-bit browsers. Looks like I need a 64-bit JRE to test. Where does one download the (off-line) 64-bit Java runtime installer for Windows?The official download page is here: Unless I'm blind, nothing 64-bit there for Windows except a link to notes. Said notes are here: Particularly relevant excerpt: The only off-line installer, as far as I can tell, has only installed the 32-bit runtime. Then we're back at square one! Am I missing something or going nuts?? I believe the link below will always give you the latest version of the 64-bit JRE\nThe trick is to visit the original page using the 64-bit version of Internet Explorer. The site will then offer you the appropriate download options.Java7 update 45 64 bit direct download link is: You can also just search on sites like Tucows and CNET, they have it there too.
Java

I need to generate classes from xml that doesn't provide a schema. I understand this is near useless, but the fact is we have xml, it's structured, and we should be able to create a model from the xml. In the past I've done it by hand, but the current xml documents I am working with are quite large and my time would probably be better spent building something that does what I need. But, I am guessing it has already been done, and I just can't find it.Any pointers?There are many tools available (a quick google search should fetch you some) that can generate XSD from XML assuming string type for almost everything. You should be able to use that XSD to run JAXB to get classes.Here's an  that lets you do that.And here is a screen cap:\nFrom your xml file, you can create a XML Schema Definition (XSD) file. Once you have the XSD, you'll be able to generate the code, need it be for java, C#, C++, or all of the above.If you have Visual Studio, you can use xsd.exe to generate the XSD file.References: XSD to Java:\nReference:XSD to C++:\nReferences:XSD to C#: \nReference:If the XML was created by JAXB, it can easily be converted back into objects. There's a  over at oracle which illustrates one way to do this. Spring framework offers similiar features using JAXB which are very conveniant. 
Java

I've stumbled upon a piece of code that has me wondering why it compiles successfully:What is interesting is that if I modify the signature of method  with  it doesn't work anymore.\nIf I move the generic type from the method to the class the code doesn't compile anymore:If you declare a type parameter at a method, you are allowing the caller to pick an actual type for it, as long as that actual type will fulfill the constraints. That type doesn\u2019t have to be an actual concrete type, it might be an abstract type, a type variable or an intersection type, in other, more colloquial words, a hypothetical type. So, , there could be a type extending  and implementing . We can\u2019t manually specify an intersection type for the invocation, but we can use a type variable to demonstrate the logic:Of course,  can\u2019t fulfill the expectation of returning such a type, but that\u2019s the problem of the definition (or implementation) of this method. You should get an \u201cunchecked\u201d warning when casting  to . The only possible correct implementation would be returning  here, which renders the method quite useless.The point, to repeat the initial statement, is that the  of a generic method chooses the actual types for the type parameters. In contrast, when you declare a generic  like withthe type parameter is part of the contract of the class, so whoever creates an instance will pick the actual types for that instance. The instance method  is part of that class and has to obey that contract. You can\u2019t pick the  you want; the actual type for  has been set and in Java, you usually can\u2019t even find out what  is.The key point of generic programming is to write code that works independently of what actual types have been chosen for the type parameters.But note that you can create , independent instance with whatever type you like and invoke the method, e.g.Here, the creator of the new instance picks the actual types for that instance. As said, that actual type doesn\u2019t need to be a concrete type.I'm guessing this is because  is an interface. If we ignore the fact that  is  for a second, you could, in theory, have a class that  (meaning you could assign it to ) but  (meaning it could be returned from ). Once you change the return type from an interface () to a concrete class () the compiler can deduce they aren't assignable from each other, and produces an error.This, of course, breaks down since  is, in fact, , and we could expect the compiler to take this into account. IMHO, it's a bug, although I must admit I'm no compiler-expert and there might be a good reason to ignore the  modifier at this point.I don't know why this compile. On the other hand, I can explain how you can fully leverage the compile-time checks. So,  is a generic method, it has one type parameter. If you specify this parameter, then the compiler will check that for you:The type parameters provide compile-time checking only. This is by design, java uses  for generic types. In order to make the compiler work for you, you have to specify those types in the code.The most common case is to specify the patterns for an object instance. I.e. for lists:Here we can see that  specifies the type for the list items. On the other hand, new  doesn't. It uses the  instead. I.e. the java compiler  the type based on the declaration.When you invoke a static method, then you have to specify the type in another way. Sometimes you can specify it as a parameter:The you can use it like this:Or like this:Say for instance, this is how you can create a type-safe empty list:The type parameter  is passed to the method . The only constraint is that you have to specify the class too. I.e. you cannot do this:If none of these tricks can help you, then you can specify a . I.e. you provide a class as a parameter. A common example is the :
Java

I'm looking for a way of getting an SHA-1 checksum with a Java byte array as the message.Should I use a third party tool or is there something built in to the JVM that can help?What about:This a snippet of code we use to convert to SHA-1 but takes a  instead of a  see this  for further info    You can do it yourself or you can rely on libraries that have been proven to work like . The  class has several methods to calculate hashes..From CommonCodec DigestUtils Implementation the Hex coversion after the Digest calculation as shown before :should be  : ...another option is to use Spring:read more HTHI Just used this to compute the hash sum inside of a dex file and compare it with the value which is saved in the dex file.i know this code hasnt very good style but its more PoC and only needed for some research which isnt time critical. may someone can use it!How about Using This: public class sha1Calculate {
Java

I like constructor-based injection as it allows me to make injected fields . I also like annotation driven injection as it simplifies my . I can mark my constructor with  and everything works fine, as long as I don't have two parameters of the same type. For example, I have a class:and an application context with:There should be a way to specify the bean ID on the constructor of the class , but I can't find it in the documentation.  Is it possible, or am I dreaming of a solution that does not exist yet?Following , I modified my class to be:and it works. is by-type (in this case); use  to autowire by-name, following the example :(below that text is the full example)
Java

I tried the following code with Spring 3.x which failed with  and it should according to the answers of a question which I asked before -   Since I was trying this with Java 6, I found the following code works fine:but I don't understand how it resolves the cyclic dependency.EDIT:\nHere's the error message. The OP mentioned it in a comment on one of the answers: will be officially supported in Spring Framework 4.3. The implementation can be seen in this .The definitive reason that you cannot autowire yourself is that the implementation of Spring's  method explicitly excludes the possibility. This is visible in the following code excerpt from this method:FYI: the name of the bean (i.e., the bean that's trying to autowire itself) is . That bean is in fact an autowire candidate, but the above if-condition returns false (since  in fact equals the ). Thus you simply cannot autowire a bean with itself (at least not as of Spring 3.1 M1).Now as for whether or not this is intended behavior semantically speaking, that's another question. ;)I'll ask Juergen and see what he has to say.Regards,Sam (Core Spring Committer)p.s. I've opened a Spring JIRA issue to consider supporting self-autowiring by type using @Autowired. Feel free to watch or vote for this issue here: This code works too:I don't know why, but it seems that Spring can get the bean from ApplicationContext if is , but not . @Autowired works before initialization and it cannot find the same bean. So, @Resource maybe works after @Autowired and before @PostConstruct.But I don't know, just speculating. Anyway, good question.By the way, the more elegant solution to the self-invocation problem is to use AspectJ Load-Time Weaving for your transactional proxies (or whatever AOP-introduced proxy you're using).For example, with annotation-driven transaction management, you can use the \"aspectj\" mode as follows:Note that the default mode is \"proxy\" (i.e., JDK dynamic proxies).Regards,Sam question suggests alternative hacky approach with  that may be suitable for special cases.It looks like spring creates and configures an object and then places it in the bean look up context. But, in the case of Java, I think it creates the object and ties it to the name and the during configuration when the object is looked up by the name it is found in the context. Given above code I don't see a cyclic dependency.\nYou injecting some instance of Service into UserService.\nThe implementation of the injected Service does not necessarily need to be another UserService so there is no cyclic dependency.I do not see why you would inject a UserService into UserService but I'm hoping this is a theoretic try out or such.Use  annotation:Why not use 'this' instead of injecting the same object into itself?
Java

Should we have a team coding standard that the names of abstract classes have prefix  ? e.g.Yes, in fact if you look at the javadocs of the standard library at  you'll find that the list of classes in the bottom-left frame begins with abstract classes using the naming convention you have mentioned in your question.Take any one of them, say the first one, and check its definition: . It indeed implements  which is again similar to your convention. It's subclasses are named like: , , etc.Generally any kind of standard is a good thing in a team setting.\nOtherwise team members might name classes in such a way that only they understand and then you could get a mix of people's different coding styles which leads to confusion.For Readability it does sound like a good idea. When reading code you will be able to know right away what the class is. As long as everyone follows the standard it is good.Modern IDEs will pop up descriptive text when you hover over an object.  Prefixing is redundant in this case.I won't say yay or nay in an answer, but whatever you choose, use a good  to ensure it.As with most questions of this type: \"it depends\".  I like consistency and clarity, so if it works for you and your shop, great.  However, if you have legacy Abstract classes, you would then want to go back and refactor them to the same naming convention.
Java

I am trying to deserialize an instance of this class using Jackson 1.9.10:When I try this I get the followingIs there a way to deserialize a class with overloaded constructors using Jackson?ThanksThough its not properly documented, you can only have one creator per type. You can have as many constructors as you want in your type, but only one of them should have a  annotation on it.This still hold true for Jackson databind 2.7.0.The Jackson  or  grammar () let believe indeed that one can  multiple constructors.Looking at the code where the  are identified, it looks like the Jackson  is ignoring  because it only .That means that code like that But this code will work : .The documentation is vague about how object creation works; from what I gather from the code though, it's that it is possible to mix different methods :For example one can have a static factory method annotated with It works but it is not ideal. In the end it could make sense, e.g. if the json is that  then maybe one should look to use a delegate constructor to handle payload variations much more elegantly than with multiple annotated constructors.Also note that Jackson , for example in this code : This time Jackson won't raise an error, but Jackson will only use the  constructor , that means the  is never used.
Java

How do I add a Java library from its GitHub repo (the library uses Maven as a build system) as a dependency to my Maven project? Can I do that without downloading and compiling the library?Now you can import a Java library from a GitHub repo using .\nIn your pom.xml:It works because JitPack will check out the code and build it. So you'll end up downloading the jar.\nIf the project doesn't have a GitHub release then its possible to use a commit id as the version.At the moment there is no way you can do this unless the maintainer of the library provided a way to do this.So on the title page of the library the should be an instruction containing the repository address like:And a dependency name:This means that all artifact of your project including your dependency will be searched in this repo.You could also have a glance at  to check if there was an effort made to deploy artifacts to a remote repo. Typically the keywords are  or  like in this case.FYI, here is a way to provide a repo for your gihub artifact: .
Java

How is the compiler not complaining when I write the following code?Even though it is an instance of the same class in which  is written, shouldn't it give a compilation error at ? After all, I am trying to access a private variable directly.\nThe code even runs fine.A private member is accessible from any method within the class in which it is declared, regardless of whether that method accesses its own () instance's private member or some other instance's private member.This is stated in :This feature of Java allows you to write methods that accept an instance of the class as an argument (for example - , ) without relying on the class having non private getters for all the private properties that need to be accessed.Private fields are private to the class as a whole, not just to the object.Other classes do not know that MyClass has a field called count; however, A MyClass object knows that another MyClass object has the count field.Accessors are not security!  They are encapsulation, to keep others from having to know about the code.Consider if someone wrote a , but disappeared once he quashed the last bug -- understanding the code causes one to be either deleted from the universe or to go mad.Despite this minor drawback, if properly encapsulated, this should become your prefered sorting algorithm, as all fields and methods except Sort should be private.You don't know how it works, and you don't want to know how it works, but it works and that's enough.  If on the other hand, everything is public, and you have to understand how it does what it does to use it correctly -- that's just to much bother, I'll stick with quicksort.. It will never throw a compilation error.This is much similar to what a simple getter and setter does or a copy constructor does. Remember we can access  members using Your  method accepts an instance of MyClass. Since  is a method inside , it will have access to  properties.Methods defined inside the class will always have access to it's  members, through  and instance variable.But if you define  outside of  then, you won't have access to  members. There you will have to use a method or a setter or a getter.Methods, Variables and Constructors that are declared private can only be accessed within the declared class itself. Check the 
Java

I am developing a Spring Boot application with a Rest interface and a dart fronted. The XMLHttpRequest does execute a OPTIONS request which is handled totally correct. After this, the final GET (\"/products\") request is issued and fails:After some debugging I have found the following:\nThe AbstractHandlerMapping.corsConfiguration is populated for all Subclasses except RepositoryRestHandlerMapping. In the RepositoryRestHandlerMapping no corsConfiguration is present / set at creation time and so it won't get recognized as cors path / resource.\n=> No CORS headers attached\nCould that be the problem? How can I set it?  Configuration classes:I even tried to set the Cors per annotation:Raw request headers:Raw response headers:Versions used:\nSpring Boot 1.3.0.M2\nSpring 4.2.0.RC2What do I miss?Indeed, when using Spring Data REST + Spring Framework 4.2, only  instances created by Spring MVC  and controllers annotated with  will be CORS aware.Spring Data REST still compiles against Spring Framework 4.1, and does not support builtin Spring Framework CORS implementation. Feel free to vote for the  related issue.Right now, I think the best solution is to use a filter based approach. You could obviously use Tomcat, Jetty or , but be aware that Spring Framework 4.2 also provides a  that use the same CORS processing logic that  and  approaches. By passing an  instance to the  constructor parameter, you could easily get something as powerful as Spring native CORS global support.If you are using Spring Boot (which supports  beans), it could be something like:The Spring Data team is currently looking into ways to let the user customize the CORS handling on it (i.e. calling  on the  instance Spring Data REST deploys), but I think it is better to use the  approach until  is resolved.Hendy's addition: In my case, the simple  definition above does not work, I had to use this: (It  have something to do with my usage of Spring Security or , but Sebastien is more expert in this.. I don't really know why)Since , the support of CORS in Spring Data is on now. There are two ways to deal with:
Java

Can Java properties file reference other properties file?Is this possible?This is what you want, it is a bit old , but may work for your needs.  which provides variable substitution along with a few other features - although substitution may arguably be the most useful.  It is a subclass of java.util.Properties, and will can be used by any other class that may take configuration information as Properties.Standard properties files are just key-value pairs. In the text format,  just separates key from value and does some simple things such as allowing escaped characters. You might be able to define entities in the verbose XML syntax.If you want your own substitution syntax, then you can manipulate a returned value as you would with any other string. Alternatively, you could write your own version of  or do the substitution when generating the file.The java.util.Properties class won't do this for you.  It wouldn't be too difficult to subclass Properties, override the load() method and do the substitution yourself. The Commons Config lib can also do this. However, as pointed out already, have a look at the EProperties library;  It supports a number of neat features (like substitution, nesting, lists) including inclusion, extends Java Properties and is a little more light weight than Commons Config (which also allows you to include properties using the include syntax). Since eproperties is sort of not maintained and commons configuration has a dependency on logging (which ironically means you can't use it to configure logging) I use this code snippet which only requires  to load interpolated properties:::Obviously you can convert the  back to a  object if you need it. I resolve based on previously declared properties and system properties but you could obviously adjust that in the .In this particular case (and in  too), you'd better resolve the duplication by defining different properties:Do the same for the other projects.Below is a code snippet in Java for reading properties that reference other properties. Specifically, these are are reusable queries but can be other stuff as well.Example properties:After running this,  will have the value .* Using apache's .
Java

I have a generic  and am trying to work out how I can sort the items contained within it. I've tried a few things but I can't get any of them working.Collections by themselves do not have a predefined order, therefore you must convert them to\na .  Then you can use one form of A  does not have an ordering, so wanting to sort it does not make sense. You can sort  instances and arrays, and the methods to do that are  and If your collections object is a list, I would use the sort method, as proposed in the other answers.However, if it is not a list, and you don't really care about what type of Collection object is returned, I think it is faster to create a TreeSet instead of a List:You have two basic options provided by :Depending on what the  is, you can also look at  or .You can't if T is all you get.  You have to have the it injected by the provider via:or pass in the Comparator via the Collections.sort(...) methodHere is an example. (I am using  class from Apache for convenience, although this can be done without using it.)If you have a specific code that you are working on and are having issues, you can post your pseudo code and we can try to help you out!
Java

I need to cut out an image in the shape of the text in another image. I think it's best shown in images.This is a photo of a cat:and this is the text I wish to cut out:The resulting image would be this:The text image will always be black with a transparent background, and the resulting cut-out should too have a transparent background. Both input images will also be the same size.Create a new BufferedImage and iterate over all the pixels of word cat and if they are black, copy the cat-image pixels to the new image.Here is some code: ()Use . Use  classYou can get outline  from glyph vector by public abstract Shape Assign the outline  as a clip to your  instance.Draw the image on the graphics.Only clipped shape will be filled.No java here, but the needed image operations are easy to understand. In Mathematica:  You can do it in Java with just a few lines of source code, using First, make the black portion of the \"Cat\" image transparent.  See  for help with this.  Then,  that image over the picture of your favorite cat (mine is Sheeba).  The nice thing about this is you can make the transparent text image once, save it, and then apply it to all of Sheeba's family and friends!  
Java

The following code:causes:  Can someone explain me what is meant by \"further generic type information will be erased at runtime\" and how to fix this?It means that if you have anything that is parameterized, e.g. , the Generics information will be erased at runtime. Instead, this is what the JVM will see .This is called . The JVM has no parameterized type information of the  (in the example) during runtime.A fix? Since the JVM has no information of the Parameterized type on runtime, there's no way you can do an  of . You can \"store\" the parameterized type explicitly and do a comparison there.You could always do this insteadDue to type erasure, the parameterized type of the  won't be known at runtime. The best you can do with  is to check whether  is an  (of anything). To do this in a generics-friendly way, use: This is sufficient: In fact,  checks whether the left operand is  or not and returns  if it is actually .\nSo: no need to catch .You can't fix that. The type information for Generics is not available at runtime and you won't have access to it. You can only check the content of the array.instanceof operator works at runtime. But java does not carry the parametrized type info at runtime. They are erased at compile time. Hence the error. You could always do thisCreate a classIs not the same but ...You can use
Java

Every single view in my Spring 3 app has a set of attributes they can rely on.  So the first line of every controller is something like:In there I'll addThis all allows each view to display the logged in user's name, easily reference an image location, a list of languages and some overall stats about the site.So the question is, is the controller model object the best place to store all the data or is there a more convenient place which makes it just as easy for views to access this info?And secondly, I'd REALLY love not to have to have the  line above as the first line in every controller.  It's actually not always the first line, sometimes I first check if I need to redirect in that controller, because I don't want to waste resources filling the model for no reason.  Maybe a filter or annotation or some Spring callback mechanism could make sure the  code is called  the controller is finished but right  the view is rendered, skipping this if a redirect was returned?You could write an . (or its convenience subclass )@See: It has the method:This method is invoked after the controller is done and before the view is rendered. So you can use it, to add some properties to the An example:webmvc-config.xmlYou can also use @ModelAttribute on methods e.g.This will add it for all request mappings in a controller. If you put this in a super class then it could be available to all controllers that extend it.You could use a Controller Class annotated with @ControllerAdvice\"@ControllerAdvice was introduced in 3.2 for @ExceptionHandler, @ModelAttribute, and @InitBinder methods shared across all or a subset of controllers.\"for some info about it have a look at this part of the video recorded during SpringOne2GX 2014\nThere is one issue that occurs with redirection when using @ModelAttribute or HandlerInterceptor approach. Another way to handle this situation is to create session-scoped bean, that can be autowired in base application controller, or explicitelly in every controller where access is needed.Details about available scopes and usage can be found .if you need add some global variables that every view can resolve these variables\uff0c\nwhy not define into a properties or map\uff1f\nthen use spring DI\uff0c refer to the view resolver bean.\nit is very useful,such as static veriable, e.g. resUrl
Java

Is there a way to retrieve the auto generated key from a DB query when using a java query with prepared statements. For example, I know AutoGeneratedKeys can work as follows. However. What if I want to do an insert with a prepared Statement. Is there a way to do this that I don't know about. It seems from the javadoc that PreparedStatements can't return the Auto Generated ID.Yes. See . Section 7.1.9. Change your code to:There's a couple of ways, and it seems different jdbc drivers handles things a bit different, or not at all in some cases(some will only give you autogenerated primary keys, not other columns) but the basic forms areOr use this form:Yes, There is a way. I just found this hiding in the java doc. They way is to pass the AutoGeneratedKeys id as followsI'm one of those that surfed through a few threads looking for solution of this issue ... and finally get it to work. FOR THOSE USING jdbc:oracle:thin: with ojdbc6.jar PLEASE TAKE NOTE:\nYou can use either methods:\n(Method 1)(Method 2)Basically, try not used Method1 if you just want the value of SEQ.Nextval, b'cse it just return the RowID ref that you may cracked your head finding way to make use of it, which also don fit all data type you tried casting it to! This may works fine (return actual val) in MySQL, DB2 but not in Oracle.AND, turn off your SQL Developer, Toad or any client which use the same login session to do INSERT when you're debugging. It MAY not affect you every time (debugging call) ... until you find your apps freeze without exception for some time. Yes ... halt without exception!
Java

How to make moving money from one account to another atomic? For:I expect that pseudo-code:update accounts safely in multithreading environment, I see danger case as:Easiest solution is to make blocking on shared object, but it will be inefficient for cases like:I expect that independent moves performed in parallel, dependent in sequence. Seems that suggested solution:lead to deadlock as 2 locks acquired sequentially...  If  and  and  I expect consistency:  has  value, not  or  if you get intermediate account value during simultaneous execution. 1000-10000 - so lock on shared object isn't efficient.A simple solution could be to use a lock per account, but to avoid deadlock you have to acquire locks in the same order always. So, you could have a final account ID, and acquire the lock of the account with a less id first:One way to do this is to have a transaction log. Before moving the money, you'll need to write to the transaction log of each account what you intend to do. The log should contain: the amount of money that's taken in/out of the account, and an lock which is shared between the log pair.Initially the lock should be in a blocked state. You created the log pair, one with amount of X and the other with amount of -X, and both shares a lock. Then deliver the log entry to the inbox of the respective accounts, the account from which money is taken out should reserve that amount. Once you've confirmed that they're delivered safely, then release the lock. The moment the lock is released you're at a point if no return. The accounts then should resolve themselves.If either of the party want to fail the transaction at any time before the lock is released, then simply remove the logs and return the reserved amount to the main balance.This approach may be a bit heavy, but it would also work in a distributed scenario where the accounts actually are in different machines, and the inboxes actually would have to be persisted, to ensure money never get lost if any of the machine crashes/goes offline unexpectedly. Its general technique is called two phase locking.I would propose to create a method Account.withdraw(amount) which throws an exception if it doesn't have sufficient funds. This method needs to be synchronized on the account itself.Edit:There also needs to be a Account.deposit(amount) method which is synchronized on the receiving account instance.Basically this will result in a lock of the first account while withdrawing and then another lock on the receiving account while depositing. So two locks but not at the same time. Assumes that withdraw/deposit are synchronized and return boolean success status rather than throw exception.You can create an extra   that exists solely for transferring the money. So if you want to transfer from  to  you actually transfer from  to  and then from  to . For each of these transfers you only lock either  or  depending on which account is participating in the transfer. Since you are using the same type for transfers, you end up with little extra code and therefore low maintenance costs.To reduce the number of extra accounts you could hold them in a pool. If you have a thread pool that is processing transfers, than you can assign each thread it's own extra account. Therefore you don't need to request and release those extra accounts from/to a pool too often.One approach is to use kind of \"striped lock\" with lock/unlock methods operating on several locks. Accounts are mapped to locks using , the more locks you allocate, the more parallelism you get.Here's code sample:Don't use built-in synchronization, use a Lock object. Use tryLock() to get an exclusive lock on both accounts at the same time. If either one fails, then release both locks and wait a random amount of time and try again.As you have mentioned there will be 1000-10000 concurrent transaction you expecting at a time than you can store accounts on which some transaction is going on and handle concurrencyOne Solution is to allow system to create only one object of particulate account id, means that if you want to make a transaction between account \"123\" and \"456\" than your thread will create account object and in that constructor of account class we will check if any other object of account is there with particulate account id, if other object of account is there with same account id means that some transaction is going on with particulate account id so you have to wait to get the account object.So we can do transaction between \"123\" and \"456\" and at same time we can do transaction between \"abc\" and \"xyz\" but if at same time some other thread will try to create object of account \"123\" than system will say please wait for reference you can see below code Please note :As stated previously, you should lock on both accounts, always in the same order. The key part, however, is ensuring both high granularity and singularity across the VM instance. This can be done using :An approach which will remain robust even if threads may get arbitrarily waylaid is to have each account maintain a list of transactions requested or posted against it.  To request a transfer from one account to another, create a transaction object defining the request and add it to the request queue for the source account.  If that account can perform the transaction, it should move it to its list of posted transactions and add it to the request queue for the destination.  Using  it's possible to ensure that from the moment the transaction is placed into the queue for the first account, the state of the system will always thereafter either have the transaction pending, completed, or aborted, and even if some or all threads were to get waylaid, examining the transaction lists would make it possible to determine what money belonged where.By contrast, when using locks, events which unexpectedly delay one thread can arbitrarily impede the execution of many others, and if a thread gets killed off while holding a lock it may be impossible to determine what exactly it had or had not done prior to that.Thanks all for interest to question.I found several solutions in As one link answer was removed here essential piece of code that help anyone when cert.org fall. Pieces are long so I didn't include any pros/cons.:::
Java

Here is an image of my default JDK (which is 1.6) and the JDK I want to set as default (which is 1.7)If I remember correctly, you'll need to set the  property in your netbeans config file. Should be in your  file.
Java

I'm wondering if there is any ideomatic way to chain multiple InputStreams into one continual InputStream in Java (or Scala).What I need it for is to parse flat files that I load over the network from an FTP-Server. What I want to do is to take file[1..N], open up streams and then combine them into one stream. So when file1 comes to an end, I want to start reading from file2 and so on, until I reach the end of fileN. I need to read these files in a specific order, data comes from a legacy system that produces files in barches so data in one depends on data in another file, but I would like to handle them as one continual stream to simplify my domain logic interface. I searched around and found PipedInputStream, but I'm not positive that is what I need. An example would be helpful.It's right there in JDK! Quoting :You want to concatenate arbitrary number of s while  accepts only two. But since  is also an  you can apply it recursively (nest them):...you get the idea.This is done using SequencedInputStream, which is straightforward in Java, as Tomasz Nurkiewicz's answer shows.  I had to do this repeatedly in a project recently, so I added some Scala-y goodness via the \"pimp my library\" pattern.With that, I can do stream sequencing as followsor evenAnother solution: first create a list of input stream and then create the sequence of input streams:Here is a more elegant solution using Vector, this is for Android specifically but use vector for any Java
Java

Short of parsing the output of , does anyone have a 100% pure java way of doing this?This is pretty easy:Some of this will only work in JDK 1.6 and above (one of the methods was added in that release.)Prior to 1.6, it's a bit more difficult - isUp() isn't supported until then.FWIW: The  note that this is the correct approach for getting all of the IP addresses for a node:This code only works in Java 1.6 because of the added InterfaceAddress code.The \"toMACAddrString\" method looks like this:and the \"toIPAddrString\" method is here:I have that first set of code in the try/catch above in a method called dump() in class called IPConfig.  Then I just put a main method in IPConfig to call new IPConfig().dump() so that when I'm trying to figure out some wacky network problem, I can see Java thinks is going on.  I figured out that my Fedora box reports different information than Windows for the LocalHost information and it was causing my Java programs some issues.I realize its similiar to the other answers but it prints out nearly everything interesting that you can get from the interface and ipaddress apis.As highlighted by Sam Skuce comment:
Java

Am torn between wicket and vaadin. i am starting a micro-isv and need to make a choice of web framework. I have narrowed down my choices to wicket and vaadin. I have used both frameworks and i love them both. however i need to make a choice. If i choose vaadin:If i go the wicket way:\nI will have to style my applications and i can hardly give them a desktop look and feel. Any advice. anyone with experience on either framework kindly tell me the cons and pros and how you made your decision. I think I've invested some time for both frameworks. I really like both because they bring the Swing-alike coding to web development. And I don't know easier ones for me (although there is click but I don't like the velocity templating thing)And yes, there are differences.true, but every serious company will style its app differently (unless you are prototyping)Then Vaadin would be 'better'.What are the advantages of that? (BTW: you could code declarative in groovy ;-)) But ok. I know what you mean: if you can effort a separate designers than wicket is 'better'.Why not? Or what do you mean here? Wicket supports ajax and there are components which supports nice 'desktop-alike' things (ajaxlink, lazycomponent, autocompletion, progressbar, see wicket stuff + extensions). ok, for any more complex component you'll have to code in javascript BUT BTW did you know that you could even Some minor experiences:Vaadin is surely faster while coding (no css, html stuff). But if you go production keep in mind that the ease of programming can come to the cost of performance on the client side: e.g. if you use the 'wrong' layouts such as Horizontal/VerticalLayout, ... the massive use of javascript could slow down old browser.But Vaadin is not slow! Use appropriate layouts such as CssLayout or FastLayout and also old browser can serve it. (Although if you would use CssLayout your coding-style is really wicket-alike.)One issue with Vaadin is that it is a bit harder to profile, because you don't see easily where the client needs all the CPU and the nested divs gets cryptic id-names.One great thing about Wicket is its (Guice can be integrated in Vaadin and Wicket)Testing the UI should be easy with Vaadin (although I didn't found unit testing stuff) and is very easy .Last but not least creating lists/tables is VERY easy in Vaadin compared to wicket.I've worked extensively with Wicket but I've not had any experience with Vaadin so this might be (a little) biased.I'd recommend Wicket for obvious reasons, but what's probably of interest to you is Wickets openness. As Gweebz rightly pointed out, Wicket uses basic HTML markup as its foundation, so any structural or cosmetic changes are often trivial to implement. Personally one of the things I really enjoy about out wicket work is the flow between front end presentation and the data backend, we've implemented Spring & JPA/Hibernate which means that any changes in the front end can be translated back into the data base with a single line of code thanks to Wickets model based architecture.Again I can't say much for Vaadin having never worked with it, but if you're looking for architectures to start off with, I'd also recommend you have a look at GWT.(continued from the comment in the first Wicket-related answer)The major difference between Vaadin and Wicket is with how UI composition and client side code is written. With Vaadin you usually compose your UI without any templates or HTML at all and you get a sleek, fully Ajax'ed UI out of the box. However, if you prefer the templating approach just use CustomLayout which does exactly that.Client side coding is rarely needed, but when it is you do it with the Java-based GWT which is IMO a lot more nicer than writing Javascript by hand. Besides, with GWT you automatically get cross-browser compliant solution instead of having to deal with those issues yourself.When comparing frameworks you also should take a look at community activity and documentation. With Vaadin both of those are excellent. Also note the Vaadin Directory which currently contains 100+ very useful UI components and other addons.I have a limited amount of experience with each but I prefer Vaadin. It allowed a richer experience with the web application I was developing. The main benefit that sold us though was how easy it was to write unit tests around our UI classes, ensuring the components functioned correctly when interacted with in the expected ways. This is also possible with Wicket however it was more difficult in my experience.I will also mention that either framework will require some styling. Wicket starts off as plain old HTML and Vaadin starts off with a MacOSX-like theme by default but almost any web-app you write will require at least SOME customization. With this in mind, customizing the CSS of a Wicket app is SIGNIFICANTLY easier than Vaadin for the simple reason that you control the markup. Vaadin hides the markup from you and generates elements with weird IDs and structures so it is harder to customize the look. Just remember this when making your decision.Also do notice that even though Vaadin base framework is free, for some additional functionality you might need to  extensions.Ex - If you need to integrate a good charting solution such as Highcharts, you'd have to pay and buy the vaadin charts extension (even though highcharts is available free for FOSS apps, the vaadin charts plugin built on that is not given free for FOSS apps).I am currently working with Wicket and I have worked in the pass with Vaadin. I wil be short in my observations:Appart from that, we are talking about two different types of frameworks, two different approach, which have pros and cons that I advice you to search and compare and see what really fits your needs.Edit: Oh, and about the look and feel, for instance you always have 
Java

Based on my understanding of the Java language, static variables can be initialized in .However, when I try to implement this in practice ( variables that are  too), I get the error shown in the screenshot below.Screenshot can be directly accessed at  (in case the image below is unreadably small).Yes of course:  variables can be initialized in a static block .... you have implicit GOTOs in that example ( is essentially a ).If an exception is thrown your  variables will not be initialized.Note that the use of static constructs goes against Object-Oriented dogma. It may complicate your testing and make debugging more difficult.You can do this but you need to exit the static block by throwing an exception - you can rethrow the exception that was caught or a new one. Generally this exception must be a . You really should not catch a generic  but more specific exception(s) that might be thrown from within your  block. Finally, if a static initializer throws an exception then it will render the class unusable during that specific run because the JVM will only attempt to initialize your class once. Subsequent attempts to use this class will result in another exception, such as .So, to work, your initializer should read something like this:Assuming that  is a custom , but you could use an existing one.Assuming no where upstream is in a position to catch either an  or a general  then the program should not ever try to use .  If however those are caught and the program doesn't end, then you need to code to watch for and handle  being null (or be happy with NullPointerExceptions coming out all over).I'm not sure there is a good way to handle this.Can you put the declaration in the finally block?
Java

I've been searching all over for a consistent and clear explanation of what 'self time' actually refers to in the VisualVM context and how does it differ to 'self time (cpu)'. Also does 'self time [%]' refer to self time or self time cpu. There doesn't appear to be much documentation on this or at least I haven't found it. So any thoughts/input will be appreciated.'self time' is a 'wall-clock' time spent in method itself (without time in methods invoked from that method). 'self time (cpu)' is a time processor time, so it does not include time spent waiting, sleeping, etc. Both 'self-time' and 'self (cpu) time' in sampler are approximation of actual data. 'self time[%]' refer to 'self time'. 
Java

I'm using Mockito to write a unit test in Java, and I'd like to verify that a certain method is the  called on an object.I'm doing something like this in the code under test:In my mock, I don't care about the order in which I edit everything on the row, but it's very important that I  try to do anything more to it after I've saved it. Is there a good way to do this? Note that I'm not looking for verifyNoMoreInteractions: it doesn't confirm that saveToDatabase is the last thing called, and it also fails if I call anything on the row that I don't explicitly verify. I'd like to be able to say something like:If it helps, I'm switching to Mockito from a JMock test that did this:I think it requires more custom work.and then Previous Answer:You are right. verifyNoMoreInteractions is what you need.Not 100% on topic but I was just looking to find the opposite of verify, and this was the only relevant result, it ends up I was after Mockito.verifyZeroInteractions(mock);Just incase anyone else ends up here looking for this...This question led me to make some enhancements to the  API in  (available in the upcoming release 0.983).The solution I came up with allows you to write (in a test method):... if you only want to verify that a certain method is called after everything else. To verify it happens  all other invocations, simply move the call to the top. This actually applies to any sequence of consecutive invocations.If in addition to the above verification, you also want to verify that some other methods are called in any order, a second  block can be added to the test (before or after the other block, it doesn't matter):Although a bit long because of the use of anonymous inner classes, this syntax is both simple and flexible; notice how it adds structure to the test and avoids the repetition of method calls (like ). There is more to it than I described here (Hamcrest matchers, invocation counts, etc.), and it's not limited to the verification of instance methods (static methods and constructors can be mocked and verified in the same way).
Java

Which of the following collection types do you use in your JPA domain model and why:I was wondering whether there are some ground rules for this. I know the difference between a  and a . A  allows duplicates and has an order and a  cannot contain duplicate elements and does not define order. I'm asking this question in the context of JPA. If you strictly follow the definition, then you should always end up using the  type, since your collection is stored in relational database, where you can't have duplicates and where you have define an order by yourself, i.e. the order in you Java  is not necessarily preserved in the DB.For example, most of the time I'm using the  type, not because it has an order or allows duplicates (which I can't have anyway), because some of the components in my component library require a list.Like your own question suggests, . JPA is just a framework which you can (and should) use in a way which best fits your problem. Choosing a suboptimal solution because of framework (or its limits) is usually a warning bell.When I need a set and never care about order, I use a . When for some reason order is important (ordered list, ordering by date, etc.), then a .You seem to be well aware of the difference between , , and . The only reason to use one vs. the other depends only on your needs. You can  (which may be subtle or implicit).  This is follows the exact same rules as using different collection types anywhere else throughout your code. You could use  or  for all your references, yet in most cases you use more concrete types.For example, when I see a , I know it comes sorted in some way, and that duplicates are either acceptable or irrelevant for this case. When I see a , I usually expect it to have no duplicates and no specific order (unless it's a ). When I see a , I don't expect anything more from it than to contain some entities.Regarding list ordering... Yes, it can be preserved. And even if it's not and you just use , it still can be useful. Think about the example of event log sorted by timestamp by default. Artificially reordering the list makes little sense, but still it can be useful that it comes sorted by default.The question of using a Set or a List is much more difficult I think. At least when you use  as JPA implementation. If you use a List in hibernate, it automatically switch to the  paradigm, where duplicates CAN exist. And that decision has significant influence on the queries hibernate executes. Here a little example:There are two entities,  and , a typical many-to-many relation. for mapping those entities to each other, a JoinTable (lets call it \"employeeCompany\") exist.You choose the  on both entities (Company/Employee)So if you now decide to  Employee  from , hibernate executes the following queries:And now the question: why the hell does hibernate not only execute that query?The answer is simple (and thx a lot to Nirav Assar for his blogpost): . In a world of bags, delete all & re-insert all remaining is the only proper way! Read that for more clarification. Now the big conclusion: And why that? Because hibernate is no longer in a world of bags (as you know, Sets allows no duplicates) and executing only one query is now possible.So the decision between List and Sets is not that simple, at least when it comes to queries & performance!I generally use a List.  I find the List API far more useful and compatible with other libraries than Set.  List is easier to iterate and generally more efficient for most operations and memory.The fact that a relationship cannot have duplicates and is not normally ordered should not require usage of a Set, you can use whatever Collection type is most useful to your application.It depends on your model though, if it is something you are going to do a lot of contains checks on, then a Set would be more efficient.You can order a relationship in JPA, either using an @OrderBy or an @OrderColumn.See,\nDuplicates are not generally supported in JPA, but some mappings such as ElementCollections may support duplicates.I use:I think using Collection as the generic default when generating entities with Netbeans is a good starting point, then when you figure out what your model actually is and need more functionality you can easily change it and stay backwards compatible.
Java

I am studying the source of the OpenJDK.My attention was attracted by the methods  and :Why do the methods  and  have different implementations?The implementation of  does not use subtraction, as this could cause an overflow in case you're comparing an integer that is close to  with another that is close to .This overflow cannot happen in case of , as there the byte values are implicitely converted to integers before  is calculated.(see also: )The Byte method can be implemented this way, becasue the result of the subtraction is representable in . This is not so in the other case. For example:and this is negative, hence the comparision would wrongly indicate that 0 is smaller than -2^31
Java

Usually, during software development, there are all sorts of utility functions I need. Like zipped file, extract zip file, launching Web Browser, get scaled image...What I did is, I place all this utility functions as static function within a single class named \"Utils\"Is it a good practice? Will things grow unmanageable when the number of functions grow larger and larger?Its absolutely a best practice! you don't want to mix all those utility functions with the rest of your application business logic. However, as your utils files and/or classes grow it is recommended to group them according to the function they provide.For example, in a web application you could end up with a package structure like this.Yes, utility classes are a good idea but, as with all object-oriented programming, you should be aiming for maximum cohesion, minimal coupling.Maximum cohesion means that everything in a single class should be heavily related  Minimal coupling means there should be no unnecessary dependencies  classes.In other words, lumping together compression with image manipulation or the launching of external processes in a single class is a bad idea. By all means have a compression utility class and an image manipulation utility class but  put them together.Doing so is akin to using the singleton pattern as a god object, a ghetto where you just dump all your rubbish that should be better organised. I would say it's okay to use an uber-utility class during development but make sure your code is better organised before shipping. Maintenance will be a lot easier.No, not in the long term although it's useful when done temporarily.Yes, no question about it.No, I don't think utilities classes are a good practice. Psycologically, the word 'Utilities' is just too broad and even if you split it into multiple classes *Util will just become a dumping ground for things that are 'too difficult' to fit into a proper class design.For an example take a pseudo-ficticious StringUtils class. You could have hundreds of methods for encoding/decoding for different schemes, case transformations, handling whitespace, etc. A better approach, I think, is to use the strategy pattern to handle these transformations, which potentially would even allow for the possibilty of client code introducing new transforms without needing to edit/recompile the original code. You get a more powerful, more flexible and more maintainable system.If it's at least , then it makes sense in a  class. That's easy! Cohesion and coupling are meant to make your life , this is a clear situation in which they wouldn't, so I would suggest to just keep it up your way.In  most cases, I use this way.Don't kill your productivity by strictly following those rules, you can see many great frameworks out there break them.Actually, the concept of  and  classes comes from the inability to write free functions in environments where every function need be owned by a class (either because of language or project restrictions). The  class with nothing but static functions ends up acting the role of a package with free functions.   Because it is a recurring phenomenon in many software projects, I'd consider it somewhat of an idiom to OOP designs, and therefore a Good Practice because people relate to it. As other replies point out, a beneficial enhancement would be to factor out your  classes to some separate project to facilitate reuse and maintenance.I agree with Mike's comment. I use C#, but similar implementation. I have a util project that I maintain secretly and then just drop the DLL in the new project. That way as bugs/changes occur I can update projects simply by replacing DLL. I do keep a separate class for different areas of the application as Mike suggested in his comment.A util class (or package of classes) is very useful. \nI generally tend to separate my utils by functionality into classes, so I may have FileUtils, DatabaseUtils, etc.I would highly suggest, however, maintaining your utils in a separate jar or project (very easy with Eclipse). If you end up having multiple projects that use the same utilities, it is a good idea to avoid code replication. Having a project or jar to include is priceless. My practice is to have both  clases and  classes. The former contains reusable static functions (for the case of Java and PHP) that are application-unrelated, where the latter are reusable application/domain logics - non static methods and usually with dependencies to other services/beans/managers.These are a few rules that I apply before I create a method or a  class:Utility classes usually tend to produce procedure style code. The go against pure OO conventions. However, they simplify your life so use them. But have each one do it's own thing otherwise you will end up with a God class that will become a catch all for methods that don't quite seem to fit the object they should reside on. Breaking up the utilities is a good approach. In general you want to avoid turning your classes into blobs.
Java

I'm trying to simply add TimeZone information back into a LocalDate before performing some more calculations. The LocalDate came from using the ObjectLab LocalDateCalculator to add days to an existing DateTime but the method needs to return a modified ReadableInstant to form an Interval which I can then inspect.The code I'm trying amounts to a conversion of Joda LocalDate to Joda DateTime:The error I get is from Joda's conversion system:I'm looking for a fix to this problem, or a workaround that results in an accurate Interval with full timezone information.There are various methods on  for this, including:You have to be explicit about what you want the time component to be in the resulting  object, which is why 's general-conversion constructor can't do it.
Java

I have some server code that is generating thumbnails when an image is uploaded.  The issue is that when the image was taken and the camera/device was rotated, the thumbnails are rotated, even though the full size images themselves are displayed in the correct orientation in any image viewing software.  This is only happening with jpgs.Using Preview on OSX, I can see that jpgs have orientation metadata embedded within.  When I use ImageTools (Grails Plugin) to generate a thumbnail, the EXIF metadata is not in the thumbnail, which is why the thumbnails appear rotated. Via offline conversations, I have learned that while it is relatively easy to read EXIF metadata, there is no easy way to write it, which is why the data is lost when generating a jpg thumbnail.So it seems I have two options: Does anyone know of any other options?If you want to rotate your images, I would suggest to use the metadata extractor library . You can get the image information with the following code:Then given the orientation you retrieve, you can rotate and/or flip the image to the right orientation. The Affine transform for the EXIF orientation is given by the following method:The rotation of the image would be done by the following method:In a server environment, don't forget to run with The  library honors EXIF orientation flags. To read an image at full size with correct orientation:Exif seems to be hard to write because of proprietary stuff in it.\nHowever, you can consider another optionRead original but only write orientation tag to thumbnails.Apache Sanselan seems to have nice collection of tools to do it.Look at ExifRewriter class, for example.This can be done surprisingly easily by using the  :That's it!I have tried Apache Commons Imaging, but that was a mess. JavaXT is way more elegant.If you just want it to look right. You can just add a \"rotate\" -PI/2 (-90 degrees), PI/2 (90 degrees), or PI (+180 degrees) as necessary depending on the 'orientation' you've already extracted. The browser or any other program will correctly display the image as the orientation will have been applied and the metadata stripped from the thumbnail output.
Java

I want to detect when a  contained in a  gets clicked, so that I can launch an intent to manage that selection.I would have done like this in my layout  file:And the following in my  code:But the method  is deprecated.Here you can check the  layout structure that my activity has, and a snapshot of the application:After clicking on the About (or Access Label Taxonomy) , I'd like to open an  of some kind (could also be a video or anything else...the names are misleading). If you are using  on API Level 11+ devices, you would call  on it. Otherwise, call  on your , as you have no choice.It will work.API Level 11+ introduced  as another way of constructing the contents of a . You are welcome to use them, but if you are still supporting older devices, you cannot use  for those devices.That being said:You do not need Java code for this. Use:(as seen in the )This will create an entry in the preference UI that, when clicked, will start an activity with the specified .If you use fragments, you can use the method \"findPreference()\" on the basis of a preferences fragment.maybe  link are  not clear. But using that feature is very simple. for example, you can use that as a twitter  page like thisit doesnt need any java code. Thanks to CommonsWare!
Java

What does the following statements mean?I have seen this message generated by Eclipse when the programmer asks Eclipse to add a Javadoc comment to some code in a location where [EDIT: Eclipse thinks] the Javadoc tool will not actually  it.A common example is the implementation of a method in an interface implemented by the class (which in Java 6 needs the @Override annotation).  Javadoc will use the javadoc placed on the method in the , not the one provided in the implementation.The rest of the comment was most likely written by a person that did not know this.Javadoc looks for comments that start with /*.\nBy tradition, method comments that are not intended to be part of the java docs start with \"/* (non-Javadoc)\" (at least when your dev environment is Eclipse).As an aside, avoid using multi-line comments  methods. For example, avoid this:The following is preferred:The reason is that you open the possibility to comment out the entire method:Now you can still see the old method's behaviour while implementing the new method. This is also useful when debugging (to simplify the code).It's just a normal comment. The note means, if you create a manual, base of javadoc, this text won't be added.
Java

What is the use of the  keyword in Python? What does it do?For example, I'm trying to understand this code:And this is the caller:What happens when the method  is called?\nIs a list returned? A single element? Is it called again? When will subsequent calls stop?To understand what  does, you must understand what  are. And before generators come .When you create a list, you can read its items one by one. Reading its items one by one is called iteration: is an . When you use a list comprehension, you create a list, and so an iterable:Everything you can use \"\" on is an iterable; , , files...These iterables are handy because you can read them as much as you wish, but you store all the values in memory and this is not always what you want when you have a lot of values.Generators are iterators, but . It's because they do not store all the values in memory, :It is just the same except you used  instead of . BUT, you  perform  a second time since generators can only be used once: they calculate 0, then forget about it and calculate 1, and end calculating 4, one by one. is a keyword that is used like , except the function will return a generator.Here it's a useless example, but it's handy when you know your function will return a huge set of values that you will only need to read once.To master , you must understand that  The function only returns the generator object, this is a bit tricky :-)Then, your code will be run each time the  uses the generator.Now the hard part:The first time the  calls the generator object created from your function, it will run the code in your function from the beginning until it hits , then it'll return the first value of the loop. Then, each other call will run the loop you have written in the function one more time, and return the next value, until there is no value to return.The generator is considered empty once the function runs but does not hit  anymore. It can be because the loop had come to an end, or because you do not satisfy an  anymore.Generator:Caller:This code contains several smart parts:Usually we pass a list to it:But in your code it gets a generator, which is good because:And it works because Python does not care if the argument of a method is a list or not. Python expects iterables so it will work with strings, lists, tuples and generators! This is called duck typing and is one of the reason why Python is so cool. But this is another story, for another question...You can stop here, or read a little bit to see an advanced use of a generator:It can be useful for various things like controlling access to a resource.The itertools module contains special functions to manipulate iterables. Ever wish to duplicate a generator?\nChain two generators? Group values in a nested list with a one liner?  without creating another list?Then just .An example? Let's see the possible orders of arrival for a 4 horse race:Iteration is a process implying iterables (implementing the  method) and iterators (implementing the  method).\nIterables are any objects you can get an iterator from. Iterators are objects that let you iterate on iterables.More about it in this article about .When you see a function with  statements, apply this easy trick to understand what will happen:This trick may give you an idea of the logic behind the function, but what actually happens with  is significantly different that what happens in the list based approach. In many cases the yield approach will be a lot more memory efficient and faster too. In other cases this trick will get you stuck in an infinite loop, even though the original function works just fine. Read on to learn more...First, the  - when you writePython performs the following two steps:The truth is Python performs the above two steps anytime it wants to  the contents of an object - so it could be a for loop, but it could also be code like  (where  is a Python list).Here  is an  because it implements the iterator protocol. In a user defined class, you can implement the  method to make instances of your class iterable. This method should return an . An iterator is an object with a  method. It is possible to implement both  and  on the same class, and have  return . This will work for simple cases, but not when you want two iterators looping over the same object at the same time.So that's the iterator protocol, many objects implement this protocol:Note that a  loop doesn't know what kind of object it's dealing with - it just follows the iterator protocol, and is happy to get item after item as it calls . Built-in lists return their items one by one, dictionaries return the  one by one, files return the  one by one, etc. And generators return... well that's where  comes in:Instead of  statements, if you had three  statements in  only the first would get executed, and the function would exit. But  is no ordinary function. When  is called, it  return any of the values in the yield statements! It returns a generator object. Also, the function does not really exit - it goes into a suspended state. When the  loop tries to loop over the generator object, the function resumes from its suspended state at the very next line after the  it previously returned from, executes the next line of code, in this case a  statement, and returns that as the next item. This happens until the function exits, at which point the generator raises , and the loop exits. So the generator object is sort of like an adapter - at one end it exhibits the iterator protocol, by exposing  and  methods to keep the  loop happy. At the other end however, it runs the function just enough to get the next value out of it, and puts it back in suspended mode.Usually you can write code that doesn't use generators but implements the same logic. One option is to use the temporary list 'trick' I mentioned before. That will not work in all cases, for e.g. if you have infinite loops, or it may make inefficient use of memory when you have a really long list. The other approach is to implement a new iterable class  that keeps state in instance members and performs the next logical step in it's  (or  in Python 3) method. Depending on the logic, the code inside the  method may end up looking very complex and be prone to bugs. Here generators provide a clean and easy solution.Think of it this way:An iterator is just a fancy sounding term for an object that has a next() method.  So a yield-ed function ends up being something like this:Original version:This is basically what the python interpreter does with the above code:For more insight as to what's happening behind the scenes, the for loop can be rewritten to this:Does that make more sense or just confuse you more?  :) I should note that this IS an oversimplification for illustrative purposes.  :) Forgot to throw the StopIteration exceptionThe  keyword is reduced to two simple facts:In a nutshell: , and  the generator should incrementally spit out.Let's define a function  that's just like Python's . Calling  RETURNS A GENERATOR:To force the generator to immediately return its pending values, you can pass it into  (just like you could any iterable):The above example can be thought of as merely creating a list which you append to and return:There is one major difference, though; see the last section.An iterable is the last part of a list comprehension, and all generators are iterable, so they're often used like so:To get a better feel for generators, you can play around with the  module (be sure to use  rather than  when warranted). For example, you might even use generators to implement infinitely-long lazy lists like . You could implement your own , or alternatively do so with the  keyword in a while-loop.Please note: generators can actually be used for many more things, such as  or non-deterministic programming or other elegant things. However, the \"lazy lists\" viewpoint I present here is the most common use you will find.This is how the \"Python iteration protocol\" works. That is, what is going on when you do . This is what I describe earlier as a \"lazy, incremental list\".The built-in function  just calls the objects  function, which is a part of the \"iteration protocol\" and is found on all iterators. You can manually use the  function (and other parts of the iteration protocol) to implement fancy things, usually at the expense of readability, so try to avoid doing that...Normally, most people would not care about the following distinctions and probably want to stop reading here.In Python-speak, an  is any object which \"understands the concept of a for-loop\" like a list , and an  is a specific instance of the requested for-loop like . A  is exactly the same as any iterator, except for the way it was written (with function syntax).When you request an iterator from a list, it creates a new iterator. However, when you request an iterator from an iterator (which you would rarely do), it just gives you a copy of itself.Thus, in the unlikely event that you are failing to do something like this...... then remember that a generator is an ; that is, it is one-time-use. If you want to reuse it, you should call  again. If you need to use the result twice, convert the result to a list and store it in a variable . Those who absolutely need to clone a generator (for example, who are doing terrifyingly hackish metaprogramming) can use  if absolutely necessary, since the copyable iterator Python  standards proposal has been deferred. is just like  - it returns whatever you tell it to.  The only difference is that the next time you call the function, execution starts from the last call to the  statement.In the case of your code, the function  is acting like an iterator so that when you extend your list, it adds one element at a time to the new list. calls an iterator until it's exhausted.  In the case of the code sample you posted, it would be much clearer to just return a tuple and append that to the list.There's one extra thing to mention: a function that yields doesn't actually have to terminate. I've written code like this:Then I can use it in other code like this:It really helps simplify some problems, and makes some things easier to work with.  is only legal inside of a function definition, and The idea for generators comes from other languages (see footnote 1) with varying implementations. In Python's Generators, the execution of the code is  at the point of the yield. When the generator is called (methods are discussed below) execution resumes and then freezes at the next yield. provides an \neasy way of , defined by the following two methods: \n and  (Python 2) or  (Python 3).  Both of those methods\nmake an object an iterator that you could type-check with the  Abstract Base \nClass from the  module.The generator type is a sub-type of iterator:And if necessary, we can type-check like this:A feature of an  , you can't reuse or reset it:You'll have to make another if you want to use its functionality again (see footnote 2):One can yield data programmatically, for example:The above simple generator is also equivalent to the below - as of Python 3.3 (and not available in Python 2), you can use :However,  also allows for delegation to subgenerators, \nwhich will be explained in the following section on cooperative delegation with sub-coroutines. forms an expression that allows data to be sent into the generator (see footnote 3)Here is an example, take note of the  variable, which will point to the data that is sent to the generator:First, we must queue up the generator with the builtin function, . It will \ncall the appropriate  or  method, depending on the version of\nPython you are using:And now we can send data into the generator. (.) :Now, recall that  is available in Python 3. This allows us to delegate\ncoroutines to a subcoroutine:And now we can delegate functionality to a sub-generator and it can be used\nby a generator just as above:You can read more about the precise semantics of  in The  method raises  at the point the function \nexecution was frozen. This will also be called by  so you \ncan put any cleanup code where you handle the :You can also throw an exception which can be handled in the generator\nor propagated back to the user:I believe I have covered all aspects of the following question:It turns out that  does a lot. I'm sure I could add even more \nthorough examples to this. If you want more or have some constructive criticism, let me know by commenting\nbelow.In :An  is basically any number of expressions separated by commas - essentially, in Python 2, you can stop the generator with , but you can't return a value.In : For those who prefer a minimal working example, meditate on this interactive  session:Yield gives you a generator. As you can see, in the first case foo holds the entire list in memory at once. It's not a big deal for a list with 5 elements, but what if you want a list of 5 million? Not only is this a huge memory eater, it also costs a lot of time to build at the time that the function is called. In the second case, bar just gives you a generator. A generator is an iterable--which means you can use it in a for loop, etc, but each value can only be accessed once. All the values are also not stored in memory at the same time; the generator object \"remembers\" where it was in the looping the last time you called it--this way, if you're using an iterable to (say) count to 50 billion, you don't have to count to 50 billion all at once and store the 50 billion numbers to count through. Again, this is a pretty contrived example, you probably would use itertools if you really wanted to count to 50 billion. :)This is the most simple use case of generators. As you said, it can be used to write efficient permutations, using yield to push things up through the call stack instead of using some sort of stack variable. Generators can also be used for specialized tree traversal, and all manner of other things.There is one type of answer that I don't feel has been given yet, among the many great answers that describe how to use generators.  Here is the PL theory answer:The  statement in python returns a generator.  A generator in python is a function that returns  (and specifically a type of coroutine, but continuations represent the more general mechanism to understand what is going on).Continuations in programming languages theory are a much more fundamental kind of computation, but they are not often used because they are extremely hard to reason about and also very difficult to implement.  But the idea of what a continuation is, is straightforward: it is the state of a computation that has not yet finished. In this state are saved the current values of variables and the operations that have yet to be performed, and so on. Then at some point later in the program the continuation can be invoked, such that the program's variables are reset to that state and the operations that were saved are carried out.Continuations, in this more general form, can be implemented in two ways. In the  way, the program's stack is literally saved and then when the continuation is invoked, the stack is restored.In continuation passing style (CPS), continuations are just normal functions (only in languages where functions are first class) which the programmer explicitly manages and passes around to subroutines. In this style, program state is represented by closures (and the variables that happen to be encoded in them) rather than variables that reside somewhere on the stack. Functions that manage control flow accept continuation as arguments (in some variations of CPS, functions may accept multiple continuations) and manipulate control flow by invoking them by simply calling them and returning afterwards. A very simple example of continuation passing style is as follows:In this (very simplistic) example, the programmer saves the operation of actually writing the file into a continuation (which can potentially be a very complex operation with many details to write out), and then passes that continuation (i.e, as a first-class closure) to another operator which does some more processing, and then calls it if necessary. (I use this design pattern a lot in actual GUI programming, either because it saves me lines of code or, more importantly, to manage control flow after GUI events trigger)The rest of this post will, without loss of generality, conceptualize continuations as CPS, because it is a hell of a lot easier to understand and read.Now let's talk about generators in python. Generators are a specific subtype of continuation. Whereas  (i.e., the program's call stack), . Although, this definition is slightly misleading for certain use cases of generators. For instance:This is clearly a reasonable iterable whose behavior is well defined -- each time the generator iterates over it, it returns 4 (and does so forever). But it isn't probably the prototypical type of iterable that comes to mind when thinking of iterators (i.e., ). This example illustrates the power of generators: if anything is an iterator, a generator can save the state of its iteration.To reiterate: Continuations can save the state of a program's stack and generators can save the state of iteration. This means that continuations are more a lot powerful than generators, but also that generators are a lot, lot easier. They are easier for the language designer to implement, and they are easier for the programmer to use (if you have some time to burn, try to read and understand ).But you could easily implement (and conceptualize) generators as a simple, specific case of continuation passing style: Whenever  is called, it tells the function to return a continuation.  When the function is called again, it starts from wherever it left off. So, in pseudo-pseudocode  (i.e., not pseudocode but not code) the generator's  method is basically as follows: where  keyword is actually syntactic sugar for the real generator function, basically something like:Remember that this is just pseudocode and the actual implementation of generators in python is more complex. But as an exercise to understand what is going on, try to use continuation passing style to implement generator objects without use of the  keyword.It's returning a generator. I'm not particularly familiar with Python, but I believe it's the same kind of thing as  if you're familiar with those.There's an  which explains it reasonably well (for Python) as far as I can see.The key idea is that the compiler/interpreter/whatever does some trickery so that as far as the caller is concerned, they can keep calling next() and it will keep returning values - . Now obviously you can't really \"pause\" a method, so the compiler builds a state machine for you to remember where you currently are and what the local variables etc look like. This is much easier than writing an iterator yourself.An example in plain language. I will provide a correspondence between high-level human concepts to low-level python concepts.I want to operate on a sequence of numbers, but I don't want to bother my self with the creation of that sequence, I want only to focus on the operation I want to do. So, I do the following:This is what a generator does (a function that contains a ); it starts executing, pauses whenever it does a , and when asked for a  value it continues from the point it was last. It fits perfectly by design with the iterator protocol of python, which describes how to sequentially request for values.The most famous user of the iterator protocol is the  command in python. So, whenever you do a:it doesn't matter if  is a list, a string, a dictionary or a generator  like described above; the result is the same: you read items off a sequence one by one.Note that ining a function which contains a  keyword is not the only way to create a generator; it's just the easiest way to create one.For more accurate information, read about , the  and  in the Python documentation.While a lot of answers show why you'd use a  to create a generator, there are more uses for .  It's quite easy to make a coroutine, which enables the passing of information between two blocks of code.  I won't repeat any of the fine examples that have already been given about using  to create a generator.To help understand what a  does in the following code, you can use your finger to trace the cycle through any code that has a .  Every time your finger hits the , you have to wait for a  or a  to be entered.  When a  is called, you trace through the code until you hit the \u2026 the code on the right of the  is evaluated and returned to the caller\u2026 then you wait.  When  is called again, you perform another loop through the code.  However, you'll note that in a coroutine,  can also be used with a \u2026 which will send a value from the caller  the yielding function. If a  is given, then  receives the value sent, and spits it out the left hand side\u2026 then the trace through the code progresses until you hit the  again (returning the value at the end, as if  was called).For example:There is another  use and meaning (since python 3.3):moreover  will introduce (since python 3.5):to avoid coroutines confused with regular generator (today  is used in both).This was my first aha-moment with yield. is a sugary way to say Same behavior:Different behavior:Yield is : you can only iterate through once. Conceptually the yield-function returns an ordered container of things. But it's revealing that we call any function with a yield in it a . And the term for what it returns is an .Yield is , it puts off computation until you need it. A function with a yield in it  when you call it. The iterator object it returns uses  to maintain the function's internal context. Each time you call  on the iterator (as happens in a for-loop), execution inches forward to the next yield. (Or , which raises  and ends the series.)Yield is . It can do infinite loops:If you need  and the series isn't humongous, just pass the iterator to Brilliant choice of the word  because  apply:...provide the next data in the series....relinquish CPU execution until the iterator advances.I was going to post \"read page 19 of Beazley's 'Python: Essential Reference' for a quick description of generators\", but so many others have posted good descriptions already.Also, note that  can be used in coroutines as the dual of their use in generator functions.  Although it isn't the same use as your code snippet,  can be used as an expression in a function.  When a caller sends a value to the method using the  method, then the coroutine will execute until the next  statement is encountered.Generators and coroutines are a cool way to set up data-flow type applications.  I thought it would be worthwhile knowing about the other use of the  statement in functions.Here are some  as if Python did not provide syntactic sugar for them (or in a language without native syntax, like ). Snippets from that link is below. (because )Here is a simple example:output :I am not a Python developer, but it looks to me  holds the position of program flow and the next loop start from \"yield\" position. It seems like it is waiting at that position, and just before that, returning a value outside, and next time continues to work.Seems to me an interesting and nice ability :D From a programming viewpoint, the iterators are implemented as  To implement iterators/generators/thread pools for concurrent execution/etc as thunks (also called anonymous functions), one uses messages sent to a closure object, which has a dispatcher, and the dispatcher answers to \"messages\".\"\" is a message sent to a closure, created by \"\" call.There are lots of ways to implement this computation.  I used mutation but it is easy to do it without mutation, by returning the current value and the next yielder.Here is a demonstration which uses the structure of R6RS but the semantics is absolutely identical as in python, it's the same model of computation, only a change in syntax is required to rewrite it in python.Here is a mental image of what  does.I like to think of a thread as having a stack (even when it's not implemented that way).When a normal function is called, it puts its local variables on the stack, does some computation, then clears the stack and returns. The values of its local variables are never seen again.With a  function, when its code begins to run (i.e. after the function is called, returning a generator object, whose  method is then invoked), it similarly puts its local variables onto the stack and computes for a while. But then, when it hits the  statement, before clearing its part of the stack and returning, it takes a snapshot of its local variables and stores them in the generator object. It also writes down the place where it's currently up to in its code (i.e. the particular  statement).So it's a kind of a frozen function that the generator is hanging onto.When  is called subsequently, it retrieves the function's belongings onto the stack and re-animates it. The function continues to compute from where it left off, oblivious to the fact that it had just spent an eternity in cold storage.Compare the following examples:When we call the second function, it behaves very differently to the first. The  statement might be unreachable, but if it's present anywhere, it changes the nature of what we're dealing with.Calling  doesn't run its code, but makes a generator out of the code. (Maybe it's a good idea to name such things with the  prefix for readability.)The  and  fields are where the frozen state is stored. Exploring them with , we can confirm that our mental model above is credible.Like every answer suggests,  is used for creating a sequence generator. It's used for generating some sequence dynamically. Eg. While reading a file line by line on a network, you can use the  function as follows:You can use it in your code as follows :The execution control will be transferred from getNextLines() to the for loop when yield is executed. Thus, every time getNextLines() is invoked, execution begins from the point where it was paused last time.Thus in short, a function with the following codewill print I hope this helps you. is like a return element for a function. The difference is, that the  element turns a function into a generator. A generator behaves just like a function until something is 'yielded'. The generator stops until it is next called, and continues from exactly the same point as it started. You can get a sequence of all the 'yielded' values in one, by calling .A  in a function will return a single value.If you want  use .More importantly,  is a  i.eIt will run the code in your function from the beginning until it hits . Then, it\u2019ll return the first value of the loop. \nThen, every other call will run the loop you have written in the function one more time, returning the next value until there is no value to return.(My below answer only speaks from the perspective of using Python generator, not the , which involves some tricks of stack and heap manipulation.)When  is used instead of a  in a python function, that function is turned into something special called . That function will return an object of  type.  Normal functions will terminate once some value is returned from it. But with the help of the compiler, the generator function  as resumable. That is, the execution context will be restored and the execution will continue from last run. Until you explicitly call return, which will raise a  exception (which is also part of the iterator protocol), or reach the end of the function. I found a lot of references about  but this  from the  is the most digestable.(Now I want to talk about the rationale behind , and the  based on my own understanding. I hope this can help you grasp the  of iterator and generator. Such concept shows up in other languages as well such as C#.)As I understand, when we want to process a bunch of data, we usually first store the data somewhere and then process it one by one. But this  approach is problematic. If the data volume is huge, it's expensive to store them as a whole beforehand. . There are 2 approaches to wrap such metadata.Either way, an iterator is created, i.e. some object that can give you the data you want. The OO approach may be a bit complex. Anyway, which one to use is up to you.The  keyword simply collects returning results. Think of  like Many people use  rather than  but in some cases  can be more efficient and easier to work with.Here is an example which  is definitely best for:Both functions do the same thing but  uses 3 lines instead of 5 and has one less variable to worry about.As you can see both functions do the same thing, the only difference is  gives a list and  gives a generatorA real life example would be something like reading a file line by line or if you just want to make a generatorMost questions regarding the  statement and the semantics/functionality that it introduces are present in . The collective knowledge from all previous answers is amazing but I'll add an answer that references the official presentation.So first of, the form of the  statement:consist of the   along with an optional . Syntactically yield can only appear inside a function definition and its presence alone is responsible for tranforming a function into a generator object:So after you define your generator you're left with a generator function that is waiting to be called: So parameters are bound in the same way as they do for all callable but the body of the generator object is not executed, what happens is:We get back an object that comforms to the  this means that the  object implements  and  and as such can be used in  loops like any object that supports iteration. The key difference that  makes is here, specifically:So everything  the  is executed and then execution stops, at that point what happens is: So in the case of a  loop:  the value of  is going to be equal to  as previously stated.But \"frozen\" you may ask, what does that mean? This is further explained as: So state is retained when  is encountered thereby allowing consequent calls to  to continue smoothly. When a  call is made the generator is going to execute everything until it finds another  statement. That cicle is repeated until no  (i.e control flows off the end of the generator) or a  is found in which case a  exception is raised signalling that the generator has been exhausted.In summary, the  statement transforms your function into a factory that produces a special object called a  which wraps around the body of your original function. When the  is iterated, it executes your function  until it reaches the next  then suspends execution and evaluates to the value passed to . It repeats this process on each iteration until the path of execution exits the function. For instance;simply outputs ;The power comes from using the generator with a loop that calculates a sequence, the generator executes the loop stopping each time to 'yield' the next result of the calculation, in this way it calculates a list on the fly, the benefit being the memory saved for especially large calculationsSay you wanted to create a your own  function that produces an iterable range of numbers, you could do it like so,and use it like this;but this is ineffecient becauseLuckily Guido and his team were generous enough to develop generators so we could just do this;Now upon each iteration a function on the generator called  executes the function until it either reaches a 'yield' statement in which it stops and  'yields' the value or reaches the end of the function. In this case on the first call,  executes up to the yield statement and yield 'n', on the next call it will execute the  increment statement, jump back to the 'while', evaluate it, and if true, it will stop and yield 'n' again, it will continue that way until the while condition returns false and the generator jumps to the end of the function. At a glance, the yield statement is used to define generators, replacing the return of a function to provide a result to its caller without destroying local variables. Unlike a function, where on each call it starts with new set of variables, a generator will resume the execution where it was left off.About Python Generators\nSince the yield keyword is only used with generators, it makes sense to recall the concept of generators first.The idea of generators is to calculate a series of results one-by-one on demand (on the fly). In the simplest case, a generator can be used as a list, where each element is calculated lazily. Let's compare a list and a generator that do the same thing - return powers of two:Iterating over the list and the generator looks completely the same. However, although the generator is iterable, it is not a collection and thus has no length. Collections (lists, tuples, sets, etc) keep all values in memory and we can access them whenever needed. A generator calculates the values on the fly and forgets them, so it does not have any overview about the own result set.Generators are especially useful for memory-intensive tasks, where there is no need to keep all of the elements of a memory-heavy list accessible at the same time. Calculating a series of values one-by-one can also be useful in situations where the complete result is never needed, yielding intermediate results to the caller until some requirement is satisfied and further processing stops.Using the Python \"yield\" keyword\nA good example is a search task, where typically there is no need to wait for all results to be found. Performing a file-system search, a user would be happier to receive results on-the-fly, rather the wait for a search engine to go through every single file and only afterwards return results. Are there any people who really navigate through all Google search results until the last page?Since a search functionality cannot be created using list-comprehensions, we are going to define a generator using a function with the yield statement/keyword. The yield instruction should be put into a place where the generator returns an intermediate result to the caller and sleeps until the next invocation occurs. So far the most practical aspects of Python generators have been described. For more detailed info and an interesting discussion take a look at the Python Enhancement Proposal 255, which discusses the feature of the language in detail.Happy Pythoning!\nYet another TL;DR:  returns the next element of the list:  will compute the next element on the fly (execute code)You can see the yield/generator as a way to manually run the  from outside (like continue loop 1 step), by calling next, however complex the flow.NOTE: the generator is  a normal function, it remembers previous state like local variables (stack), see other answers or articles for detailed explanation, the generator can only be .\nYou could do without  but it would not be as nice, so it can be considered 'very nice' language sugar.
Python

Is there a simple way to determine if a variable is a list, dictionary, or something else? I am getting an object back that may be either type and I need to be able to tell the difference.To get the type of an object, you can use the built-in  function. Passing an object as the only parameter will return the type object of that object:This of course also works for custom types:Note that  will only return the immediate type of the object, but won\u2019t be able to tell you about type inheritance.To cover that, you should use the  function. This of course also works for built-in types: is usually the preferred way to ensure the type of an object because it will also accept derived types. So unless you actually need the type object (for whatever reason), using  is preferred over .The second parameter of  also accepts a tuple of types, so it\u2019s possible to check for multiple types at once.  will then return true, if the object is of any of those types:You can do that using :It might be more Pythonic to use a ... block. That way, if you have a class which quacks like a list, or quacks like a dict, it will behave properly regardless of what its type  is.To clarify, the preferred method of \"telling the difference\" between variable types is with something called : as long as the methods (and return types) that a variable responds to are what your subroutine expects, treat it like what you expect it to be. For example, if you have a class that overloads the bracket operators with  and , but uses some funny internal scheme, it would be appropriate for it to behave as a dictionary if that's what it's trying to emulate.The other problem with the  checking is that if  is a subclass of , it evaluates to  when, programmatically, you would hope it would be . If an object is a subclass of a list, it should work like a list: checking the type as presented in the other answer will prevent this. ( will work, however).On instances of object you also have the:attribute. Here is a sample taken from Python 3.3 consoleBeware that in python 3.x and in New-Style classes (aviable optionally from Python 2.6) class and type have been merged and this can sometime lead to unexpected results. Mainly for this reason my favorite way of testing types/classes is to the  built in function.You can use  or .Be warned that you can clobber  or any other type by assigning a variable in the current scope of the same name.Above we see that  gets reassigned to a string, therefore the test:...fails.To get around this and use  more cautiously:Determine the type of an object with Although it works, avoid double underscore attributes like  - they're not semantically public, and, while perhaps not in this case, the builtin functions usually have better behavior.Well that's a different question, don't use type - use :This covers the case where your user might be doing something clever or sensible by subclassing  - according to the principle of Liskov Substitution, you want to be able to use subclass instances without breaking your code - and  supports this. Even better, you might look for a specific Abstract Base Class from  or :Or, perhaps best of all, use duck-typing, and don't explicitly type-check your code. Duck-typing supports Liskov Substitution with more elegance and less verbosity. While the questions is pretty old, I stumbled across this while finding out a proper way myself, and I think it still needs clarifying,  (did not check on Python 3, but since the issue arises with classic classes which are gone on such version, it probably doesn't matter).Here I'm trying to answer the title's question: ? Other suggestions about using or not using isinstance are fine in many comments and answers, but I'm not addressing those concerns.The main issue with the  approach is that :Executing this snippet would yield:Which, I argue, is not what most people would expect.The  approach is the most close to correctness, but it won't work in one crucial case: when the passed-in object is an old-style  (not an instance!), since those objects lack such attribute.This is the smallest snippet of code I could think of that satisfies such legitimate question in a consistent fashion:As an aside to the previous answers, it's worth mentioning the existence of  which contains several abstract base classes (ABCs) that complement duck-typing.For example, instead of explicitly checking if something is a list with: you could, if you're only interested in seeing if the object you have allows getting items, use :if you're strictly interested in objects that allow getting, setting  deleting items (i.e  sequences), you'd opt for .Many other ABCs are defined there,  for objects that can be used as maps, , , et cetera. A full list of all these can be seen in 
Python

In the following method definitions, what does the  and  do for ?The  and  is a common idiom to allow arbitrary number of arguments to functions as described in the section  in the Python documentation.The  will give you all function parameters :The  will give you all \n except for those corresponding to a formal parameter as a dictionary.Both idioms can be mixed with normal arguments to allow a set of fixed and some variable arguments:Another usage of the  idiom is to  when calling a function.In Python 3 it is possible to use  on the left side of an assignment (), though it gives a list instead of a tuple in this context:Also Python 3 adds new semantic (refer ):Such function accepts only 3 positional arguments, and everything after  can only be passed as keyword arguments.It's also worth noting that you can use * and ** when calling functions as well. This is a shortcut that allows you to pass multiple arguments to a function directly using either a list/tuple or a dictionary. For example, if you have the following function:You can do things like:The single * means that there can be any number of extra positional arguments.  can be invoked like . In the body of foo() param2 is a sequence containing 2-5.The double ** means there can be any number of extra named parameters.  can be invoked like . In the body of bar() param2 is a dictionary containing {'a':2, 'b':3 }With the following code:the output isThey allow for  and for  any number of arguments, positional () and keyword (). allows for any number of optional positional arguments (parameters), which will be assigned to a tuple named .  allows for any number of optional keyword arguments (parameters), which will be in a dict named .You can (and should) choose any appropriate name, but if the intention is for the arguments to be of non-specific semantics,  and  are standard names.You can also use  and  to pass in parameters from lists (or any iterable) and dicts (or any mapping), respectively.The function recieving the parameters does not have to know that they are being expanded. For example, Python 2's xrange does not explicitly expect , but since it takes 3 integers as arguments:As another example, we can use dict expansion in :You can have  after the  - for example, here,  must be given as a keyword argument - not positionally:Usage:Also,  can be used by itself  to indicate that keyword only arguments follow, without allowing for unlimited positional arguments.Here,  again must be an explicitly named, keyword argument:And we can no longer accept unlimited positional arguments because we don't have :Again, more simply, here we require  to be given by name, not positionally:In this example, we see that if we try to pass  positionally, we get an error:We must explicitly pass the  parameter as a keyword argument. (typically said \"star-args\") and  (stars can be implied by saying \"kwargs\", but be explicit with \"double-star kwargs\") are common idioms of Python for using the  and  notation. These specific variable names aren't required (e.g. you could use  and ), but a departure from convention is likely to enrage your fellow Python coders. We typically use these when we don't know what our function is going to receive or how many arguments we may be passing, and sometimes even when naming every variable separately would get very messy and redundant (but this is a case where usually explicit is better than implicit).The following function describes how they can be used, and demonstrates behavior. Note the named  argument will be consumed by the second positional argument before :We can check the online help for the function's signature, with , which tells us Let's call this function with  which prints:We can also call it using another function, into which we just provide : prints:OK, so maybe we're not seeing the utility yet. So imagine you have several functions with redundant code before and/or after the differentiating code. The following named functions are just pseudo-code for illustrative purposes.We might be able to handle this differently, but we can certainly extract the redundancy with a decorator, and so our below example demonstrates how  and  can be very useful:And now every wrapped function can be written much more succinctly, as we've factored out the redundancy:And by factoring out our code, which  and  allows us to do, we reduce lines of code, improve readability and maintainability, and have sole canonical locations for the logic in our program. If we need to change any part of this structure, we have one place in which to make each change.Let us first understand what are positional arguments and keyword arguments.\nBelow is an example of function definition with So this is a function definition with positional arguments.\nYou can call it with keyword/named arguments as well:Now let us study an example of function definition with :You can call this function with positional arguments as well:So we now know function definitions with positional as well as keyword arguments.Now let us study the '*' operator and '**' operator.Please note these operators can be used in 2 areas:a) b) The use of '*' operator and '**' operator in  Let us get straight to an example and then discuss it.So remember when the '*' or '**' operator is used in a  -'*' operator unpacks data structure such as a list or tuple  into arguments needed by function definition.'**' operator unpacks a dictionary into arguments needed by function definition.Now let us study the '*' operator use in .\nExample:In function  the '*' operator packs the received arguments into a tuple.Now let us see an example of '**' used in function definition:In function  The '**' operator packs the received arguments into a dictionary.So remember:In a  the '*'  data structure of tuple or list into positional or keyword arguments to be received by function definition.In a  the '**'  data structure of dictionary into positional or keyword arguments to be received by function definition.In a  the '*'  positional arguments into a tuple.In a  the '**'  keyword arguments into a dictionary. and  have special usage in the function argument list. \nimplies that the argument is a list and  implies that the argument\nis a dictionary. This allows functions to take arbitrary number of\nargumentsFrom the Python documentation:In Python 3.5, you can also use this syntax in , , , and  displays (also sometimes called literals). See .It also allows multiple iterables to be unpacked in a single function call.(Thanks to mgilson for the PEP link.)In addition to function calls, *args and **kwargs are useful in class hierarchies and also avoid having to write  method in Python. Similar usage is seen in frameworks like Django code.For example,A subclass can then beThe subclass then be called as Also, a subclass with a new attribute which makes sense only to that subclass instance can call the Base class  to offload the attributes setting.\nThis is done through *args and **kwargs. kwargs mainly used so that code is readable using named arguments. For example,which can be instatiated asThe complete code is I want to give an example which others haven't  mentioned* can also unpack a An example from Python3 Documentunzip_x will be [1, 2, 3], unzip_y will be [4, 5, 6]The zip() receives multiple iretable args, and return a generator. A good example of using both in a function is:This example would help you remember ,  and even  and inheritance in Python at once.
Python

Is it possible to upgrade all Python packages at one time with ?Note that there is  for this on the official issue tracker.There isn't a built-in flag yet, but you can useNote: there are infinite potential variations for this. I'm trying to keep this answer short and simple, but please do suggest variations in the comments!Relevant edits:You can use the following Python code. Unlike , this will not print warnings and FIXME errors.To upgrade all local packages; you could use : is a fork of . See  mentioned by .  package works but  package no longer works. works on Windows .Works on Windows. Should be good for others too.\n($ is whatever directory you're in, in command prompt. eg. C:/Users/Username>)dothen doIf you have a problem with a certain package stalling the upgrade (numpy sometimes), just go to the directory ($), comment out the name (add a # before it) and run the upgrade again. You can later uncomment that section back.Windows version after consulting excellent  for  by Rob van der WoudeYou can just print the packages that are outdatedThe following one-liner might prove of help: keeps going if an error occurs. If you need more \"fine grained\" control over what is omitted and what raises an error you should not add the  flag and explicitly define the errors to ignore, by \"piping\" the following line for each separate error:Here is an example:This option seems to me more straightforward and readable:( selects the first word of the line (separated by a space))And this version allows for the suppression of warning message from :( removes line containing a given pattern. In my case the warning messages include \"Could not\" and \"ignored\" respectively)From  :however you need to get yolk first:This seems more concise.Explanation: gets lines like theseIn ,  sets \"space\" as the delimiter,  means to get the first column. So the above lines becomes:then pass them to  to run the command, , with each line as appending arguments limits the number of arguments passed to each command  to be 1One-liner version of @Ramana's answer.`when using a virtualenv and if you just want to upgrade packages  to your virtualenv, you may want to do:You can try this :@Ramana's worked the best for me, of those here, but I had to add a few catches:The  check excludes my development packages, because they are not located in the system site-packages directory. The try-except simply skips packages that have been removed from PyPI.@endolith: I was hoping for an easy , too, but it doesn't look like pip was meant to be used by anything but the command line (the docs don't mention the internal API, and the pip developers didn't use docstrings).Sent through ; in the meantime use this pip library solution I wrote:This seemed to work for me...I used  with a space afterwards to properly separate the package names.The rather amazing yolk makes this easy.For more info on yolk: It can do lots of things you'll probably find useful.I had the same problem with upgrading. Thing is, i never upgrade all packages. I upgrade only what i need, because project may break.Because there was no easy way for upgrading package by package, and updating the requirements.txt file, i wrote this  which  for the packages chosen (or all packages).Activate your virtualenv (important, because it will also install the new versions of upgraded packages in current virtualenv). into your project directory, then run:If the requirements are placed in a non-standard location, send them as arguments:If you already know what package you want to upgrade, simply send them as arguments:If you need to upgrade to  pre-release / post-release version, add  argument to your command.Full disclosure: I wrote this package.Windows Powershell solutionMy script:Here is my variation on rbp's answer, which bypasses \"editable\" and development distributions. It shares two flaws of the original: it re-downloads and reinstalls unnecessarily; and an error on one package will prevent the upgrade of every package after that.Related bug reports, a bit disjointed after the migration from bitbucket:I have tried the code of Ramana and I found out on Ubuntu you have to write  for each command. Here is my script which works fine on ubuntu 13.10:Isn't this more effective?here is another way of doing with a script in pythonHere is a scripts that only updates the outdated packages.    I've been using  lately. It's simple and to the point. It updates your  file to reflect the upgrades and you can then upgrade with your  file as usual.For pip3 use this:For pip, just remove the 3s as such:This solution is well designed and tested, whereas there are problems with even the most popular solutions.The above command uses the simplest and most portable pip syntax in combination with sed and sh to overcome these issues completely.  Details of sed operation can be scrutinized with the commented version.[1] Tested and regularly used in a Linux 4.8.16-200.fc24.x86_64 cluster and tested on five other Linux/Unix flavors.  It also runs on Cygwin64 installed on Windows 10.  Testing on iOS is needed.[2] To see the anatomy of the command more clearly, this is the exact equivalent of the above pip3 command with comments: [3] Upgrading a Python or PIP component that is also used in the upgrading of a Python or PIP component can be a potential cause of a deadlock or package database corruption.or even:Works fast as it is not constantly launching a shell.  I would love to find the time to get this actually using the list outdated to speed things up still more.Here is my variation:I took @Ramana's answer and made it pip3 friendly.
Python

This has always confused me. It seems like this would be nicer:Than this:Is there a specific reason it is like this?It's because any iterable can be joined, not just lists, but the result and the \"joiner\" are always strings.E.G:Because the  method is in the string class, instead of the list class?I agree it looks funny.See :This was discussed in the  thread in the Python-Dev achive, and was accepted by Guido. This thread began in Jun 1999, and  was included in Python 1.6 (which supported Unicode) was released in Sep 2000. Python 2.0 (supported  methods including ) was released in Oct 2000.Here are some additional thoughts (my own, and my friend's):Guido's decision is recorded in a , deciding on :I agree that it's counterintuitive at first, but there's a good reason. Join can't be a method of a list because:There are actually two join methods (Python 3.0):If join was a method of a list, then it would have to inspect its arguments to decide which one of them to call. And you can't join byte and str together, so the way they have it now makes sense. This is because  is a \"string\" method! It creates a string from any iterable. If we stuck the method on lists, what about when we have iterables that aren't lists? What if you have a tuple of strings? If this were a  method, you would have to cast every such iterator of strings as a  before you could join the elements into a single string! For example:Let's roll our own list join method:And to use it, note that we have to first create a list from each iterable to join the strings in that iterable, wasting both memory and processing power:So we see we have to add an extra step to use our list method, instead of just using the builtin string method:The algorithm Python uses to create the final string with  actually has to pass over the iterable twice, so if you provide it a generator expression, it has to materialize it into a list first before it can create the final string. Thus, while passing around generators is usually better than list comprehensions,  is an exception:Nevertheless, the  operation is still semantically a \"string\" operation, so it still makes sense to have it on the  object than on miscellaneous iterables.Think of it as the natural orthogonal operation to split.I understand why it is applicable to anything iterable and so can't easily be implemented  on list.For readability, I'd like to see it in the language but I don't think that is actually feasible - if iterability were an interface then it could be added to the interface but it is just a convention and so there's no central way to add it to the set of things which are iterable.Primarily because the result of a  is a string.The sequence (list or tuple or whatever) doesn't appear in the result, just a string.  Because the result is a string, it makes sense as a method of a string.
Python

What is the Python equivalent of Perl's  function, which removes the last character of a value?Try the method  (see doc  and )Python's  method strips  kinds of trailing whitespace by default, not just one newline as Perl does with .To strip only newlines:There are also the methods  and :And I would say the \"pythonic\" way to get lines without trailing newline characters is splitlines().The canonical way to strip end-of-line (EOL) characters is to use the string rstrip() method removing any trailing \\r or \\n.  Here are examples for Mac, Windows, and Unix EOL characters.Using '\\r\\n' as the parameter to rstrip means that it will strip out any trailing combination of '\\r' or '\\n'.  That's why it works in all three cases above.This nuance matters in rare cases.  For example, I once had to process a text file which contained an HL7 message.  The HL7 standard requires a trailing '\\r' as its EOL character.  The Windows machine on which I was using this message had appended its own '\\r\\n' EOL character.  Therefore, the end of each line looked like '\\r\\r\\n'.  Using rstrip('\\r\\n') would have taken off the entire '\\r\\r\\n' which is not what I wanted.  In that case, I simply sliced off the last two characters instead.Note that unlike Perl's  function, this will strip all specified characters at the end of the string, not just one:Note that rstrip doesn't act exactly like Perl's chomp() because it doesn't modify the string. That is, in Perl:results in  being .but in Python:will mean that the value of  is  . Even  doesn't always give the same result, as it strips all whitespace from the end of the string, not just one newline at most.I might use something like this:I think the problem with  is that you'll probably want to make sure the line separator is portable. (some antiquated systems are rumored to use ). The other gotcha is that  will strip out repeated whitespace. Hopefully  will contain the right characters. the above works for me.You may use . This will strip all newlines from the end of the string, not just one.will remove all newlines at the end of the string . The assignment is needed because  returns a new string instead of modifying the original string. Careful with : That will only chomp the newline characters for the platform where your Python is being executed. Imagine you're chimping the lines of a Windows file under Linux, for instance:Use  instead, as Mike says above.or you could always get geekier with regexps :)have fun!you can use strip:demo:An  simply uses .Perl's  function removes one linebreak sequence from the end of a string only if it's actually there.Here is how I plan to do that in Python, if  is conceptually the function that I need in order to do something useful to each line from this file:rstrip doesn't do the same thing as chomp, on so many levels. Read  and see that chomp is very complex indeed.However, my main point is that chomp removes at most 1 line ending, whereas rstrip will remove as many as it can.Here you can see rstrip removing all the newlines:A much closer approximation of typical Perl chomp usage can be accomplished with re.sub, like this:I don't program in Python, but I came across an  at python.org advocating S.rstrip(\"\\r\\n\") for python 2.2 or later.workaround solution for special case:if the newline character is the last character (as is the case with most file inputs), then for any element in the collection you can index as follows: to slice out your newline character. If your question is to clean up all the line breaks in a multiple line str object (oldstr), you can split it into a list according to the delimiter '\\n' and then join this list into a new str(newstr).    This would replicate exactly perl's chomp (minus behavior on arrays) for \"\\n\" line terminator:(Note: it does not modify string 'in place'; it does not strip extra trailing whitespace; takes \\r\\n in account)Here we go Official Complete Documentation  Just use : orYou don't need any of this complicated stuffA catch all:There are three types of line endings that we normally encounter: ,  and . A rather simple regular expression in , namely , is able to catch them all.(And we , am I right?)With the last argument, we limit the number of occurences replaced to one, mimicking chomp to some extent. Example:... where  is .I find it convenient to have be able to get the chomped lines via in iterator, parallel to the way you can get the un-chomped lines from a file object. You can do so with the following code:Sample usage:If you are concerned about speed (say you have a looong list of strings) and you know the nature of the newline char, string slicing is actually faster than rstrip. A little test to illustrate this:Output:It looks like there is not a perfect analog for perl's .  In particular,  cannot handle multi-character newline delimiters like . However,  does .\nFollowing  on a different question, you can combine  and  to remove/replace all newlines from a string :The following removes  newline (as chomp would, I believe). Passing  as the  argument to splitlines retain the delimiters.  Then, splitlines is called again to remove the delimiters on just the last \"line\": 
Python

Is it possible to have static methods in Python so I can call them without initializing a class, like:Yep, using the  decoratorNote that some code might use the old method of defining a static method, using  as a function rather than a decorator. This should only be used if you have to support ancient versions of Python (2.2 and 2.3)This is entirely identical to the first example (using ), just not using the nice decorator syntaxFinally, use  sparingly! There are very few situations where static-methods are necessary in Python, and I've seen them used many times where a separate \"top-level\" function would have been clearer.:I think that Steven is actually right. To answer the original question, then, in order to set up a class method, simply assume that the first argument is not going to be a calling instance, and then make sure that you only call the method from the class.(Note that this answer refers to Python 3.x. In Python 2.x you'll get a  for calling the method on the class itself.)For example:In this code, the \"rollCall\" method assumes that the first argument is not an instance (as it would be if it were called by an instance instead of a class). As long as \"rollCall\" is called from the class rather than an instance, the code will work fine. If we try to call \"rollCall\" from an instance, e.g.:however, it would cause an exception to be raised because it would send two arguments: itself and -1, and \"rollCall\" is only defined to accept one argument.Incidentally, rex.rollCall() would send the correct number of arguments, but would also cause an exception to be raised because now n would be representing a Dog instance (i.e., rex) when the function expects n to be numerical.This is where the decoration comes in:\nIf we precede the \"rollCall\" method withthen, by explicitly stating that the method is static, we can even call it from an instance. Now, would work. The insertion of @staticmethod before a method definition, then, stops an instance from sending itself as an argument.You can verify this by trying the following code with and without the @staticmethod line commented out.Yes, check out the  decorator:You don't really need to use the  decorator. Just declaring a method (that doesn't expect the self parameter) and call it from the class. The decorator is only there in case you want to be able to call it from an instance as well (which was not what you wanted to do)Mostly, you just use functions though...Yes, static methods can be created like this (although it's a bit more  to use underscores instead of CamelCase for methods):The above uses the decorator syntax. This syntax is equivalent to This can be used just as you described:A builtin example of a static method is  in Python 3, which was a function in the  module in Python 2.Another option that can be used as you describe is the , the difference is that the classmethod gets the class as an implicit first argument, and if subclassed, then it gets the subclass as the implicit first argument.Note that  is not a required name for the first argument, but most experienced Python coders will consider it badly done if you use anything else.These are typically used as alternative constructors. A builtin example is :Aside from the particularities of how  behave, there is a certain kind of beauty you can strike with them when it comes to organizing your module-level code..........It now becomes a bit more intuitive and self-documenting in which context certain components are meant to be used and it pans out ideally for naming distinct test cases as well as having a straightforward approach to how test modules map to actual modules under tests for purists.I frequently find it viable to apply this approach to organizing a project's utility code. Quite often, people immediately rush and create a  package and end up with 9 modules of which one has 120 LOC and the rest are two dozen LOC at best. I prefer to start with this and convert it to a package and create modules only for the beasts that truly deserve them:Perhaps the simplest option is just to put those functions outside of the class:Using this method, functions which modify or use internal object state (have side effects) can be kept in the class, and the reusable utility functions can be moved outside.Let's say this file is called . To use these, you'd call  instead of .If you really need a static method to be part of the class, you can use the  decorator.
Python

I'm mainly a C# developer, but I'm currently working on a project in Python.How can I represent the equivalent of an Enum in Python?  Enums have been added to Python 3.4 as described in .  It has also been  on pypi.  For more advanced Enum techniques try the  (2.7, 3.3+, same author as . Code is not perfectly compatible between py2 and py3, e.g. you'll need ).Installing  (no numbers) will install a completely different and incompatible version.or equivalently:In earlier versions, one way of accomplishing enums is:which is used like so:You can also easily support automatic enumeration with something like this:and used like so:Support for converting the values back to names can be added this way:This overwrites anything with that name, but it is useful for rendering your enums in output.  It will throw KeyError if the reverse mapping doesn't exist.  With the first example:Before PEP 435, Python didn't have an equivalent but you could implement your own.Myself, I like keeping it simple (I've seen some horribly complex examples on the net), something like this ...In Python 3.4 (), you can make Enum the base class.  This gets you a little bit of extra functionality, described in the PEP.  For example, enum values are distinct from integers.If you don't want to type the values, use the following shortcut:Here is one implementation:Here is its usage:If you need the numeric values, here's the quickest way:In Python 3.x you can also add a starred placeholder at the end, which will soak up all the remaining values of the range in case you don't mind wasting memory and cannot count:The best solution for you would depend on what you require from your  .If you need the  as only a list of  identifying different , the solution by  (above) is great:Using a  also allows you to set any :In addition to the above, if you also require that the items belong to a  of some sort, then embed them in a class:To use the enum item, you would now need to use the container name and the item name:For long lists of enum or more complicated uses of enum, these solutions will not suffice. You could look to the recipe by Will Ware for  published in the . An online version of that is available . has the interesting details of a proposal for enum in Python and why it was rejected.The typesafe enum pattern which was used in Java pre-JDK 5 has a\nnumber of advantages. Much like in Alexandru's answer, you create a\nclass and class level fields are the enum values; however, the enum\nvalues are instances of the class rather than small integers. This has\nthe advantage that your enum values don't inadvertently compare equal\nto small integers, you can control how they're printed, add arbitrary\nmethods if that's useful and make assertions using isinstance:A recent  pointed out there are a couple of enum libraries in the wild, including:An Enum class can be a one-liner.How to use it (forward and reverse lookup, keys, values, items, etc.)Python doesn't have a built-in equivalent to , and other answers have ideas for implementing your own (you may also be interested in the  in the Python cookbook).However, in situations where an  would be called for in C, I usually end up : because of the way objects/attributes are implemented, (C)Python is optimized to work very fast with short strings anyway, so there wouldn't really be any performance benefit to using integers. To guard against typos / invalid values you can insert checks in selected places.(One disadvantage compared to using a class is that you lose the benefit of autocomplete)So, I agree. Let's not enforce type safety in Python, but I would like to protect myself from silly mistakes. So what do we think about this?It keeps me from value-collision in defining my enums.There's another handy advantage: really fast reverse lookups:Use it like this:  if you just want unique symbols and don't care about the values, replace this line:  with this:I prefer to define enums in Python like so:It's more bug-proof than using integers since you don't have to worry about ensuring that the integers are unique (e.g. if you said Dog = 1 and Cat = 1 you'd be screwed).It's more bug-proof than using strings since you don't have to worry about typos (e.g.\nx == \"catt\" fails silently, but x == Animal.Catt is a runtime exception).On 2013-05-10, Guido agreed to accept  into the Python 3.4 standard library. This means that Python finally has builtin support for enumerations!There is a backport available for Python 3.3, 3.2, 3.1, 2.7, 2.6, 2.5, and 2.4.  It's on Pypi as .Declaration:Representation:Iteration:Programmatic access:For more information, refer to . Official documentation will probably follow soon.Another, very simple, implementation of an enum in Python, using :or, alternatively,Like the method above that subclasses , this allows:But has more flexibility as it can have different keys and values. This allowsto act as is expected if you use the version that fills in sequential number values.Hmmm... I suppose the closest thing to an enum would be a dictionary, defined either like this:orThen, you can use the symbolic name for the constants like this:There are other options, like a list of tuples, or a tuple of tuples, but the dictionary is the only one that provides you with a \"symbolic\" (constant string) way to access the \nvalue.Edit: I like Alexandru's answer too!What I use:How to use:So this gives you integer constants like state.PUBLISHED and the two-tuples to use as choices in Django models.davidg recommends using dicts.  I'd go one step further and use sets:Now you can test whether a value matches one of the values in the set like this:like dF, though, I usually just use string constants in place of enums.This is the best one I have seen: \"First Class Enums in Python\"It gives you a class, and the class contains all the enums. The enums can be compared to each other, but don't have any particular value; you can't use them as an integer value. (I resisted this at first because I am used to C enums, which are integer values. But if you can't use it as an integer, you can't use it as an integer by mistake so overall I think it is a win.) Each enum is a unique value. You can print enums, you can iterate over them, you can test that an enum value is \"in\" the enum. It's pretty complete and slick.Edit (cfi): The above link is not Python 3 compatible. Here's my port of enum.py to Python 3:From Python 3.4 there will be official support for enums. You can find documentation and examples .I have had occasion to need of an Enum class, for the purpose of decoding a binary file format. The features I happened to want is concise enum definition, the ability to freely create instances of the enum by either integer value or string, and a useful esentation.  Here's what I ended up with:A whimsical example of using it:Key features:Keep it simple:Then:I really like Alec Thomas' solution (http://stackoverflow.com/a/1695250):It's elegant and clean looking, but it's just a function that creates a class with the specified attributes.With a little modification to the function, we can get it to act a little more 'enumy':This creates an enum based off a specified type. In addition to giving attribute access like the previous function, it behaves as you would expect an Enum to with respect to types.  It also inherits the base class.For example, integer enums:Another interesting thing that can be done with this method is customize specific behavior by overriding built-in methods:The new standard in Python is , so an Enum class will be available in future versions of Python:However to begin using it now you can install the  that motivated the PEP:Then you :If you name it, is your problem, but if not creating objects instead of values allows you to do this:When using other implementations sited here (also when using named instances in my example) you must be sure you never try to compare objects from different enums. For here's a possible pitfall:Yikes!Alexandru's suggestion of using class constants for enums works quite well. I also like to add a dictionary for each set of constants to lookup a human-readable string representation. This serves two purposes: a) it provides a simple way to pretty-print your enum and b) the dictionary logically groups the constants so that you can test for membership.The enum package from  provides a robust implementation of enums. An earlier answer mentioned PEP 354; this was rejected but the proposal was implemented \n.Usage is easy and elegant:This solution is a simple way of getting a class for the enumeration defined as a list (no more annoying integer assignments):enumeration.py:example.py:While the original enum proposal, , was rejected years ago, it keeps coming back up. Some kind of enum was intended to be added to 3.2, but it got pushed back to 3.3 and then forgotten. And now there's a  intended for inclusion in Python 3.4. The reference implementation of PEP 435 is .As of April 2013, there seems to be a general consensus that  should be added to the standard library in 3.4\u2014as long as people can agree on what that \"something\" should be. That's the hard part. See the threads starting  and , and a half dozen other threads in the early months of 2013.Meanwhile, every time this comes up, a slew of new designs and implementations appear on PyPI, ActiveState, etc., so if you don't like the FLUFL design, try a .Here's an approach with some different characteristics I find valuable:and most importantly !Based closely on .Many doctests included here to illustrate what's different about this approach.I had need of some symbolic constants in pyparsing to represent left and right associativity of binary operators.  I used class constants like this:Now when client code wants to use these constants, they can import the entire enum using:The enumerations are unique, they can be tested with 'is' instead of '==', they don't take up a big footprint in my code for a minor concept, and they are easily imported into the client code.  They don't support any fancy str() behavior, but so far that is in the  category.Here is a variant on :
Python

I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.I was looking for something useful in  but I couldn't find anything obviously useful. Might've missed it, though.Related question: Here's a generator that yields the chunks you want:If you're using Python 2, you should use  instead of :Also you can simply use list comprehension instead of write a function. Python 3:Python 2 version:If you want something super simple:Directly from the (old) Python documentation (recipes for itertools):The current version, as suggested by J.F.Sebastian:I guess Guido's time machine works\u2014worked\u2014will work\u2014will have worked\u2014was working again.These solutions work because  (or the equivalent in the earlier version) creates  iterator, repeated  times in the list.  then effectively performs a round-robin of \"each\" iterator; because this is the same iterator, it is advanced by each such call, resulting in each such zip-roundrobin generating one tuple of  items.Here is a generator that work on arbitrary iterables:Example:I know this is kind of old but I don't why nobody mentioned :I'm surprised nobody has thought of using 's :Demo:This works with any iterable and produces output lazily. It returns tuples rather than iterators, but I think it has a certain elegance nonetheless. It also doesn't pad; if you want padding, a simple variation on the above will suffice:Demo:Like the -based solutions, the above  pads. As far as I know, there's no one- or two-line itertools recipe for a function that  pads. By combining the above two approaches, this one comes pretty close:Demo:I believe this is the shortest chunker proposed that offers optional padding. Simple yet elegantor if you prefer:I saw the most awesome Python-ish answer in a  of this question:You can create n-tuple for any n.It also has a lot more things, including all the recipes in the itertools documentation.None of these answers are evenly sized chunks, they all leave a runt chunk at the end, so they're not completely balanced. If you were using these functions to distribute work, you've built-in the prospect of one likely finishing well before the others, so it would sit around doing nothing while the others continued working hard.For example, the current top answer ends with:I just hate that runt at the end!Others, like , and  both return: . The 's are just padding, and rather inelegant in my opinion. They are NOT evenly chunking the iterables.Why can't we divide these better?Here's a balanced solution, adapted from a function I've used in production (Note in Python 3 to replace  with ):And I created a generator that does the same if you put it into a list:And finally, since I see that all of the above functions return elements in a contiguous order (as they were given):To test them out:Which prints out:Notice that the contiguous generator provide chunks in the same length patterns as the other two, but the items are all in order, and they are as evenly divided as one may divide a list of discrete elements.If you had a chunk size of 3 for example, you could do:source:\nI would use this when my chunk size is fixed number I can type, e.g. '3', and would never change.A generator expression:eg.I like the Python doc's version proposed by tzot and J.F.Sebastian a lot,\n but it has two shortcomings:I'm using this one a lot in my code:UPDATE: A lazy chunks version:If you know list size:If you don't (an iterator):In the latter case, it can be rephrased in a more beautiful way if you can be sure that the sequence always contains a whole number of chunks of given size (i.e. there is no incomplete last chunk).The  library has the  function for this:At this point, I think we need a , just in case...In python 2:In python 3:Also, in case of massive Alien invasion, a  might become handy:usage:Where AA is array, SS is chunk size. For example:You may also use  function of  library as:You can install  via pip:.Consider using  piecesfor example:Another more explicit version.code:result:heh, one line versionI realise this question is old (stumbled over it on Google), but surely something like the following is far simpler and clearer than any of the huge complex suggestions and only uses slicing:See Python3If you are into brackets - I picked up a book on Erlang :)
Python

How do I concatenate two lists in Python?Example:Expected outcome:Python makes this ridiculously easy.It's also possible to create a generator that simply iterates over the items in both lists.  This allows you to chain lists (or any iterable) together for processing without copying the items to a new list:You can use sets to obtain merged list of unique valuesYou could also use  in order to add a  add the end of another one:This is quite simple, I think it was even shown in the :You could simply use the  or  operator as follows:Or:Also, if you want the values in the merged list to be unique you can do:Even though this is an old answer, another alternative has been introduced via the acceptance of  which deserves mentioning. The PEP, titled , generally reduced some syntactic restrictions when using the starred  expression in Python; with it, joining two lists (applies to any iterable) can now also be done with:This functionality ; from testing it in  I don't belive it has been backported to previous versions in the  family. In unsupported versions a  is going to be raised.The  to this approach is that you really don't need lists in order to perform it, anything that is iterable will do. As stated in the PEP:So while addition with  would raise a  due to type mismatch:The following won't:because it will first unpack the contents of the iterables and then simply create a  from the contents.It's worth noting that the  function accepts variable number of arguments:If an iterable (tuple, list, generator, etc.) is the input, the  class method may be used:This question directly asks about joining two lists. However it's pretty high in search even when you are looking for a way of joining many lists (including the case when you joining zero lists). Consider this more generic approach:Will output:Note, this also works correctly when  is  or .Consider better alternative suggested by Patrick Collins in the comments:With Python 3.3+ you can use :Or, if you want to support an arbitrary number of iterators:If you want to merge the two lists in sorted form, you can use merge function from the heapq library.If you don't want to or can't use the plus operator (), you can uses the   function:If you need to merge two ordered lists with complicated sorting rules, you might have to roll it yourself like in the following code (using a simple sorting rule for readability :-) ).As a more general way for more lists you can put them within a list and use  function which based on  answer is the best way for flatting a nested list :Joining two lists in Python:If you don't want any duplication:You could use the  method defined on  objects: The above code, does not preserve order, removes duplicate from each list (but not from the concatenated list)Yes, it's that simple.. This gives a new list that is the concatenation of  and .As already pointed out by many,  is the way to go if one needs to apply  to both lists. In my case, I had a label and a flag which were different from one list to the other, so I needed something slightly more complex. As it turns out, behind the scenes  simply does the following:(see ), so I took inspiration from here and wrote something along these lines:The main points to understand here are that lists are just a special case of iterable, which are objects like any other; and that  loops in python can work with tuple variables, so it is simple to loop on multiple variables at the same time. lst1 = [1,2]lst2 = [3,4]def list_combinationer(Bushisms, are_funny):list_combinationer(lst1, lst2)[1,2,3,4]you just take the values of the first and second and  add them to one variable. if I:I will have:If you wanted a new list whilst keeping the two old lists:
Python

I spent most of the day yesterday searching for a clear answer for installing  (package manager for Python). I can't find a good solution.How do I install it?All you need to do isYou can install it through Homebrew on OS X.  Why would you install Python with Homebrew?Homebrew is something of a package manager for OS X.  Find more details on the .  Once Homebrew is installed, run the following to install the latest Python, Pip & Setuptools:: All you have to do is:MacOS comes with  installed. But to make sure that you have  installed open the terminal and run the following command.If this command returns a version number that means  exists. That also means you already have access to  considering you are using .\u2139\ufe0f Now, all you have to do is run the following command.After that,  will be installed and you'll be able to use it for installing other packages.Let me know if you have any problems installing  this way.Complimentary GIF.Cheers! On Mac: is available on OS X via .\nOpen a terminal and type:When prompted for a password enter your normal login password.\nAfter the installation has completed you should be able to use  as expected.   The simplest solution is to follow the .Basically, this consists in:The main advantage of that solution is that it install pip for the python version that has been used to run , which means that if you use the default OS X installation of python to run  you will install pip for the python install from the system.Most solutions that use a package manager (homebrew or macport) on OS X create a redundant installation of python in the environment of the package manager which can create inconsistencies in your system since, depending on what you are doing, you may call one installation of python instead of another.I'm surprised no-one has mentioned this - it's a built-in way to install pip, without external tools or scripts:Works in pretty much the same way as , but worth knowing anyway.Installing a separate copy of Python is a popular option, even though Python already comes with MacOS. You take on the responsibility to make sure you're using the copy of Python you intend. But, the benefits are having the latest Python release and some protection from hosing your system if things go badly wrong.To install Python using :Now confirm that we're working with our newly installed Python:...should show a symbolic link to a path with \"Cellar\" in it like:Pip should be installed along with Python. You might want to upgrade it by typing:Now you're ready to install any of the 50,000+ packages on .Formerly, I've used . But, the docs warn that get-pip.py does not coordinate with package managers and may leave your system in an inconsistent state. Anyway, there's no need, given that pip is now .Note that pip isn't the only package manager for Python. There's also easy_install. It's no good to mix the two, so don't do it.Finally, if you have both Python 2 and 3 installed,  will point to whichever Python you installed last. Get in the habit of explicitly using either  or , so you're sure which Python is getting the new library.Happy hacking!You should install Brew first:Then brew install PythonThen  will workNEW 2016 December: This worked for me on  (El Capitan):Mac comes with , but not with pip.Requirements:With this I got these errors (but I've solved them in step 3):The directory  or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want .The directory  or its parent directory is not owned by the current user and caching wheels has been disabled. Check the permissions and owner of that directory. If executing pip with sudo, you may want .Finally you can install an app like:: If you install , pip will be installed automatically.You need only to upgrade pip, but before that you need create a virtual environment to work with Python 3. You can use a project folder or any folder:Check the versions:To deactivate the environment:Download this file: Then simply typeMake sure you are on the same directory as get-pip.py or you supply the correct path for that file.For details, you can visit: or,  Then update your PATH to include py27-pip bin directory (you can add this in ~/.bash_profile\nPATH=/opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin:$PATHpip will be available in new terminal window.To install or upgrade , download  from Then run the following:\nFor example:Download python setup tools from the below website:Use the tar file.Once you download, go to the downloaded folder and run Once you do that,you will have easy_install.Use the below then to install pip:Install python3 first, then use pip3 to install packages.python3 will be installed, and pip is shipped with it. To use pip to install some package, run the followingNotice it's pip3 because you want to use python3.I recommend Anaconda to you. It`s the leading open data science platform powered by Python. There are many basic packages installed. 
Python

I happened to find myself having a basic filtering need: I have a list and I have to filter it by an attribute of the items.My code looked like this:But then I thought, wouldn't it be better to write it like this?It's more readable, and if needed for performance the lambda could be taken out to gain something.  Question is: are there any caveats in using the second way? Any performance difference? Am I missing the Pythonic Way\u2122 entirely and should do it in yet another way (such as using itemgetter instead of the lambda)?It is strange how much beauty varies for different people. I find the list comprehension much clearer than the ugly +, but use whichever you find easier. However, do stop giving your variables names already used for builtins, that's just ugly, and not open for discussion.There are two things that may slow down your use of .The first is the function call overhead: as soon as you use a Python function (whether created by  or ) it is likely that filter will be slower than the list comprehension. It almost certainly is not enough to matter, and you shouldn't think much about performance until you've timed your code and found it to be a bottleneck, but the difference will be there.The other overhead that might apply is that the lambda is being forced to access a scoped variable (). That is slower than accessing a local variable and in Python 2.x the list comprehension only accesses local variables. If you are using Python 3.x the list comprehension runs in a separate function so it will also be accessing  through a closure and this difference won't apply.The other option to consider is to use a generator instead of a list comprehension:Then in your main code (which is where readability really matters) you've replaced both list comprehension and filter with a hopefully meaningful function name.This is a somewhat religious issue in Python. Even though , there was enough of a backlash that in the end only  was moved from built-ins to .Personally I find list comprehensions easier to read. It is more explicit what is happening from the expression  as all the behaviour is on the surface not inside the filter function.I would not worry too much about the performance difference between the two approaches as it is marginal. I would really only optimise this if it proved to be the bottleneck in your application which is unlikely.Also since the  wanted  gone from the language then surely that automatically makes list comprehensions more Pythonic ;-)Since any speed difference is bound to be miniscule, whether to use filters or list comprehensions comes down to a matter of taste. In general I'm inclined to use comprehensions (which seems to agree with most other answers here), but there is one case where I prefer . A very frequent use case is pulling out the values of some iterable X subject to a predicate P(x):but sometimes you want to apply some function to the values first:\nAs a specific example, considerI think this looks slightly better than using . But now considerIn this case we want to  against the post-computed value. Besides the issue of computing the cube twice (imagine a more expensive calculation), there is the issue of writing the expression twice, violating the  aesthetic. In this case I'd be apt to useAlthough  may be the \"faster way\", the \"Pythonic way\" would be not to care about such things unless performance is absolutely critical (in which case you wouldn't be using Python!).I find the second way more readable. It tells you exactly what the intention is: filter the list.\nPS: do not use 'list' as a variable nameAn important difference is that list comprehension will return a  while the filter returns a , which you cannot manipulate like a  (ie: call  on it, which does not work with the return of ).My own self-learning brought me to some similar issue.That being said, if there is a way to have the resulting  from a , a bit like you would do in .NET when you do , I am curious to know it.EDIT: This is the case for Python 3, not 2 (see discussion in comments). is just that. It filters out the elements of a list. You can see the definition mentions the same(in the official docs link I mentioned before). Whereas, list comprehension is something that produces a new list after acting upon  on the previous list.(Both filter and list comprehension creates new list and not perform operation in place of the older list. A new list here is something like a list with, say, an entirely new data type. Like converting integers to string ,etc)In your example, it is better to use filter than list comprehension, as per the definition. However, if you want, say other_attribute from the list elements, in your example is to be retrieved as a new list, then you can use list comprehension.This is how I actually remember about filter and list comprehension. Remove a few things within a list and keep the other elements intact, use filter. Use some logic on your own at the elements and create a watered down list suitable for some purpose, use list comprehension.generally  is slightly faster if using a builtin function.I would expect the list comprehension to be slightly faster in your case Here's a short piece I use when I need to filter on something  the list comprehension.  Just a combination of filter, lambda, and lists (otherwise known as the loyalty of a cat and the cleanliness of a dog).In this case I'm reading a file, stripping out blank lines, commented out lines, and anything after a comment on a line:I thought I'd just add that in python 3, filter() is actually an iterator object, so you'd have to pass your filter method call to list() in order to build the filtered list. So in python 2:lists b and c have the same values, and were completed in about the same time as filter() was equivalent [x for x in y if z]. However, in 3, this same code would leave list c containing a filter object, not a filtered list. To produce the same values in 3:The problem is that list() takes an iterable as it's argument, and creates a new list from that argument. The result is that using filter in this way in python 3 takes up to twice as long as the [x for x in y if z] method because you have to iterate over the output from filter() as well as the original list. My take
Python

Reading the , I found something... unexpected:I never heard about named tuples before, and I thought elements could either be indexed by numbers (like in tuples and lists) or by keys (like in dicts). I never expected they could be indexed both ways.Thus, my questions are:Named tuples are basically easy-to-create, lightweight object types.  Named tuple instances can be referenced using object-like variable dereferencing or the standard tuple syntax.  They can be used similarly to  or other common record types, except that they are immutable.  They were added in Python 2.6 and Python 3.0, although there is a .For example, it is common to represent a point as a tuple .  This leads to code like the following:Using a named tuple it becomes more readable:However, named tuples are still backwards compatible with normal tuples, so the following will still work:Thus, .  I personally have started using them to represent very simple value types, particularly when passing them as parameters to functions.  It makes the functions more readable, without seeing the context of the tuple packing.Furthermore, , only fields with them.  You can even use your named tuple types as base classes:However, as with tuples, attributes in named tuples are immutable:If you want to be able change the values, you need another type.  There is a handy recipe for  which allow you to set new values to attributes.I am not aware of any form of \"named list\" that lets you add new fields, however.  You may just want to use a dictionary in this situation. Named tuples can be converted to dictionaries using  which returns  and can be operated upon with all the usual dictionary functions.  As already noted, you should  for more information from which these examples were constructed. is a  for making a tuple class. With that class we can create tuples that are callable by name also.namedtuples are a great feature, they are perfect container for data. When you have to \"store\" data you would use tuples or dictionaries, like:or:The dictionary approach is overwhelming, since dict are mutable and slower than tuples. On the other hand, the tuples are immutable and lightweight but lack readability for a great number of entries in the data fields.namedtuples are the perfect compromise for the two approaches, the have great readability, lightweightness and immutability (plus they are polymorphic!).named tuples allow backward compatibility with code that checks for the version like thiswhile allowing future code to be more explicit by using this syntaxTo understand named tuples, you first need to know what a tuple is. A tuple is essentially an immutable (can't be changed in-place in memory) list.Here's how you might use a regular tuple:You can expand a tuple with iterable unpacking:Named tuples are tuples that allow their elements to be accessed by name instead of just index! You make a namedtuple like this:You can also use a single string with the names separated by spaces, a slightly more readable use of the API:You can do everything tuples can do (see above) as well as do the following:Use them when it improves your code to have the semantics of tuple elements expressed in your code. You can use them instead of an object if you would otherwise use an object with unchanging data attributes and no functionality. You can also :It would probably be a regression to switch from using named tuples to tuples. The upfront design decision centers around whether the cost from the extra code involved is worth the improved readability when the tuple is used. There is no extra memory used by named tuples versus tuples. You're looking for either a slotted object that implements all of the functionality of a statically sized list or a subclassed list that works like a named tuple (and that somehow blocks the list from changing in size.) An incomplete example of the first:And usage:What is namedtuple ?As the name suggests, namedtuple is a tuple with name.  In standard tuple, we access the elements using the index, whereas namedtuple allows user to define name for elements.  This is very handy especially processing csv (comma separated value) files and working with complex and large dataset, where the code becomes messy with the use of indices (not so pythonic).How to use them ?Reading Interesting Scenario in CSV Processing :In Python inside there is a good use of container called a named tuple, it can be used to create a definition of class and has all the features of the original tuple.Using named tuple will be directly applied to the default class template to generate a simple class, this method allows a lot of code to improve readability and it is also very convenient when defining a class.is one of the easiest ways to clean up your code and make it more readable. It self-documents what is happening in the tuple. Namedtuples instances are just as memory efficient as regular tuples as they do not have per-instance dictionaries, making them faster than dictionaries. Without naming each element in the tuple, it would read like this:It is so much harder to understand what is going on in the first example. With a namedtuple, each field has a name. And you access it by name rather than position or index. Instead of , we can call it p.saturation. It's easier to understand. And it looks cleaner.Creating an instance of the namedtuple is easier than creating a dictionary.You can still access namedtuples by their position, if you so choose. . It still unpacks like a regular tuple.All the  are supported. Ex: min(), max(), len(), in, not in, concatenation (+), index, slice, etc. And there are a few additional ones for namedtuple. Note: these all start with an underscore. , , .\nReturns a new instance of the named tuple replacing specified fields with new values.: The field names are not in quotes; they are keywords here.\n: Tuples are immutable - even if they are namedtuples and have the  method. The  produces a  instance; it does not modify the original or replace the old value. You can of course save the new result to the variable. Makes a new instance from an existing sequence or iterable.What happened with the last one? The item inside the parenthesis should be the iterable. So a list or tuple inside the parenthesis works, but the sequence of values without enclosing as an iterable returns an error.Returns a new  which maps field names to their corresponding values.: There is also named list which is similar to named tuple but mutable\n
Python

How do I remove leading and trailing whitespace from a string in Python?For example:Just one space, or all such spaces?  If the second, then strings already have a  method:If you need only to remove one space however, you could do it with:Also, note that  removes other whitespace characters as well (e.g. tabs and newlines).  To remove only spaces, you can specify the character to remove as an argument to , i.e.:As pointed out in answers above will remove all the leading and trailing whitespace characters such as \\n, \\r, \\t, \\f, space.For more flexibility use the followingMore details are available in the  is not limited to whitespace characters either:You want strip():
Python

When trying to delete a key from a dictionary, I write:Is there a one line way of doing this?Use :This will return  if  exists in the dictionary, and  otherwise. If the second parameter is not specified (ie. ) and  does not exist, a  is raised.Specifically to answer \"is there a one line way of doing this?\"...well, you  ;-)You should consider, though, that this way of deleting an object from a  is \u2014it is possible that  may be in  during the  statement, but may be deleted before  is executed, in which case  will fail with a .  Given this, it would be safest to either  or something along the lines ofwhich, of course, is definitely  a one-liner.It took me some time to figure out what exactly  is doing. So I'll add this as an answer to save others googling time:If you need to remove a lot of keys from a dictionary in one line of code, I think using map() is quite succinct and pythonic readable: And if you need to catch errors where you pop a value that isn't in the dictionary, use lambda inside map() like this:Works. and 'e' did not cause an error, even there myDict did not have an 'e' key.Timing of the three solutions described above.Small dictionary:Larger dictionary:Another way You can delete by conditions.\nNo error if key doesn't exist
Python

According to the documentation, they're pretty much interchangeable.  Is there a stylistic reason to use one over the other?I like to use double quotes around strings that are used for interpolation or that are natural language messages, and single quotes for small symbol-like strings, but will break the rules if the strings contain quotes, or if I forget. I use triple double quotes for docstrings and raw string literals for regular expressions even if they aren't needed.For example:Quoting the official docs at :So there is no difference. Instead, people will tell you to choose whichever style that matches the context, . And I would agree - adding that it is pointless to try to come up with \"conventions\" for this sort of thing because you'll only end up confusing any newcomers.I used to prefer , especially for , as I find . Also,  can be typed without the  key on my Swiss German keyboard.I have since changed to using triple quotes for , to conform to .I'm with Will: I'll stick with that even if it means a lot of escaping. I get the most value out of single quoted identifiers standing out because of the quotes. The rest of the practices are there just to give those single quoted identifiers some standing room. If the string you have contains one, then you should use the other.  For example, , or .  Other than that, you should simply be as consistent as you can (within a module, within a package, within a project, within an organisation).If your code is going to be read by people who work with C/C++ (or if you switch between those languages and Python), then using  for single-character strings, and  for longer strings might help ease the transition.  (Likewise for following other languages where they are not interchangeable).The Python code I've seen in the wild tends to favour  over , but only slightly.  The one exception is that  are much more common than , from what I have seen.Triple quoted comments are an interesting subtopic of this question. . I did a quick check using Google Code Search and found that  are about 10x as popular as  -- 1.3M vs 131K occurrences in the code Google indexes. So in the multi line case your code is probably going to be more familiar to people if it uses triple double quotes.For that simple reason, I always use double quotes on the outside. Speaking of fluff, what good is streamlining your string literals with ' if you're going to have to use escape characters to represent apostrophes? Does it offend coders to read novels? I can't imagine how painful high school English class was for you!Python uses quotes something like this:Which gives the following output:I use double quotes in general, but not for any specific reason - Probably just out of habit from Java.I guess you're also more likely to want apostrophes in an inline literal string than you are to want double quotes.Personally I stick with one or the other. It doesn't matter. And providing your own meaning to either quote is just to confuse other people when you collaborate.It's probably a stylistic preference more than anything.  I just checked PEP 8 and didn't see any mention of single versus double quotes.I prefer single quotes because its only one keystroke instead of two.  That is, I don't have to mash the shift key to make single quote.PHP makes the same distinction as Perl: content in single quotes will not be interpreted (not even \\n will be converted), as opposed to double quotes which can contain variables to have their value printed out.Python does not, I'm afraid. Technically seen, there is no $ token (or the like) to separate a name/text from a variable in Python. Both features make Python more readable, less confusing, after all. Single and double quotes can be used interchangeably in Python.I chose to use double quotes because they are easier to see.I just use whatever strikes my fancy at the time; it's convenient to be able to switch between the two at a whim!Of course, when quoting quote characetrs, switching between the two might not be so whimsical after all...Your team's taste or your project's coding guidelines.If you are in a multilanguage environment, you might wish to encourage the use of the same type of quotes for strings that the other language uses, for instance. Else, I personally like best the look of 'None as far as I know. Although if you look at some code, \" \" is commonly used for strings of text (I guess ' is more common inside text than \"), and ' ' appears in hashkeys and things like that.I aim to minimize both pixels and surprise. I typically prefer  in order to minimize pixels, but  instead if the string has an apostrophe, again to minimize pixels. For a docstring, however, I prefer  over  because the latter is non-standard, uncommon, and therefore surprising. If now I have a bunch of strings where I used  per the above logic, but also one that can get away with a , I may still use  in it to preserve consistency, only to minimize surprise.Perhaps it helps to think of the pixel minimization philosophy in the following way. Would you rather that English characters looked like  or ? The latter choice wastes 50% of the non-empty pixels.I use double quotes because I have been doing so for years in most languages (C++, Java, VB\u2026) except Bash, because I also use double quotes in normal text and because I'm using a (modified) non-English keyboard where both characters require the shift key. =  =  = example :  Results are the same=>> no, they're not the same.\nA single backslash will escape characters. You just happen to luck out in that example because  and  aren't valid escapes like  or  or  or If you want to use single backslashes (and have them interpreted as such), then you need to use a \"raw\" string. You can do this by putting an '' in front of the stringAs far as paths in Windows are concerned, forward slashes are interpreted the same way. Clearly the string itself is different though. I wouldn't guarantee that they're handled this way on an external device though.
Python

What is the difference between old style and new style classes in Python?  Is there ever a reason to use old-style classes these days?From  :New-style classes inherit from object, or from another new-style class.Old-style classes don't.It was mentioned in other answers, but here goes a concrete example of the difference between classic MRO and C3 MRO (used in new style classes).The question is the order in which attributes (which include methods and member variables) are searched for in multiple inheritance. do a depth first search from left to right. Stop on first match. They do not have the  attribute. MRO is more complicated to synthesize in a single English sentence. It is explained in detail . One of its properties is that a Base class is only searched for once all its Derived classes have been. They have the  attribute which shows the search order. Around Python 2.5 many classes could be raised, around Python 2.6 this was removed. On Python 2.7.3:Old style classes are still marginally faster for attribute lookup. This is not usually important, but may be useful in performance-sensitive Python 2.x code:Guido has written , a really great article about new-style and old-style class in Python.Python 3 has only new-style class, even if you write an 'old-style class', it is implicitly derived from .New-style classes have some advanced features lacking in old-style classes, such as  and the new , some magical methods, etc.Here's a very practical, True/False difference. The only difference between the two versions of the following code is that in the second version Person inherits from object. Other than that the two versions are identical, but with different results :1) old-style classes2) new-style classes New-style classes inherit from  and must be written as such in Python 2.2 onwards (i.e.  instead of ). The core change is to unify types and classes, and the nice side-effect of this is that it allows you to inherit from built-in types.Read  for more details.Or rather, you should always use new-style classes,  you have code that needs to work with versions of Python older than 2.2.New style classes may use  where  is a class and  is the instance.And in Python 3.x you can simply use  inside a class with no parameters.
Python

Is there a function that will trim not only spaces for whitespace, but also tabs?Whitespace on both sides:Whitespace on the right side:Whitespace on the left side:As  points out, you can provide an argument to strip arbitrary characters to any of these functions like this:This will strip any space, , , or  characters from the left-hand side, right-hand side, or both sides of the string. The examples above only remove strings from the left-hand and right-hand sides of strings. If you want to also remove characters from the middle of a string, try :That should print out:Python  method is called :For leading and trailing whitespace:Otherwise, a regular expression works:You can also use very simple, and basic function: , works with the whitespaces and tabs:Simple and easy.No one has posted these regex solutions yet.Matching:Searching (you have to handle the \"only spaces\" input case differently):If you use , you may remove inner whitespace, which could be undesirable.Whitespace includes . So an elegant and  string function we can use is .  if you want to be thoroughoutput:\n  please_remove_all_whitespacestry translateGenerally, I am using the following method:Note: This is only for removing \"\\n\", \"\\r\" and \"\\t\" only. It does not remove extra spaces.To remove , , , the better way is:Output:This is the easiest way to remove the above characters.\nIf any python package or library is available, then please let me know and also suggest how to remove character/??, occurs due to pressing Enter.
Python

I have this JSON in a file:I wrote this script which prints all of the json text:How can I parse the file and extract single values?I think what Ignacio is saying is that your JSON file is incorrect. You have  when you should have .  are for lists,  are for dictionaries.Here's how your JSON file should look, your JSON file wouldn't even load for me:Then you can use your code:With data, you can now also find values like so:Try those out and see if it starts to make sense.Your  should look like this:Your code should be:Note that this only works in Python 2.6 and up, as it depends upon the . In Python 2.5 use , in Python <= 2.4, see , which this answer is based upon.You can now also access single values like this:@Justin Peel's answer is really helpful, but if you are using Python 3 reading JSON should be done like this:Note: use  instead of . In Python 3,  takes a string parameter.  takes a file-like object parameter.  returns a string object.\"Ultra JSON\" or simply \"ujson\" can handle having  in your JSON file input. If you're reading a JSON input file into your program as a list of JSON elements; such as,  ujson can handle any arbitrary order of lists of dictionaries, dictionaries of lists. You can find ujson in the  and the API is almost identical to Python's built-in  library. ujson is also much more faster if you're loading larger JSON files. You can see the performance details in comparison to other Python JSON libraries in the same link provided.if you are in python 3 here is how you can do itThe code should look like assuming connection.json file looks like above
Python

I'm building a web application with Django. The reasons I chose Django were:Now that I'm getting closer to thinking about publishing my work, I start being concerned about scale. The only information I found about the scaling capabilities of Django is provided by the Django team (I'm not saying anything to disregard them, but this is clearly not objective information...).My questions:There are, of course, many more sites and bloggers of interest, but I have got to stop somewhere!Blog post about  described as a .   and .We're doing load testing now.  We think we can support 240 concurrent requests (a sustained rate of 120 hits per second 24x7) without any significant degradation in the server performance.  That would be 432,000 hits per hour.  Response times aren't small (our transactions are large) but there's no degradation from our baseline performance as the load increases.We're using Apache front-ending Django and MySQL.  The OS is Red Hat Enterprise Linux (RHEL).  64-bit.  We use mod_wsgi in daemon mode for Django.  We've done no cache or database optimization other than to accept the defaults.  We're all in one VM on a 64-bit Dell with (I think) 32Gb RAM. Since performance is almost the same for 20 or 200 concurrent users, we don't need to spend huge amounts of time \"tweaking\".  Instead we simply need to keep our base performance up through ordinary SSL performance improvements, ordinary database design and implementation (indexing, etc.), ordinary firewall performance improvements, etc.What we do measure is our load test laptops struggling under the insane workload of 15 processes running 16 concurrent threads of requests.Not sure about the number of daily visits but here are a few examples of large Django sites:Screencast on how to deploy django with scaling in mind Here is a link to list of .In the US, . I'm told they handle roughly 10 million uniques a month. Abroad, the  network (a network of news, sports, and entertainment sites in Brazil); Alexa ranks them in to top 100 globally (around 80th currently).Other notable Django users include PBS, National Geographic, Discovery, NASA (actually a number of different divisions within NASA), and the Library of Congress.Yes -- but only if you've written your application right, and if you've got enough hardware. Django's not a magic bullet.Yes (but see above).Technology-wise, easily: see  for one attempt. Traffic-wise, compete pegs StackOverflow at under 1 million uniques per month. I can name at least dozen Django sites with more traffic than SO.Playing devil's advocate a little bit:You should check the , delivered by , titled \"Why I hate Django\" where he pretty much goes over everything Django is missing that you might want to do in a high traffic website. At the end of the day you have to take this all with an open mind because it  perfectly possible to write Django apps that scale, but I thought it was a good presentation and relevant to your question.The largest django site I know of is the , which would certainly indicate that it  scale well.Good design decisions probably have a bigger performance impact than anything else. Twitter is often cited as a site which embodies the performance issues with another dynamic interpreted language based web framework, Ruby on Rails - yet Twitter engineers have stated that the framework isn't as much an issue as some of the database design choices they made early on. Django works very nicely with memcached and provides some classes for managing the cache, which is where you would resolve the majority of your performance issues. What you deliver on the wire is almost more important than your backend in reality - using a tool like yslow is critical for a high performance web application. You can always throw more hardware at your backend, but you can't change your users bandwidth.Scaling Web apps is not about web frameworks or languages, is about your architecture.\nIt's about how you handle you browser cache, your database cache, how you use non-standard persistence providers (like ), how tuned is your database and a lot of other stuff...Don't bother...I was at the EuroDjangoCon conference the other week, and this was the subject of a couple of talks - including from the founders of what was the largest Django-based site, Pownce (slides from one talk ). The main message is that it's not Django you have to worry about, but things like proper caching, load balancing, database optimisation, etc.Django actually has hooks for most of those things - caching, in particular, is made very easy.I'm sure you're looking for a more solid answer, but the most obvious objective validation I can think of is that Google pushes Django for use with its  framework. If anybody knows about and deals with scalability on a regular basis, it's Google. From what I've read, the most limiting factor seems to be the database back-end, which is why Google uses their own...I think we might as well add Apple's App of the year for 2011, , to the list which uses django intensively.Chinese version of Stack Overflow is using Django: If you haven't already, I recommend reading the section on scaling in The Django Book:Or the newer version:Yes it can. It could be Django with Python or Ruby on Rails. It will still scale. There are few different techniques. First, caching is not scaling. You could have several application servers balanced with nginx as the front in addition to hardware balancer(s).\nTo scale on the database side you can go pretty far with read slave in MySQL / PostgreSQL if you go the RDBMS way.Some good examples of heavy traffic websites in Django could be:You can feel safe.Today we use many web apps and sites for our needs. Most of them are highly useful. I will show you some of them used by python or django.The Washington Post\u2019s website is a hugely popular online news source to accompany their daily paper. Its\u2019 huge amount of views and traffic can be easily handled by the Django web framework.\nThe National Aeronautics and Space Administration\u2019s official website is the place to find news, pictures, and videos about their ongoing space exploration. This Django website can easily handle huge amounts of views and traffic.\nThe Guardian is a British news and media website owned by the Guardian Media Group. It contains nearly all of the content of the newspapers The Guardian and The Observer. This huge data is handled by Django.\nWe all know YouTube as the place to upload cat videos and fails. As one of the most popular websites in existence, it provides us with endless hours of video entertainment. The Python programming language powers it and the features we love.DropBox started the online document storing revolution that has become part of daily life. We now store almost everything in the cloud. Dropbox allows us to store, sync, and share almost anything using the power of Python.Survey Monkey is the largest online survey company. They can handle over one million responses every day on their rewritten Python website.Quora is the number one place online to ask a question and receive answers from a community of individuals. On their Python website relevant results are answered, edited, and organized by these community members.A majority of the code for Bitly URL shortening services and analytics are all built with Python. Their service can handle hundreds of millions of events per day.Reddit is known as the front page of the internet. It is the place online to find information or entertainment based on thousands of different categories. Posts and links are user generated and are promoted to the top through votes. Many of Reddit\u2019s capabilities rely on Python for their functionality.Hipmunk is an online consumer travel site that compares the top travel sites to find you the best deals. This Python website\u2019s tools allow you to find the cheapest hotels and flights for your destination.Click here for more: \n, \nHere's a list of some relatively high-profile things built in Django:I imagine a number of these these sites probably gets well over 100k+ hits per day. Django can certainly do 100k hits/day and more. But YMMV in getting your particular site there depending on what you're building.There are caching options at the Django level (for example caching querysets and views in  can work wonders) and beyond (upstream caches like ). Database Server specifications will also be a factor (and usually the place to splurge), as is how well you've tuned it. Don't assume, for example, that Django's going set up indexes properly. Don't assume that the default  or  configuration is the right one.Furthermore, you always have the option of having multiple application servers running Django if that is the slow point, with a software or hardware load balancer in front.Finally, are you serving static content on the same server as Django? Are you using Apache or something like  or ? Can you afford to use a  for static content? These are things to think about, but it's all very speculative. 100k hits/day isn't the only variable: how much do you want to spend? How much expertise do you have managing all these components? How much time do you have to pull it all together?Note that if you're expecting 100K users per day, that are active for hours at a time (meaning max of 20K+ concurrent users), you're going to need A LOT of servers.  SO has ~15,000 registered users, and most of them are probably not active daily.  While the bulk of traffic comes from unregistered users, I'm guessing that very few of them stay on the site more than a couple minutes (i.e. they follow google search results then leave).  For that volume, expect at least 30 servers ... which is still a rather heavy 1,000 concurrent users per server.Another example is rasp.yandex.ru, Russian transport timetable service. Its attendance satisfies your requirements.I have been using Django for over a year now, and am very impressed with how it manages to combine modularity, scalability and speed of development. Like with any technology, it comes with a learning curve. However, this learning curve is made a lot less steep by the excellent documentation from the Django community. Django has been able to handle everything I have thrown at it really well. It looks like it will be able to scale well into the future. is a moderately sized Django powered website. It is a very dynamic website and does handle a good number of page views a day. If you have a site with some static content, then putting a  server in front will dramatically increase your performance. Even a single box can then easily spit out 100 Mbit/s of traffic.Note that with dynamic content, using something like Varnish becomes a lot more tricky.The developer advocate for YouTube gave a , which is also relevant to scaling Django.YouTube has more than a , and YouTube is built on Python.My experience with Django is minimal but I do remember in The Django Book they have a chapter where they interview people running some of the larger Django applications.    I guess it could provide some insights.It says curse.com is one of the largest Django applications with around 60-90 million page views in a month.You can definitely run a high-traffic site in Django. Check out this pre-Django 1.0 but still relevant post here: Check out this micro news aggregator called .It's entirely written in Django. In fact they are the people who developed the Django  framework itself.If you want to use Open source then there are many options for you. But python is best among them it have many libraries and a super awesome community.\nThese are reasons which might change your mind:Conclusion is a framework or language won't do everything for you. A better architecture, designing and strategy will give you a scalable website. Instagram is biggest example,this small team is managing such huge data. Here is one  about its architecture must read it.As stated in High Performance Django Book  \n and Go through this See further details as mentioned below:It\u2019s not uncommon to hear people say \u201cDjango doesn\u2019t scale\u201d. Depending on how you look at it, the statement is either completely true or patently false. Django, on its own, doesn\u2019t scale.The same can be said of Ruby on Rails, Flask, PHP, or any other language used by a database-driven dynamic website.The good news, however, is that Django interacts beautifully with a suite of caching and\nload balancing tools that will allow it to scale to as much traffic as you can throw at it.Contrary to what you may have read online, \nit can do so without replacing core components often labeled as \u201ctoo slow\u201d such as the database ORM or the template layer.Disqus serves over 8 billion page views per month. Those are some huge numbers. These teams have proven Django most certainly does scale.\n Our experience here at Lincoln Loop backs it up.We\u2019ve built big Django sites capable of spending the day on the Reddit homepage without breaking a sweat.Django\u2019s scaling success stories are almost too numerous to list at this point.It backs Disqus, Instagram, and Pinterest. Want some more proof? Instagram was able to sustain over 30 million users on Django with only 3 engineers (2 of which had no back-end developmentEven-though there have been a lot of great answers here, I just feel like pointing out, that nobody have put emphasis on.. If you application is light on writes, as in you are reading a lot more data from the DB than you are writing. Then scaling django should be fairly trivial, heck, it comes with some fairly decent output/view caching straight out of the box. Make use of that, and say, redis as a cache provider, put a load balancer in front of it, spin up n-instances and you should be able to deal with a VERY large amount of traffic.Now, if you have to do thousands of complex writes a second? Different story. Is Django going to be a bad choice? Well, not necessarily, depends on how you architect your solution really, and also, what your requirements are.Just my two cents :-)Spreading the tasks evenly, in short optimizing each and every aspect including DBs, Files, Images, CSS etc. and balancing the load with several other resources is necessary once your site/application starts growing. OR you make some more space for it to grow. Implementation of latest technologies like CDN, Cloud are must with huge sites. Just developing and tweaking an application won't give your the cent percent satisfation, other components also play an important role.I develop high traffic sites using Django for the national broadcaster in Ireland. It works well for us. Developing a high performance site is more than about just choosing a framework. A framework will only be one part of a system that is as strong as it's weakest link. Using the latest framework 'X' won't solve your performance issues if the problem is slow database queries or a badly configured server or network.The problem is not to know if django can scale or not. The right way is to understand and know which are the network design patterns and tools to put under your django/symfony/rails project to scale well.Some ideas can be :Hope it help a bit. This is my tiny rock to the mountain.I don't think the issue is really about Django scaling. I really suggest you look into your architecture that's what is going to help you with you scaling needs.If you get that wrong there is not point on how well Django performs. Performance != Scale. You can have a system that has amazing performance but does not scale and vice versa.Is your application database bound? If it is then your scale issues lie there as well. How are you planning on interacting with the database from Django? What happens when you database cannot process requests as fast as Django accepts them? What happens when your data outgrows one physical machine. You need to account for how you plan on dealing with those circumstances.Moreover, What happens when your traffic outgrows one app server? how you handle sessions in this case can be tricky, more often than not you'd probably require a shared nothing architecture. Again that depends on your application.In short Languages is not what determines scale, a language is responsible for performance(again depending on your applications different languages perform differently). It is your design and architecture that makes scaling a reality. I hope it helps, would be glad to help further if you have questions.
Python

I'm using this code to get standard output from an external program:The communicate() method returns an array of bytes:However, I'd like to work with the output as a normal Python string. So that I could print it like this:I thought that's what the  method is for, but when I tried it, I got the same byte array again:Does anybody know how to convert the bytes value back to string? I mean, using the \"batteries\" instead of doing it manually. And I'd like it to be ok with Python 3.You need to decode the bytes object to produce a string:I think this way is easy:You need to decode the byte string and turn it in to a character (unicode) string. or If you don't know the encoding, then to read binary input into string in Python 3 and Python 2 compatible way, use ancient MS-DOS  encoding:Because encoding is unknown, expect non-English symbols to translate to characters of  (English chars are not translated, because they match in most single byte encodings and UTF-8).Decoding arbitrary binary input to UTF-8 is unsafe, because you may get this:The same applies to , which was popular (default?) for Python 2. See the missing points in  - it is where Python chokes with infamous .: There are rumors that Python 3 has  error strategy for encoding stuff into binary data without data loss and crashes, but it needs conversion tests  to validate both performance and reliability.: Thanks to comment by Nearoo - there is also a possibility to slash escape all unknown bytes with  error handler. That works only for Python 3, so even with this workaround you will still get inconsistent output from different Python versions:See  for details.: I decided to implement slash escaping decode that works for both Python 2 and Python 3. It should be slower that  solution, but it should produce  on every Python version.I think what you actually want is this:Aaron's answer was correct, except that you need to know WHICH encoding to use. And I believe that Windows uses 'windows-1252'. It will only matter if you have some unusual (non-ascii) characters in your content, but then it will make a difference.By the way, the fact that it DOES matter is the reason that Python moved to using two different types for binary and text data: it can't convert magically between them because it doesn't know the encoding unless you tell it! The only way YOU would know is to read the Windows documentation (or read it here).Set universal_newlines to True, i.e.In Python 3 you can use directly:which is equivalent tohere the default encoding is \"utf-8\", or you can check it by:While  just works, a user You can use has a To interpret a byte sequence as a text, you have to know the\ncorresponding character encoding:Example: command may produce output that can't be interpreted as text. File names\non Unix may be any sequence of bytes except slash  and zero\n:Trying to decode such byte soup using utf-8 encoding raises .It can be worse. The decoding may fail silently and produce \nif you use a wrong incompatible encoding:The data is corrupted but your program remains unaware that a failure\nhas occurred.In general, what character encoding to use is not embedded in the byte sequence itself. You have to communicate this info out-of-band. Some outcomes are more likely than others and therefore  module exists that can  the character encoding. A single Python script may use multiple character encodings in different places. output can be converted to a Python string using \nfunction that succeeds even for  (it uses\n and  error handler on\nUnix):To get the original bytes, you could use .If you pass  parameter then  uses\n to decode bytes e.g., it can be\n on Windows.To decode the byte stream on-the-fly,\n\ncould be used: .Different commands may use different character encodings for their\noutput e.g.,  internal command () may use cp437. To decode its\noutput, you could pass the encoding explicitly (Python 3.6+):The filenames may differ from  (which uses Windows\nUnicode API) e.g.,  can be substituted with \u2014Python's\ncp437 codec maps  to control character U+0014 instead of\nU+00B6 (\u00b6). To support filenames with arbitrary Unicode characters, see  From ,To write or read binary data from/to the standard streams, use the underlying binary buffer. For example, to write bytes to stdout, use sys.stdout.buffer.write(b'abc').For Python 3,this is a much safer and  approach to convert from  to :Output:I made a function to clean a listI made a function to clean a list
Python

I tried to install the Python package :But I get a cryptic error message:The same happens if I try installing the package manually:: Comments point out that the instructions here may be dangerous. Consider using the Visual C++ 2008 Express edition or the purpose-built  () and  using the original answer below. Original error message means the required version of Visual C++ is not installed.For Windows installations:While running setup.py for package installations, Python 2.7 searches for an installed Visual Studio 2008. You can trick Python to use a newer Visual Studio by setting the correct path in  environment variable before calling .Execute the following command based on the version of Visual Studio installed:WARNING: As noted below, this answer is unlikely to work if you are trying to compile python modules.See  for details.You can install compiled version from I found the solution. \nI had the exact same problem, and error, installing 'amara'. I had mingw32 installed, but distutils needed to be configured.Make sure environment is set by opening a new .What's going on? Python modules can be  (typically for speed). If you try to install such a package with Pip (or ), it has to compile that C/C++ from source. Out the box, Pip will brazenly assume you the compiler Microsoft Visual C++ installed. If you don't have it, you'll see this cryptic error message \"Error: Unable to find vcvarsall.bat\".The prescribed solution is to install a C/C++ compiler, either Microsoft Visual C++, or  (an open-source project). However, installing and configuring either is prohibitively difficult. (Edit 2014: Microsoft have published a special  for Python 2.7)The easiest solution is to use Christoph Gohlke's Windows installers (.msi) for popular Python packages. He builds installers for Python 2.x and 3.x, 32 bit and 64 bit. You can download them from If you too think \"Error: Unable to find vcvarsall.bat\" is a ludicrously cryptic and unhelpful message, then please comment on the bug at  to replace it with a more helpful and user-friendly message. For comparison, Ruby ships with a package manager Gem and offers a quasi-official C/C++ compiler, DevKit. If you try to install a package without it, you see this helpful friendly useful message:You can read a longer rant about Python packaging at You'll need to install a Microsoft compiler, compatible with the compiler used to build Python. This means you need Visual C++ 2008 (or newer, with ).Microsoft now supplies a bundled compiler and headers  to be able to compile Python extensions, at the memorable URL: This is a relatively small package; 85MB to download, installable without admin privileges, no reboot required. The name is a little misleading, the compiler will work for any Python version originally compiled with Visual C++ 2008, not just Python 2.7.If you start a Python interactive prompt or print , look for the  version string; if it is  you can use this tool.From the :Note that you need to have  installed (listed in the system requirements on the download page). The project you are installing must use , not  or the auto-detection won't work.Microsoft has stated that they want to keep the URL stable, so that automated scripts can reference it easily.I just had this same problem, so I'll tell my story here hoping it helps someone else with the same issues and save them the couple of hours I just spent:I have mingw (g++ (GCC) 4.6.1) and python 2.7.3 in a windows 7 box and I'm trying to install PyCrypto.It all started with this error when running setup.py install: Easily solved after googling the error by specifying mingw as the compiler of choice: The problem is that then I got a different error: It turns out that my anti-virus was blocking the execution of a freshly compiled .exe. I just disabled the anti-virus \"resident shield\" and went to the next error:This solved it: \"Either install a slightly older version of MinGW, or edit distutils\\cygwinccompiler.py in your Python directory to remove all instances of -mno-cygwin.\" (from )Now, I can finally start working.Looks like its looking for VC compilers, so you could try to mention compiler type with , since you have msysI have python 2.73 and windows 7 .The solution that worked for me was:To deal with MinGW not recognizing the -mno-cygwin flag anymore, remove the flag in C:\\Python27\\Lib\\distutils\\cygwincompiler.py line 322 to 326, so it looks like this:Look in the  file of the package you are trying to install. If it is an older package it may be importing  rather than .I ran in to this (in 2015) with a combination of these factors:If you use a recent version of pip, it will force (monkeypatch) the package to use setuptools, even if its  calls for distutils. However, if you are not using pip, and instead are just doing , the build process will use , which does not know about the compiler install location. Open the appropriate Visual C++ 2008 Command PromptOpen the Start menu or Start screen, and search for \"Visual C++ 2008 32-bit Command Prompt\" (if your python is 32-bit) or \"Visual C++ 2008 64-bit Command Prompt\" (if your python is 64-bit). Run it. The command prompt should say Visual C++ 2008 ... in the title bar. Set environment variablesSet these environment variables in the command prompt you just opened.Reference  Build and install to the package you want to build, and run , then . If you want to install in to a virtualenv, activate it before you build. Maybe somebody can be interested, the following worked for me for the py2exe package.\n(I have windows 7 64 bit and portable python 2.7, Visual Studio 2005 Express with Windows SDK for Windows 7 and .NET Framework 4)then:I tried all the above answers, and found all of them not to work, this was perhaps I was using Windows 8 and had installed Visual Studio 2012. In this case, this is what you do.The  file is located here:\nSimply select the file, and copy it.Then go to this directory:\nand paste the file. And then, all should be well.I spent almost 2 days figuring out how to fix this problem in my python 3.4 64 bit version: Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC v.1600 64 bit (AMD64)] on win32 (before reading this, read first Solution 2 below)\nFinally, this is what helped me:It took very long - several minutes for numpy to compile, I even thought that there was an error, but finally everything was ok.\n(I know this approach has already been mentioned in a highly voted , but let me repeat since it really is easier)\nAfter going through all of this work I understood that the best way for me is just to use already precompiled binaries from  in future. There is very small chance that I will ever need some package (or a version of a package) which this site doesn't contain. The installation process is also much quicker this way. For example, to install :You can download the free Visual C++ 2008 Express Edition from , which will set the VS90COMNTOOLS environment variable during installation and therefore build with a compatible compiler.As @PiotrDobrogost mentioned in a comment, his answer to this other question goes into details about why Visual C++ 2008 is the right thing to build with, but this can change as the Windows build of Python moves to newer versions of Visual Studio: I had this problem using , and unfortunately the packages I needed didn't have suitable exe or wheels that I could use. This system requires a few 'workarounds', which are detailed below (and ).Using the info in , I determined I needed Visual Studio C++ 2010 (sys.version return MSC v.1600), so I installed Visual C++ 2010 Express from the link in his answer, which is . I installed everything with updates, but as you can read below, this was a mistake. Only the original version of Express should be installed at this time (no updated anything).vcvarsall.bat was now present, but there was a new error when installing the package, . There are other stackoverflow questions with this error, such as I determined from that answer that 2010 Express only installs 32-bit compilers. To get 64-bit (and other) compilers, you need to install Windows 7.1 SDK. See This would not install for me though, and the installer returned the error . I found the solution at the following link: . In short, if newer versions of x86 and x64 Microsoft Visual C++ 2010 Redistributable's are installed, they conflict with the ones in SDK installer, and need uninstalling first.The SDK then installed, but I noticed vcvars64.bat still did not exist in , nor its subfolders. vcvarsall.bat runs the vcvars64 batch file, so without it, the python package still wouldn't install (I forgot the error that was shown at this time).I then found some instructions here: \nFollowing the instructions, I had already installed Express and 7.1 SDK, so installed SDK 7.1 SP1, and did the missing header file fix. I then manually created vcvars64.bat with the content . I will paste all those instructions here, so they don't get lost.My python package still did not install (can't recall error). I then found some instructions (copied below) to use the special SDK 7.1 Command Prompt, see: I opened the Windows SDK 7.1 Command Prompt as instructed, and used it to run easy_install on the python package. And at last, success!;I wanted to run pysph on Windows 10 under Python 2.7 and got vcvarsall.bat was not found (from distutils)My solution was the following:Install Microsoft Visual C++ for Python 2.7 (like @Michael suggested)On Windows 10 it was installed into (my username is Andreas):Set environment variable  to the installation path of Visual C++ for Python 2.7 (see above path).If it still doesn't work, then modifiy in the modulethe file . Find in it the function  and do following modification.Replace the line:withThis is where vcvarsall.bat resides in my case (check, where vcvarsall.bat is in your installation).I encountered this issue when I tried to install numpy library on my python 3.5. The solution is to install VS2015. I had VS2008, 2012, 2013, none of which is compatible with python 3.5. Apparently newer version of python has dependency on newer versions of VS.Also make sure C++ Common Tools are installed with Visual Studio.I tried many solutions but only one worked for me, the install of Microsoft Visual Studio  Express C++.I got this issue with a Python 2.7 module written in C (yEnc, which has other issues with MS VS). Note that Python 2.7 is built with MS VS 2008 version, not 2010!Despite the fact it's free, it is quite hard to find since MS is promoting VS 2010.\nStill, the MSDN official very direct links are still working: check  for download links.If you have mingw installedworks, forcing pip to build using the mingw compiler instead of Microsoft's. See here  for details (last post).Is Microsoft Visual C++ Compiler for Python 2.7 at  not a solution? The easiest way to solve this in 2016 is to install Chocolatey and then the   package. Open Powershell:You can use easy_install instead of pip it works for me.I don't know if it is too late, but I found  which readsHope this helps!If you're looking to install pyodbc on a Windows box that  have Visual Studio installed another option is to manually install pyodbc using the binary distribution.This is particularly useful if you do not have administrator privileges on the machine you're working with and are trying to set up a .Steps:With Python 3.4, the dependency is on Visual Studio 2010. Installing Visual C++ 2010 Express fixed the problem for me. Tricking it into using the VS 2008 or 2013 installs that I happened to have didn't work.The answer given by @monkey is one of the correct ones, but it is incomplete.In case you'd like to use , you should select the C, C++ and also other development tools suggested during the MinGW installation process to also get \"make.exe.\"You must also have the path set to make.exe in the env.To complete his answer, here are the steps:Make sure the environment variables is set by opening a new cmd.exe.I had the same error (which I find silly and not really helpful whatsoever as error messages go) and continued having problems, despite having a C compiler available. Surprising, what ended up working for me was simply . Hope this helps someone else out there.:If you have , the solution is simply to install \nVC++ 2010 since it is used to compile itself into.my python version is\nMSC v.1600 32 bit (intel)] on win32Go here: There are instructions to install anaconda which will provide a GUI and a silent install of a majority of the packages that seem to be causing this issue from .  I am aware of the solution for 2.7 here  but I did not see an option for Python 3.4.  After downloading and installing Anaconda you should be able to import a majority of the packages you need from scipy.Hope this helps some people.  Took me 45 minutes of scouring posts and sites.EDIT: Just wanted to note there is a Python34 link on the GUI page next to the OS symbols.Install Visual Studio 2015 Community Edition from ,\nthenfor Python 3.4
Python

I want to clear this up once and for all. Can someone please explain the exact meaning of having leading underscores before an object's name in Python? Also explain the difference between a single and a double leading underscore. Also, does that meaning stay the same whether the object in question is a variable, a function, a method, etc?Names, in a class, with a leading underscore are simply to indicate to other programmers that the attribute or method is intended to be private.  However, nothing special is done with the name itself.To quote :From :And a warning from the same page:Excellent answers so far but some tidbits are missing. A single leading underscore isn't exactly  a convention: if you use , and module  does not define an  list, the names imported from the module  include those with a leading underscore. Let's say it's  a convention, since this case is a pretty obscure corner;-).The leading-underscore convention is widely used not just for  names, but also for what C++ would call  ones -- for example, names of methods that are fully intended to be overridden by subclasses (even ones that  to be overridden since in the base class they !-) are often single-leading-underscore names to indicate to code  instances of that class (or subclasses) that said methods are not meant to be called directly.For example, to make a thread-safe queue with a different queueing discipline than FIFO, one imports Queue, subclasses Queue.Queue, and overrides such methods as  and ; \"client code\" never calls those (\"hook\") methods, but rather the (\"organizing\") public methods such as  and  (this is known as the  design pattern -- see e.g.  for an interesting presentation based on a video of a talk of mine on the subject, with the addition of synopses of the transcript).: this is just a convention, a way for the Python system to use names that won't conflict with user names.: this is just a convention, a way for the programmer to indicate that the variable is private (whatever that means in Python).: this has real meaning: the interpreter replaces this name with  as a way to ensure that the name will not overlap with a similar name in another class.No other form of underscores have meaning in the Python world.There's no difference between class, variable, global, etc in these conventions. is semiprivate and meant just for convention is often incorrectly considered superprivate, while it's actual meaning is just to namemangle to  is typically reserved for builtin methods or variablesYou can still access  variables if you desperately want to. The double underscores just namemangles, or renames, the variable to something like Example:t._b is accessible because it is only hidden by conventiont.__a isn't found because it no longer exists due to namemanglingBy accessing  instead of just the double underscore name, you can access the hidden valuePython doesn't have real private methods, so one underscore at the start of a method or attribute name means you shouldn't access this method, because it's not part of the API.code snippet taken from django source code (django/forms/forms.py). This means errors is a property, and it's part of the module, but the method this property calls, _get_errors, is \"private\", so you shouldn't access it.This causes a lot of confusion. It should not be used to create a private method. It should be used to avoid your method to be overridden by a subclass or accessed accidentally. Let's see an example:Output: Now create a subclass B and do customization for __test methodOutput will be....As we have seen, A.test() didn't call B.__test() methods, as we might expect. But in fact, this is the correct behavior for __. So when you create a method starting with __ it means that you don't want to anyone to be able to override it, it will be accessible only from inside the own class.When we see a method like , don't call it. Because it means it's a method which python calls, not by you. Let's take a look:There is always an operator or native function which calls these magic methods. Sometimes it's just a hook python calls in specific situations. For example  is called when the object is created after  is called to build the instance...Let's take an example...For more details  will help more.Please find more magic methods in python here. Sometimes you have what appears to be a tuple with a leading underscore as in In this case, what's going on is that _() is an alias for a localization function that operates on text to put it into the proper language, etc. based on the locale. For example, Sphinx does this, and you'll find among the importsand in sphinx.locale, _() is assigned as an alias of some localization function.If one really wants to make a variable read-only, IMHO the best way would be to use property() with only getter passed to it. With property() we can have complete control over the data.I understand that OP asked a little different question but since I found another question asking for 'how to set private variables' marked duplicate with this one, I thought of adding this additional info here.Single leading underscores is a convention. there is no difference from the interpreter's point of view if whether names starts with a single underscore or not. Double leading and trailing underscores are used for built-in methods, such as , , etc.Double leading underscores w/o trailing counterparts are a convention too, however, the class methods will be  by the interpreter. For variables or basic function names no difference exists.Your question is good, it is not only about methods. Functions and objects in modules are commonly prefixed with one underscore as well, and can be prefixed by two.But __double_underscore names are not name-mangled in modules, for example. What happens is that names beginning with one (or more) underscores are not imported if you import all from a module (from module import *), nor are the names shown in help(module).\u201cPrivate\u201d instance variables that cannot be accessed except from inside an object don\u2019t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.reference\nHere is a simple illustrative example on how double underscore properties can affect an inherited class. So with the following setup:if you then create a child instance in the python REPL, you will see the belowThis may be obvious to some, but it caught me off guard in a much more complex environment
Python

How do I see the type of a variable whether it is unsigned 32 bit, signed 16 bit, etc.?How do I view it?Python doesn't have the same types as C/C++, which appears to be your question.Try this:The distinction between int and long goes away in Python 3.0, though.You may be looking for the  function.See the examples below, but there's no \"unsigned\" type in Python just like Java.Positive integer: positive integer:Negative integer:Literal sequence of characters:It is so simple. You do it like this.So if you have a variable, for example:You want to know its type?There are right ways and wrong ways to do just about everything in Python. Here's the right way: You can use the  attribute to get the name of the object. (This is one of the few special attributes that you need to use the  name to get to - there's not even a method for it in the  module.) (Except when absolutely necessary.)Since  gives us the class of the object, we should avoid getting this directly. :This is usually the first idea people have when accessing the type of an object in a method - they're already looking for attributes, so type seems weird. For example:Don't. Instead, do type(self):In Python, these specifics are implementation details. So, in general, we don't usually worry about this in Python. However, to sate your curiosity...In Python 2, int is usually a signed integer equal to the implementation's  width (limited by the system). It's usually implemented as a . When integers get bigger than this, we usually convert them to Python longs (with unlimited precision, not to be confused with C longs).For example, in a 32 bit Python 2, we can deduce that int is a signed 32 bit integer:In Python 3, the old int goes away, and we just use (Python's) long as int, which has We can also get some information about Python's floats, which are usually implemented as a  in C:Don't use , a semantically private attribute, to get the type of a variable. Use  instead. And don't worry too much about the implementation details of Python. I've not had to deal with issues around this myself. You probably won't either, and if you really do, you should know enough not to be looking to this answer for what to do.One more way using :The question is somewhat ambiguous -- I'm not sure what you mean by \"view\". If you are trying to  the type of a native Python object, 's answer will steer you in the right direction.However, if you are trying to  Python objects that have the semantics of primitive C-types, (such as , ), use the  module. You can determine the number of bits in a given C-type primitive thusly:This is also reflected in the  module, which can make arrays of these lower-level types:The maximum integer supported (Python 2's ) is given by .There is also , which returns the actual size of the  object in residual memory:For float data and precision data, use :Do you mean in  or using ?In the first case, you simply cannot - because Python does not have signed/unsigned, 16/32 bit integers.In the second case, you can use :For more reference on ctypes, an its type, see .It may be little irrelevant. but you can check types of an object with  as mentioned .I also highly recommend the  interactive interpreter when dealing with questions like this. It lets you type  and will return a whole list of information about the object including the type and the doc string for the type.e.g.Python doesn't have such types as you describe. There are two types used to represent integral values: , which corresponds to platform's int type in C, and , which is an arbitrary precision integer (i.e. it grows as needed and doesn't have an upper limit). s are silently converted to  if an expression produces result which cannot be stored in .Examples of simple type checking in Python:It really depends on what level you mean. In Python 2.x, there are two integer types,  (constrained to ) and  (unlimited precision), for historical reasons. In Python code, this shouldn't make a bit of difference because the interpreter automatically converts to long when a number is too large. If you want to know about the actual data types used in the underlying interpreter, that's implementation dependent. (CPython's are located in Objects/intobject.c and Objects/longobject.c.) To find out about the systems types look at cdleary answer for using the struct module.Simple, for python 3.4 and abovePython 2.7 and above
Python

I want to convert an integer to a string in Python. I am typecasting it in vain:When I try to convert it to string, it's showing an error like  doesn't have any attribute called .[Edit]Links to the documentation:\n\n[Edit]The problem seems to come from this line: \nConversion to string is done with the builtin  function, which basically calls the  method of its parameter.Also, it shouldn't be necessary to call . Try using the  operator.Try this:There is not typecast and no type coercion in Python. You have to convert your variable in an explicit way.To convert an object in string you use the  function. It works with any object that has a method  called  defined. In factis equivalent toThe same if you want to convert something to int, float, etc.You can use  which gives you a string object of .To manage non-integer inputs:Ok, if I take your latest code and rewrite a bit to get it working with Python:It gives me something like:Which is the first characters of the string result .\nWhat are we trying to do here?The most decent way in my opinion is ``.
Python

What is the most pythonic way to pad a numeric string with zeroes to the left, i.e., so the numeric string has a specific length?Strings:And for numbers:.Just use the  method of the string object.This example will make a string of 10 characters long, padding as necessary.For numbers:See also: .: It's worth noting that as of  December 3rd, 2008, this method of formatting is deprecated in favour of the  string method:See  for details.if you want the opposite: will work with s, s, s... and is Python 2. and 3. compatible:Works in both Python 2 and Python 3:See the print documentation for all the exciting details!That last line should now be:I.e.  is now a function, not a statement. Note that I still prefer the Old School  style because, IMNSHO, it reads better, and because, um, I've been using that notation since January, 1980. Something ... old dogs .. something something ... new tricks.For the ones who came here to understand and not just a quick answer.\nI do these especially for time strings:this will work in python 3.xFor zip codes saved as integers:You could also repeat \"0\", prepend it to  and get the rightmost width slice. Quick and dirty little expression.
Python

I was working on my AI pathfinding(which you don't need to understand),\nfor some reason, my On[3] list was expanding when I did this in the shell:\n(After the program messed up.) WHY?The program didn't crash, but that isn't my question.\nA screenshot(Ignore the extra prints, I was trying to narrow down the code that was causing it.) was my Y coordinates.The code in question is at # Find Path\n(Under the bottom section.)\nMy code(Over 200 lines long. :/)I don't use classes or sprites. :P\nThanks for taking a look!Because your  and  are the same object. And this is how it works with same objects:
Python

When debugging in PHP, I frequently find it useful to simply stick a  in my code to show me what a variable is, what its value is, and the same for anything that it contains.What is a good Python equivalent for this?To display a value nicely, you can use the  module. The easiest way to dump all variables with it is to doIf you are running in CGI, a useful debugging feature is the  module, which displays the value of local variables as part of the traceback.I think the best equivalent to PHP's  is combine  with :The closest thing to 's  is  with the  function in the built-in  module:PHP's  usually shows a serialized version of the object that can be exec()'d to re-create the object.    The closest thing to that in Python is \"For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval() [...]\"So I have taken the answers from this question and  and came up below.  I suspect this is not pythonic enough for most people, but I really wanted something that let me get a deep representation of the values some unknown variable has.  I would appreciate any suggestions about how I can improve this or achieve the same behavior easier.Here is the usageand the results.I wrote a very light-weight alternative to PHP's var_dump for using in Python and made it open source later.GitHub: You can simply install it using :For your own classes, just def a  methodOld topic, but worth a try.Here is a simple and efficient var_dump function:Sample output:I don't have PHP experience, but I have an understanding of the Python standard library.For your purposes, Python has several methods: module;Object serialization module which is called . You may write your own wrapper of the pickle module.If your using  for testing, Python has its own  and  modules. It's very simple and fast for design.I use self-written Printer class, but dir() is also good for outputting the instance fields/values.The sample of usage:
Python

There seem to be many ways to define  in Python. Is there a consensus opinion on Stack\u00a0Overflow?I don't really see the need, as a module with functions (and not a class) would serve well as a singleton. All its variables would be bound to the module, which could not be instantiated repeatedly anyway. If you do wish to use a class, there is no way of creating private classes or private constructors in Python, so you can't protect against multiple instantiations, other than just via convention in use of your API. I would still just put methods in a module, and consider the module as the singleton.Here's my own implementation of singletons. All you have to do is decorate the class; to get the singleton, you then have to use the  method. Here's an example:And here's the code:You can override the  method like this: A slightly different approach to implement the singleton in Python is the  by Alex Martelli (Google employee and Python genius).So instead of forcing all instances to have the same identity, they share state.The module approach works well. If I absolutely need a singleton I prefer the Metaclass approach.See this implementation from , implementing the singleton pattern with a decorator:As the  says, the most idiomatic way is to just .With that in mind, here's a proof of concept:See the  for more details on .Example:Notes:The one time I wrote a singleton in Python I used a class where all the member functions had the classmethod decorator.I'm very unsure about this, but my project uses 'convention singletons' (not enforced singletons9, that is, if I have a class called DataController, I define this in the same module:It is not elegant, since it's a full six lines. But all my singletons use this pattern, and it's at least very explicit (which is pythonic).Creating a singleton decorator (aka an annotation) is an elegant way if you want to decorate (annotate) classes going forward. Then you just put @singleton before your class definition. The  does cover this:I would probably rewrite it to look more like this:It should be relatively clean to extend this:There are also some interesting articles on the Google Testing blog, discussing why singleton are/may be bad and are an anti-pattern:Here is an example from Peter Norvig's Python IAQ  (You should use search feature of your browser to find this question, there is no direct link, sorry)Also Bruce Eckel has another example in his book  (again there is no direct link to the code)I think that  a class or an instance to be a singleton is overkill. Personally, I like to define a normal instantiable class, a semi-private reference, and a simple factory function.Or if there is no issue with instantiating when the module is first imported:That way you can write tests against fresh instances without side effects, and there is no need for sprinkling the module with global statements, and if needed you can derive variants in the future. courtesy of ActiveState.It looks like the trick is to put the class that's supposed to only have one instance inside of another class.My simple solution which is based on the default value of function parameters.Being relatively new to Python I'm not sure what the most common idiom is, but the simplest thing I can think of is just using a module instead of a class. What would have been instance methods on your class become just functions in the module and any data just becomes variables in the module instead of members of the class. I suspect this is the pythonic approach to solving the type of problem that people use singletons for.If you really want a singleton class, there's a reasonable implementation described on the  for \"Python singleton\", specifically:That seems to do the trick.OK, singleton could be good or evil, I know. This is my implementation, and I simply extend a classic approach to introduce a cache inside and produce many instances of a different type or, many instances of same type, but with different arguments.I called it Singleton_group, because it groups similar instances together and prevent that an object of the same class, with same arguments, could be created:Every object carries the singleton cache... This could be evil, but it works great for some :)I completely agree with staale and I leave here a sample of creating a singleton half brother: will report now as being of the same class as singleton even if it does not look like it. So singletons using complicated classes end up depending on we don't mess much with them.Being so, we can have the same effect and use simpler things like a variable or a module. Still, if we want use classes for clarity and because , so we already have the object (not and instance, but it will do just like).There we have a nice assertion error if we try to create an instance, and we can store on derivations static members and make changes to them at runtime (I love Python). This object is as good as other about half brothers (you still can create them if you wish), however it will tend to run faster due to simplicity.In cases where you don't want the metaclass-based solution above, and you don't like the simple function decorator-based approach (e.g. because in that case static methods on the singleton class won't work), this compromise works:
Python

In a comment on the , someone said they weren't sure what functools.wraps was doing.  So I'm asking this question so that there will be a record of it on StackOverflow for future reference: what does functools.wraps do, exactly?When you use a decorator, you're replacing one function with another.  In other words, if you have a decoratorthen when you sayit's exactly the same as sayingand your function f is replaced with the function with_logging.  Unfortunately, this means that if you then sayit will print  because that's the name of your new function.  In fact, if you look at the docstring for f, it will be blank because with_logging has no docstring, and so the docstring you wrote won't be there anymore.  Also, if you look at the pydoc result for that function, it won't be listed as taking one argument ; instead it'll be listed as taking  and  because that's what with_logging takes.If using a decorator always meant losing this information about a function, it would be a serious problem.  That's why we have .  This takes a function used in a decorator and adds the functionality of copying over the function name, docstring, arguments list, etc.  And since  is itself a decorator, the following code does the correct thing:I very often use classes, rather than functions, for my decorators.  I was having some trouble with this because an object won't have all the same attributes that are expected of a function.  For example, an object won't have the attribute .  I had a specific issue with this that was pretty hard to trace where Django was reporting the error \"object has no attribute ''\".  Unfortunately, for class-style decorators, I don't believe that @wrap will do the job.  I have instead created a base decorator class like so:This class proxies all the attribute calls over to the function that is being decorated.  So, you can now create a simple decorator that checks that 2 arguments are specified like so:
Python

I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process. For example, let's say I have three files. Using :How can I get the file name and path of , , without having to pass that information as arguments from ?(Executing  returns the original starting script's filepath not the current file's.)p1.py:p2.py:as others have said. You may also want to use:I think this is cleaner:and gets the same information as:Where [0] is the current frame in the stack (top of stack) and [1] is for the file name, increase to go backwards in the stack i.e.would be the file name of the script that called the current frame. Also, using [-1] will get you to the bottom of the stack, the original calling script.Here is an experiment based on the answers in this thread - with Python 2.7.10 on Windows., ie -Here's to these being added to  as functions! Credit to @Usagi and @pablogBased on the following three files, and running script1.py from its folder with  (also tried execfiles with absolute paths and calling from a separate folder). C:\\testpath\\script1.py: \nC:\\testpath\\script2.py: \nC:\\testpath\\lib\\script3.py:The suggestions marked as best are all true if your script consists of only one file. If you want to find out the name of the executable (i.e. the root file passed to the python interpreter for the current program) from a file that may be imported as a module, you need to do this (let's assume this is in a file named ):Because the last thing () on the stack is the first thing that went into it (stacks are LIFO/FILO data structures).Then in file  if you  it'll print , rather than , which would be the value of all of these:this will give us the filename only. i.e. if abspath of file is c:\\abcd\\abc.py then 2nd line will print abc.pyIt's not entirely clear what you mean by \"the filepath of the file that is currently running within the process\".\n usually contains the location of the script that was invoked by the Python interpreter.\nCheck the  for more details.As @Tim and @Pat Notz have pointed out, the __file__ attribute provides access toThe  attribute works for both the file containing the main execution code as well as imported modules.See I have a script that must work under windows environment.\nThis code snipped is what I've finished with:it's quite a hacky decision. But it requires no external libraries and it's the most important thing in my case.this would print the path of the currently executing scriptI think it's just    Sounds like you may also want to checkout the .No need for inspect or any other library.This worked for me when I had to import a script (from a different directory then the executed script), that used a configuration file residing in the same folder as the imported script.You can use This should work:I used the approach with __file__\n\nbut there is a little trick, it returns the .py file \nwhen the code is run the first time, \nnext runs give the name of *.pyc file\nso I stayed with:\n\nor\n  if you want just the filename without  or  you can try this will print testscript\nyou can generate whatever you want by changing the index inside []I wrote a function which take into account eclipse  and .\nIt return the folder of the first script you launch. You can optionally specify the  var, but the main thing is that you don't have to share this variable across all your .Maybe you can handle others stack particular cases I didn't see, but for me it's ok.To get directory of executing script  
Python

How can I write a / block that catches all exceptions?You can but you shouldn't:However, this will also catch exceptions like  and you usually don't want that, do you? Unless you re-raise the exception right away - see the following example :Apart from a bare  clause (which as others have said you shouldn't use), you can simply catch :You would normally only ever consider doing this at the outermost level of your code if for example you wanted to handle any otherwise uncaught exceptions before terminating.The advantage of  over the bare  is that there are a few exceptions that it wont catch, most obviously  and : if you caught and swallowed those then you could make it hard for anyone to exit your script.You can do this to handle general exceptionsVery simple example, similar to the one found here:If you're attempting to catch ALL exceptions, then put all your code within the \"try:\" statement, in place of 'print \"Performing an action which may throw an exception.\"'.In the above example, you'd see output in this order:1) Performing an action which may throw an exception.2) Finally is called directly after executing the try statement whether an exception is thrown or not.3) \"An exception was thrown!\" or \"Everything looks great!\" depending on whether an exception was thrown.Hope this helps!To catch all possible exceptions, catch . It's on top of the Exception hierarchy:Python 3:\nPython 2.7:\nBut as other people mentioned, you should usually not do this, unless you have a very good reason.It is worth mentioning this is not proper Python coding. This will catch also many errors you might not want to catch.I've just found out this little trick for testing if exception names in Python 2.7 . Sometimes i have handled specific exceptions in the code, so i needed a test to see if that name is within a list of handled exceptions.
Python

I have seen many projects using  module instead of  module from the Standard Library. Also, there are many different  modules. Why would use these alternatives, instead of the one in the Standard Library?  , added to the stdlib. But since  was added in 2.6,  has the advantage of working on more Python versions (2.4+).  is also updated more frequently than Python, so if you need (or want) the latest version, it's best to use  itself, if possible.A good practice, in my opinion, is to use one or the other as a fallback.I have to disagree with the other answers: the built in  library (in Python 2.7) is not necessarily slower than . It also doesn't have .Here is a simple benchmark:And the results on my system (Python 2.7.4, Linux 64-bit):For dumping,  is faster than .\nFor loading,  is faster.Since I am currently building a web service,  is more important\u2014and using a standard library is always preferred.Also,  was not updated in the past 4 years, so I wouldn't touch it.I've been benchmarking json, simplejson and cjson.:All of these answers aren't very helpful because they are . After doing some research of my own I found that  is indeed faster than the builtin,  you keep it updated to the latest version. wanted to install 2.3.2 on ubuntu 12.04, but after finding out the latest  version is actually 3.3.0, so I updated it and reran the time tests. The above statements are in python-2.7.3 and simplejson 3.3.0 (with c speedups)\nAnd to make sure my answer also isn't time sensitive, you should  to check since it varies so much between versions; there's no easy answer that isn't time sensitive. I recently came across a library called  that is performing ~3x faster than  with some basic tests. An API incompatibility I found, with Python 2.7 vs simplejson 3.3.1 is in whether output produces str or unicode objects.\ne.g.vsIf the preference is to use simplejson, then this can be addressed by coercing the argument string to unicode, as in:The coercion does require knowing the original charset, for example:This is the won't fix The builtin  module got included in Python 2.6.  Any projects that support versions of Python < 2.6 need to have a fallback.  In many cases, that fallback is .Another reason projects use simplejson is that the builtin json did not originally include its C speedups, so the performance difference was noticeable.Here's (a now outdated) comparison of Python json libraries: ()Regardless of the results in this comparison you should use the standard library json if you are on Python 2.6.  And.. might as well just use simplejson otherwise.simplejson module is simply 1,5 times faster than json (On my computer, with simplejson 2.1.1 and Python 2.7 x86).If you want, you can try the benchmark: \nOn my PC simplejson is faster than cPickle. I would like to know also your benchmarks!Probably, as said Coady, the difference between simplejson and json is that simplejson includes _speedups.c.\nSo, why don't python developers use simplejson?Some values are serialized differently between simplejson and json.Notably, instances of  are serialized as arrays by  but as objects by . You can override this behaviour by passing  to , but by default the behaviours do not match.I came across this question as I was looking to install simplejson for Python 2.6. I needed to use the 'object_pairs_hook' of json.load() in order to load a json file as an OrderedDict. Being familiar with more recent versions of Python I didn't realize that the json module for Python 2.6 doesn't include the 'object_pairs_hook' so I had to install simplejson for this purpose. From personal experience this is why i use simplejson as opposed to the standard json module.In python3, if you a string of ,  with  you have to  the content before you can load it.   takes care of this so you can just do .
Python

I have some data either in list contains lists, or list contains tuples.And I want to sort by the 2nd element in the subset. Meaning, sorting by 2,5,8 where 2 is from (1,2,3), 5 is from (4,5,6). What is the common way to do this? Should I store tuples or lists in my list? Since tuples are more inflexible.or: is the one I'd use.  For completeness, here's the DSU (decorate-sort-undecorate) pattern with list comprehensions:Or, more tersely:As noted in the , this has been unnecessary since Python 2.4, when key functions became available.I just want to add to Stephen's answer if you want to sort the array from high to low, another way other than in the comments above is just to add this to the line: and the result will be as follows:For sorting by multiple criteria, namely for instance by the second and third elements in a tuple, letand so define a lambda that returns a tuple that describes priority, for instanceIn more general case (without using lambda) you can use defined function:and then use key to sort it by second parameter: is somewhat faster than , but the increase is relatively modest (around 10 to 25 percent).(IPython session)In order to sort a list of tuples , for  in descending order and  in alphabetical order:I use this method:and it gives me the result:@Stephen 's answer is to the point! Here is an example for better visualization, =) is a function that will be called to transform the collection's items for comparison.. like  method in Java. The parameter passed to key must be something that is callable. Here, the use of  creates an anonymous function (which is a callable).\nThe syntax of lambda is the word lambda followed by a iterable name then a single block of code. Below example, we are sorting a list of tuple that holds the info abt time of certain event and actor name. We are sorting this list by time of event occurrence - which is the 0th element of a tuple.Note -   sorts the items of s in placeSorting a tuple is quite simple:
Python

How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?I'm trying to look for the source of the  module in particular, but I'm interested in a more general answer as well.For a pure python module you can find the source by looking at .\nThe datetime module, however, is written in C, and therefore  points to a .so file (there is no  on Windows), and therefore, you can't see the source.If you download a python source tarball and extract it, the modules' code can be found in the  subdirectory.For example, if you want to find the datetime code for python 2.6, you can look atYou can also find the latest Mercurial version on the web at \nRunning  from the command line should tell you what is being imported and from where.  This works for me on Windows and Mac OS X.I'm not sure what those bad mtime's are on my install!I realize this answer is 4 years late, but the existing answers are misleading people.The right way to do this is never , or trying to walk through  and search for yourself, etc. (unless you need to be backward compatible beyond 2.1).It's the  module\u2014in particular,  or .Unless you want to learn and implement the rules (which are documented, but painful, for CPython 2.x, and not documented at all for other implementations, or 3.x) for mapping  to  files; dealing with .zip archives, eggs, and module packages; trying different ways to get the path to / files that don't support ; figuring out what Jython/IronPython/PyPy do; etc. In which case, go for it.Meanwhile, every Python version's source from 2.0+ is available online at  (e.g.,  or ). So, once you discover that  is a  or  file like , you can look it up inside the Modules directory. Strictly speaking, there's no way to be sure of which file defines which module, but nearly all of them are either  or , so it shouldn't be hard to guess that  is what you want.The  list contains the list of directories which will be searched for modules at runtime: is a builtin module, so there is no (Python) source file.For modules coming from  (or ) files, you can use , e.g.from the standard library try If you're using pip to install your modules, just  the location is returned.New in Python 3.2, you can now use e.g.  from the dis module:\nIn the python interpreter you could import the particular module and then type help(module). This gives details such as Name, File, Module Docs, Description et al.Ex:et alCheck out this  to cd to the directory containing the source for the indicated Python module:Here's a one-liner to get the filename for a module, suitable for shell aliasing:Set up as an alias:To use:On windows you can find the location of the python module as shown below:i.e find rest_framework module\nNot all python modules are written in python. Datetime happens to be one of them that is not, and (on linux) is datetime.so.You would have to download the source code to the python standard library to get at it.For those who prefer a GUI solution: if you're using a gui such as Spyder (part of the Anaconda installation) you can just right-click the module name (such as \"csv\" in \"import csv\") and select \"go to definition\" - this will open the file, but also on the top you can see the exact file location (\"C:....csv.py\") On Ubuntu 12.04, for example numpy package for python2, can be found at:Of course, this is not generic answer
Python

I am looking for minimum and maximum values for integers in python. For eg., in Java, we have  and . Is there something like this in python?In Python 2, there's :And you can calculate the minimum value with  as seen . Of course Python just switches from plain to long integers once you exceed this value.In Python 3 this value has no significance at all for integers. (However, a closely related value is still available as , in case you're actually looking for the machine's .) constant has been removed from Python 3.0 onward, instead use Refer : In Python integers will automatically switch from a fixed-size  representation into a variable width  representation once you pass the value , which is either 2 - 1 or 2 - 1 depending on your platform. Notice the  that gets appended here:From the :Python tries very hard to pretend its integers are mathematical integers and are unbounded. It can, for instance, calculate a  with ease:If you just need a number that's bigger than all others, you can usein similar fashion, a number smaller than all others:This works in both python 2 and 3.I came here from google and was looking for python 3.  In that case its, 
Python

What would be the quickest way to construct a python binding to a C or C++ library?(using windows if this matters)You should have a look at , here is the short introdution taken from their website:I like  a lot,  always tended to give me . Also ctypes has the advantage that you don't need to satisfy any compile time dependency on python, and your binding will work on any python that has ctypes, not just the one it was compiled against.Suppose you have a simple C++ example class you want to talk to in a file called foo.cpp:Since ctypes can only talk to C functions, you need to provide those declaring them as extern \"C\"Next you have to compile this to a shared libraryAnd finally you have to write your python wrapper (e.g. in fooWrapper.py)Once you have that you can call it likeThe quickest way to do this is using .Example from SWIG :Interface file:Building a Python module on Unix:Usage:Note that you have to have python-dev. Also in some systems python header files will be in /usr/include/python2.7 based on the way you have installed it.From the tutorial:I started my journey in the python <-> C++ binding from this page, with the objective of linking high level data types (multidimensional STL vectors with python lists) :-)Having tried the solutions based on both  and  (and not being a software engineer) I have found them complex when high level datatypes binding is required, while I have found  much more simple for such cases.\nThis example uses therefore SWIG and it has been tested in Linux (but swig is available and is widely used in Windows too).The objective is to make available to python a C++ function that takes a matrix in form of a 2D STL vector and returns an average of each row (as a 1D STL vector).The code in C++ (\"code.cpp\") is as follow:The equivalent header (\"code.h\") is:We first compile the C++ code to create an object file:We then define a  (\"code.i\") for our C++ functions.Using swig, we generate a C++ interface source code from the swig interface definition file..We finally compile the generated C++ interface source file and link everything together to generate a shared library that is directly importable by python (the \"_\" matters):We can now use the function in python scripts:Check out  or .  They're python-like languages for interfacing between C/C++ and python.I\u2019ve never used it but I\u2019ve heard good things about . If you\u2019re trying to use it with C++, be sure to evade name mangling via .  basically says: first prototype everything in Python. Then when you need to speed a part up, use SWIG and translate this part to C.I think cffi for python can be an option.There is also , which is like a lightweight version of  and compatible with all modern C++ compilers :  The question is how to call a C function from Python, if I understood correctly. Then the best bet are Ctypes (BTW portable across all variants of Python).For a detailed guide you may want to refer to .First you should decide what is your particular purpose. The official Python documentation on  was mentioned above, I can add a good . The use cases can be divided into 3 categories:In order to give some broader perspective for other interested and since your initial question is a bit vague (\"to a C or C++ library\") I think this information might be interesting to you. On the link above you can read on disadvantages of using binary extensions and its alternatives. Apart from the other answers suggested, if you want an accelerator module, you can try . It works \"by generating optimized machine code using the LLVM compiler infrastructure at import time, runtime, or statically (using the included pycc tool)\". One of the official Python documents contains details on .\nEven without the use of , it\u2019s quite straightforward and works perfectly well on Windows.Cython is definitely the way to go, unless you anticipate writing Java wrappers, in which case SWIG may be preferable.  I recommend using the  command line utility, it makes the process of using Cython extremely easy.  If you need to pass structured data to C++, take a look at Google's protobuf library, it's very convenient.  Here is a minimal examples I made that uses both tools: Hope it can be a useful starting point.  
Python

I haven't been able to find an understandable explanation of how to actually use Python's  function.  What I'm trying to do is this:I've reviewed , and , but I've had trouble trying to apply them beyond a simple list of numbers. So, how do I use of ?  Is there another technique I should be using?  Pointers to good \"prerequisite\" reading would also be appreciated.As Sebastjan said, The part I didn't get is that in the example construction is the current grouping key, and  is an iterator that you can use to iterate over the group defined by that grouping key. In other words, the  iterator itself returns iterators.Here's an example of that, using clearer variable names:This will give you the output:In this example,  is a list of tuples where the first item in each tuple is the group the second item belongs to. The  function takes two arguments: (1) the data to group and (2) the function to group it with. Here,  tells  to use the first item in each tuple as the grouping key.In the above  statement,  returns three (key, group iterator) pairs - once for each unique key. You can use the returned iterator to iterate over each individual item in that group.Here's a slightly different example with the same data, using a list comprehension:This will give you the output:Can you show us your code?The example on the Python docs is quite straightforward:So in your case, data is a list of nodes, keyfunc is where the logic of your criteria function goes and then  groups the data.You must be careful to  by the criteria before you call  or it won't work.  method actually just iterates through a list and whenever the key changes it creates a new group.A neato trick with groupby is to run length encoding in one line:will give you a list of 2-tuples where the first element is the char and the 2nd is the number of repetitions.Another example:results inNote that igroup is an iterator (a sub-iterator as the documentation calls it).This is useful for chunking a generator:Another example of groupby - when the keys are not sorted.  In the following example, items in xx are grouped by values in yy.  In this case, one set of zeros is output first, followed by a set of ones, followed again by a set of zeros.Produces:WARNING:The syntax list(groupby(...)) won't work the way that you intend. It seems to destroy the internal iterator objects, so usingwill produce:Instead, of list(groupby(...)), try [(k, list(g)) for k,g in groupby(...)], or if you use that syntax often,and get access to the groupby functionality while avoiding those pesky (for small data) iterators all together.I would like to give another example where groupby without sort is not working. Adapted from example by James Sulakoutput isthere are two groups with vehicule, whereas one could expect only one group@CaptSolo, I tried your example, but it didn't work.Output:As you can see, there are two o's and two e's, but they got into separate groups. That's when I realized you need to sort the list passed to the groupby function. So, the correct usage would be:Output:Just remembering, if the list is not sorted, the groupby function !You can use groupby to group things to iterate over. You give groupby an iterable, and a optional  function/callable by which to check the items as they come out of the iterable, and it returns an iterator that gives a two-tuple of the result of the key callable and the actual items in another iterable. From the help:Here's an example of groupby using a coroutine to group by a count, it uses a key callable (in this case, ) to just spit out the count for however many iterations and a grouped sub-iterator of elements:prints
Python

How to select rows from a DataFrame based on values in some column in pandas?\nIn SQL I would use: To select rows whose column value equals a scalar, , use :To select rows whose column value is in an iterable, , use :Combine multiple conditions with : To select rows whose column value  , use : returns a boolean Series, so to select rows whose value is  in , negate the boolean Series using :For example,yieldsIf you have multiple values you want to include, put them in a\nlist (or more generally, any iterable) and use :yieldsNote, however, that if you wish to do this many times, it is more efficient to\nmake an index first, and then use :yieldsor, to include multiple values from the index use :yieldsThe pandas equivalent to isMultiple conditions:orIn the above code it is the line  that gives the rows based on the column value,  in this case.Multiple conditions are also possible:But at that point I would recommend using the query function, since it's less verbose and yields the same result:I find the syntax of the previous answers to be redundant and difficult to remember. Pandas introduced the  method in v0.13 and I much prefer it. For your question, you could do Reproduced from You can also access variables in the environment by prepending an .Here is a simple example  I just tried editing this, but I wasn't logged in, so I'm not sure where my edit went. I was trying to incorporate multiple selection. So I think a better answer is:For a single value, the most straightforward (human readable) is probably:For lists of values you can also use:For example,yieldsIf you have multiple criteria you want to select against, you can put them in a list and use 'isin':yieldsNote, however, that if you wish to do this many times, it is more efficient to make A the index first, and then use df.loc:yieldsIf you came here looking to select rows from a dataframe by including those whose column's value is NOT any of a list of values, here's how to flip around unutbu's answer for a list of values above:(To not include a single value, of course, you just use the regular not equals operator, .)Example:gives usTo subset to just those rows that AREN'T  or  in column :yieldsTo append to this famous question (though a bit too late): You can also do  to make a new data frame with specified column having a particular value. E.g.Run this gives:
Python

...do something here... should be :What's the easiest way to do this?The  method of a string (either ASCII or Unicode is fine) does this:However, look out for strings with embedded apostrophes, as noted in the docs.the 'title' method can't work well, Try string.capwords, From the :Just because this sort of thing is fun for me, here are two more solutions.Split into words, initial-cap each word from the split groups, and rejoin.  This will change the white space separating the words into a single white space, no matter what it was.EDIT: I don't remember what I was thinking back when I wrote the above code, but there is no need to build an explicit list; we can use a generator expression to do it in lazy fashion.  So here is a better solution:Use a regular expression to match the beginning of the string, or white space separating words, plus a single non-whitespace character; use parentheses to mark \"match groups\".  Write a function that takes a match object, and returns the white space match group unchanged and the non-whitespace character match group in upper case.  Then use  to replace the patterns.  This one does not have the punctuation problems of the first solution, nor does it redo the white space like my first solution.  This one produces the best result.I'm glad I researched this answer.  I had no idea that  could take a function!  You can do nontrivial processing inside  to produce the final result!Copy-paste-ready version of @jibberia anwser:Why do you complicate your life with joins and for loops when the solution is simple and safe??Just do this:If str.title() doesn't work for you, do the capitalization yourself.One-liner:Clear example:Capitalize words...As Mark pointed out you should use :However, if would like to make the first letter uppercase , you could use this:or using a variable:The suggested method str.title() does not work in all cases.\nFor example:instead of . I think, it is better to do something like this:The simplest solution is to split the sentence into words and capitalize the first letter then join it back together.If you don't want to split the input string into words first, and using fancy generators:or without importing itertoolsor you can use regular expressions, from  Now, these are some  that were posted, and inputs for which they don't work as expected if we are using the definition of a word being the start of the sentence or anything after a blank space:using ' ' for the split will fix the second output, but capwords() still won't work for the firstBe careful with multiple blank spacesAn empty string will raise an Error if you access [1:], therefore I would use:to uppercase the first letter only.I really like this answer:Copy-paste-ready version of @jibberia anwser:But some of the lines that I was sending split off some blank '' characters that caused errors when trying to do s[1:].  There is probably a better way to do this, but I had to add in a if len(s)>0, as in
Python

Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.I'm just going to start with a tip from myself :)Don't hardcode path's in your settings.py if you want to run your project in different locations. Use the following code in settings.py if your templates and static files are located within the Django project directory:Credits: I got this tip from the screencast ''.Install  and  and then issue the following command to get a really nice looking Django model visualization:Use   decorator instead of .Edited to point out that returning an HttpResponse (such as a redirect) will short circuit the decorator and work just as you expect.There's a set of custom tags I use all over my site's templates. Looking for a way to autoload it (DRY, remember?), I found the following:If you put this in a module that's loaded by default (your main urlconf for instance), you'll have the tags and filters from your custom tag module available in any template, without using .The argument passed to  can be any module path; your custom tag module doesn't have to live in a specific application. For example, it can also be a module in your project's root directory (eg. ). + Python = life saver if you are working on multiple Django projects and there is a possibility that they all don't depend on the same version of Django/an application.Don't hard-code your URLs! Use  instead, and the  function to get the URL itself.When you define your URL mappings, give names to your URLs. Make sure the name is unique per URL.I usually have a consistent format \"project-appplication-view\", e.g. \"cbx-forum-thread\" for a thread view. (shamelessly stealing ):This name can be used in templates with the .Use . For example, it allows to view all SQL queries performed while rendering view and you can also view stacktrace for any of them.Don't write your own login pages.  If you're using django.contrib.auth.The real, dirty secret is that if you're also using django.contrib.admin, and django.template.loaders.app_directories.load_template_source is in your template loaders,  Say you have a different user model and you want to include\nthat in every response. Instead of doing this:Context processes give you the ability to pass any variable to your\ntemplates. I typically put mine in :In your  add the following line to your Now every time a request is made it includes the  key automatically.I wrote a blog post about this a few months ago so I'm just going to cut and paste:Out of the box Django gives you several signals that are\nincredibly useful. You have the ability to do things pre and\npost save, init, delete, or even when a request is being\nprocessed. So lets get away from the concepts and\ndemonstrate how these are used. Say we\u2019ve got a blogSo somehow you want to notify one of the many blog-pinging\nservices we\u2019ve made a new post, rebuild the most recent\nposts cache, and tweet about it. Well with signals you have\nthe ability to do all of this without having to add any\nmethods to the Post class.There we go, by defining that function and using the\npost_init signal to connect the function to the Post model\nand execute it after it has been saved.When I was starting out, I didn't know that there was a , make sure you know of its existence!!Use  to jump into your code at any level and debug using the power of IPython.  Once you have installed IPython just put this code in wherever you want to debug: Then, refresh the page, go to your runserver window and you will be in an interactive IPython window.I have a snippet set up in TextMate so I just type ipshell and hit tab.  I couldn't live without it.Run a development SMTP server that will just output whatever is sent to it (if you don't want to actually install SMTP on your dev server.)command line:From the :If you use the Bash shell, consider installing the Django bash completion script, which lives in  in the Django distribution. It enables tab-completion of  and  commands, so you can, for instance...The  facilty which comes with  is truly awesome.  It creates an enhanced debug page that, amongst other things, uses the Werkzeug debugger to create interactive debugging consoles for each point in the stack (see screenshot).  It also provides a very useful convenience debugging method  for displaying information about an object/frame.To install, you can use pip:Then add  to your  tuple in  and start the development server with the new extension:This will change the way you debug.I like to use the Python debugger pdb to debug Django projects.This is a helpful link for learning how to use it: When trying to exchange data between Django and another application,  is a good friend. Use it to receive and custom-process, say, XML data.Documentation:\nAdd  in your view code to dump debug information.Use  alongside Django.If you find the Django template language extremely restricting (like me!) then you don't have to be stuck with it. Django is flexible, and the template language is loosely coupled to the rest of the system, so just plug-in another template language and use it to render your http responses!I use , it's almost like a powered-up version of the django template language, it uses the same syntax, and allows you to use expressions in if statements! no more making a custom if-tags such as ! you can simply say , or .But that's not all; it has many more features to ease template creation, that I can't go though all of them in here.This adds to the reply above about .The URL names can also be effectively used within templates. For example, for a given URL pattern:you can have the following in templates:Since Django \"views\" only need to be callables that return an HttpResponse, you can easily create class-based views like those in Ruby on Rails and other frameworks.There are several ways to create class-based views, here's my favorite:You can add all sorts of other stuff like conditional request handling and authorization in your base view.Once you've got your views setup your urls.py will look something like this:Instead of using  to bind your context to a template and render it (which is what the Django docs usually show) use the generic view . It does the same thing that  does but it also automatically adds RequestContext to the template context, implicitly allowing context processors to be used. You can do this manually using , but why bother? It's just another step to remember and another LOC. Besides making use of context processors, having RequestContext in your template allows you to do things like:which is very useful. In fact, +1 on generic views in general. The Django docs mostly show them as shortcuts for not even having a views.py file for simple apps, but you can also use them inside your own view functions:I don't have enough reputation to reply to the comment in question, but it's important to note that if you're going to use , it does NOT support the '-' character in template block names, while Django does. This caused me a lot of problems and wasted time trying to track down the very obscure error message it generated.The  is very useful when starting to design your website.  Once imported, you can add this to generate sample text: does allow you to retrieve a model without importing it.James shows how handy it can be: .Everybody knows there is a development server you can run with \"manage.py runserver\", but did you know that there is a development view for serving static files (CSS / JS / IMG) as well ?Newcomers are always puzzled because Django doesn't come with any way to serve static files. This is because the dev team think it is the job for a real life Web server.But when developing, you may not want to set up Apache + mod_wisgi, it's heavy. Then you can just add the following to urls.py:Your CSS / JS / IMG will be available at www.yoursite.com/site_media/.Of course, don't use it in a production environment.I learned this one from the documentation for the  app. You can use the \"as\" keyword in template tags to use the results of the call elsewhere in your template.For example:This is mentioned in passing in the Django templatetag documentation, but in reference to loops only. They don't call out that you can use this elsewhere (anywhere?) as well. -- It provides all the logic & template variables for pagination (one of those I've-written-that-a-thousand-times-now drudgeries).   allows for any logic you need.  This gem has saved me many hours of debugging off-by-one errors in my \"Search Results\" pages and makes the view code cleaner in the process. is a nice environment to code and especially debug, with built-in support for Django.Use  to create Django models that use an XML REST API backend (instead of a SQL one).  This is very useful especially when modelling third party APIs - you get all the same QuerySet syntax that you're used to.  You can install it from PyPI.XML from an API:And now in python:It can also handle relationships and collections.  We use it every day in heavily used production code, so even though it's beta it's very usable.  It also has a good set of stubs that you can use in your tests.(Disclaimer: while I'm not the author of this library, I am now a committer, having made a few minor commits)Use database migrations. Use .
Python

This is what I normally do in order to ascertain that the input is a / - but not a . Because many times I stumbled upon bugs where a function passes a  object by mistake, and the target function does  assuming that  is actually a  or .My question is: is there a better way of achieving this?I thinkIs actually what you want, otherwise you'll miss out on a lot of things which act like lists, but aren't subclasses of  or .Remember that in Python we want to use \"duck typing\".  So, anything that acts like a list can be treated as a list.  So, don't check for the type of a list, just see if it acts like a list.But strings act like a list too, and often that is not what we want.  There are times when it is even a problem!  So, check explicitly for a string, but then use duck typing.Here is a function I wrote for fun.  It is a special version of  that prints any sequence in angle brackets ('<', '>').This is clean and elegant, overall.  But what's that  check doing there?  That's kind of a hack.  But it is essential.This function calls itself recursively on anything that acts like a list.  If we didn't handle the string specially, then it would be treated like a list, and split up one character at a time.  But then the recursive call would try to treat each character as a list -- and it would work!  Even a one-character string works as a list!  The function would keep on calling itself recursively until stack overflow.Functions like this one, that depend on each recursive call breaking down the work to be done, have to special-case strings--because you can't break down a string below the level of a one-character string, and even a one-character string acts like a list.Note: the / is the cleanest way to express our intentions.  But if this code were somehow time-critical, we might want to replace it with some sort of test to see if  is a sequence.  Rather than testing the type, we should probably test behaviors.  If it has a  method, it's a string, so don't consider it a sequence; otherwise, if it is indexable or iterable, it's a sequence:EDIT: I originally wrote the above with a check for  but I noticed that in the  module documentation, the interesting method is ; this makes sense, that's how you index an object.  That seems more fundamental than  so I changed the above.Python with PHP flavor:For Python 3, note per the :Generally speaking, the fact that a function which iterates over an object works on strings as well as tuples and lists is more feature than bug.  You certainly  use  or duck typing to check an argument, but why should you?That sounds like a rhetorical question, but it isn't.  The answer to \"why should I check the argument's type?\" is probably going to suggest a solution to the real problem, not the perceived problem.  Why is it a bug when a string is passed to the function?  Also:  if it's a bug when a string is passed to this function, is it also a bug if some other non-list/tuple iterable is passed to it?  Why, or why not?I think that the most common answer to the question is likely to be that developers who write  are expecting the function to behave as though they'd written .  There are probably circumstances where it makes more sense to protect developers from themselves than it does to support the use case of iterating across the characters in a string.  But I'd think long and hard about it first.The  object doesn't have an  attributeso you can do a checkand this will also raise a nice  for any other non-iterable object too.\nAs Tim mentions in the comments, this will only work in python 2.x, not 3.xThis is not intended to directly answer the OP, but I wanted to share some related ideas.I was very interested in @steveha answer above, which seemed to give an example where duck typing seems to break. On second thought, however, his example suggests that duck typing is hard to conform to, but it does  suggest that  deserves any special handling.After all, a non- type (e.g., a user-defined type that maintains some complicated recursive structures) may cause @steveha  function to cause an infinite recursion. While this is admittedly rather unlikely, we can't ignore this possibility. Therefore, rather than special-casing  in , we should clarify what we want  to do when an infinite recursion results.It may seem that one reasonable approach is to simply break the recursion in  the moment . This would, in fact, completely solve the problem with , without any .However, a really complicated recursive structure may cause an infinite loop where  never happens. Therefore, while the above check is useful, it's not sufficient. We need something like a hard limit on the recursion depth.My point is that if you plan to handle arbitrary argument types, handling  via duck typing is far, far easier than handling the more general types you may (theoretically) encounter. So if you feel the need to exclude  instances, you should instead demand that the argument is an instance of one of the few types that you explicitly specify.I do this in my testcases.Untested on generators, I think you are left at the next 'yield' if passed in a generator, which may screw things up downstream.  But then again, this is a 'unittest'I find such a function named . And I have verified that it meets your needs. Just do thisI tend to do this (if I really, really had to):If you have pandas already available you can just do this:This is what I do to ensure a list.
Python

Does  in the Python time module return the system's time or the time in UTC?The  function returns the number of seconds since the epoch as seconds in UTC.Here is some sample output I ran on my computer, converting it to a string as well.The  variable is the time returned in seconds.  I then converted it to a string using the  library making it a string that is human readable. This is for the  that can be used in your text files. (The title of the question was different in the past, so the introduction to this answer was changed to clarify how it could be interpreted a the time. [updated 2016-01-14])You can get the timestamp as a string using the  or  of the :The  differs from  as expected -- otherwise they work the same way:You can render the timestamp to the string explicitly:Or you can be even more explicit to format the timestamp the way you like:If you want the ISO format, use the  method of the object:You can use these in variables for calculations and printing without conversions.Based on the answer from #squiguy, to get a true timestamp I would type cast it from float. At least that's the concept.The answer could be neither or both.On how to get timestamps from UTC time in various Python versions, see  There is no such thing as an \"epoch\" in a specific timezone. The epoch is well-defined as a specific moment in time, so if you change the timezone, the time itself changes as well. Specifically, this time is . So  returns the number of seconds since the epoch.
Python

I want to import a function from another file in the same directory.Sometimes it works for me with  but sometimes I get a:Sometimes it works with , but sometimes I also get a:I don't understand the logic here, and I couldn't find any explanation. This looks completely random.Could someone explain to me what's the logic behind all this?It's quite common to have a layout like this......with a  like this......a  like this......and a  like this......which works fine when you run  or , but fails with , due to the relative import...The way you're supposed to run it is......but it's somewhat verbose, and doesn't mix well with a shebang line like .The simplest fix for this case, assuming the name  is globally unique, would be to avoid using relative imports, and just use......although, if it's not unique, or your package structure is more complex, you'll need to include the directory containing your package directory in , and do it like this......or if you want it to work \"out of the box\", you can frob the  in code first with this...It's kind of a pain, but there's a clue as to why in  written by a certain Guido van Rossum...Whether running scripts inside a package is an antipattern or not is subjective, but personally I find it really useful in a package I have which contains some custom wxPython widgets, so I can run the script for any of the source files to display a  containing only that widget for testing purposes.Once  conflicted with :and to address the issue,  introduced the top level variable :(emphasis mine)In case  is ,  returns empty string. This is why there's empty string literal in the error description:The relevant part of the CPython's :CPython raises this exception if it was unable to find  (the name of the package) in  (accessible as ). Since  is , it's now clear that .  The patch from the  has added , which will be executed  the code above:If  (same as above) is empty string, the error message will be . However, you will only see this in Python 3.6 or newer.Consider a directory (which is a Python ):\nAll of the files in  begin with the same 2 lines of code:I'm including these two lines  to make the order of operations obvious. We can ignore them completely, since they don't affect the execution. and  contain only those two lines (i.e., they are effectively empty). additionally attempts to import  via relative import:We're well aware that  will fail. However, we can run the module with  that will : does all the importing stuff for you and automatically sets , but you can do that yourself in theUnfortunately, setting  alone is not enough. You're going to need to import at least  preceding packages in the module hierarchy, where  is the number of parent directories (relative to the directory of the script) that will be searched for the module being imported.Thus,I'll borrow files from the  and add some more subpackages:This time  will import  from the  package using the following relative importWe'll need to precede that line with the boilerplate code, to make it work.It allows us to execute  by filename:A more general solution wrapped in a function can be found . Example usage:The steps are -For instance, the directory structure may be as followswhere  isThe rest of the files were borrowed from the .Installation will allow you to import the package regardless of your working directory (assuming there'll be no naming issues).We can modify  to use this advantage (step 1):Change your working directory to  and run  ( installs the package in ) (step 2):Let's verify that it's now possible to run  as a script:Frankly, the installation is not necessary - you could add some boilerplate code to your script to make absolute imports work.I'm going to borrow files from  and change : runs without problems:I feel that I should warn you: try not to do this,  if your project has a complex structure.As a side note,  recommends the use of absolute imports, but states that in some scenarios explicit relative imports are acceptable:I ran into this issue.  A Hack work around is using a try/except block like this:if both packages are in your import path (sys.path), and the module/class you want is in example/example.py, then to access the class without relative import try:
Python

I'm trying to convert a list to a tuple. When I google it, I find a lot of answers similar to:But if I do that I get this error message:How can I fix this problem?It should work fine. Don't use ,  or other special names as a variable name. It's probably what's causing your problem.Expanding on eumiro's comment, normally  will convert a list  into a tuple:However, if you've redefined  to be a tuple rather than the  :then you get a TypeError since the tuple itself is not callable:You can recover the original definition for  by quitting and restarting your interpreter, or (thanks to @glglgl):You might have done something like this:Here's the problem... Since you have used a  variable to hold a  earlier... So, now  is an  of type  now...It is no more a  and hence, it is no more . use any built-in types as your variable name... You do have any other name to use. Use any arbitrary name for your variable instead...to convert list to tuple,I find many answers up to date and properly answered but will add something new to stack of answers.In python there are infinite ways to do this, \nhere are some instances\nNormal way Remember tuple is immutable ,used for storing something valuable.\nFor example password,key or hashes are stored in tuples or dictionaries.\nIf knife is needed why to use sword to cut apples.\nUse it wisely,will also make your program efficient. 
Python

Is there any benefit in using compile for regular expressions in Python?vsI've had a lot of experience running a compiled regex 1000s of times versus compiling on-the-fly, and have not noticed any perceivable difference.  Obviously, this is anecdotal, and certainly not a great argument  compiling, but I've found the difference to be negligible.EDIT:\nAfter a quick glance at the actual Python 2.5 library code, I see that Python internally compiles AND CACHES regexes whenever you use them anyway (including calls to ), so you're really only changing WHEN the regex gets compiled, and shouldn't be saving much time at all - only the time it takes to check the cache (a key lookup on an internal  type).From module re.py (comments are mine):I still often pre-compile regular expressions, but only to bind them to a nice, reusable name, not for any expected performance gain.For me, the biggest benefit to  isn't any kind of premature optimization (which is the , ). It's being able to separate definition of the regex from its use.Even a simple expression such as  (integer in base 10 without leading zeros) can be complex enough that you'd rather not have to retype it, check if you made any typos, and later have to recheck if there are typos when you start debugging. Plus, it's nicer to use a variable name such as num or num_b10 than .It's certainly possible to store strings and pass them to re.match; however, that's  readable:Versus compiling:Though it is fairly close, the last line of the second feels more natural and simpler when used repeatedly.FWIW:so, if you're going to be using  the  regex a lot, it may be worth it to do  (especially for more complex regexes).The standard arguments against premature optimization apply, but I don't think you really lose much clarity/straightforwardness by using  if you suspect that your regexps may become a performance bottleneck.Here's a simple test case:with re.compile:    So, it would seem to compiling is faster with this simple case, .I just tried this myself. For the simple case of parsing a number out of a string and summing it, using a compiled regular expression object is about twice as fast as using the  methods.As others have pointed out, the  methods (including ) look up the regular expression string in a cache of previously compiled expressions. Therefore, in the normal case, the extra cost of using the  methods is simply the cost of the cache lookup.However, examination of the , shows the cache is limited to 100 expressions. This begs the question, how painful is it to overflow the cache? The code contains an internal interface to the regular expression compiler, . If we call it, we bypass the cache. It turns out to be about two orders of magnitude slower for a basic regular expression, such as .Here's my test:And here is the output on my machine:The 'reallyCompiled' methods use the internal interface, which bypasses the cache. Note the one that compiles on each loop iteration is only iterated 10,000 times, not one million.I agree with Honest Abe that the  in the given examples are different.  They are not a one-to-one comparisons and thus, outcomes are vary.  To simplify my reply, I use A, B, C, D for those functions in question.  Oh yes, we are dealing with 4 functions in  instead of 3.Running this piece of code:is same as running this code:Because, when looked into the source , (A + B) means:and (C) is actually:So, (C) is not the same as (B).  In fact, (C) calls (B) after calling (D) which is also called by (A).  In other words, .  Therefore, comparing (A + B) inside a loop has same result as (C) inside a loop.  George's  proved this for us.Everyone's interest is, how to get the result of 2.323 seconds.  In order to make sure  only get called once, we need to store the compiled regex object in memory.  If we are using a class, we could store the object and reuse when every time our function get called.If we are not using class (which is my request today), then I have no comment.  I'm still learning to use global variable in Python, and I know global variable is a bad thing.One more point, I believe that using  approach has an upper hand.  Here are some facts as I observed (please correct me if I'm wrong):Here are the only cases that (A + B) is better than (C):Case that (C) is good enough:Just a recap, here are the A B C:Thanks for reading.In general, I find it is easier to use flags (at least easier to remember how), like  when compiling patterns than to use flags inline.vs Interestingly, compiling does prove more efficient for me (Python 2.5.2 on Win XP):Running the above code once as is, and once with the two  lines commented the other way around, the compiled regex is twice as fastI ran this test before stumbling upon the discussion here.  However, having run it I thought I'd at least post my results.I stole and bastardized the example in Jeff Friedl's \"Mastering Regular Expressions\".  This is on a macbook running OSX 10.6 (2Ghz intel core 2 duo, 4GB ram).  Python version is 2.6.1.Using the given examples:The  method in the example above is not the same as the one used below: returns a , which means  is a regex object.The regex object has its own  method with the optional  and  parameters:  The regex object's , , and  methods also support these parameters. does not support them as you can see,\nnor does its , , and  counterparts.A  has attributes that complement these parameters:A  has two unique, possibly useful, attributes:And finally, a  has this attribute:There is one addition perk of using re.compile(), in the form of adding comments to my regex patterns using re.VERBOSEAlthough this does not affect the speed of running your code, I like to do it this way as it is part of my commenting habit. I throughly dislike spending time trying to remember the logic that went behind my code 2 months down the line when I want to make modifications.This is a good question. You often see people use re.compile without reason. It lessens readability. But sure there are lots of times when pre-compiling the expression is called for. Like when you use it repeated times in a loop or some such.It's like everything about programming (everything in life actually). Apply common sense.Performance difference aside, using re.compile and using the compiled regular expression object to do match (whatever regular expression related operations) makes the semantics clearer to Python run-time.I had some painful experience of debugging some simple code:and later I'd use compare in where  is supposed to be a variable containing regular expression string,  is a variable containing string.I had trouble that  did not match some expected string!But if I used the re.compile form:then in Python would have complained that \"string does not have attribute of match\", as by positional argument mapping in ,  is used as regular expression!, when I actually meantIn my case, using re.compile is more explicit of the purpose of regular expression, when it's value is hidden to naked eyes, thus I could get more help from Python run-time checking. So the moral of my lesson is that when the regular expression is not just literal string, then I should use re.compile to let Python to help me to assert my assumption.This answer might be arriving late but is an interesting find. Using compile can really save you time if you are planning on using the regex multiple times (this is also mentioned in the docs). Below you can see that using a compiled regex is the fastest when the match method is directly called on it. passing a compiled regex to re.match makes it even slower and passing re.match with the patter string is somewhere in the middle. Mostly, there is little difference whether you use  or not.  Internally, all of the functions are implemented in terms of a compile step:If you use re.compile() you by-pass a little of overhead for the extra indirection and for the overhead of the caching logic:In addition to the small speed benefit from using , people also like the readability that comes from naming potentially complex pattern specifications and separating them from the business logic where there are applied:Note, one other respondent incorrectly believed that  files stored compiled patterns directly; however, in reality they are rebuilt each time when the PYC is loaded:The above disassembly comes from the PYC file for a  containing:Regular Expressions are compiled before being used when using the second version.  If you are going to executing it many times it is definatly better to compile it first.  If not compiling every time you match for one off's is fine.(months later) it's easy to add your own cache around re.match,\nor anything else for that matter --A wibni, wouldn't it be nice if: cachehint( size= ), cacheinfo() -> size, hits, nclear ...i'd like to motivate that pre-compiling is both conceptually and 'literately' (as in 'literate programming') advantageous. have a look at this code snippet:in your application, you'd write:this is about as simple in terms of functionality as it can get. because this is example is so short, i conflated the way to get  all in one line. the disadvantage of this code is that it occupies a little memory for whatever the lifetime of the  library object is; the advantage is that when doing a foobar search, you'll get away with two function calls and two class dictionary lookups. how many regexes are cached by  and the overhead of that cache are irrelevant here. compare this with the more usual style, below:In the application:I readily admit that my style is highly unusual for python, maybe even debatable. however, in the example that more closely matches how python is mostly used, in order to do a single match, we must instantiate an object, do three instance dictionary lookups, and perform three function calls; additionally, we might get into  caching troubles when using more than 100 regexes. also, the regular expression gets hidden inside the method body, which most of the time is not such a good idea. be it said that every subset of measures---targeted, aliased import statements; aliased methods where applicable; reduction of function calls and object dictionary lookups---can help reduce computational and conceptual complexity. The votes on the accepted answer leads to the assumption that what @Triptych says is true for all cases. This is not necessarily true. One big difference is when you have to decide whether to accept a regex string or a compiled regex object as a parameter to a function:It is always better to compile your regexs in case you need to reuse them. Note the example in the timeit above simulates creation of a compiled regex object once at import time versus \"on-the-fly\" when required for a match.I really respect all the above answers. From my opinion\nYes! For sure it is worth to use re.compile instead of compiling the regex, again and again, every time. My understanding is that those two examples are effectively equivalent. The only difference is that in the first, you can reuse the compiled regular expression elsewhere without causing it to be compiled again.Here's a reference for you: 
Python

Which Python library can I use to extract filenames from paths, no matter what the operating system or path format could be?For example, I'd like all of these paths to return me :Using  or  as others suggest won't work in all cases: if you're running the script on Linux and attempt to process a classic windows-style path, it will fail.Windows paths can use either backslash or forward slash as path separator. Therefore, the  module (which is equivalent to os.path when running on windows) will work for all paths on all platforms.Of course, if the file ends with a slash, the basename will be empty, so make your own function to deal with it:Verification:Actually, there's a  that returns exactly what you want\nis the function you are looking forAssume p is the input string, tail is what you want.See  for detailIn your example you will also need to strip slash from right the right side to return :Second level:update: I think  has provided the right answer. My code will not work with windows-like paths on unix systems and vice versus with unix-like paths on windows system.this will return : This is working for linux and windows as well with standard libraryResults:I have never seen double-backslashed paths, are they existing? The built-in feature of python module  fails for those. All others work, also the caveat given by you with :The Windows separator can be in a Unix filename or Windows Path.  The Unix separator can only exist in the Unix path.  The presence of a Unix separator indicates a non-Windows path.The following will strip (cut trailing separator) by the OS specific separator, then split and return the rightmost value.   It's ugly, but simple based on the assumption above.   If the assumption is incorrect, please update and I will update this response to match the more accurate conditions.sample code:Maybe just my all in one solution without important some new(regard the tempfile for creating temporary files :D )Getting the values of  will be a string like this: \nSo I can replace the  with a space  and then call . That will return a list and I get the\nlast element of the list with No need to get any module imported. best regards4k3nd0Here's a regex-only solution, which seems to work with any OS path on any OS.No other module is needed, and no preprocessing is needed either :The regex can be tested .
Python

How do I get my python program to sleep for 50 milliseconds?Note that if you rely on sleep taking  50ms, you won't get that. It will just be about it.
Python

I understand that pandas is designed to load fully populated  but I need to .\nWhat is the best way to do this ?I successfully created an empty DataFrame with :Then I can add a new row and fill a field with :It works but seems very odd :-/ (it fails for adding string value)How can I add a new row to my DataFrame (with different columns type) ?Example at @Nasser's answer:You could use  or . For details and examples, see .You could create a list of dictionaries, where each dictionary corresponds to an input data row. Once the list is complete, then create a data frame. This is a much faster approach. I had a similar problem where if I created a data frame for each row and appended it to the main data frame it took 30 mins. On the other hand, if I used the below methodology, it was successful within seconds.If you know the number of entries ex ante, you should preallocate the space by also providing the index (taking the data example from a different answer):And - as from the comments - with a size of 6000, the speed difference becomes even larger:For efficient appending see  and .Add rows through  on  key index data. e.g. :Or:You can append a single row as a dictionary using the  option.This is not an answer to the OP question but a toy example to illustrate the answer of @ShikharDua above which I found very useful. While this fragment is trivial, in the actual data I had 1,000s of rows, and many columns, and I wished to be able to group by different columns and then perform the stats below for more than one taget column. So having a reliable method for building the data frame one row at a time was a great convenience. Thank you @ShikharDua ! Create a  and add to .\npass list of  and corresponding  names to create a  (data_frame)Another way to do it (probably not very performant):You can also enhance the DataFrame class like this:
Python

What is the proper way to use  in Python when it comes to default values? returns a dictionary, but what is the best way to set default values, or is there one?  Should I just access it as a dictionary?  Use get function?  A simple question, but one that I can't find good resources on.  People do it different ways in code that I've seen and it's hard to know what to use.You can pass a default value to  for keys that are not in the dictionary:However, if you plan on using a particular argument with a particular default value, why not use named arguments in the first place?While most answers are saying that, e.g.,is \"the same as\"this is not true.  In the latter case,  can be called as , while the former case accepts named arguments  -- no positional calls.  Often you want to allow the caller maximum flexibility and therefore the second form, as most answers assert, is preferable: but that is not always the case.  When you accept many optional parameters of which typically only a few are passed, it may be an excellent idea (avoiding accidents and unreadable code at your call sites!) to force the use of named arguments --  is an example.  The first form is how you implement that in Python 2.The idiom is so important that in Python 3 it now has special supporting syntax: every argument after a single  in the  signature is keyword-only, that is, cannot be passed as a positional argument, but only as a named one. So in Python 3 you could code the above as:Indeed, in Python 3 you can even have keyword-only arguments that  optional (ones without a default value).However, Python 2 still has long years of productive life ahead, so it's better to  forget the techniques and idioms that let you implement in Python 2 important design ideas that are directly supported in the language in Python 3!I suggest something like thisAnd then use the values any way you want adds the contents of  to  overwriting any duplicate keys.You'd doorIf you use , then you can check if there are any spurious values sent, and take the appropriate action (if any).Using **kwargs and default values is easy.  Sometimes, however, you shouldn't be using **kwargs in the first place.In this case, we're not really making best use of **kwargs.The above is a \"why bother?\" declaration.  It is the same asWhen you're using **kwargs, you mean that a keyword is not just optional, but conditional.  There are more complex rules than simple default values.When you're using **kwargs, you usually mean something more like the following, where simple defaults don't apply.Since  is used when the number of arguments is unknown, why not doing this?Here's another approach:You could do something like thisI think the proper way to use **kwargs in Python when it comes to default values is to use the dictionary method setdefault, as given below:In this way, if a user passes 'val' or 'val2' in the keyword args, they will be used; otherwise, the default values that have been set will be used.Following up on  suggestion of using :This variant is useful when the class is expected to have all of the items in our  list.If you want to combine this with *args you have to keep *args and **kwargs at the end of the definition.So:@AbhinavGupta and @Steef suggested using , which I found very helpful for processing large argument lists:What if we want to check that the user hasn't passed any spurious/unsupported arguments? @VinaySajip pointed out that  can be used to iteratively process the list of arguments. Then, any leftover arguments are spurious. Nice.Here's another possible way to do this, which keeps the simple syntax of using : is a  containing the names of arguments that don't occur in the defaults.
Python

How do I have a Python script that can accept user input (assuming this is possible) and how do I make it read in arguments if run from the command line?To read user input you can try  for easily creating a mini-command line interpreter (with help texts and autocompletion) and  for less fancy stuff (just reading a line of text from the user).Command line inputs are in sys.argv. Try this in your script for Python 2:For Python 3:Since print has changed from a keyword in Python 2 into a function call in Python 3. There are two modules for parsing command line options:  and . If you just want to input files to your script, behold the power of .The . is no longer available in Python 3.x.  But  was renamed , so the same functionality exists.The best way to process command line arguments is the Use  to get user input.  If you import the  your users will have line editing and history.Careful not to use the  function, unless you know what you're doing. Unlike ,  will accept any python expression, so it's kinda like If you are running Python <2.7, you need , which as the doc explains will create an interface to the command line arguments that are called when your application is run.However, in Python \u22652.7, optparse has been deprecated, and was replaced with the  as shown above. A quick example from the docs...Use 'raw_input' for input from a console/terminal.if you just want a command line argument like a file name or something e.g. then you can use sys.argv...sys.argv is a list where 0 is the program name, so in the above example sys.argv[1] would be \"file_name.txt\"If you want to have full on command line options use the optparse module.PevThis simple program helps you in understanding how to feed the user input from command line and to show help on passing invalid argument.1) To find the square root of 52) Passing invalid argument other than numberAs of Python  2.7, there is now  for processing command line arguments.If it's a 3.x version then just simply use:For example, you want to input 8:x will equal 8 but it's going to be a string except if you define it otherwise.So you can use the convert command, like:In Python 2:In Python 3:
Python

I was wondering about the best practices for indicating invalid argument combinations in Python. I've come across a few situations where you have a function like so:The only annoyance with this is that every package has its own, usually slightly differing . I know that in Java there exists  -- is it well understood that everybody will be creating their own s in Python or is there another, preferred method?I would just raise , unless you need a more specific exception..There's really no point in doing  - your custom class is identical in use to , so why not use that?I would inherit from It is sometimes better to create your own exceptions, but inherit from a built-in one, which is as close to what you want as possible.If you need to catch that specific error, it is helpful to have a name.I've mostly just seen the builtin  used in this situation.I'm not sure I agree with inheritance from  -- my interpretation of the documentation is that  is  supposed to be raised by builtins... inheriting from it or raising it yourself seems incorrect.-- 
Python

How do you express an integer as a binary number with Python literals?I was easily able to find the answer for hex:and octal:For reference\u2014 Python possibilities:\nStarting with Python 2.6 you can express binary literals using the prefix  or :You can also use the new  function to get the binary representation of a number:Development version of the documentation: Another way.They're not \"binary\" literals, but rather, \"integer literals\". You can express integer literals with a binary format with a  followed by a  or  followed by a series of zeros and ones, for example:From the Python 3 , these are the ways of providing integer literals in Python:You can have the zeros and ones in a string object which can be manipulated (although you should probably just do bitwise operations on the integer in most cases) - just pass int the string of zeros and ones and the base you are converting from (2):You can optionally have the  or  prefix:If you pass it  as the base, it will assume base 10 if the string doesn't specify with a prefix:You can pass an integer to bin to see the string representation of a binary literal:And you can combine  and  to go back and forth:You can use a format specification as well, if you want to have minimum width with preceding zeros:0 in the start here specifies that the base is 8 (not 10), which is pretty easy to see: If you don't start with a 0, then python assumes the number is base 10.As far as I can tell Python, up through 2.5, only supports hexadecimal & octal literals.  I did find some discussions about adding binary to future versions but nothing definite.I am pretty sure this is one of the things due to change in Python 3.0 with perhaps bin() to go with hex() and oct().EDIT:\nlbrandy's answer is correct in all cases.
Python

I have a list:and want to search for items that contain the string . How can I do that?would check if  exists in the list but it is a part of  and ,  does not exist on its own. So how can I get all items that contain  ?If you only want to check for the presence of  in any string in the list, you could tryIf you really want to get all the items containing , useUse  to get at the elements that have .You can also use a list comprehension.By the way, don't use the word  as a variable name since it is already used for the  type.Just throwing this out there: if you happen to need to match against more than one string, for example  and , you can put combine two list comprehensions as follows:Output:This is quite an old question, but I offer this answer because the previous answers do not cope with items in the list that are not strings (or some kind of iterable object). Such items would cause the entire list comprehension to fail with an exception.To gracefully deal with such items in the list by skipping the non-iterable items, use the following:then, with such a list:you will still get the matching items ()The test for iterable may not be the best. Got it from here: This is the shortest way:From my knowledge, a 'for' statement will always consume time.When the list length is growing up, the execution time will also grow.I think that, searching a substring in a string with 'is' statement is a bit faster.But, I agree that the  statement is more readable.
Python

Is this the cleanest way to write a list to a file, since  doesn't insert newline characters?It seems like there would be a standard way...I'd use a loop:or:If you're keen on a single function call, at least remove the square brackets  so that the strings to be printed get made one at a time (a genexp rather than a listcomp) -- no reason to take up all the memory required to materialize the whole list of strings.What are you going to do with the file?  Does this file exist for humans, or other programs with clear interoperability requirements, or are you just trying to serialize a list to disk for later use by the same python app.  If the second case is it, you should be  the list.To read it back:The best way is:Yet another way.  Serialize to json using  (included as  in python 2.6):If you examine output.txt:This is useful because the syntax is pythonic, it's human readable, and it can be read by other programs in other languages.Using  syntax:This is platform-independent.I thought it would be interesting to explore the benefits of using a genexp, so here's my take.The example in the question uses square brackets to create a temporary list, and so is equivalent to:Which needlessly constructs a temporary list of all the lines that will be written out, this may consume significant amounts of memory depending on the size of your list and how verbose the output of  is.Drop the square brackets (equivalent to removing the wrapping  call above) will instead pass a temporary  to :This generator will create newline-terminated representation of your  objects on-demand (i.e. as they are written out). This is nice for a couple of reasons:This avoids memory issues, such as:(I triggered this error by limiting Python's max. virtual memory to ~100MB with ).Putting memory usage to one side, this method isn't actually any faster than the original:(Python 2.6.2 on Linux)Following is the syntax for  methodSerialize list into text file with comma sepparated valueYou can also use the print function if you're on python3 as follows.Why don't you tryLet avg be the list, then:You can use  or  depending on your requirement.How It Works:\nFirst, open a \ufb01le by using the built-in open function and specifying the name of\nthe \ufb01le and the mode in which we want to open the \ufb01le. The mode can be a\nread mode (\u2019r\u2019), write mode (\u2019w\u2019) or append mode (\u2019a\u2019). We can also specify\nwhether we are reading, writing, or appending in text mode (\u2019t\u2019) or binary\nmode (\u2019b\u2019). There are actually many more modes available and help(open)\nwill give you more details about them. By default, open() considers the \ufb01le to\nbe a \u2019t\u2019ext \ufb01le and opens it in \u2019r\u2019ead mode.\nIn our example, we \ufb01rst open the \ufb01le in write text mode and use the write\nmethod of the \ufb01le object to write to the \ufb01le and then we \ufb01nally close the \ufb01le.\n
Python

I have a basic dict as follows:When I try to do  I get:What can I do such that my dictionary sample can overcome the error above?Note: Though it may not be relevant, the dictionaries are generated from the retrieval of records out of mongodb where when I print out , the output is .As you are using mongoengine (per comments) and pymongo is a dependency, pymongo has built-in utilities to help with json serialization:\nExample usage (serialization):Example usage (deserialization):Building on other answers, a simple solution based on a specific serializer that just converts  and  objects to strings.As seen, the code just checks to find out if object is of class  or , and then uses  to produce a serialized version of it, according to ISO 8601 format, YYYY-MM-DDTHH:MM:SS (which is easily decoded by JavaScript). If more complex serialized representations are sought, other code could be used instead of str() (see other answers to this question for examples). The code ends by raising an exception, to deal with the case it is called with a non-serializable type.This json_serial function can be used as follows:The details about how the default parameter to json.dumps works can be found in . Convert the date to a stringI have just encountered this problem and my solution is to subclass :In your call do something like:  The  I got from one of the answers above.For others who do not need or want to use the pymongo library for this.. you can achieve datetime JSON conversion easily with this small snippet:Then use it like so:output:\u00a0My quick & dirty JSON dump that eats dates and everything:I have an application with a similar issue; my approach was to JSONize the datetime value as a 6-item list (year, month, day, hour, minutes, seconds); you could go to microseconds as a 7-item list, but I had no need to:produces:Here is my solution:Then you can use it like that:My solution (with less verbosity, I think):Then use  instead of . It will print:I you want, later you can add other special cases to this with a simple twist of the  method. Example:  This Q repeats time and time again - a simple way to patch the json module such that serialization would support datetime.  Than use json serialization as you always do - this time with datetime being serialized as isoformat.Resulting in: '{\"created\": \"2015-08-26T14:21:31.853855\"}'See more details and some words of caution at:\nHere is a simple solution to over come \"datetime not JSON serializable\"\nproblem.  {\"date\": \"2015-12-16T04:48:20.024609\"} You have to supply a custom encoder class with the  parameter of . To quote from the :This uses complex numbers as the example, but you can just as easily create a class to encode dates (except I think JSON is a little fuzzy about dates)The simplest way to do this is to change the part of the dict that is in datetime format to isoformat. That value will effectively be a string in isoformat which json is ok with.Here is my full solution for converting datetime to JSON and back..OutputJSON FileThis has enabled me to import and export strings, ints, floats and datetime objects.\nIt shouldn't be to hard to extend for other types.If you are using the result in a view be sure to return a proper response. According to the API, jsonify does the following:To mimic this behavior with json.dumps you have to add a few extra lines of code.You should also return a dict to fully replicate jsonify's response. So, the entire file will look like thisMy solution ...Ok, now some tests.I got the same error message while writing the serialize decorator inside a Class  with sqlalchemy. So instead of :I  simply borrowed jgbarah's idea of using isoformat() and appended the original value with isoformat(), so that it now looks like:Convert the   to  A quick fix if you want your own formattingGenerally there are several ways to serialize datetimes, like:If you're okay with the last way, the  package handles dates, times and datetimes including timezones.which gives:So all you need to do isand then import from  instead of .The advantage of not storing it as a single string, int or float comes when decoding: if you encounter just a string or especially int or float, you need to know something about the data to know if it's a datetime. As a dict, you can store metadata so it can be decoded automatically, which is what  does for you. It's also easily editable for humans.Disclaimer: it's made by me. Because I had the same problem.I had encountered same problem when externalizing django model object to dump as JSON.\nHere is how you can solve it.Either make both the dates in mysql as well as in python code json as String or both date or datetime.\nIt worked for me as I converted mysql type to String.My solution was just to use EPOCH time (which is a number) since my use case didn't require an end user to read the time in the JSON. It was SO MUCH EASIER to work with epoch time.I may not 100% correct but,\nthis is the simple way to do serialize
Python

I am learning the ropes in Python. When I try to print an object of class  using the  function, I get an output like this:Is there a way I can set the  (or the ) of a  and its ? For instance, when I call  on a class object, I would like to print its data members in a certain format. How to achieve this in Python?If you are familiar with C++ classes, the above can be achieved for the standard  by adding a  method for the class.The  method is what happens when you print it, and the  method is what happens when you use the  function (or when you look at it with the interactive prompt). If this isn't the most  method, I apologize, because I'm still learning too - but it works.If no  method is given, Python will print the result of  instead. If you define  but not , Python will use what you see above as the , but still use  for printing.As Chris Lutz mentioned, this is defined by the  method in your class.From the documentation of :Given the following class Test:..it will act the following way in the Python shell:If no  method is defined,  (or ) will use the result of  insteadIf no  method is defined then the default is used, which is pretty much equivalent to..You need to use . This is a standard function like .\nFor example:Just to add my two cents to @dbr's answer, following is an example of how to implement this sentence from the official documentation he's cited:Given this class definition:Now, is easy to serialize instance of  class:So, running last piece of code, we'll get:But, as I said in my last comment: more info is just !A generic way that can be applied to any class without specific formatting could be done as follows:And then,producesFor Python 3:If the specific format isn't important (e.g. for debugging) just inherit from the Printable class below.  No need to write code for every object.  Inspired by  answerThere are already a lot of answers in this thread but none of them particularly helped me, I had to work it out myself, so I hope this one is a little more informative.You just have to make sure you have parentheses at the end of your class, e.g:Here's an example of code from a project I was working on:To print my Hydrogen class, I used the following:Please note, this will not work without the parentheses at the end of Hydrogen. They are necessary.Hope this helps, let me know if you have anymore questions. 
Python

I have a Python script which takes as input a list of integers, which I need to work with four integers at a time.  Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples.  Currently, I'm iterating over it this way:It looks a lot like \"C-think\", though, which makes me suspect there's a more pythonic way of dealing with this situation.  The list is discarded after iterating, so it needn't be preserved.  Perhaps something like this would be better?Still doesn't quite \"feel\" right, though.  :-/Related question: Modified from the  section of Python's  docs:\nIn pseudocode to keep the example terse.  is new to Python 2.6. In Python 3 use .Simple. Easy. Fast. Works with any sequence:I'm a fan of Another way:Posting this as an answer since I cannot comment...Using map() instead of zip() fixes the padding issue in J.F. Sebastian's answer:Example:I needed a solution that would also work with sets and generators. I couldn't come up with anything very short and pretty, but it's quite readable at least.List:Set:Generator:Similar to other proposals, but not exactly identical, I like doing it this way, because it's simple and easy to read:This way you won't get the last partial chunk. If you want to get  as last chunk, just use  from .Since nobody's mentioned it yet here's a  solution:It works only if your sequence's length is always divisible by the chunk size or you don't care about a trailing chunk if it isn't.Example:Or using  to return an iterator instead of a list:Padding can be fixed using :Using little functions and things really doesn't appeal to me; I prefer to just use slices:If the list is large, the highest-performing way to do this will be to use a generator:In your second method, I would advance to the next group of 4 by doing this:However, I haven't done any performance measurement so I don't know which one might be more efficient.Having said that, I would usually choose the first method. It's not pretty, but that's often a consequence of interfacing with the outside world.Yet another answer, the advantages of which are:1) Easily understandable\n2) Works on any iterable, not just sequences (some of the above answers will choke on filehandles)\n3) Does not load the chunk into memory all at once\n4) Does not make a chunk-long list of references to the same iterator in memory\n5) No padding of fill values at the end of the listThat being said, I haven't timed it so it might be slower than some of the more clever methods, and some of the advantages may be irrelevant given the use case.\nA couple of drawbacks due to the fact the inner and outer loops are pulling values from the same iterator:\n1) continue doesn't work as expected in the outer loop - it just continues on to the next item rather than skipping a chunk. However, this doesn't seem like a problem as there's nothing to test in the outer loop.\n2) break doesn't work as expected in the inner loop - control will wind up in the inner loop again with the next item in the iterator. To skip whole chunks, either wrap the inner iterator (ii above) in a tuple, e.g. , or set a flag and exhaust the iterator.Another approach would be to use the two-argument form of : This can be adapted easily to use padding (this is similar to \u2019s answer):These can even be combined for optional padding:You can use  or  function from  library:These functions also has iterator versions  and , which will be more efficient in this case.You can also peek at .To avoid all conversions to a list  and:Produces:I checked  and it doesn't convert to list or use  so I (think) this will delay resolution of each value until it is actually used.  Sadly none of the available answers (at this time) seemed to offer this variation.Obviously if you need to handle each item in turn nest a for loop over g:My specific interest in this was the need to consume a generator to submit changes in batches of up to 1000 to the gmail API:With NumPy it's simple:output:About solution gave by  :It's clever, but has one disadvantage - always return tuple. How to get string instead?\nOf course you can write , but the temporary tuple is constructed anyway.You can get rid of the temporary tuple by writing own , like this:ThenExample usage:Here is a chunker without imports that supports generators:Example of use:There doesn't seem to be a pretty way to do this.   is a page that has a number of methods, including:If the lists are the same size, you can combine them into lists of 4-tuples with . For example:Here's what the  function produces:If the lists are large, and you don't want to combine them into a bigger list, use , which produces an iterator, rather than a list.The ideal solution for this problem works with iterators (not just sequences). It should also be fast.This is the solution provided by the documentation for itertools:Using ipython's  on my mac book air, I get 47.5 us per loop.However, this really doesn't work for me since the results are padded to be even sized groups. A solution without the padding is slightly more complicated. The most naive solution might be:Simple, but pretty slow: 693 us per loopThe best solution I could come up with uses  for the inner loop:With the same dataset, I get 305 us per loop.Unable to get a pure solution any faster than that, I provide the following solution with an important caveat: If your input data has instances of  in it, you could get wrong answer.I really don't like this answer, but it is significantly faster. 124 us per loopOne-liner, adhoc solution to iterate over a list  in chunks of size  -At first, I designed it to split strings into substrings to parse string containing hex.\nToday I turned it into complex, but still simple generator.It is easy to make  work for you to get an iterable of iterables, without creating any temporary lists:Don't get put off by the nested lambdas, outer lambda runs just once to put  generator and the constant  into the scope of the inner lambda.I use this to send chunks of rows to mysql.I like this. It feels simple and not magical, and supports all iterable types.
Python

Why do I receive a syntax error when printing a string in Python 3?In Python 3,  . This means that you need to include parenthesis now like mentioned below:It looks like you're using Python 3.0, in which  rather than a statement.Because in Python 3,  has been replaced with a , with keyword arguments to replace most of the special syntax of the old print statement. So you have to write it as But if you write this in a programme and some one using Python 2.x tries to run, they will get an error. To avoid this, it is a good practice to import print functionNow you code works on both 2.x & 3.xCheck out below examples also to get familiar with print() function.Source: In Python 3.0,  is a regular function that requires ():In Python 3, it's  , not .It looks like you're using Python 3. In Python 3, print has been changed to a method instead of a statement. Try this:You have to use bracket with print In Python 3, you must do . This is because in Python 3 it has become a function. If you must, you can use your Python 2 code and convert it to Python 3 code using  - it is a great built-in program which comes with Python. For more, see .In Python 2.X  is a keyword as you can see in this . However, in Python 3.X  becomes a function, so the correct way to do it is .\nYou can get the list of keywords for each version by executing the following:2to3 is a Python program that reads Python 2.x source code and applies a series of fixers to transform it into valid Python 3.x codeFurther informations can be found here: 
Python

What would be your preferred way to concatenate strings from a sequence such that between each two consecutive pair a comma is added. That is, how do you map, for instance,  to ? (The cases  and  should be mapped to  and , respectively.)I usually end up using something like , but also feeling somewhat unsatisfied.Edit: I'm both ashamed and happy that the solution is so simple. Obviously I have hardly a clue as to what I'm doing. (I probably needed \"simple\" concatenation in the past and somehow memorised  as a shorthand for .)This won't work if the list contains numbers.As  suggested, if it contains non-string types (such as integers, floats, bools, None) then do:Why the map/lambda magic? Doesn't this work?Edit: @mark-biek points out the case for numbers.\nPerhaps the list comprehension:is more \"pythonic\".Edit2:\nThanks for the suggestions. I'll use the generator rather than the list comprehension in the future.Don't you just want:Obviously it gets more complicated if you need to quote/escape commas etc in the values. In that case I would suggest looking at the csv module in the standard library:@Peter HoffmannUsing generator expressions has the benefit of also producing an iterator but saves importing itertools. Furthermore, list comprehensions are generally preferred to map, thus, I'd expect generator expressions to be preferred to imap.Here is a alternative solution in Python 3.0 which allows non-string list items:NOTE: The space after comma is intentional.@jmanning2k using a list comprehension has the downside of creating a new temporary list. The better solution would be using itertools.imap which returns an iterator will not work for all cases. I'd suggest using the csv module with StringIOfor converting list containing numbers do the following:Unless I'm missing something,  should do what you're asking for.(edit:  and as jmanning2k points out, is safer and quite Pythonic, though the resulting string will be difficult to parse if the elements can contain commas -- at that point, you need the full power of the  module, as Douglas points out in his answer.)Here is an example with listMore Accurate:-Example 2:- may contain any type of variables. This avoid the result .
Python

I want to install . It should support Python 3, but it requires setuptools, which is available only for Python 2.How can I install pip with Python 3?edit: Manual installation and use of  is not the standard process anymore.Congrats, you  already have  installed. If you do not, read onward.You can usually install the package for  through your package manager if your version of Python is older than 2.7.9 or 3.4, or if your system did not include it for whatever reason.Instructions for some of the more common distros follow.Run the following command from a terminal:Run the following command from a terminal:On CentOS 7, you have to install setup tools first, and then use that to install , as there is no direct package for it.Assuming you installed Python 3.4 , you can install Python 3's setup tools and use it to install .Install using the manual way detailed below.If you want to do it the manual way, the now-recommended method is to install using the  script from .I was able to install pip for python 3 on Ubuntu just by running . Good news!  (released March 2014) ships with Pip. This is the best feature of any Python release. It makes the community's wealth of libraries accessible to everyone. Newbies are no longer excluded by the prohibitive difficulty of setup. In shipping with a package manager, Python joins Ruby, Nodejs, Haskell, Perl, Go--almost every other contemporary language with a majority open-source community. Thank you Python.Of course, that doesn't mean Python packaging is problem solved. The experience remains frustrating. I discuss this at Alas for everyone using an earlier Python. Manual instructions follow.Follow my detailed instructions at   . EssentiallyPer Download , being careful to save it as a  file rather than . Then, run it from the command prompt.You possibly need an administrator command prompt to do this. Follow For me, this installed Pip at . Find  on your computer, then add its folder (eg.  ) to your path (Start / Edit environment variables). Now you should be able to run  from the command line. Try installing a package:There you go (hopefully)! For Ubuntu 12.04 or older, won't work. Instead, use:As per  the current way is:I think that should work for any versionI'm not sure when exactly this was introduced, but it's installed pip3 for me when it didn't already exist.To install packages in Python always follow these steps:Note: This is assuming no alias is set for Through this method, there will be no confusion regarding which python version is receiving the package.If you use several different versions of python try using  Then install a local environment in the current directory by:Then there are now an local pythonenvironment in that folder. Now there should be use \n to list the local installed libraries.use  to install at the local environment.use  to run your python script.if you're using python 3.4+just type:Here is my way to solve this problem at ubuntu 12.04:Then install the python3 from source code:When you finished installing all of them, pip3 will get installed automatically.This is what I did on OS X Mavericks to get this to work.Firstly, have  installedInstall python 3.4Then I get the latest version of distribute:I hope this helps.For python3 try this:The good thing is that It will also detect what version of python you have (even if it's an environment of python in your custom location).\nAfter this you can proceed normally with (for example)source:\nAssuming you are in a highly restricted computer env (such as myself) without root access or ability to install packages...  I had never setup a fresh/standalone/raw/non-root instance of Python+virtualenv before this post.  I had do quite a bit of Googling to make this work.Then... pip, pip, pip!Final tip to newbie Pythoneers: You don't think you need virtualenv when you start, but you will be happy to have it later.  Helps with \"what if\" installation / upgrade scenarios for open source / shared packages.Ref: pip should always be availableBy default, the commands pipX and pipX.Y will be installed on all platforms (where X.Y stands for the version of the Python installation), along with the pip Python package and its dependencies.so if you have python 3.4 installed, you can just: To install pip, securely download .Then run the following:Refer: 
Python

I'm having some brain failure in understanding reading and writing text to a file (Python 2.4).So I type in  into my favorite editor, in file f2.Then:What am I not understanding here? Clearly there is some vital bit of magic (or good sense) that I'm missing. What does one type into text files to get proper conversions?What I'm truly failing to grok here, is what the point of the UTF-8 representation is, if you can't actually get Python to recognize it, when it comes from outside. Maybe I should just JSON dump the string, and use that instead, since that has an asciiable representation! More to the point, is there an ASCII representation of this Unicode object that Python will recognize and decode, when coming in from a file?  If so, how do I get it?In the notationthe \"\\xe1\" represents just one byte. \"\\x\" tells you that \"e1\" is in hexadecimal.\nWhen you writeinto your file you have \"\\xc3\" in it. Those are 4 bytes and in your code you read them all. You can see this when you display them:You can see that the backslash is escaped by a backslash. So you have four bytes in your string: \"\\\", \"x\", \"c\" and \"3\".Edit:As others pointed out in their answers you should just enter the characters in the editor and your editor should then handle the conversion to UTF-8 and save it.If you actually have a string in this format you can use the  codec to decode it into a normal string:The result is a string that is encoded in UTF-8 where the accented character is represented by the two bytes that were written  in the original string. If you want to have a unicode string you have to decode again with UTF-8.To your edit: you don't have UTF-8 in your file. To actually see how it would look like:Compare the content of the file  to the content of the file you saved with your editor.Rather than mess with the encode and decode methods I find it easier to use the open method from the codecs module.Then after calling f's read() function, an encoded Unicode object is returned.If you know the encoding of a file, using the codecs package is going to be much less confusing.See So, I've found a solution for what I'm looking for, which is:There are some unusual codecs that are useful here. This particular reading allows one to take UTF-8 representations from within Python, copy them into an ASCII file, and have them be read in to Unicode. Under the \"string-escape\" decode, the slashes won't be doubled.This allows for the sort of round trip that I was imagining.Now all you need in Python3 is Python3 added the  parameter to its open function. The following information about the open function is gathered from here: So by adding  as a parameter to the open function, the file reading and writing is all done as utf8 (which is also now the default encoding of everything done in Python.)Actually, this worked for me for reading a file with UTF-8 encoding in Python 3.2:To read in an Unicode string and then send to HTML, I did this:Useful for python powered http servers.Well, your favorite text editor does not realize that  are supposed to be character literals, but it interprets them as text. That's why you get the double backslashes in the last line -- it's now a real backslash + , etc. in your file.If you want to read and write encoded files in Python, best use the  module.Pasting text between the terminal and applications is difficult, because you don't know which program will interpret your text using which encoding. You could try the following:Then paste this string into your editor and make sure that it stores it using Latin-1. Under the assumption that the clipboard does not garble the string, the round trip should work.You have stumbled over the general problem with encodings: How can I tell in which encoding a file is?Answer: You can't  the file format provides for this. XML, for example, begins with:This header was carefully chosen so that it can be read no matter the encoding. In your case, there is no such hint, hence neither your editor nor Python has any idea what is going on. Therefore, you must use the  module and use  which provides the missing bit in Python.As for your editor, you must check if it offers some way to set the encoding of a file.The point of UTF-8 is to be able to encode 21-bit characters (Unicode) as an 8-bit data stream (because that's the only thing all computers in the world can handle). But since most OSs predate the Unicode era, they don't have suitable tools to attach the encoding information to files on the hard disk.The next issue is the representation in Python. This is explained perfectly in the . You must understand that your console can only display ASCII. In order to display Unicode or anything >= charcode 128, it must use some means of escaping. In your editor, you must not type the escaped display string but what the string means (in this case, you must enter the umlaut and save the file).That said, you can use the Python function eval() to turn an escaped string into a string:As you can see, the string \"\\xc3\" has been turned into a single character. This is now an 8-bit string, UTF-8 encoded. To get Unicode: asked: I think there are some pieces missing here: the file f2 contains: hex:, for example, reads them all in a separate chars (expected) Is there any way to write to a file in ASCII that would work?Answer: That depends on what you mean. ASCII can't represent characters > 127. So you need some way to say \"the next few characters mean something special\" which is what the sequence \"\\x\" does. It says: The next two characters are the code of a single character. \"\\u\" does the same using four characters to encode Unicode up to 0xFFFF (65535).So you can't directly write Unicode to ASCII (because ASCII simply doesn't contain the same characters). You can write it as string escapes (as in f2); in this case, the file can be represented as ASCII. Or you can write it as UTF-8, in which case, you need an 8-bit safe stream.Your solution using  does work, but you must be aware how much memory you use: Three times the amount of using .Remember that a file is just a sequence of bytes with 8 bits. Neither the bits nor the bytes have a meaning. It's you who says \"65 means 'A'\". Since  should become \"\u00e0\" but the computer has no means to know, you must tell it by specifying the encoding which was used when writing the file.The \\x.. sequence is something that's specific to Python. It's not a universal byte escape sequence. How you actually enter in UTF-8-encoded non-ASCII depends on your OS and/or your editor. . For OS X to enter  with an acute accent you can just hit  + , then , and almost all text editors in OS X support UTF-8.You can also improve the original  function to work with Unicode files by replacing it in place, using the  function. The beauty of this solution is you don't need to change any old code. It's transparent.I was trying to parse  using Python 2.7.9:But I was getting:and it was fixed with just:(Now it can print lik\u00e9 \u00e1 b\u00f6ss.)
Python

I'm using the Python bindings to run Selenium WebDriver.I know I can grab a webelement like so...And I know I can get the full page source with...But is there anyway to get the \"element source\"?The selenium webdriver docs for Python are basically non-existent and I don't see anything in the code that seems to enable that functionality.Any thoughts on the best way to access the HTML of an element (and its children)?You can read  attribute to get source of the  of the element or  for source  the current element.Python:Java:C#:Ruby:JS:Tested and works with the .There is not really a straight-forward way of getting the html source code of a webelement. You will have to use JS. I am not too sure about python bindings but you can easily do like this in Java. I am sure there must be something similar to  class in Python.Sure we can get all HTML source code with this script below in Selenium Python:If you you want to save it to file:I suggest saving to a file because source code is very very long.In Ruby, using selenium-webdriver (2.32.1), there is a  method that contains the entire page source.Using the attribute method is, in fact, easier and more straight forward.  Using Ruby with the Selenium and PageObject gems, to get the class associated with a certain element, the line would be . The same concept applies if you wanted to get other attributes tied to the element. For example, if I wanted the String of an element, . Looks outdated, but let it be here anyway. The correct way to do it in your case:orBoth are working for me (selenium-server-standalone-2.35.0)Java with Selenium 2.53.0I hope this could help:\nHere is described Java method:But unfortunately it's not available in Python. So you can translate the method names to Python from Java and try another logic using present methods without getting the whole page source...E.g.And in PHPUnit selenium test it's like this:If you are interested in a solution for Remote Control in Python, here is how to get innerHTML:This code really works to get JavaScript from source as well!
Python

I have a python script that needs to execute an external program, but for some reason fails.If I have the following script:Then it fails with the following error:If I escape the program with quotes:Then it works. However, if I add a parameter, it stops working again:What is the right way to execute a program and wait for it to complete? I do not need to read output from it, as it is a visual program that does a job and then just exits, but I need to wait for it to complete.Also note, moving the program to a non-spaced path is not an option either. This does not work either:Note the swapped single/double quotes.with or without a parameter to notepad here, it fails with the error message will avoid problems with having to deal with quoting conventions of various shells. It accepts a list, rather than a string, so arguments are more easily delimited. i.e.Here's a different way of doing it.If you're using windows the following acts like double-clicking the file in Explorer, or giving the file name as an argument to the DOS \"start\" command:  the file is opened with whatever application (if any) its extension is associated.Example:This will open textfile.txt with notepad if notepad is associted with .txt files.The outermost quotes are consumed by Python itself, and the Windows shell doesn't see it. As mentioned above, Windows only understands double-quotes. \nPython will convert forward-slashed to backslashes on Windows, so you can useThe ' is consumed by Python, which then passes \"C://Temp/a b c/Notepad.exe\" (as a Windows path, no double-backslashes needed) to CMD.EXEAt least in Windows 7 and Python 3.1,  in Windows wants the command line  if there are spaces in path to the command. For example:A real-world example that was stumping me was cloning a drive in VirtualBox. The  solution above didn't work because of some access rights issue, but when I double-quoted the command,  became happy:I suspect it's the same problem as when you use shortcuts in Windows... Try this:
Python

How do I get the path of a the Python script I am running in? I was doing , however on Mac I only get the filename - not the full path as I do on Windows.No matter where my application is launched from, I want to open files that are relative to my script file(s). will give you the path of the current file, resolving any symlinks in the path. This works fine on my mac.7.2 of Dive Into Python: .The accepted solution for this will not work if you are planning to compile your scripts using py2exe.  If you're planning to do so, this is the functional equivalent:Py2exe does not provide an  variable.  For reference:  If you have even the relative pathname (in this case it appears to be ) you can open files relative to your script file(s). I use Perl, but the same general solution can apply: I split the directory into an array of folders, then  off the last element (the script), then  (or for you, ) on whatever I want, and then join them together again, and BAM! I have a working pathname that points to exactly where I expect it to point, relative or absolute.Of course, there are better solutions, as posted. I just kind of like mine.
Python

Can I run the python interpreter without generating the compiled .pyc files?From :Update 2010-11-27: Python 3.2 addresses the issue of cluttering source folders with  files by introducing a special  subfolder, see .There actually IS a way to do it in Python 2.3+, but it's a bit esoteric.  I don't know if you realize this, but you can do the following:According to the  library:Thus, all you have to do is zip the files up, add the zipfile to your sys.path and then import them.If you're building this for UNIX, you might also consider packaging your script using this recipe:  , but note that you might have to tweak this if you plan on using stdin or reading anything from sys.args (it CAN be done without too much trouble).In my experience performance doesn't suffer too much because of this, but you should think twice before importing any very large modules this way.In 2.5, theres no way to suppress it, other than measures like not giving users write access to the directory.In python 2.6 and 3.0 however, there may be a setting in the sys module called \"dont_write_bytecode\" that can be set to suppress this.  This can also be set by passing the \"-B\" option, or setting the environment variable \"PYTHONDONTWRITEBYTECODE\"I have several test cases in a test suite and before I was running the test suite in the Mac Terminal like this: Running the command this way my directory was being populated with .pyc files. I tried the below stated method and it solved the issue:This method works if you are importing test cases into the test suite and running the suite on the command line. As far as I know python will compile all modules you \"import\". However python will NOT compile a python script run using: \"python script.py\" (it will however compile any modules that the script imports).The real questions is why you don't want python to compile the modules? You could probably automate a way of cleaning these up if they are getting in the way.You could make the directories that your modules exist in read-only for the user that the Python interpreter is running as.I don't think there's a more elegant option.  appears to have been an attempt to introduce a simple option for this, but it appears to have been abandoned.I imagine there's probably some other problem you're trying to solve, for which disabling .py[co] would appear to be a workaround, but it'll probably be better to attack whatever this original problem is instead.
Python

How can I get the current time in milliseconds in Python? For what I needed, here's what I did, based on @samplebias' comment above:Quick'n'easy. Thanks all, sorry for the brain fart.For reuse:Then:time.time() may only give resolution to the second, the preferred approach for milliseconds is datetimeanother solution is the function you can embed into your own utils.pyIf you want a simple method in your code that returns the milliseconds with datetime:Microseconds is 1/1000000 seconds, milliseconds is 1/1000 seconds sodt.microseconds/1000.0 should be dt.microseconds/1000000.0
Python

Is there a way to dump a NumPy array into a CSV file? I have a 2D NumPy array and need to dump it in human-readable format. saves an array to a text file. is a convenient function to do this:The man page has some useful notes:Note. This fuction does not produce multi-line csv files, it saves everything to one line.It's easy and fast with pandasWriting record arrays as CSV files with headers requires a bit more work.This example reads a CSV file with the header on the first line, then writes the same file.Note that this example does not consider strings with commas, which would require quotes.If you want to save your numpy array (e.g. ) to one cell, you could convert it first with .Then save it the normal way to one cell, with \nand the cell in the csv-file will look like this Then you could restore your array like this:\nHere 'a' is the name of numpy array and 'file' is the variable to write in a file.
Python

In Python, without using the  module, is there a way to determine a function's name from within that function?Say I have a module foo with a function bar.  When executing , is there a way for bar to know bar's name?  Or better yet, 's name?Python doesn't have a feature to access the function or its name within the function itself. It has been  but rejected. If you don't want to play with the stack yourself, you should either use  or  depending on context.There are a few ways to get the same result:Note that the  calls are thousands of times slower than the alternatives:You can get the name that it was defined with using , but that may not be the name that the function was called with:Whether that distinction is important to you or not I can't say.I wanted a very similar thing because I wanted to put the function name in a log string that went in a number of places in my code. Probably not the best way to do that, but here's a way to get the name of the current function.I found a wrapper that will write the function nameThis will printI keep this handy utility nearby:Usage:This is actually derived from the other answers to the question.Here's my take:The likely advantage of this version over using inspect.stack() is that it should be thousands of times faster [see Alex Melihoff's post and timings regarding using sys._getframe() versus using inspect.stack() ].In IDE the code outputsI guess  is the best way to do this. Example:Here's a future-proof approach.Combining @CamHart's and @Yuval's suggestions with @RoshOxymoron's  has the benefit of avoiding:So I think this plays nice with future python versions (tested on 2.7.3 and 3.3.2): seems to work too (Python 3.5).Test:Output:Your could use a decorator/wrapper:I do my own approach used for calling super with safety inside multiple inheritance scenario (I put all the code)sample usage:testing it :output:I did what CamHart said:Output:
Python

What will happen if two modules import each other?To generalize the problem, what about the cyclic imports in Python?There was a really good discussion on this over at  last year. It answers your question pretty thoroughly.If you do  inside  and  inside , it will work fine. By the time anything actually runs, both modules will be fully loaded and will have references to each other.The problem is when instead you do  and . Because now each module requires the other module to already be imported (so that the name we are importing exists) before it can be imported.Cyclic imports terminate, but you need to be careful not to use the cyclically-imported modules during module initialization.Consider the following files:a.py:b.py:If you execute a.py, you'll get the following:On the second import of b.py (in the second ), the Python interpreter does not import  again, because it already exists in the module dict.If you try to access  from  during module initialization, you will get an .Append the following line to :Then, the output is:This is because modules are executed on import and at the time  is accessed, the line  has not be executed yet, which will only happen after .As other answers describe this pattern is acceptable in python:Which will avoid the execution of the import statement when the file is imported by other modules. Only if there is a logical circular dependency, this will fail.Most Circular Imports are not actually logical circular imports but rather raise  errors, because of the way  evaluates top level statements of the entire file when called.:Consider this circular import:From David Beazleys excellent talk , , here is a way to deal with circular imports in python:This tries to import  and if  is raised, because it already is imported, it will pull it from the importcache.I got an example here that struck me! $ python main.pyI completely agree with pythoneer's answer here. But I have stumbled on some code that was flawed with circular imports and caused issues when trying to add unit tests. So to quickly patch it without changing everything you can resolve the issue by doing a dynamic import.Again, this isn't a permanent fix but may help someone that wants to fix an import error without changing too much of the code.Cheers! Ok, I think I have a pretty cool solution.\nLet's say you have file  and file .\nYou have a  or a  in file  that you want to use in module , but you have something else, either a , , or variable from file  that you need in your definition or class in file . \nWhat you can do is, at the bottom of file , after calling the function or class in file  that is needed in file , but before calling the function or class from file  that you need for file , say \nThen, and here is the , in all of the definitions or classes in file  that need the  or  from file  (let's call it ), you say This works because you can import file  without Python executing any of the import statements in file , and thus you elude any circular imports.For example:Voila.
Python

I found some answers online, but I have no experience with regular expressions, which I believe is what is needed here.I have a string that needs to be split by either a ';' or ', '\nThat is, it has to be either a semicolon or a comma followed by a space. Individual commas without trailing spaces should be left untouchedExample string:should be split into a list containing the following:Luckily, Python has this built-in :)Following your comment:Do a  and then a Here's a safe way for any iterable of delimiters, using regular expressions: allows to build the pattern automatically and have the delimiters escaped nicely.Here's this solution as a function for your copy-pasting pleasure:If you're going to split often using the same delimiters, compile your regular expression beforehand like described and use .In response to Jonathan's answer above, this only seems to work for certain delimiters.  For example:By putting the delimiters in square brackets it seems to work more effectively.This is how the regex look like:
Python

I have a file called , located on . has a subdirectory called , with a file called :I want to import  from . I have tried this:Which resulted:Any ideas how to import  from the subdirectory?The  was the problem, but don't forget to refer to  as , or use:Take a look at the Packages documentation (Section 6.4) here: In short, you need to put a blank file named in the \"lib\" directory.Much later -- in linux, it would look like this:You can try inserting it in :Does your lib directory contain a  file?Python uses  to determine if a directory is a module.Try . For more information read about relative import in .I do this which basically covers all cases (make sure you have  in relative/path/to/your/lib/folder):\n \nYou have in your project folder: You have in another project folder: You want to use  and call foo function which is in it.So you write in app.py:try this:
Python

I want to find out the following:\ngiven a date ( object), what is the corresponding day of the week.For instance Sunday is the first day, Monday: second day.. and so onAnd then if the input is something like Today's date.\nThe output is maybe  (since its Friday)Use  ():From the documentation:If you'd like to have the date in English:Use  or .A solution whithout imports for dates after 1700/1/1 I solved this for a codechef .This is a solution if the date is a datetime object.Assuming you are given the day, month, and year, you could do:If you have reason to avoid the use of the datetime module, then this function will work.Note: The change from the Julian to the Gregorian calendar is assumed to have occurred in 1582. If this is not true for your calendar of interest then change the line  accordingly.datetime library sometimes gives errors with strptime() so I switched to dateutil library. Here's an example of how you can use it :The output that you get from this is . If you want the output as 'Monday', use the following :This worked for me pretty quickly. I was having problems while using the datetime library because I wanted to store the weekday name instead of weekday number and the format from using the datetime library was causing problems. If you're not having problems with this, great! If you are, you cand efinitely go for this as it has a simpler syntax as well. Hope this helps.To get Sunday as 1 through Saturday as 7, this is the simplest solution to your question:All of them:Output::)
Python

I have some python code that have inconsistent indentation, there is a lot of mixture of tabs and spaces to make the matter even worse even space indentation is not preserved.The code works as expected but it's difficult to maintain.How can I fix the indentation (like \"html tidy\" but for python) without breaking the code?Use the  script that you find in the  directory of your Python installation:Have a look at that script for detailed usage instructions.If you're using , see .For example, if you simply typeall your tabs will be expanded into spaces.You may want toto make sure that any new lines will not use literal tabs.If you're not using Vim,will replace tabs with spaces, assuming tab stops every 8 characters, in  (with the original going to , just in case).  Replace the 8s with 4s if your tab stops are every 4 spaces instead.I would reach for  to do this:You can apply this to your entire project using recursive flag:Use autopep8 automatically formats Python code to conform to the PEP 8\n nullstyle guide. It uses the pep8 utility to determine what parts of the\n nullcode needs to be formatted. autopep8 is capable of fixing most of the\n nullformatting issues that can be reported by pep8.There is also PythonTidy (since you said you like HTMLTidy)\nIt can be found here: \nIt can do a lot more than just clean up tabs though.  If you like that type of thing it's worth a look.Using vim, it shouldn't be more involved than hitting Esc, and then typing....on the file you want to change.  That will convert all tabs to 4 spaces.  If you have inconsistent spacing as well, then that will be more difficult.If you're lazy (like me), you can also download a trial version of Wingware Python IDE, which has an auto-fix tool for messed up indentation. It works pretty well.\nThe reindent script did not work for me, due to some missing module. Anyways, I found this  command which does the job perfect for me:Try emacs. It has good support for indentation needed in Python. Please check this link cheersOn most UNIX-like systems, you can also run:from the command line, changing the number if you want to replace tabs with a number of spaces other than 4. You can easily write a shell script to do this with a bunch of files at once, retaining the original file names.I have a simple solution for this problem. You can first type \":retab\" and then \":retab!\", then everything would be finetry Idle, and use ALT+X to find indentation
Python

What is the recommended way of handling settings for local development and the production server? Some of them (like constants, etc) can be changed/accessed in both, but some of them (like paths to static files) need to remain different, and hence should not be overwritten every time the new code is deployed.Currently, I am adding all constants to . But every time I change some constant locally, I have to copy it to the production server and edit the file for production specific changes... :( In :You can override what needed in ; it should stay out of your version control then. But since you mention copying I'm guessing you use none ;) suggests using version control for your settings files and storing the files in a separate directory:The  file contains common settings (such as MEDIA_ROOT or ADMIN), while  and  have site-specific settings:In the base file :In the local development settings file :In the file production settings file :Then when you run django, you add the  option:The authors of the book have also put up  on Github.Instead of , use this layout: is where most of your configuration lives. imports everything from common, and overrides whatever it needs to override:Similarly,  imports everything from  and overrides whatever it needs to override.Finally,  is where you decide which settings to load, and it's also where you store secrets (therefore this file should not be versioned):What I like about this solution is:I use a slightly modified version of the \"if DEBUG\" style of settings that Harper Shelby posted.  Obviously depending on the environment (win/linux/etc.) the code might need to be tweaked a bit.I was in the past using the \"if DEBUG\" but I found that occasionally I needed to do testing with DEUBG set to False.  What I really wanted to distinguish if the environment was production or development, which gave me the freedom to choose the DEBUG level.I'd still consider this way of settings a work in progress. I haven't seen any one way to handling Django settings that covered all the bases and at the same time wasn't a total hassle to setup (I'm not down with the 5x settings files methods).I use a settings_local.py and a settings_production.py. After trying several options I've found that it's easy to waste time with complex solutions when simply having two settings files feels easy and fast.When you use mod_python/mod_wsgi for your Django project you need to point it to your settings file. If you point it to app/settings_local.py on your local server and app/settings_production.py on your production server then life becomes easy. Just edit the appropriate settings file and restart the server (Django development server will restart automatically).The problem with most of these solutions is that you either have your local settings applied  the common ones, or  them.So it's impossible to override things likeat the same time.One solution can be implemented using \"ini\"-style config files with the ConfigParser class. It supports multiple files, lazy string interpolation, default values and a lot of other goodies.\nOnce a number of files have been loaded, more files can be loaded and their values will override the previous ones, if any.You load one or more config files, depending on the machine address, environment variables and even values in previously loaded config files. Then you just use the parsed values to populate the settings. One strategy I have successfully used has been:As an example of something you can achieve with this, you can define a \"subdomain\" value per-env, which is then used in the default settings (as ) to define all the necessary hostnames and cookie things django needs to work.This is as DRY I could get, most (existing) files had just 3 or 4 settings. On top of this I had to manage customer configuration, so an additional set of configuration files (with things like database names, users and passwords, assigned subdomain etc) existed, one or more per customer.One can scale this as low or as high as necessary, you just put in the config file the keys you want to configure per-environment, and once there's need for a new config, put the previous value in the default config, and override it where necessary.This system has proven reliable and works well with version control. It has been used for long time managing two separate clusters of applications (15 or more separate instances of the django site per machine), with more than 50 customers, where the clusters were changing size and members depending on the mood of the sysadmin...I manage my configurations with the help of . It is a drop-in replacement for the default settings. It is simple, yet configurable. And refactoring of your exisitng settings is not required.Here's a small example (file ):That's it.Remember that settings.py is a live code file. Assuming that you don't have DEBUG set on production (which is a best practice), you can do something like:Pretty basic, but you could, in theory, go up to any level of complexity based on just the value of DEBUG - or any other variable or code check you wanted to use.I am also working with Laravel and I like the implementation there. I tried to mimic it and combining it with the solution proposed by T. Stone (look above):Maybe something like this would help you.My solution to that problem is also somewhat of a mix of some solutions already stated here:I then base all my environment-dependent settings on that one:I prefer this to having two separate settings.py files that I need to maintain as I can keep my settings structured in a single file easier than having them spread across several files. Like this, when I update a setting I don't forget to do it for both environments.Of course that every method has its disadvantages and this one is no exception. The problem here is that I can't overwrite the  file whenever I push my changes into production, meaning I can't just copy all files blindly, but that's something I can live with.For most of my projects I use following pattern:(To run manage.py with custom settings file you simply use --settings command option: )I use a variation of what jpartogi mentioned above, that I find a little shorter:Basically on each computer (development or production) I have the appropriate hostname_settings.py file that gets dynamically loaded.There is also Django Classy Settings. I personally am a big fan of it. It's built by one of the most active people on the Django IRC. You would use environment vars to set things.I differentiate it in manage.py and created two separate settings file: local_settings.py and prod_settings.py. In manage.py I check whether the server is local server or production server. If it is a local server it would load up local_settings.py and it is a production server it would load up prod_settings.py. Basically this is how it would look like:I found it to be easier to separate the settings file into two separate file instead of doing lots of ifs inside the settings file.As an alternative to maintain different file if you wiil:\nIf you are using git or any other VCS to push codes from local to server, what you can do is add the settings file to .gitignore.This will allow you to have different content in both places without any problem. SO on server you can configure an independent version of settings.py and any changes made on the local wont reflect on server and vice versa.In addition, it will remove the settings.py file from github also, the big fault, which i have seen many newbies doing.In order to use different  configuration on different environment, create different settings file. And in your deployment script, start the server using  parameter, via which you can use different  on different environment.:TL;DR: The trick is to modify  before you import  in any , this will greatly simplify things.Just thinking about all these intertwining files gives me a headache. \nCombining, importing (sometimes conditionally), overriding, patching of what was already set in case  setting changed later on. \nWhat a nightmare!Through the years I went through all different solutions. They all  work, but are so painful to manage. \nWTF! Do we really need all that hassle? We started with just one  file. \nNow we need a documentation just to correctly combine all these together in a correct order!I hope I finally hit the (my) sweet spot with the solution below.My strategy consists of excellent  used with  style files, \nproviding  defaults for local development, some minimal and short  files that have an \n  the  was set from an  file. This effectively give us a kind of settings injection.The trick here is to modify  before you import .To see the full example go do the repo: A defaults for local development. A secret file, to mostly set required environment variables. \nSet them to empty values if they are not required in local development. \nWe provide defaults here and not in  to fail on any other machine if the're missing from the environment.What happens in here, is loading environment from , then importing common settings \nfrom . After that we can override a few to ease local development.For production we should not expect an environment file, but it's easier to have one if we're testing something. \nBut anyway, lest's provide few defaults inline, so  can respond accordingly. The main point of interest here are  and  overrides, \nthey will be applied to the python  ONLY if they are MISSING from the environment and the file. These will be our production defaults, no need to put them in the environment or file, but they can be overridden if needed. Neat!These are your mostly vanilla django settings, with a few conditionals and lot's of reading them from the environment. \nAlmost everything is in here, keeping all the purposed environments consistent and as similar as possible.The main differences are below (I hope these are self explanatory):The last bit shows the power here.  has a sensible default, \nwhich can be overridden in  and even that that can be overridden by an environment setting! Yay! In effect we have a mixed hierarchy of importance:1 - Create a new folder inside your app and name settings to it.2 - Now create a new .py file in it and inside it writefrom .local import *passfrom .production import *pass3 - Create three new files in the settings folder name local.py and production.py and base.py4 - Inside base.py copy all the content of previous settings.p folder and rename it with something different let say old_settings.py5 - In base.py change your BASE_DIR path to point to your new path of settingOld path-> BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath()))New path -> BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath()))now in this way the project dir can be structured and can be manageable among production and local development.I found the responses here very helpful. (Has this been more definitively solved? The last response was a year ago.) After considering all the approaches listed, I came up with a solution that I didn't see listed here. My criteria were:I thought switching on the host machine made some sense, but then figured the real issue here is different settings for different , and had an aha moment. I put this code at the  of my settings.py file:This way, the app  to production settings, which means you are explicitly \"whitelisting\" your development environment. It is much safer to forget to set the environment variable locally than if it were the other way around and you forgot to set something in production and let some dev settings be used. When developing locally, either from the shell or in a .bash_profile or wherever:(Or if you're developing on Windows, set via the Control Panel or whatever its called these days... Windows always made it so obscure that you could set environment variables.)With this approach, the dev settings are all in one (standard) place, and simply override the production ones where needed. Any mucking around with development settings should be completely safe to commit to source control with no impact on production. 
Python

I understand how this construct works:But I don't understand why  is used as the keyword here, since it suggests the code in question only runs if the  block does not complete, which is the opposite of what it does! No matter how I think about it, my brain can't progress seamlessly from the  statement to the  block. To me,  or  would make more sense (and I'm trying to train myself to read it as such).I'm wondering how Python coders read this construct in their head (or aloud, if you like). Perhaps I'm missing something that would make such code blocks more easily decipherable?It's a strange construct even to seasoned Python coders. When used in conjunction with for-loops it basically means \"find some item in the iterable, else if none was found do ...\". As in:But anytime you see this construct, a better alternative is to either encapsulate the search in a function:Or use a list comprehension:It is not semantically equivalent to the other two versions, but works good enough in non-performance critical code where it doesn't matter whether you iterate the whole list or not. Others may disagree, but I personally would avoid ever using the for-else or while-else blocks in production code. See also A common construct is to run a loop until something is found and then to break out of the loop. The problem is that if I break out of the loop or the loop ends I need to determine which case happened. One method is to create a flag or store variable that will let me do a second test to see how the loop was exited.For example assume that I need to search through a list and process each item until a flag item is found and then stop processing. If the flag item is missing then an exception needs to be raised.Using the Python ... construct you haveCompare this to a method that does not use this syntactic sugar:In the first case the  is bound tightly to the for loop it works with. In the second the binding is not as strong and errors may be introduced during maintenance.There's an excellent presentation by Raymond Hettinger, titled , in which he briefly addresses the history of the  construct. The relevant section is \"Distinguishing multiple exit points in loops\"  and continuing for about three minutes. Here are the high points:So, if the question is, \"Why don't they change this keyword?\" then  \u2013 at this point, it would be too destructive to existing code to be practical. But if the question you're really asking is why  was reused in the first place, well, apparently it seemed like a good idea at the time.Personally, I like the compromise of commenting  in-line wherever the  could be mistaken, at a glance, as belonging inside the loop. It's reasonably clear and concise. This option gets a brief mention in  at the end of his answer:Because they didn't want to introduce a new keyword to the language. Each one steals an identifier and causes backwards compatibility problems, so it's usually a last resort.I read it something like:If still on the conditions to run the loop, do stuff,  do something else.The easiest way I found to 'get' what the for/else did, and more importantly, when to use it, was to concentrate on where the break statement jumps to. The For/else construct is a single block. The break jumps out of the block, and so jumps 'over' the else clause. If the contents of the else clause simply followed the for clause, it would never be jumped over, and so the equivalent logic would have to be provided by putting it in an if. This has been said before, but not quite in these words, so it may help somebody else. Try running the following code fragment. I'm wholeheartedly in favour of the 'no break' comment for clarity.I think documentation has a great explanation of  , Source: I read it like \"When the  is exhausted completely, and the execution is about to proceed to the next statement after finishing the , the else clause will be executed.\" Thus, when the iteration is broken by , this will not be executed.Since the technical part has been pretty much answered, my comment is just in relation with the  that produce this  keyword.Being Python a very  programming language, the misuse of a keyword is more notorious. The  keyword perfectly describes  part of the flow of a decision tree, \"if you can't do this, (else) do that\". It's  in our own language.Instead, using this keyword with  and  statements creates confusion. The reason, our career as programmers has taught us that the  statement resides within a decision tree; its , a wrapper that  return a path to follow. Meanwhile, loop statements have a figurative explicit goal to reach something. The goal is met after continuous iterations of a process.  . Loops .The issue is that  is a word that clearly define the last option in a condition. The  of the word are both  by Python and Human Language. But the else word in Human Language is never used to indicate the actions someone or something will take after something is completed. It will be used if, in the process of completing it, an issue rises (more like a  statement).At the end, the keyword will remain in Python. It's clear it was mistake, clearer when every programmer tries to come up with a story to understand its usage like some mnemonic device. I'd have loved if they have chosen instead the keyword . I believe that this keyword fits perfectly in that iterative flow, the  after the loop.It resembles that situation that some child has after following every step in assembling a toy: And  what Dad?You could think of it like,\n as in the rest of the stuff, or the other stuff, that wasn't done in the loop.I know this is an old thread, but I am looking into the same question right now,  and I'm not sure anyone has captured the answer to this question in the way I understand it.For me, there are three ways of \"reading\" the  in  or  statements, all of which are equivalent, are:I think the key is that the  is pointless without the 'break', so a  includes:So, essential elements of a  loop are as follows, and you would read them in plainer English as:As the other posters have said, a break is generally raised when you are able to locate what your loop is looking for, so the  becomes \"what to do if target item not located\".You can also use exception handling, breaks, and for loops all together.Simple example with a break being hit.Simple example where there no break, no condition raising a break, and no error are encountered.The  keyword can be confusing here, and as many people have pointed out, something like ,  is more appropriate.In order to understand  logically, compare it with , not , most of python programmers are familiar with the following code:Similarly, think of  as a special kind of :The difference is  implies  and you can not write it out, so it becomes:Yes, I know this comparison can be difficult and tiresome, but it does clarify the confusion.Codes in  statement block will be executed when the  loop was not be broke.From the 
Python

I have a list :For numbers above 45 inclusive, I would like to add 1; and for numbers less than it, 5.I triedBut it gives me a syntax error. How can I achieve an  \u2013  like this in a list comprehension?Do-something if , else do-something else.The reason you're getting this error has to do with how the list comprehension is performed.Keep in mind the following:Is equivalent to:Where the  is in a slightly different format (think switching the subject and verb order in a sentence).Therefore, your code  does this:However, this code  does this (after rearranging the ):And for a reward, here is the comment, I wrote to remember this the first time I did this error:You must put the expression at the beginning of the list comprehension, an if statement at the end filters elements!You can also put the conditional expression in brackets inside the list comprehension:[false,true][condition] is the syntaxYou could move the conditional to:But it's starting to look a little ugly, so you might be better off using a normal loop. Note that I used  instead of  for the list variable to reduce confusion with the number 1 (I think  and  should be avoided as variable names under any circumstances, even in quick-and-dirty example code).I just had a similar problem, and found this question and the answers really useful. Here's the part I was confused about. I'm writing it explicitly because no one actually stated it simply in English: Normally, a loop goes Everyone states the list comprehension part simply as the first answer did, but that's actually not what you do in this case. (I was trying to do it that way)In this case, it's more like this:Like in , the two s with  and  doing two different things. The part  is from a lambda expression:while the other  is another lambda:Whole list comprehension can be regard as combination of  and :
Python

Given the name of a Python (2.X) package that can be installed with  and , is there any way to find out a list of all the possible versions of it that pip could install? Right now it's trial and error.I'm trying to install a version for a third party library, but the newest version is too new, there were backwards incompatible changes made. So I'd like to somehow have a list of all the versions that pip knows about, so that I can test them.The script at pastebin does work. However it's not very convenient if you're working with multiple environments/hosts because you will have to copy/create it every time.A better all-around solution would be to use , which is available to install with pip. E.g. to see what versions of Django are available:A minor caveat: yolk depends on distribute. This is not a bad thing, but it may be a problem if you need for some reason to stick with (the deprecated) python setuptools. I am not involved in the development of yolk.  Use the  instead and consider submitting a fix, if possible.Without actually having to download or install any additional packages you can use  for specifying a particular version while , and the available versions will be printed:update: I had changed my answer to have nothing after the ==, this however doesn't work for older versions of pip (those of you should probably update pip) add any string after the == that is not likely to be an install candidate:Use , you can see all versions that availableTo not install any package, use one of following solution:or Tested with pip 1.0You don't need a third party package to get this information. pypi provides simple JSON feeds for all packages underHere's some Python code using only the standard library which gets all versions.That code prints (as of Feb 23rd, 2015):You could the yolk3k package instead of yolk. yolk3k is a fork from the original yolk and it supports both python2 and 3.After looking at pip's code for a while, it looks like the code responsible for locating packages can be found in the  class in . Its method  looks up the versions of a , but unfortunately only returns the most recent version. The code below is almost a 1:1 copy of the original function, with the return in line 114 changed to return all versions.The script expects one package name as first and only argument and returns all versions. But hopefully this helps.Sample outputThe code:I came up with dead-simple bash script. Thanks to 's author. - works for packages whose maintainers choose to show all packages\n - should do the trick anyhow (lists all links)Pip 7.1.0 has removed --no-install option from install. I found a method to get all versions of a package without any extra package.I just ran this:e.g.:I didn't have any luck with ,  or  but so I ended up using this (adapted to Python 3 from eric chiang's answer):You can use this short Python3 snippet to grab the list of available versions for a package from . Unlike some other Python solutions posted here, this doesn't break on loose versions like 's  or 's :This works for me on OSX:It returns the list one per line:Or to get the latest version available:Keep in mind  has to be installed (on OSX) to parse the versions. You can install it with you can grep the result of your 
Python

I am  to understand what Python's descriptors are and what they can be useful for. However, I am failing at it. I understand how they work, but here are my doubts. Consider the following code:The descriptor is how Python's  type is implemented. A descriptor simply implements , , etc. and is then added to another class in its definition (as you did above with the Temperature class). For example:Accessing the property you assigned the descriptor to ( in the above example) calls the appropriate descriptor method. in  is the instance of the class (so above,  would receive , while  is the class with the descriptor (so it would be ).You need to use a descriptor class to encapsulate the logic that powers it. That way, if the descriptor is used to cache some expensive operation (for example), it could store the value on itself and not its class.An article about descriptors can be found at EDIT: As jchl pointed out in the comments, if you simply try ,  will be .it gives you extra control over how attributes work.  if you're used to getters and setters in java, for example, then it's python's way of doing that.  one advantage is that it looks to users just like an attribute (there's no change in syntax).  so you can start with an ordinary attribute and then, when you need to do something fancy, switch to a descriptor.an attribute is just a mutable value.  a descriptor lets you execute arbitrary code when reading or setting (or deleting) a value.  so you could imagine using it to map an attribute to a field in a database, for example - a kind of ORM.another use might be refusing to accept a new value by throwing an exception in  - effectively making the \"attribute\" read only.this is pretty subtle (and the reason i am writing a new answer here - i found this question while wondering the same thing and didn't find the existing answer that great).a descriptor is defined on a class, but is typically called from an instance.  when it's called from an instance both  and  are set (and you can work out  from  so it seems kinda pointless).  but when called from a class, only  is set - which is why it's there.this is only needed for  because it's the only one that can be called on a class.  if you set the class value you set the descriptor itself.  similarly for deletion.  which is why the  isn't needed there.well, here's a cool trick using similar classes:(i'm using python 3; for python 2 you need to make sure those divisions are  and ).  that gives:now there are other, arguably better ways to achieve the same effect in python (eg if celsius were a property, which is the same basic mechanism but places all the source inside the Temperature class), but that shows what can be done...Descriptors are objects with any of , , or . These descriptor objects can be used as attributes on other object class definitions. Descriptor objects can be used to programmatically manage the results of a dotted lookup (e.g. ) in a normal expression, an assignment, and even a deletion. Bound methods, , , and  all use these special methods to manage how they are accessed via the dotted lookup.A descriptor is an object with any of the following methods (, , or ), intended to be used via dotted-lookup as if it were a typical attribute of an instance. For an owner-object, , with a  object: is the instance whose class contains the descriptor object's instance.  is the instance of the  (probably just one for the class of the )To define this with code, an object is a descriptor if the set of its attributes intersects with any of the required attributes:A  has a  and/or .\nA  has neither  nor .We can see that  and  are Non-Data-Descriptors:Both only have the  method:Note that all functions are also Non-Data-Descriptors:However,  is a Data-Descriptor:These are important , as they affect the lookup order for a dotted lookup. The consequence of this lookup order is that Non-Data-Descriptors like functions/methods can be .We have learned that descriptors are objects with any of , , or . These descriptor objects can be used as attributes on other object class definitions. Now we will look at how they are used, using your code as an example.Here's your code, followed by your questions and answers to each:Your descriptor ensures you always have a float for this class attribute of , and that you can't use  to delete the attribute:Otherwise, your descriptors ignore the owner-class and instances of the owner, instead, storing state in the descriptor. You could just as easily share state across all instances with a simple class attribute (so long as you always set it as a float to the class and never delete it, or are comfortable with users of your code doing so):This gets you exactly the same behavior as your example (see response to question 3 below), but uses a Pythons builtin (), and would be considered more idiomatic: is the instance of the owner that is calling the descriptor. The owner is the class in which the descriptor object is used to manage access to the data point. See the descriptions of the special methods that define descriptors next to the first paragraph of this answer for more descriptive variable names.Here's a demonstration:You can't delete the attribute:And you can't assign a variable that can't be converted to a float:Otherwise, what you have here is a global state for all instances, that is managed by assigning to any instance.  The expected way that most experienced Python programmers would accomplish this outcome would be to use the  decorator, which makes use of the same descriptors under the hood, but brings the behavior into the implementation of the owner class:Which has the exact same expected behavior of the original piece of code:We've covered the attributes that define descriptors, the difference between data- and non-data-descriptors, builtin objects that use them, and specific questions about use.So again, how would you use the question's example? I hope you wouldn't. I hope you would start with my first suggestion (a simple class attribute) and move on to the second suggestion (the property decorator) if you feel it is necessary. I tried (with minor changes as suggested) the code from Andrew Cooke's answer. (I am running python 2.7).The code:The result:With Python prior to 3, make sure you subclass from object which will make the descriptor work correctly as the  magic does not work for old style classes.
Python

If I do the following:I get:Apparently a cStringIO.StringIO object doesn't quack close enough to a file duck to suit subprocess.Popen.  How do I work around this? documentation:So your example could be written as follows:I figured out this workaround:Is there a better one?I'm a bit surprised nobody suggested creating a pipe, which is in my opinion the far simplest way to pass a string to stdin of a subprocess:\"Apparently a cStringIO.StringIO object doesn't quack close enough to a file duck to suit subprocess.Popen\":-)I'm afraid not.  The pipe is a low-level OS concept, so it absolutely requires a file object that is represented by an OS-level file descriptor.  Your workaround is the right one.I am using python3 and found out that you need to encode your string before you can pass it into stdin:Beware that may give you trouble ifis too big, because apparently the parent process will buffer it  forking the child subprocess, meaning it needs \"twice as much\" used memory at that point (at least according to the \"under the hood\" explanation and linked documentation found ). In my particular case,was a generator that was first fully expanded and only then written to so the parent process was huge right before the child was spawned, \nand no memory was left to fork it:There's a beatiful solution if you're using Python 3.4 or better. Use the  argument instead of the  argument, which accepts a bytes argument:
Python

I wonder if there is a direct way to import the contents of a csv file into a record array, much in the way that R's , , and  family imports data to R's data frame? Or is the best way to use  and then apply something like ?You can use Numpy's  method to do so, by setting the  kwarg to a comma.More information on the function can be found at its respective .I would recommend the  function from the  library:This gives a pandas  - allowing .I would also recommend . However, since the question asks for a , as opposed to a normal array, the  parameter needs to be added to the  call:Given an input file, :gives an array:and gives a record array:This has the advantage that file with .You can also try  which can guess data types and return a properly formatted record array.I timed the versus on 4.6 million rows with about 70 columns and found that the numpy path took 2 min 16s and the csv-list comprehension method took 13s.I would recommend the csv-list comprehension method as it is most likely relies on pre-compiled libraries and not the interpreter as much as numpy. i suspect the pandas method would have similar interpreter overhead.
Python

I have a list of dictionaries like this:and I want to turn this into a pandas  like this:Ultimately, the goal is to write this to a text file and this seems like the best solution I could find.  How can I turn the list of dictionaries into a panda DataFrame as shown above?Supposing  is your list of dicts, simply:in pandas 16.2, I had to do  to get this to work. 
Python

Let's say I have a class that has a member called data which is a list.  I want to be able to initialize the class with, for example, a filename (which contains data to initialize the list) or with an actual list.What's your technique for doing this?Do you just check the type by looking at ?Is there some trick I might be missing?I'm used to C++ where overloading by argument type is easy. A much neater way to get 'alternate constructors' is to use classmethods. For instance:The reason it's neater is that there is no doubt about what type is expected, and you aren't forced to guess at what the caller intended for you to do with the datatype it gave you. The problem with  is that there is no way for the caller to tell you, for instance, that even though the type is not a basestring, you should treat it as a string (and not another sequence.) And perhaps the caller would like to use the same type for different purposes, sometimes as a single item, and sometimes as a sequence of items. Being explicit takes all doubt away and leads to more robust and clearer code.Excellent question. I've tackled this problem as well, and while I agree that \"factories\" (class-method constructors) are a good method, I would like to suggest another, which I've also found very useful:Here's a sample (this is a  method and not a constructor, but the idea is the same):The key idea is here is using Python's excellent support for named arguments to implement this. Now, if I want to read the data from a file, I say:And to read it from a string, I say:This way the user has just a single method to call. Handling it inside, as you saw, is not overly complexQuick and dirty fixThen you can call it withA better way would be to use isinstance and type conversion. If I'm understanding you right, you want this:You should use isinstanceYou probably want the  builtin function:My preferred solution is:Then invoke it with either  or .Hope that helps. Happy Coding!OK, great. I just tossed together this example with a tuple, not a filename, but that's easy. Thanks all.a = [1,2]b = (2,3)c = MyData(a)d = MyData(b)c.GetData()d.GetData()[1, 2][2, 3]Why don't you go even more pythonic?\n
Python

I want to create string using integer appended to it, in a for loop.  Like this:But it returns an error:What's the best way to concatenate the String and Integer?The method used in this answer (backticks) is deprecated in later versions of Python 2, and removed in Python 3. Use the  function instead.You can use :It will print .To get  you can use this as @YOU suggestedYou can use :It will print .To get  you can use this as @YOU suggestedTo get , you could do likeThe  function converts the integer into a string.What you did () is And  is a TypeError since you can't add an integer to a string (unlike JavaScript).Look at the documentation for , it is very powerful.You can use a generator to do this ! If we want output like  then we can use  and  method of string. If we want List of string values then use  method. Use  for Python 2.xUSe  for Python 3.xI did something else.\nI wanted to replace a word, in lists off lists, that contained phrases.\nI wanted to replace that sttring / word with a new word that will be a join between string and number, and that number / digit will indicate the position of the phrase / sublist / lists of lists. That is, I replaced a string with a string and an incremental number that follow it. Concatenation of a string and integer is simmple:\njust use
Python

Is there a way to expand a Python tuple into a function - as actual parameters?For example, here  does the magic:I know one could define  as , but of course there may be legacy code.\nThanks does  what you request.Side issue:  use as your identifiers builtin type names such as , , , , and so forth -- it's horrible practice and it  come back and byte you when you least expect it,\nso just get into the habit of actively  hiding builtin names with your own identifiers.Note that you can also expand part of argument list:Take a look at  section 4.7.3 and 4.7.4.\nIt talks about passing tuples os arguments.I would also consider using named parameters (and passing a dictionary) over a tuple and passing a sequence. I find the use of positional arguments to be a bad practice when the positions are not intuitive or there are multiple parameters. This is the functional programming method. It lifts the tuple expansion feature out of syntax sugar:Example usage: redefiniton of  saves a lot of  calls in the long run.
Python

How can I delete the contents of a local folder in Python?The current project is for Windows but I would like to see *nix also.Updated to only delete files and to used the os.path.join() method suggested in the comments. If you also want to remove subdirectories, uncomment the elif statement.Try the shutil moduleYou can simply do this :You can of corse use an other filter in you path, for exemple : /YOU/PATH/*.txt for removing all text files in a directory.Expanding on mhawke's answer this is what I've implemented. It removes all the content of a folder but not the folder itself. Tested on Linux with files, folders and symbolic links, should work on Windows as well.Using  and recreating the folder could work, but I have run into errors when deleting and immediately recreating folders on network drives.The proposed solution using walk does not work as it uses  to remove folders and then may attempt to use  on the files that were previously in those folders.  This causes an error.The posted  solution will also attempt to delete non-empty folders, causing errors.I suggest you use:As a oneliner:A more robust solution accounting for files and directories as well would be (2.7):You might be better off using  for this. doesn't distinguish files from directories and you will quickly get into trouble trying to unlink these. There is a good example of using  to recursively remove a directory , and hints on how to adapt it to your circumstances.Here's a long and ugly, but reliable and efficient solution.It resolves a few problems which are not addressed by the other answerers:Here's the code (the only useful function is ):I konw it's an old thread but I have found something interesting from the official site of python. Just for sharing another idea for removing of all contents in a directory. Because I have some problems of authorization when using shutil.rmtree() and I don't want to remove the directory and recreate it. The address original is . Hope that could help someone.Yet Another Solution:An earlier comment also mentions using os.scandir in Python 3.5+.  For example:I used to solve the problem this way:This is the only answer so far, which:Code:As many other answers, this does not try to adjust permissions to enable removal of files/directories.I resolved the error issue with rmtree makedirs by adding time.sleep() between.Answer for a limited, specific situation:\nassuming you want to delete the files while maintainig the subfolders tree, you could use a recursive algorithm:Maybe slightly off-topic, but I think many would find it usefulThis should do the trick just using the OS module to list and then remove!Worked for me, any problems let me know!    
Python

A (long) while ago I wrote a web-spider that I multithreaded to enable concurrent requests to occur at the same time.  That was in my Python youth, in the days before I knew about the  and the associated woes it creates for multithreaded code (IE, most of the time stuff just ends up serialized!)...I'd like to rework this code to make it more robust and perform better.  There are basically two ways I could do this: I could use the new  in 2.6+ or I could go for a reactor / event-based model of some sort.  I would rather do the later since it's far simpler and less error-prone.So the question relates to what framework would be best suited to my needs.  The following is a list of the options I know about so far:Is there anything I have missed at all?  Surely there must be a library out there that fits the sweet-spot of a simplified async networking library![edit: big thanks to  for his pointer to .  If you scroll to the bottom you will see there is a really nice list of projects that aim to tackle this task in one way or another.  It seems actually that things have indeed moved on since the inception of Twisted: people now seem to favour a  based solution rather than a traditional reactor / callback oriented one.  The benefits of this approach are clearer more direct code: I've certainly found in the past, especially when working with  in C++ that callback based code can lead to designs that can be hard-to-follow and are relatively obscure to the untrained eye.  Using co-routines allows you to write code that looks a little more synchronous at least.  I guess now my task is to work out which one of these many libraries I like the look of and give it a go!  Glad I asked now...][edit: perhaps of interest to anyone who followed or stumbled on this this question or cares about this topic in any sense: I found a really great writeup of the current state of  for this job]I liked the  Python module which relies on either Stackless Python microthreads or Greenlets for light-weight threading. All blocking network I/O is transparently made asynchronous through a single  loop, so it should be nearly as efficient as an real asynchronous server.I suppose it's similar to Eventlet in this way.The downside is that its API is quite different from Python's / modules; you need to rewrite a fair bit of your application (or write a compatibility shim layer) It seems that there's also , which is similar, but uses Python 2.5's  for its coroutines, instead of Greenlets. This makes it more portable than concurrence and other alternatives. Network I/O is done directly with epoll/kqueue/iocp.Twisted is complex, you're right about that. Twisted is  bloated. If you take a look here:  you'll find an organized, comprehensive, and very well tested suite of  protocols of the internet, as well as helper code to write and deploy very sophisticated network applications. I wouldn't confuse bloat with comprehensiveness.It's well known that the Twisted documentation isn't the most user-friendly from first glance, and I believe this turns away an unfortunate number of people. But Twisted is amazing (IMHO) if you put in the time.  I did and it proved to be worth it, and I'd recommend to others to try the same. is .API-wise it follows the same conventions as the standard library (in particular, threading and multiprocessing modules) where it makes sense. So you have familiar things like  and  to work with.It only supports  ( ) as reactor implementation but takes full advantage of it, featuring a fast WSGI server based on libevent-http and resolving DNS queries through libevent-dns as opposed to using a thread pool like most other libraries do. ( since 1.0 c-ares is used to make async DNS queries; threadpool is also an option.)Like eventlet, it makes the callbacks and Deferreds unnecessary by using .Check out the examples: , .A really  of such frameworks was compiled by Nicholas Pi\u00ebl on his blog: it's well worth a read!None of these solutions will avoid that fact that the GIL prevents CPU parallelism - they are just better ways of getting IO parallelism that you already have with threads.  If you think you can do better IO, by all means pursue one of these, but if your bottleneck is in processing the results nothing here will help except for the multiprocessing module.  I wouldn't go as far as to call Twisted bloated, but it is difficult to wrap your head around. I avoided really settling in an learn for quite a while as I always wanted something a little easier for 'small tasks'. However, now that I have worked with it some more I have to say having all the batteries included is VERY nice.All the other async libraries I've worked with end being way less mature than they even appear. Twisted's event loop is solid. I'm not quite sure how to solve the steep Twisted learning curve. It might help if someone would fork it and clean a few things up, like removing all the backwards compatability cruft and the dead projects. But that's the nature of mature software I guess. hasn't been mentioned yet. Its concurrency model is based on wiring together components with message passing between inboxes and outboxes. 's a brief overview.I've started to use twisted for some things.  The beauty of it almost is because it's \"bloated.\"  There are connectors for just about any of the main protocols out there.  You can have a jabber bot that will take commands and post to an irc server, email them to someone, run a command, read from an NNTP server, and monitor a web page for changes.  The bad news is it can do all of that and can make things overly complex for simple tasks like the OP explained.  The advantage of python though is you only include what you need.  So while the download may be 20mb, you may only include 2mb of libraries (which is still a lot).  My biggest complaint with twisted is although they include examples, anything beyond a basic tcp server you're on your own.  While not a python solution, I've seen node.js gain a lot more traction as of late.  In fact I've considered looking into it for smaller projects but I just cringe when I hear javascript :)There is a good book on the subject: \"Twisted Network Programming Essentials\", by Abe Fettig.  The examples show how to write very Pythonic code, and to me personally, do not strike me as  based on a bloated framework.  Look at the solutions in the book, if they aren't clean, then I don't know what clean means. My only enigma is the same I have with other frameworks, like Ruby. I worry, does it scale up?  I would hate to commit a client to  a framework that is going to have scalability problems. is a tiny asynchronous socket framework that uses pyev. Its very fast, primarily because of pyev. It attempts to provide a similiar interface as twisted with some slight changes.Also try . It's coroutine-based (so it's similar to Concurrence, Eventlet and gevent). It implements drop-in non-blocking replacements for socket.socket, socket.gethostbyname (etc.), ssl.SSLSocket, time.sleep and select.select. It's fast. It needs Stackless Python and libevent. It contains a mandatory Python extension written in C (Pyrex/Cython).I Confirm the goodness of . It can use libev (the newer, cleaner and better performance version of libevent). Some times ago it doesn't has as much support as libevent has, but now the development process go further and is very useful.If you just want a Simplified, lightweight HTTP Request Library then I find  really good   You are welcome to have a look at PyWorks, which takes a quite different approach. It lets object instances run in their own thread and makes function call's to that object async. Just let a class inherit from Task instead of object and it is async, all methods calls are Proxies. Return values (if you need them) are Future proxies.PyWorks can be found on 
Python

When I print a numpy array, I get a truncated representation, but I want the full array. Is there any way to do this?To clarify on Reed's replyNote that the reply as given above works with an initial 'from numpy import *', which is not advisable. \nThis also works for meFor full documentation, see . I suggest using  instead of  which is suggested by others. They both work for your purpose, but by setting the threshold to \"infinity\" it is obvious to everybody reading your code what you mean. Having a threshold of \"not a number\" seems a little vague to me.This sounds like you're using numpy.If that's the case, you can add:That will disable the corner printing.  For more information, see this .Here is a one-off way to do this, which is useful if you don't want to change your default settings:The previous answers are the correct ones, but as a weeker alternative you can transform into a list:Using a context manager as  sugggested is a good option for a one time usage:or if you need a string:Default output format is:and it can be configured with further arguments.Tested on Python 2.7.12, numpy 1.11.1.For these who like to import as np:Will also work 
Python

I have a Python pandas DataFrame :I can filter the rows whose stock id is  like this: and I want to get all the rows of some stocks together, such as . That means I want a syntax like this: Since pandas not accept above command, how to achieve the target? Use the  method.  . is ideal if you have a list of exact matches, but if you have a list of partial matches or substrings to look for, you can filter using the  method and regular expressions.For example, if we want to return a DataFrame where all of the stock IDs which begin with  and then are followed by any three digits:Suppose now we have a list of strings which we want the values in  to end with, e.g.We can join these strings with the regex 'or' character  and pass the string to  to filter the DataFrame: Finally,  can ignore case (by setting ), allowing you to be more general when specifying the strings you want to match.For example,would match , , , and so on.you can also use ranges by using:You can also directly  your DataFrame for this information.Or similarly search for ranges:Given a dataframe like this:There are multiple ways of selecting or slicing the data.The most obvious is the  feature. You can create a mask that gives you a series of / statements, which can be applied to a dataframe like this:Masking is the ad-hoc solution to the problem, but does not always perform well in terms of speed and memory.By setting the index to the  column, we can use the pandas builtin slicing object This is the fast way of doing it, even if the indexing can take a little while, it saves time if you want to do multiple queries like this.This can also be done by merging dataframes. This would fit more for a scenario where you have a lot more data than in these examples.All the above methods work even if there are multiple rows with the same You can use , i.e.:
Python

I want to get, given a character, its  value.For example, for the character , I want to get , and vice versa.Use  and :The question has been answered but I think this reference is a good thing to keep note of. ord and chr
Python

I am trying to fix how python plots my data.Say and Then I would do:and the x axis' ticks are plotted in intervals of 5. Is there a way to make it show intervals of 1?You could explicitly set where you want to tick marks with :For example,( was used rather than Python's  function just in case  and  are floats instead of ints.) The  (or ) function will automatically set default  and  limits. If you wish to keep those limits, and just change the stepsize of the tick marks, then you could use  to discover what limits Matplotlib has already set. The default tick formatter should do a decent job rounding the tick values to a sensible number of significant digits. However, if you wish to have more control over the format, you can define your own formatter. For example,Here's a runnable example:Another approach is to set the axis locator:There are several different types of locator depending upon your needs.I like this solution (from the ):This solution give you explicit control of the tick spacing via the number given to , allows automatic limit determination, and is easy to read later.In case anyone is interested in a general one-liner, simply get the current ticks and use it to set the new ticks by sampling every other tick.This is a bit hacky, but by far the cleanest/easiest to understand example that I've found to do this. It's from an answer on SO here:Then you can loop over the labels setting them to visible or not depending on the density you want.edit: note that sometimes matplotlib sets labels == , so it might look like a label is not present, when in fact it is and just isn't displaying anything. To make sure you're looping through actual visible labels, you could try:This is an old topic, but I stumble over this every now and then and made this function. It's very convenient:One caveat of controlling the ticks like this is that one does no longer enjoy the interactive automagic updating of max scale after an added line. Then doand run the resadjust function again.I developed an inelegant solution. Consider that we have the X axis and also a list of labels for each point in X.
Python

I want to create an empty list (or whatever is the best way) that can hold 10 elements.After that I want to assign values in that list, for example this is supposed to display 0 to 9:But when I run this code, it generates an error or in another case it just displays  (empty). Can someone explain why?You cannot assign to a list like . You need to use append. .(You could use the assignment notation if you were using a dictionary).Creating an empty list:range(x) creates a list from [0, 1, 2, ... x-1]Using a function to create a list:List comprehension (Using the squares because for range you don't need to do all this, you can just return  ):Try this instead:The above will create a list of size 10, where each position is initialized to . After that, you can add elements to it:Admittedly, that's not the Pythonic way to do things. Better do this:Or , use list comprehensions like this:You can  to the list, e.g.: . What you are currently trying to do is access an element () that does not exist.varunl's currently accepted answerWorks well for non-reference types like numbers. Unfortunately if you want to create a list-of-lists you will run into referencing errors. Example in Python 2.7.6:As you can see, each element is pointing to the same list object. To get around this, you can create a method that will initialize each position to a different object reference.There is likely a default, built-in python way of doing this (instead of writing a function), but I'm not sure what it is. Would be happy to be corrected! There are two \"quick\" methods:It appears that  is faster:But if you are ok with a range (e.g. ), then  might be fastest:All lists can hold as many elements as you like, subject only to the limit of available memory. The only \"size\" of a list that matters is the number of elements  in it. is not valid syntax; based on your description of what you're seeing, I assume you meant  and then . For that to run, you must have previously defined a global  to pass into the function.Calling  does not modify the list you pass in, as written. Your code says \" is a name for whatever thing was passed in to the function; ok, now the first thing we'll do is forget about that thing completely, and let  start referring instead to a newly created . Now we'll modify that \". This has no effect on the value you passed in.There is no reason to pass in a value here. (There is no real reason to create a function, either, but that's beside the point.) You want to \"create\" something, so that is the output of your function. No information is required to create the thing you describe, so don't pass any information in. To get information out,  it.That would give you something like:The next problem you will note is that your list will actually have only 9 elements, because the end point is skipped by the  function. (As side notes,  works just as well as , the semicolon is unnecessary,  is a poor name for the variable, and only one parameter is needed for  if you're starting from .) So then you end up withHowever, this is still missing the mark;  is not some magical keyword that's part of the language the way  and  are, but instead it's a function. And guess what that function returns? That's right - a list of those integers. So the entire function collapses to and now you see why we don't need to write a function ourselves at all;  is already the function we're looking for. Although, again, there is no need or reason to \"pre-size\" the list.
Python

Is there a way to have a  in order to make the following code work? needs to be built ad-hoc, depending on  and  elements.I could use:but then I wouldn't be able to use:Yes like this:The parameter to the defaultdict constructor is the function which will be called for building new elements. So let's use a lambda !Since Python 2.7, there's an :Some bonus featuresFor more information see  and I find it slightly more elegant to use :Of course, this is the same as a lambda.Others have answered correctly your question of how to get the following to work:An alternative would be to use tuples for keys:The nice thing about this approach is that it is simple and can be easily expanded.  If you need a mapping three levels deep, just use a three item tuple for the key.
Python

The below code will not join, when debugged the command does not store the whole path but just the last entry.When I test this it only stores the  part of the code.The latter strings shouldn't start with a slash. If they start with a slash, then they're considered an \"absolute path\" and everything before them is discarded.Quoting the :Note on Windows, the behaviour in relation to drive letters, which seems to have changed compared to earlier Python versions:The idea of  is to make your program cross-platform (linux/win32/etc).Even one slash ruins it.So it only makes sense when being used with some kind of reference point like\n or . can be used in conjunction with  to create an absolute rather than relative path.do not use forward slashes at the beginning of path components, except when refering to the root dir:see also: It's because your  begins with a  and thus is assumed to be relative to the root directory. Remove the leading .To help understand why this surprising behavior isn't  terrible, consider an application which accepts a config file name as an argument:If the application is executed with:The config file  will be used.But consider what happens if the application is called with:Then   use the config file at  (and not  or similar).It may not be great, but I believe this is the motivation for the absolute path behaviour.To make your function more portable, use it as such:orTry with  onlydo it like this, without too the extra slashesNote that a similar issue can bite you if you use  to include an extension that already includes a dot, which is what happens automatically when you use . In this example:Even though  might be  you end up with a folder named \"foobar\" rather than a file called \"foobar.jpg\". To prevent this you need to append the extension separately:
Python

I am new to Django and pretty new to Ajax. I am working on a project where I need to integrate the two. I believe that I understand the principles behind them both, but have not found a good explanation of the two together. Could someone give me a quick explanation of how the codebase must change with the two of them integrating together?For example, can I still use the  with Ajax, or do my responses have to change with the use of Ajax? If so, could you please provide an example of how the responses to the requests must change? If it makes any difference, the data I am returning is JSON. Even though this isn't entirely in the SO spirit, I love this question, because I had the same trouble when I started so I'll give you a quick guide. Obviously you don't understand the principles behind them (don't take it as an offense, but if you did you wouldn't be asking). Django is server-side. It means, say a client goes to url you have a function inside views that renders what he sees and returns a response in html. let's break it up into examples:views.pyindex.html:urls.pyThat's an example of the simplest of usages. Going to  means a request to the hello function, going to  will return the  and replace all the variables as asked (you probably know all this by now).Now let's talk about AJAX. AJAX calls are client-side code that does asynchronous requests. That sounds complicated, but it simply means it does a request for you in the background and then handles the response. So when you do an AJAX call for some url, you get the same data you would get as a user going to that place. For example, an ajax call to  will return the same thing it would as if you visited it. Only this time, you have it inside a js function and you can deal with it however you'd like. Let's look at a simple use case:The general process is this:Now what would happen here? You would get an alert with 'hello world' in it. What happens if you do an ajax call to home? Same thing, you'll get an alert stating .In other words - there's nothing new about AJAX calls. They are just a way for you to let the user get data and information without leaving the page, and it makes for a smooth and very neat design of your website. A few guidelines you should take note of:That's everything that comes to my head. It's a vast subject, but yeah, there's probably not enough examples out there. Just work your way there, slowly, you'll get it eventually.Further from yuvi's excellent answer, I would like to add a small specific example on how to deal with this within Django (beyond any js that will be used). The example uses  and assumes an Author model.Source: Simple and Nice. You don't have to change your views. Bjax handles all your links. Check this out:\nUsage:Finally, include this in the HEAD of your html:For more settings, checkout demo here: \nI have tried to use  in my project, but had ended up with the following error message:That is because the CreateView will return a  instead of returning a HttpResponse for you to send JSON result to the browser. So I have made some changes to the . If the request is an ajax request, it will not call the  method, just call the  directly.
Python

When should I use a dictionary, list or set?Are there scenarios that are more suited for each data type?A  keeps order,  and  don't: when you care about order, therefore, you must use  (if your choice of containers is limited to these three, of course;-). associates with each key a value, while  and  just contain values: very different use cases, obviously. requires items to be hashable,  doesn't: if you have non-hashable items, therefore, you cannot use  and must instead use . forbids duplicates,  does not: also a crucial distinction.  (A \"multiset\", which maps duplicates into a different count for items present more than once, can be found in  -- you could build one as a , if for some weird reason you couldn't import , or, in pre-2.7 Python as a , using the items as keys and the associated value as the count).Checking for membership of a value in a  (or , for keys) is blazingly fast (taking about a constant, short time), while in a list it takes time proportional to the list's length in the average and worst cases.  So, if you have hashable items, don't care either way about order or duplicates, and want speedy membership checking,  is better than .When you want an unordered collection of unique elements, use a . (For example, when you want the set of all the words used in a document).When you want to collect an immutable ordered list of elements, use a . (For example, when you want a (name, phone_number) pair that you wish to use as an element in a set, you would need a tuple rather than a list since sets require elements be immutable).When you want to collect a mutable ordered list of elements, use a . (For example, when you want to append new phone numbers to a list: [number1, number2, ...]).When you want a mapping from keys to values, use a . (For example, when you want a telephone book which maps names to phone numbers: ). Note the keys in a dict are unordered. (If you iterate through a dict (telephone book), the keys (names) may show up in any order).Although this doesn't cover s, it is a good explanation of s and s:
Python

I am using the datetime Python module.  I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?The reason I want to generate a date 6 months from the current date is to produce a Review Date.  If the user enters data into the system it will have a review date of 6 months from the date they entered the data.  I found this solution to be good.  (This uses the )The advantage of this approach is that it takes care of issues with 28, 30, 31 days etc. This becomes very useful in handling business rules and scenarios (say invoice generation etc.)Well, that depends what you mean by 6 months from the current date.What do you mean by '6 months'. Is 2009-02-13 + 6 months == 2009-08-13 or is it 2009-02-13 + 6*30 days?More info about This solution works correctly for December, which most of the answers on this page do not.\nYou need to first shift the months from base 1 (ie Jan = 1) to base 0 (ie Jan = 0) before using modulus ( % ) or integer division ( // ), otherwise November (11) plus 1 month gives you 12, which when finding the remainder ( 12 % 12 ) gives 0.(And dont suggest \"(month % 12) + 1\" or Oct + 1 = december!)However ... This doesnt account for problem like Jan 31 + one month. So we go back to the OP - what do you mean by adding a month? One soln is to backtrack until you get to a valid day, given that most people would presume the last day of jan, plus one month, equals the last day of Feb.\nThis will work on negative numbers of months too.\nProof: has implementation of such functionality. But be aware, that this will be , as others pointed already.There's no direct way to do it with Python's datetime.Check out the relativedelta type at . It allows you to specify a  time delta in months.I know this was for 6 months, however the answer shows in google for \"adding months in python\" if you are adding one month:this would count the days in the current month and add them to the current date, using 365/12 would ad 1/12 of a year can causes issues for short / long months if your iterating over the date.Just use the  method to extract the months, add your months and build a new dateobject. If there is a already existing method for this I do not know it.The API is a bit clumsy, but works as an example. Will also obviously not work on corner-cases like 2008-01-31 + 1 month. :)So, here is an example of the  which I found useful for iterating through the past year, skipping a month each time to the present date:As with the other answers, you have to figure out what you actually mean by \"6 months from now.\"  If you mean \"today's day of the month in the month six years in the future\" then this would do:For beginning of month to month calculation:The QDate class of PyQt4 has an addmonths function.I have a better way to solve the 'February 31st' problem:I think that it also works with negative numbers (to subtract months), but I haven't tested this very much.Modified the AddMonths() for use in Zope and handling invalid day numbers:How about this? Not using another library () or ?\nbuilding on 's answer I did this and I believe it works:I tried using , but because it is counting the days,  or  does not always translate to 6 months, but rather 182 days. e.g.I believe that we usually assume that 6 month's from a certain day will land on the same day of the month but 6 months later (i.e.  --> , Not )I hope you find this helpful.I solved this problem like this:Modified Johannes Wei's answer in the case 1new_month = 121.  This works perfectly for me.  The months could be positive or negative.Yet another solution - hope someone will like it:This solution doesn't work for days 29,30,31 for all cases, so more robust solution is needed (which is not so nice anymore :) ):From , see . Code example follows. More details: , and apparent .The above code generates the following from a MacOSX machine:given that your datetime variable is called date:Use the python datetime module to add a timedelta of six months to datetime.today() .You will of course have to solve the issue raised by Johannes Wei\u00df-- what  you mean by 6 months?This is what I came up with. It moves the correct number of months and years but ignores days (which was what I needed in my situation).I use this function to change year and month but keep day:You should write:I think it would be safer to do something like this instead of manually adding days:my modification to tony diep's answer, possibly marginally more elegant:adds months according to a business needs interpretationRework of an earlier answer by user417751. Maybe not so pythonic way, but it takes care of different month lengths and leap years. In this case 31 January 2012 + 1 month = 29 February 2012. In this function, n can be positive or negative.Here's a example which allows the user to decide how to return a date where the day is greater than the number of days in the month.
Python

What's your preferred way of getting current system status (current CPU, RAM, free disk space, etc.) in Python? Bonus points for *nix and Windows platforms.There seems to be a few possible ways of extracting that from my search:It's not that those methods are bad but is there already a well-supported, multi-platform way of doing the same thing? will give you some system information (CPU / Memory usage) on a variety of platforms:Use the .  For me on Ubuntu, pip installed 0.4.3.  You can check your version of psutil by doing in Python.To get some memory and CPU stats:I also like to do:which gives the current memory use of your Python script.There are some more in-depth examples on the  and .For Ubuntu 16 and 14, installing from pip gave me version 4.3.0, which doesn't have the phymem_usage() method. To get 0.5.0, , then do Here's something I put together a while ago, it's windows only but may help you get part of what you need done.Derived from:\n\"for sys available mem\"\n\"individual process information and python script examples\"\nNOTE: the WMI interface/process is also available for performing similar tasks\n        I'm not using it here because the current method covers my needs, but if someday it's needed to extend or improve this, then may want to investigate the WMI tools a vailable.WMI for python:The code:\"... current system status (current CPU, RAM, free disk space, etc.)\"  And \"*nix and Windows platforms\" can be a difficult combination to achieve.The operating systems are fundamentally different in the way they manage these resources.  Indeed, they differ in core concepts like defining what counts as system and what counts as application time.\"Free disk space\"?  What counts as \"disk space?\"  All partitions of all devices?  What about foreign partitions in a multi-boot environment?I don't think there's a clear enough consensus between Windows and *nix that makes this possible.  Indeed, there may not even be any consensus between the various operating systems called Windows.  Is there a single Windows API that works for both XP and Vista?Below codes, without external libraries worked for me. I tested at Python 2.7.9You can use psutil or psmem with subprocess\nexample code Reference  One-liner for the RAM usage with only stdlib dependency:I don't believe that there is a well-supported multi-platform library available. Remember that Python itself is written in C so any library is simply going to make a smart decision about which OS-specific code snippet to run, as you suggested above. 
Python

Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like ). I know there's a function in Windows for it, but I'd like something that is cross-platform.Here's a link to a site that says how you can read a single character in Windows, Linux and OSX: will basically read 1 byte from STDIN.If you must use the method which does not wait for the  you can use this code as suggested in previous answer:( )The ActiveState  quoted verbatim in two answers is over-engineered. It can be boiled down to this:Also worth trying is the  library, which is in part based on the ActiveState recipe mentioned in other answers.Installation:Usage:Tested on Windows and Linux with Python 2.7.On Windows, only keys which map to letters or ASCII control codes are supported (, , , , +). On GNU/Linux (depending on exact terminal, perhaps?) you also get , , , , ,  and  keys... but then, there's issues separating these special keys from an .Caveat: Like with most (all?) answers in here, signal keys like +, + and + are caught and returned (as ,  and  respectively); your program can be come difficult to abort.An alternative method:From .I think it gets extremely clunky at this point, and debugging on the different platforms is a big mess.You'd be better off using something like pyglet, pygame, cocos2d - if you are doing something more elaborate than this and will need visuals, OR  if you are going to work with the terminal.Curses is standard: This code, based off , will correctly raise KeyboardInterrupt and EOFError if + or + are pressed.Should work on Windows and Linux. An OS X version is available from the original source.The (currently) top-ranked answer (with the ActiveState code) is overly complicated. I don't see a reason to use classes when a mere function should suffice. Below are two implementations that accomplish the same thing but with more readable code. I missed one advantage of the ActiveState code. If you plan to read characters multiple times, that code avoids the (negligible) cost of repeating the Windows import and the ImportError exception handling on Unix-like systems. While you probably should be more concerned about code readability than that negligible optimization, here is an alternative (it is similar to Louis's answer, but getChar() is self-contained) that functions the same as the ActiveState code and is more readable:This might be a use case for a context manager.  Leaving aside allowances for Windows OS, here's my suggestion:The answers  were informative, however I also wanted a way to get key presses asynchronously and fire off key presses in separate events, all in a thread-safe, cross-platform way. PyGame was also too bloated for me. So I made the following (in Python 2.7 but I suspect it's easily portable), which I figured I'd share here in case it was useful for anyone else. I stored this in a file named keyPress.py.The idea is that you can either simply call , which will read a key from the keyboard, then return it.If you want something more than that, I made a  object. You can create one via something like .Then there are three things you can do: takes in any function that takes in one parameter. Then every time a key is pressed, this function will be called with that key's string as it's input. These are ran in a separate thread, so you can block all you want in them and it won't mess up the functionality of the KeyCapturer nor delay the other events. returns a key in the same blocking way as before. It is now needed here because the keys are being captured via the  object now, so  would conflict with that behavior and both of them would miss some keys since only one key can be captured at a time. Also, say the user presses 'a', then 'b', you call , the the user presses 'c'. That  call  will immediately return 'a', then if you call it again it will return 'b', then 'c'. If you call it again it will block until another key is pressed. This ensures that you don't miss any keys, in a blocking way if desired. So in this way it's a little different than  from beforeIf you want the behavior of  back,  is like , except that it only returns keys pressed  the call to . So in the above example,  would block until the user presses 'c', and then if you call it again it will block until another key is pressed. is a little different. It's designed for something that does a lot of processing, then occasionally comes back and checks which keys were pressed. Thus  returns a list of all the keys pressed since the last call to , in order from oldest key pressed to most recent key pressed. It also doesn't block, meaning that if no keys have been pressed since the last call to , an empty   will be returned.To actually start capturing keys, you need to call  with your  object made above.  is non-blocking, and simply starts one thread that just records the key presses, and another thread to process those key presses. There are two threads to ensure that the thread that records key presses doesn't miss any keys.If you want to stop capturing keys, you can call  and it will stop capturing keys. However, since capturing a key is a blocking operation, the thread capturing keys might capture one more key after calling .To prevent this, you can pass in an optional parameter(s) into  of a function that just does something like checks if a key equals 'c' and then exits. It's important that this function does very little before, for example, a sleep here will cause us to miss keys.However, if  is called in this function, key captures will be stopped immediately, without trying to capture any more, and that all  calls will be returned immediately, with None if no keys have been pressed yet.Also, since  and  store all the previous keys pressed (until you retrieve them), you can call  and  to forget the keys previously pressed.Note that ,  and events are independent, so if a key is pressed:\n1. One call to  that is waiting, with lossy on, will return\n   that key. The other waiting calls (if any) will continue waiting.\n2. That key will be stored in the queue of get keys, so that  with lossy off will return the oldest key pressed not returned by  yet.\n3. All events will be fired with that key as their input\n4. That key will be stored in the list of  keys, where that lis twill be returned and set to empty list on the next call to If all this is too much, here is an example use case:It is working well for me from the simple test I made, but I will happily take others feedback as well if there is something I missed.I posted this  as well.This is NON-BLOCKING, reads a key and and stores it in keypress.key. in your programmTry this with pygame:Try using this: \nIt's non-blocking (that means that you can have a while loop and detect a key press without stopping it) and cross-platform.An example to use this:Or you could use the . But this would block the while loopThe build-in raw_input should help. The  package in python can be used to enter \"raw\" mode for character input from the terminal with just a few statements.  Curses' main use is to take over the screen for output, which may not be what you want. This code snippet uses  statements instead, which are usable, but you must be aware of how curses changes line endings attached to output. My solution for python3, not depending on any pip packages.
Python

What would be the most elegant and efficient way of finding/returning the first list item that matches a certain criterion?For example, if I have a list of objects and I would like to get the first object of those with attribute . I could of course use list comprehension, but that would incur O(n) and if n is large, it's wasteful. I could also use a loop with  once the criterion was met, but I thought there could be a more pythonic/elegant solution.If you don't have any other indexes or sorted information for your objects, then you will have to iterate until such an object is found:This is however faster than a complete list comprehension. Compare these two:The first one needs 5.75ms, the second one 58.3\u00b5s (100 times faster because the loop 100 times shorter).it'll return the object if found else it'll return \"not found\"
Python

Does anyone know how the built in dictionary type for python is implemented?  My understanding is that it is some sort of hash table, but I haven't been able to find any sort of definitive answer.Here is everything about Python dicts that I was able to put together (probably more than anyone would like to know; but the answer is comprehensive). NOTE: I did the research on Python Dict implementation in response to my own  about how multiple entries in a dict can have same hash values. I posted a slightly edited version of the response here because all the research is very relevant for this question as well.Python Dictionaries use  () , a.k.a  should, as noted in Wikipedia, not be confused with its opposite ! (which we see in the accepted answer).Open addressing means that the dict uses array slots, and when an object's primary position is taken in the dict, the object's spot is sought at a different index in the same array, using a \"perturbation\" scheme, where the object's hash value plays part.It is a hash table.  You can read about it some in the .  Otherwise, the code is well-written and should be easy to understand.For a long time, it worked like this. Python would preallocate 8 empty rows and use the hash to determine where to stick the key-value pair. For example, if the hash for the key ended in 001, it would stick it in the 1 index (like the example below.) Each row takes up 24 bytes on a 64 bit architecture, 12 on a 32 bit. (Note that the column headers are just labels - they don't actually exist in memory.)If the hash ended the same as a preexisting key's hash, this is a collision, and then it would stick the key-value pair in a different location.After 5 key-values are stored, when adding another key-value pair, the probability of hash collisions is too large, so the dictionary is doubled in size. In a 64 bit process, before the resize, we have 72 bytes empty, and after, we are wasting 240 bytes due to the 10 empty rows.This takes a lot of space, but the lookup time is fairly constant. The key comparison algorithm is to compute the hash, go to the expected location, compare the key's id - if they're the same object, they're equal. If not then compare the hash values, if they are  the same, they're not equal. Else, then we finally compare keys for equality, and if they are equal, return the value. The final comparison for equality can be quite slow, but the earlier checks usually shortcut the final comparison, making the lookups very quick.(Collisions slow things down, and an attacker could theoretically use hash collisions to perform a denial of service attack, so we randomized the hash function such that it computes a different hash for each new Python process.)The wasted space described above has led us to modify the implementation of dictionaries, with an exciting new (if unofficial) feature that dictionaries are now ordered (by insertion).We start, instead, by preallocating an array for the index of the insertion.Since our first key-value pair goes in the second slot, we index like this:And our table just gets populated by insertion order:So when we do a lookup for a key, we use the hash to check the position we expect (in this case, we go straight to index 1 of the array), then go to that index in the hash-table (e.g. index 0), check that the keys are equal (using the same algorithm described earlier), and if so, return the value.We retain constant lookup time, with minor speed losses in some cases and gains in others, with the upside that we save quite a lot of space over the pre-existing implementation. The only space wasted are the null bytes in the index array.Raymond Hettinger introduced this to  in December of 2012. It finally got into CPython in . Ordering by insertion is still considered an implementation detail to allow other implementations of Python a chance to catch up.Another optimization to save space is an implementation that shares keys. Thus, instead of having redundant dictionaries that take up all of that space, we have dictionaries that reuse the shared keys and keys' hashes. You can think of it like this:For a 64 bit machine, this could save up to 16 bytes per key per extra dictionary.These shared-key dicts are intended to be used for custom objects' . To get this behavior, I believe you need to finish populating your  before you instantiate your next object (). This means you should assign all your attributes in the  or , else you might not get your space savings.However, if you know all of your attributes at the time your  is executed, you could also provide  for your object, and guarantee that  is not created at all (if not available in parents), or even allow  but guarantee that your foreseen attributes are stored in slots anyways. For more on , .
Python

I'm launching a subprocess with the following command:However, when I try to kill using:or The command keeps running in the background, so I was wondering how can I actually terminate the process. Note that when I run the command with:It does terminate successfully when issuing the .Use a  so as to enable sending a signal to all the process in the groups. For that, you should attach a  to the parent process of the spawned/child processes, which is a shell in your case. This will make it the group leader of the processes. So now, when a signal is sent to the process group leader, it's transmitted to all of the child processes of this group.Here's the code: ends up killing the shell process and  is still running.I found a convenient fix this by:This will cause cmd to inherit the shell process, instead of having the shell launch a child process, which does not get killed.   will be the id of your cmd process then. should work.I don't know what effect this will have on your pipe though.If you can use , then this works perfectly:I could do it using it killed the  and the program that i gave the command for.(On Windows)As Sai said, the shell is the child, so signals are intercepted by it -- best way I've found is to use shell=False and use shlex to split the command line:Then p.kill() and p.terminate() should work how you expect.When  the shell is the child process, and the commands are its children. So any  or  will kill the shell but not its child processes, and I don't remember a good way to do it.\n The best way I can think of is to use , otherwise when you kill the parent shell process, it will leave a defunct shell process.
Python

I want to run a Python script from another Python script. I want to pass variables like I would using the command line.For example, I would run my first script that would iterate through a list of values (0,1,2,3) and pass those to the 2nd script  then  , etc.I found SO  which is a similar question but ars's answer calls a function, where as I want to run the whole script not just a function, and balpha's answer calls the script but with no args. I altered this to something like the below as a test: But it is not accepting variables properly.  When I print out the  in script2.py it is the original command call to first script \"['C:\\script1.py'].I don't really want to change the original script (i.e. script2.py in my example) since I don't own it.I figure there must be a way to do this, I am just confused how you do it.  Try using : is different because it is designed to run a sequence of Python statements in the  execution context. That's why  didn't change for you.This is inherently the wrong thing to do. If you are running a Python script from another Python script, you should communicate through Python instead of through the OS:In an ideal world, you will be able to call a function inside  directly:If necessary, you can hack . There's a neat way of doing this using a context manager to ensure that you don't make any permanent changes.I think this is preferable to passing all your data to the OS and back; that's just silly.Ideally, the Python script you want to run will be set up with code like this near the end:In other words,  the module is called from the command line, it parses the command line options and then calls another function, , to do the actual work. (The actual arguments will vary, and the parsing may be more involved.)If you want to call such a script from another Python script, however, you can simply  it and call  directly, rather than going through the operating system. will work, but it is the roundabout (read \"slow\") way to do it, as you are starting a whole new Python interpreter process each time for no raisin.SubProcess module:\nWith this, you can also redirect stdin, stdout, and stderr.I think the good practice may be something like this; according to documentation \nThe subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several older modules and functions:Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process.\nIf os.system isn't powerful enough for you, there's .
Python

Many Python programmers are probably unaware that the syntax of  loops and  loops includes an optional  clause:The body of the  clause is a good place for certain kinds of clean-up actions, and is executed on normal termination of the loop: I.e., exiting the loop with  or  skips the  clause; exiting after a  executes it. I know this only because I just  (yet again), because  I can never remember  the  clause is executed.Always? On \"failure\" of the loop, as the name suggests? On regular termination? Even if the loop is exited with ? I can never be entirely sure without looking it up.I blame my persisting uncertainty on the choice of keyword: I find  incredibly unmnemonic for this semantics. My question is not \"why is this keyword used for this purpose\" (which I would probably vote to close, though only after reading the answers and comments), but I'm sure there was a fair amount of discussion about this, and I can imagine that the choice was made for consistency with the  statement's  clause (which I also have to look up), and with the goal of not adding to the list of Python's reserved words. Perhaps the reasons for choosing  will clarify its function and make it more memorable, but I'm after connecting name to function, not after historical explanation per se.The answers to , which my question was briefly closed as a duplicate of, contain a lot of interesting back story. My question has a different focus (how to connect the specific semantics of  with the keyword choice), but I feel there should be a link to this question somewhere.(This is inspired by @Mark Tolonen's answer.)An  statement runs its  clause if its condition evaluates to false.\nIdentically, a  loop runs the else clause if its condition evaluates to false.This rule matches the behavior you described: loops behave the same way. Just consider the condition as true if the iterator has more elements, or false otherwise.Better to think of it this way: The  block will  be executed if everything goes  in the preceding  block such that it reaches exhaustion.  in this context will mean no , no , no . Any statement that hijacks control from  will cause the  block to be bypassed.A common use case is found when searching for an item in an , for which the search is either called off when the item is found or a  flag is raised/printed via the following  block:A  does not hijack control from , so control will proceed to the  after the  is exhausted.When does an  execute an ? When its condition is false. It is exactly the same for the /.  So you can think of / as just an  that keeps running its true condition until it evaluates false.  A  doesn't change that.  It just jumps of of the containing loop with no evaluation.  The  is only executed if  the / condition is false.The  is similar, except its false condition is exhausting its iterator.  and  don't execute .  That isn't their function.  The  exits the containing loop.  The  goes back to the top of the containing loop, where the loop condition is evaluated.  It is the act of evaluating / to false (or  has no more items) that executes  and no other way.This is what it essentially means:It's a nicer way of writing of this common pattern:The  clause will not be executed if there is a  because  leaves the function, as it is meant to. The only exception to that which you may be thinking of is , whose purpose is to be sure that it is always executed. has nothing special to do with this matter. It causes the current iteration of the loop to end which may happen to end the entire loop, and clearly in that case the loop wasn't ended by a . is similar:If you think of your loops as a structure similar to this (somewhat pseudo-code):it might make a little bit more sense. A loop is essentially just an  statement that is repeated until the condition is . And this is the important point. The loop checks its condition and sees that it's , thus executes the  (just like a normal ) and then the loop is done.So notice that the  . That means that if you exit the body of the loop in the middle of execution with for example a  or a , since the condition is not checked again, the  case won't be executed.A  on the other hand stops the current execution and then jumps back to check the condition of the loop again, which is why the  can be reached in this scenario.My gotcha moment with the loop's  clause was when I was watching a talk by , who told a story about how he thought it should have been called . Take a look at the following code, what do you think it would do?What would you guess it does? Well, the part that says  would only be executed if a  statement wasn't hit in the loop.Usually I tend to think of a loop structure like this:To be a lot like a variable number of  statements:In this case the  statement on the for loop works exactly like the  statement on the chain of s, it only executes if none of the conditions before it evaluate to True. (or break execution with  or an exception)  If my loop does not fit this specification usually I choose to opt out of using  for the exact reason you posted this question: it is non-intuitive.In  (TDD), when using the  paradigm, you treat loops as a generalization of conditional statements.This approach combines well with this syntax, if you consider only simple  (no ) statements:generalizes to:nicely.In other languages, TDD steps from a single case to cases with collections require more refactoring.Here is an example from :In the linked article at 8thlight blog, the Word Wrap kata is considered: adding line breaks to strings (the  variable in the snippets below) to make them fit a given width (the  variable in the snippets below). At one point the implementation looks as follows (Java):and the next test, that currently fails is:So we have code that works conditionally: when a particular condition is met, a line break is added. We want to improve the code to handle multiple line breaks. The solution presented in the article proposes to apply the  transformation, however the author makes a comment that:which forces to do more changes to the code in the context of one failing test:In TDD we want to write as less code as possible to make tests pass. Thanks to Python's syntax the following transformation is possible:from:to:Others have already explained the mechanics of , and the  has the authoritative definition (see  and ), but here is my personal mnemonic, FWIW. I guess the key for me has been to break this down into two parts: one for understanding the meaning of the  in relation to the loop conditional, and one for understanding loop control.I find it's easiest to start by understanding :The  mnemonic is basically the same:In both cases, the  part is only reached once there are no more items to process, and the last item has been processed in a regular manner (i.e. no  or ). A  just goes back and sees if there are any more items. My mnemonic for these rules applies to both  and :\u2013 with \"loop back to start\" meaning, obviously, the start of the loop where we check whether there are any more items in the iterable, so as far as the  is concerned,  really plays no role at all.The way I see it,  fires when you iterate past the end of the loop.If you  or  or  you don't iterate past the end of loop, you stop immeadiately, and thus the  block won't run. If you  you still iterate past the end of loop, since continue just skips to the next iteration. It doesn't stop the loop. Think of the  clause as being part of the loop construct;  breaks out of the loop construct entirely, and thus skips the  clause.But really, my mental mapping is simply that it's the 'structured' version of the pattern C/C++ pattern:So when I encounter  or write it myself, rather than understand it , I mentally translate it into the above understanding of the pattern and then work out which parts of the python syntax map to which parts of the pattern.(I put 'structured' in scare quotes because the difference is not whether the code is structured or unstructured, but merely whether there are keywords and grammar dedicated to the particular structure)The way I think about it, the key is to consider the meaning of  rather than .The other keywords you mention break out of the loop (exit abnormally) whilst  does not, it just skips the remainder of the code block inside the loop. The fact that it can precede loop termination is incidental: the termination is actually done in the normal way by evaluation of the loop conditional expression.Then you just need to remember that the  clause is executed after normal loop termination.Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome. You need to determine which action to take and which statements to execute if outcome is TRUE or FALSE otherwise.In the above code, it get breaks when i equal to 6..otherwise it print welcome for 5 times.!Thanks,\n
Python

Which tar do I need to download off this site?I've tried the fortrans, but I keep getting this error (after setting the environment variable obviously).The  used to provide build and installation instructions, but the instructions there now rely on OS binary distributions. To build SciPy (and NumPy) on operating systems without precompiled packages of the required libraries, you must build and then statically link to the Fortran libraries  and :Execute only one of the five g77/gfortran/ifort commands. I have commented out all, but the gfortran which I use. The subsequent LAPACK installation requires a  compiler, and since both installs should use the same Fortran compiler, g77 should not be used for BLAS.Next, you'll need to install the LAPACK stuff. The SciPy webpage's instructions helped me here as well, but I had to modify them to suit my environment:Update on 3-Sep-2015:\nVerified some comments today (thanks to all): Before running  edit the  file and add  option to  and  settings. If you are on a 64bit architecture or want to compile for one, also add . It is important that BLAS and LAPACK are compiled with these options set to the same values. If you forget the  SciPy will actually give you an error about missing symbols and will recommend this switch. The specific section of  looks like this in my setup:On old machines (e.g. RedHat 5), gfortran might be installed in an older version (e.g. 4.1.2) and does not understand option . Simply remove it from the  file in such cases.The lapack test target of the Makefile fails in my setup because it cannot find the blas libraries. If you are thorough you can temporarily move the blas library to the specified location to test the lapack. I'm a lazy person, so I trust the devs to have it working and verify only in SciPy.If you need to use the latest versions of SciPy rather than the packaged version, without going through the hassle of building BLAS and LAPACK, you can follow the below procedure.Install linear algebra libraries from repository (for Ubuntu),Then install SciPy, (after downloading the SciPy source):  orAs the case may be.On Fedora, this works: Remember to install '' and '' in addition to 'blas' and 'lapack' otherwise you'll get the error you mentioned or the \"numpy.distutils.system_info.\" error. I guess you are talking about installation in Ubuntu. Just use: That should take care of the BLAS libraries compiling as well. Else, compiling the BLAS libraries is very difficult.For Windows users there is a nice binary package by Chris (warning: it's a pretty large download, 191\u00a0MB):Following the instructions given by 'cfi' works for me, although there are a few pieces he left out that you might need:   1) Your lapack directory, after unzipping, may be called lapack-X-Y (some version number), so you can just rename that to LAPACK.  2) In that directory, you may need to do:Try using 
Python

I got a lot of errors with the message :after changed from python-psycopg to python-psycopg2 as Django project's database engine.The code remains the same, just dont know where those errors are from.This is what postgres does when a query produces an error and you try to run another query without first rolling back the transaction.  To fix it, you'll want to figure out where in the code that bad query is being executed.  It might be helpful to use the  and  options in your postgresql server.To get rid of the error,  after you've fixed your code:You can use try-except to prevent the error from occurring:Refer : So, I ran into this same issue. The problem I was having here was that my database wasn't properly synced. Simple problems always seem to cause the most angst...To sync your django db, from within your app directory, within terminal, type:Edit: Note that if you are using django-south, running the '$ python manage.py migrate' command may also resolve this issue.Happy coding!In my experience, these errors happen this way:There nothing wrong with the second query, but since the real error was caught, the second query is the one that raises the (much less informative) error.edit: this only happens if the  clause catches  (or any other low level database exception), If you catch something like  this error will not come up, because  does not corrupt the transaction.The lesson here is don't do try/except/pass.I think the pattern priestc mentions is more likely to be the usual cause of this issue when using PostgreSQL.However I feel there are valid uses for the pattern and I don't think this issue should be a reason to always avoid it. For example:If you do feel OK with this pattern, but want to avoid explicit transaction handling code all over the place then you might want to look into turning on autocommit mode (PostgreSQL 8.2+): I am unsure if there are important performance considerations (or of any other type).If you get this while in interactive shell and need a quick fix, do this:originally seen in I've got the silimar problem. The solution was to migrate db ( or  if you use south).I encountered a similar behavior while running a malfunctioned transaction on the  terminal. Nothing went through after this, as the  is in a state of . However, just as a quick fix, if you can afford to avoid . Following did the trick for me:I just had this error too but it was masking another more relevant error message where the code was trying to store a 125 characters string in a 100 characters column:I had to debug through the code for the above message to show up, otherwise it displaysIn response to @priestc and @Sebastian, what if you do something like this?I just tried this code and it seems to work, failing silently without having to care about any possible errors, and working when the query is good.I believe @AnujGupta's answer is correct. However the rollback can itself raise an exception which you should catch and handle:If you find you're rewriting this code in various  locations, you can extract-method:Finally, you can prettify it using a decorator that protects methods which use :Even if you implement the decorator above, it's still convenient to keep  as an extracted method in case you need to use it manually for cases where specific handling is required, and the generic decorator handling isn't enough.This is very strange behavior for me. I'm surprised that no one thought of savepoints. In my code failing query was expected behavior:I have changed code this way to use savepoints:i got the same error. first check your models. actually it occurs due to some field or length mismatch in your models. for finding exact error use \"try except\" to find the exact error and its location. in \"except:\" use print repr(format_exc())\neg:\ntry:\n # your code\nexcept:\n print repr(format_exc())imp: please import-  from traceback import format_exc\nit helps to get your exact error.you could disable transaction via \"set_isolation_level(0)\"
Python

I have a list with 15 numbers in, and I need to write some code that produces all 32,768 combinations of those numbers. I've found  (by Googling) that apparently does what I'm looking for, but I found the code fairly opaque and am wary of using it. Plus I have a feeling there must be a more elegant solution.The only thing that occurs to me would be to just loop through the decimal integers 1\u201332768 and convert those to binary, and use the binary representation as a filter to pick out the appropriate numbers. Does anyone know of a better way? Using , maybe?Have a look at :Since 2.6, batteries are included! missed one aspect: the OP asked for ALL combinations... not just combinations of length \"r\".So you'd either have to loop through all lengths \"L\":Or -- if you want to get snazzy (or bend the brain of whoever reads your code after you) -- you can generate the chain of \"combinations()\" generators, and iterate through that:Here's a lazy one-liner, also using itertools:Main idea behind this answer: there are 2^N combinations -- same as the number of binary strings of length N. For each binary string, you pick all elements corresponding to a \"1\".Things to consider:I agree with Dan H that Ben indeed asked for  combinations.  does not give all combinations.Another issue is, if the input iterable is big, it is perhaps better to return a generator instead of everything in a list:Here is one using recursion:This one-liner gives you all the combinations (between  and  items if the original list/set contains  distinct elements) and uses the native method :The output will be:Try it online:In comments under the highly upvoted  by @Dan H, mention is made of the  recipe in the \u2014including one by . , so far no one has posted it as an answer. Since it's probably one of the better if not the best approach to the problem\u2014and given a  from another commenter, it's shown below. The function produces  unique combinations of the list elements of  length possible.: If the, subtly different, goal is to obtain only combinations of unique elements, change the line  to  to eliminate any duplicate elements. Regardless, the fact that the  is ultimately turned into a  means it will work with generators (unlike several of the other answers).Output:Here is yet another solution (one-liner), involving using the  function, but here we use a double list comprehension (as opposed to a for loop or sum):Demo:Below is a \"standard recursive answer\", similar to the other similar answer  . (We don't realistically have to worry about running out of stack space since there's no way we could process all N! permutations.)It visits every element in turn, and either takes it or leaves it (we can directly see the 2^N cardinality from this algorithm).Demo:Using list comprehension:Output would be:I thought I would add this function for those seeking an answer without importing itertools or any other extra libraries.Simple Yield Generator Usage:Output from Usage example above:This code employs a simple algorithm with nested lists...This is my implementation
Python

Consider three functions:They all appear to return None. Are there any differences between how the returned value of these functions behave?  Are there any reasons to prefer one versus the other?On the actual behavior, there is no difference. They all return  and that's it. However, there is a time and  place for all of these.\nThe following instructions are basically how the different methods should be used (or atleast how I was taught they should be used), but they are not absolute rules so you can mix them up if you feel necessary to.Using .This tells that the function is indeed meant to return a value for later use, and in this case it returns . This value  can then be used elsewhere.  is never used if there are no other possible return values from the function.In the following example, we return person's mother if the person given is a human. If it's not a human, we return  since the \"person\" doesn't have a mother (let's suppose it's not an animal or so).Using .This is used for the same reason as  in loops. The return value doesn't matter and you only want to exit the whole function. It's extremely useful in some places, even tho you don't need it that often.We got 15 prisoners and we know one of them has a knife. We loop through each prisoner one by one to check if they have a knife. If we hit the person with a knife, we can just exit the function cause we know there's only one knife and no reason the check rest of the prisoners. If we don't find the prisoner with a knife, we raise an the alert. This could be done in many different ways and using  is probably not even the best way, but it's just an example to show how to use  for exiting a function.Note: You should never do , since the return value is not meant to be caught.Using no return at all.This will also return , but that value is not meant to be used or caught. It simply means that the function ended successfully. It's basically the same as  in  functions in languages such as C++ or Java.In the following example, we set person's mother's name, and then the function exits after completing successfully.Note: You should never do , since the return value is not meant to be caught.Yes, they are all the same. We can review the interpreted machine code to confirm that that they're all doing the exact same thing.They each return the same singleton  -- There is no functional difference. I think that it is reasonably idiomatic to leave off the  statement unless you need it to break out of the function early (in which case a bare  is more common), or return something other than .  It also makes sense and seems to be idiomatic to write  when it is in a function that has another path that returns something other than .  Writing  out explicitly is a visual cue to the reader that there's another branch which returns something more interesting (and that calling code will probably need to handle both types of return values).Often in Python, functions which return  are used like  functions in C -- Their purpose is generally to operate on the input arguments  (unless you're using global data ()).  Returning  usually makes it more explicit that the arguments were mutated.  This makes it a little more clear why it makes sense to leave off the  statement from a \"language conventions\" standpoint.That said, if you're working in a code base that already has pre-set conventions around these things, I'd definitely follow suit to help the code base stay uniform...
Python

I think I understand , but every time I look for examples for what is weak typing I end up finding examples of programming languages that simply coerce/convert types automatically.For instance, in this article named  says that Python is strongly typed because you get an exception if you try to:However, such thing is possible in Java and in C#, and we do not consider them weakly typed just for that.In this another article named  the author says that Perl is weakly typed simply because I can concatenate a string to a number and viceversa without any explicit conversion.So the same example makes Perl weakly typed, but not Java and C#?.Gee, this is confusing The authors seem to imply that a language that prevents the application of certain operations on values of different types is strongly typed and the contrary means weakly typed.Therefore, at some point I have felt prompted to believe that if a language provides a lot of automatic conversions or coercion between types (as perl) may end up being considered weakly typed, whereas other languages that provide only a few conversions may end up being considered strongly typed. I am inclined to believe, though, that I must be wrong in this interepretation, I just do not know why or how to explain it.So, my questions are: UPDATE:  Thanks for the great question!It means \"this language uses a type system that I find distasteful\". A \"strongly typed\" language by contrast is a language with a type system that I find pleasant.The terms are essentially meaningless and you should avoid them.  lists  for \"strongly typed\", several of which are contradictory. This indicates that the odds of confusion being created are high in any conversation involving the term \"strongly typed\" or \"weakly typed\". All that you can really say with any certainty is that a \"strongly typed\" language under discussion has some additional restriction in the type system, either at runtime or compile time, that a \"weakly typed\" language under discussion lacks. What that restriction might be cannot be determined without further context.Instead of using \"strongly typed\" and \"weakly typed\", you should describe in detail what kind of type safety you mean. For example, C# is a  language and a  language and a  language, . C# allows all three of those forms of \"strong\" typing to be violated.  The cast operator violates static typing; it says to the compiler \"I know more about the runtime type of this expression than you do\". If the developer is wrong, then the runtime will throw an exception in order to protect type safety. If the developer wishes to break type safety or memory safety, they can do so by turning off the type safety system by making an \"unsafe\" block. In an unsafe block you can use pointer magic to treat an int as a float (violating type safety) or to write to memory you do not own. (Violating memory safety.)C# imposes type restrictions that are checked at both compile-time and at runtime, thereby making it a \"strongly typed\" language compared to languages that do less compile-time checking or less runtime checking. C# also allows you to in special circumstances do an end-run around those restrictions, making it a \"weakly typed\" language compared with languages which do not allow you to do such an end-run. Which is it really?  It is impossible to say; it depends on the point of view of the speaker and their attitude towards the various language features. As others have noted, the terms \"strongly typed\" and \"weakly typed\" have so many different meanings that there's no single answer to your question.  However, since you specifically mentioned Perl in your question, let me try to explain in what sense Perl is weakly typed.The point is that, in Perl, there is no such thing as an \"integer variable\", a \"float variable\", a \"string variable\" or a \"boolean variable\".  In fact, as far as the user can (usually) tell, there aren't even integer, float, string or boolean : all you have are \"scalars\", which are all of these things at the same time.  So you can, for example, write:Of course, as you correctly note, all of this can be seen as just type coercion.  But the point is that, in Perl, types are  coerced.  In fact, it's quite hard for a user to tell what the internal \"type\" of a variable might be: at line 2 in my example above, asking whether the value of  is the string  or the number  is pretty much meaningless, since, as far as Perl is concerned, .  Indeed, it's even possible for a Perl scalar to internally have  a string and a numeric value at the same time, as is e.g. the case for  after line 2 above.The flip side of all this is that, since Perl variables are untyped (or, rather, don't expose their internal type to the user), operators cannot be overloaded to do different things for different types of arguments; you can't just say \"this operator will do X for numbers and Y for strings\", because the operator can't (won't) tell which kind of values its arguments are.Thus, for example, Perl has and needs both a numeric addition operator () and a string concatenation operator (): as you saw above, it's perfectly fine to add strings () or to concatenate numbers ().  Similarly, the numeric comparison operators , , , , ,  and  compare the numeric values of their arguments, while the string comparison operators , , , , ,  and  compare them lexicographically as strings.  So , but  (but , while ).  (Mind you, certain  languages, like JavaScript, try to accommodate Perl-like weak typing while  doing operator overloading.  This often leads to ugliness, like the loss of associativity for .)(The fly in the ointment here is that, for historical reasons, Perl 5 does have a few corner cases, like the bitwise logical operators, whose behavior depends on the internal representation of their arguments.  Those are generally considered an annoying design flaw, since the internal representation can change for surprising reasons, and so predicting just what those operators do in a given situation can be tricky.)All that said, one could argue that Perl  have strong types; they're just not the kind of types you might expect.  Specifically, in addition to the \"scalar\" type discussed above, Perl also has two structured types: \"array\" and \"hash\".  Those are  distinct from scalars, to the point where Perl variables have different  indicating their type ( for scalars,  for arrays,  for hashes).  There  coercion rules between these types, so you  write e.g. , but many of them are quite lossy: for example,  assigns the  of the array   to , not its contents.  (Also, there are a few other strange types, like typeglobs and I/O handles, that you don't often see exposed.)Also, a slight chink in this nice design is the existence of reference types, which are a special kind of scalars (and which  be distinguished from normal scalars, using the  operator).  It's possible to use references as normal scalars, but their string/numeric values are not particularly useful, and they tend to lose their special reference-ness if you modify them using normal scalar operations.  Also, any Perl variable can be ed to a class, turning it into an object of that class; the OO class system in Perl is somewhat orthogonal to the primitive type (or typelessness) system described above, although it's also \"weak\" in the sense of following the  paradigm.  The general opinion is that, if you find yourself checking the class of an object in Perl, you're doing something wrong. Actually, the sigil denotes the type of the value being accessed, so that e.g. the first scalar in the array  is denoted .  See  for more details. Objects in Perl are (normally) accessed through references to them, but what actually gets ed is the (possibly anonymous) variable the reference points to.  However, the blessing is indeed a property of the variable,  of its value, so e.g. that assigning the actual blessed variable to another one just gives you a shallow, unblessed copy of it.  See  for more details.In addition to what Eric has said, consider the following C code:In contrast to languages such as Python, C#, Java or whatnot, the above is weakly typed because we  type information. Eric correctly pointed out that in C# we can circumvent the compiler by casting, effectively telling it \u201cI know more about the type of this variable than you\u201d.But even then, the runtime will still check the type! If the cast is invalid, the runtime system will catch it and throw an exception.With type erasure, this doesn\u2019t happen \u2013 type information is thrown away. A cast to  in C does exactly that. In this regard, the above is fundamentally different from a C# method declaration such as .(Technically, C# also allows type erasure through unsafe code or marshalling.) is as weakly typed as it gets. Everything else is just a matter of static vs. dynamic type checking, i.e. of the time  a type is checked.A perfect example comes from :Generally strong typing implies that the programming language places severe restrictions on the intermixing that is permitted to occur.Notice that a weak typing language can intermix different types without errors. A strong type language requires the input types to be the expected types. In a strong type language a type can be converted ( converts an integer to a string) or cast (). This all depends on the interpretation of typing.I would like to contribute to the discussion with my own research on the subject, as others comment and contribute I have been reading their answers and following their references and I have found interesting information. As suggested, it is probable that most of this would be better discussed in the Programmers forum, since it appears to be more theoretical than practical.From a theoretical standpoint, I think the article by Luca Cardelli and Peter Wegner named  has one of the best arguments I have read.This statement seems to suggest that weakly typing would let us access the inner structure of a type and manipulate it as if it was something else (another type). Perhaps what we could do with unsafe code (mentioned by Eric) or with c type-erased pointers mentioned by Konrad.The article continues...As such, strong typing means the absence of type errors, I can only assume that weak typing means the contrary: the likely presence of type errors. At runtime or compile time? Seems irrelevant here.Funny thing, as per this definition, a language with powerful type coercions like Perl would be considered strongly typed, because the system is not failing, but it is dealing with the types by coercing them into appropriate and well defined equivalences.On the other hand, could I say than the allowance of  and  (in Java) and ,  (in C#) would indicate a level of weakly typing, at least at compile time? Eric's answer seems to agree with this.In a second article named  provided in one of the references provided in one of the answers in this question, Luca Cardelli delves into the concept of type violations:As such, type coercions like those provided by operators could be considered type violations, but unless they break the consistency of the type system, we might say that they do not lead to a weakly typed system.Based on this neither Python, Perl, Java or C# are weakly typed.Cardelli mentions two type vilations that I very well consider cases of truly weak typing:This kind of things possible in languages like C (mentioned by Konrad) or through unsafe code in .Net (mentioned by Eric) would truly imply weakly typing.I believe the best answer so far is Eric's, because the definition of this concepts is very theoretical, and when it comes to a particular language, the interpretations of all these concepts may lead to different debatable conclusions.Weak typing does indeed mean that a high percentage of types can be implicitly coerced, attempting to guess what the coder intended.Strong typing means that types are not coerced, or at least coerced less.Static typing means your variables' types are determined at compile time.Many people have recently been confusing \"manifestly typed\" with \"strongly typed\".  \"Manifestly typed\" means that you declare your variables' types explicitly.Python is mostly strongly typed, though you can use almost anything in a boolean context, and booleans can be used in an integer context, and you can use an integer in a float context.  It is not manifestly typed, because you don't need to declare your types (except for Cython, which isn't entirely python, albeit interesting).  It is also not statically typed.C and C++ are manifestly typed, statically typed, and somewhat strongly typed, because you declare your types, types are determined at compile time, and you can mix integers and pointers, or integers and doubles, or even cast a pointer to one type into a pointer to another type.Haskell is an interesting example, because it is not manifestly typed, but it's also statically and strongly typed.The strong <=> weak typing is not only about the continuum on how much or how little of the values are coerced automatically by the language for one datatype to another, but how strongly or weakly the actual  are typed. In Python and Java, and mostly in C#, the values have their types set in stone. In Perl, not so much - there are really only a handful of different valuetypes to store in a variable. Let's open the cases one by one.In Python example ,  operator calls the  for type  giving it the string  as an argument - however, this results in NotImplemented:Next, the interpreter tries the  of str:As it fails, the  operator fails with the  the result . As such, the exception does not say much about strong typing, but the fact that the operator   its arguments automatically to the same type, is a pointer to the fact that Python is not the most weakly typed language in the continuum.On the other hand, in Python   implemented:That is, The fact that the operation is different requires some strong typing - however the opposite of  coercing the values to numbers before multiplying still would not necessarily make the values weakly typed.The Java example,  works only because as a fact of convenience, the operator  is overloaded for strings. The Java  operator replaces the sequence with creating a  (see ):This is rather an example of very static typing, without no actual coercion -  has a method  that is specifically used here. The documentation says the following:Where  then Thus this is a case of absolutely no coercion by the language - delegating every concern to the objects itself.According to the , operator  is not even overloaded for the  class - akin to Java, this is just convenience generated by the compiler, thanks to both static and strong typing.As the  explains,Perl however does not have a separate data type for numbers, booleans, strings, nulls, s, references to other objects etc - it just has one type for these all, the scalar type; 0 is a scalar value as much as is \"0\". A scalar  that was set as a string can really change into a number, and from there on behave differently from \"just a string\", . The scalar can hold anything in Perl, it is as much the object as it exists in the system. whereas in Python the names just refers to the objects, in Perl the scalar values in the names are changeable objects. Furthermore, the Object Oriented Type system is glued on top of this: there are just 3 datatypes in perl - scalars, lists and hashes. A user defined object in Perl is a reference (that is a pointer to any of the 3 previous) ed to a package - you can take any such value and bless it to any class at any instant you want. Perl even allows you to change the classes of values at whim - this is not possible in Python where to create a value of some class you need to explicitly construct the value belonging to that class with  or similar. In Python you cannot really change the essence of the object after the creation, in Perl you can do much anything:thus the type identity is weakly bound to the variable, and it can be changed through any reference on the fly. In fact, if you do does not have the class identity, even though  will still give the blessed reference.There are much more about weak typing to Perl than just automatic coercions, and it is more about that the types of the values themselves are not set into stone, unlike the Python which is dynamically yet very strongly typed language. That python gives  on  is an indication that the language is strongly typed, even though the contrary one of doing something useful, as in Java or C# does not preclude them being strongly typed languages.I like , but to address the question - strongly typed languages typically have explicit knowledge of the types of variables at each point of the program. Weakly typed languages do not, so they can attempt to perform an operation that may not be possible for a particular type.\nIt think the easiest way to see this is in a function.\nC++:The variable  is known to be of type string and any incompatible operation will be caught at compile time.Python:The variable  could be anything and we can have code that calls an invalid method, which will only get caught at runtime.As many others have expressed, the entire notion of \"strong\" vs \"weak\" typing is problematic.As a archetype, Smalltalk is very strongly typed -- it will  raise an exception if an operation between two objects is incompatible. However, I suspect few on this list would call Smalltalk a strongly-typed language, because it is I find the notion of \"static\" versus \"dynamic\" typing more useful than \"strong\" versus \"weak.\" A statically-typed language has all the types figured out at compile-time, and the programmer has to explicitly declare if otherwise.Contrast with a dynamically-typed language, where typing is performed at run-time. This is typically a requirement for polymorphic languages, so that decisions about whether an operation between two objects is legal does not have to be decided by the programmer in advance.In polymorphic, dynamically-typed languages (like Smalltalk and Ruby), it's more useful to think of a \"type\" as a \"conformance to protocol.\" If an object obeys a protocol the same way another object does -- even if the two objects do not share any inheritance or mixins or other voodoo -- they are considered the same \"type\" by the run-time system. More correctly, an object in such systems is autonomous, and can decide if it makes sense to respond to any particular message referring to any particular argument.Want an object that can make some meaningful response to the message \"+\" with an object argument that describes the colour blue? You can do that in dynamically-typed languages, but it is a pain in statically-typed languages.
Python

I've come across situations where a current version of a package seems not to be working and requires reinstallation. But  won't touch a package that is already up-to-date. I see how to force a reinstallation by first uninstalling (with ) and then installing, but is there a way to simply force an \"update\" to a nominally current version in a single step?When upgrading, reinstall all packages even if they are already up-to-date.Ignore the installed packages (reinstalling instead).You might want to have all three options:  and  ensures reinstallation, while  avoids reinstalling dependencies.Otherwise you might run into the problem that pip starts to recompile Numpy or other large packages.doesn't appear to force reinstall using python2.7 with pip-1.5I've had to useIf you want to reinstall packages specified in a requirements.txt file, without upgrading, so just reinstall the specific versions specified in the requirements.txt file:
Python

I'm trying to get the name of the Python script that is currently running.For example, I have a script called  and I would like to do something like this inside it:and get: .Use .  If you want to omit the directory part (which might be present), you can use ,.This will print  for ,  for , etc. It's the first argument to . (Note that after py2exe it would be .)Note that  will give the file where this code resides, which can be imported and different from the main file being interpreted. To get the main file, the special  module can be used:Note that  works in Python 2.7 but not in 3.2, so use the import-as syntax as above to make it portable.The Above answers are good . But I found this method more efficient using above results.\nThis results in actual script file name not a path.For completeness' sake, I thought it would be worthwhile summarizing the various possible outcomes and supplying references for the exact behaviour of each: may be invoked of any of the above in order to extract the actual file name.Try this:The first argument in sys will be the current file name so this will work
Python

I want to perform my own complex operations on financial data in dataframes in a sequential manner.For example I am using the following MSFT CSV file taken from :I then do the following:Is that the most efficient way? Given the focus on speed in pandas, I would assume there must be some special function to iterate through the  values in a manner that one also retrieves the index (possibly through a generator to be memory efficient)?  unfortunately only iterates column by column.The newest versions of pandas now include a built-in function for iterating over rows. Or, if you want it faster use But, unutbu's suggestion to use numpy functions to avoid iterating over rows will produce the fastest code. Pandas is based on NumPy arrays.\nThe key to speed with NumPy arrays is to perform your operations on the whole array at once, never row-by-row or item-by-item.For example, if  is a 1-d array, and you want the day-over-day percent change,This computes the entire array of percent changes as one statement, instead of So try to avoid the Python loop  entirely, and\nthink about how to perform your calculations with operations on the entire array (or dataframe) as a whole, rather than row-by-row.You can loop through the rows by transposing and then calling iteritems:I am not certain about efficiency in that case. To get the best possible performance in an iterative algorithm, you might want to explore writing it in , so you could do something like:I would recommend writing the algorithm in pure Python first, make sure it works and see how fast it is-- if it's not fast enough, convert things to Cython like this with minimal work to get something that's about as fast as hand-coded C/C++.Like what has been mentioned before, pandas object is most efficient when process the whole array at once. However for those who really need to loop through a pandas DataFrame to perform something, like me, I found at least three ways to do it. I have done a short test to see which one of the three is the least time consuming.Result:This is probably not the best way to measure the time consumption but it's quick for me.Here are some pros and cons IMHO:I checked out  after noticing  answer, but found that it yields (index, Series) tuples. Not sure which would work best for you, but I ended up using the  method for my problem, which yields (index, row_value1...) tuples.There's also , which iterates through (column, series) tuples.Just as a small addition, you can also do an apply if you have a complex function that you apply to a single column:Another suggestion would be to combine groupby with vectorized calculations if subsets of the rows shared characteristics which allowed you to do so. 
Python

I want to use  in . I googled this problem but couldn't find proper solutions.I find   may be a good choice. But I couldn't pass some arguments to it.Using  may be a proper solution for now. I want to know whether there's a better solution or not.Is there a way to use PhantomJS in Python?The easiest way to use PhantomJS in python is via Selenium. The simplest installation method isAfter installation, you may use phantom as simple as:If your system path environment variable isn't set correctly, you'll need to specify the exact path as an argument to .  Replace this:... with the following:References:PhantomJS recently  altogether. However, PhantomJS now embeds .A new project has since stepped up to fill the void: . You probably want to use that instead:Now since the GhostDriver comes bundled with the PhantomJS, it has become even more convenient to use it through Selenium.I tried the Node installation of PhantomJS, as suggested by Pykler, but in practice I found it to be slower than the standalone installation of PhantomJS. I guess standalone installation didn't provided these features earlier, but as of v1.9, it very much does so. Now you can use like thisHere's how I test javascript using PhantomJS and Django::::this is what I do, python3.3.  I was processing huge lists of sites, so failing on the timeout was vital for the job to run through the entire list.If using Anaconda, install with:in your script:works perfectly.  In case you are using , you can easily automate the installation processes that Pykler describes using the  recipe.That part installs node.js as binary (at least on my system) and then uses npm to install PhantomJS. Finally it creates an entry point , which you can call the PhantomJS webdriver with. (To install Selenium, you need to specify it in your egg requirements or in the Buildout configuration.)The  is great but the Node requirement is outdated. The comments in that answer suggest the simpler answer, which I've put here to save others time:
Python

I have such db model:And when new instance is added:I've an issue: all records in database have the same value in date field - the date of the first payment. After server restart - one record have new date and others have the same as the first. It's look like some data cache is used but I can't find where.database: mysql 5.1.25django v1.1.1it looks like  is being evaluated when the model is defined, and not each time you add a record.Django has a feature to accomplish what you are trying to do already:orThe difference between the second example and what you currently have is the lack of parentheses. By passing  without the parentheses, you are passing the actual function, which will be called each time a record is added. If you pass it , then you are just evaluating the function and passing it the return value.More information is available at Django's Instead of using  you should be really using From the  on the django model default field:Therefore following should work:David had the right answer. The parenthesis () makes it so that the  timezone.now() is called every time the model is evaluated. If you remove the () from timezone.now() (or datetime.now(), if using the naive datetime object) to make it just this:Then it will work as you expect:\n    New objects will receive the current date when they are created, but the date won't be overridden every time you do manage.py makemigrations/migrate.I just encountered this. Much thanks to David.The  is evaluated when the class is created, not when new record is being added to the database.To achieve what you want define this field as:This way the  field will be set to current date for each new record.The answer to this one is actually wrong.Auto filling in the value (auto_now/auto_now_add isn't the same as default).  The default value will actually be what the user sees if its a brand new object.  What I typically do is:    Make sure, if your trying to represent this in an Admin page, that you list it as 'read_only' and reference the field nameAgain, I do this since my default value isn't typically editable, and Admin pages ignore non-editables unless specified otherwise.  There is certainly a difference however between setting a default value and implementing the auto_add which is key here.  Test it out! is being evaluated once, when your class is instantiated. Try removing the parenthesis so that the function  is returned and THEN evaluated. I had the same issue with setting default values for my s and wrote up my solution .From the Python language reference, under :Fortunately, Django has a way to do what you want, if you use the  argument for the :See the Django docs for .
Python

I'd like to grab daily sunrise/sunset times from a web site. Is it possible to scrape web content with Python? what are the modules used? Is there any tutorial available?Use urllib2 in combination with the brilliant  library:I'd really recommend Scrapy, for reasons being elaborated in .Quote from the answer:I collected together scripts from my web scraping work into .Example script for your case:Output:I would strongly suggest checking out . It uses jquery-like (aka css-like) syntax which makes things really easy for those coming from that background.For your case, it would be something like:Output:You can use  to make the HTTP requests, and then you'll have web content.You can get it like this: is a python HTML parser that is supposed to be good for screen scraping.In particular,  is their tutorial on parsing an HTML document.Good luck!I use a combination of  (finding urls - py2) and  (downloading images - py2+3). The scrapemark.py has 500 lines of code, but uses regular expressions, so it may be not so fast, did not test.Example for scraping your website:\nUsage:Result:I just saw  in .Scrapy open source framework will help to web scrap in python.This open source and collaborative framework for extracting the data you need from websites. Web scraping is closely related to web indexing, which indexes information on the web using a bot or web crawler and is a universal technique adopted by most search engines.I know I have come late to party but I have a nice suggestion for you.Using  is already been suggested I would rather prefer using  to scrape data inside HTMLHere is a simple web crawler, i used BeautifulSoup and we will search for all the links(anchors) who's class name is _3NFO0d. I used Flipkar.com, it is an online retailing store.If we think of getting all the links to the Mobile names then it is easier to use this:
Python

I'm trying to plot a figure without tickmarks or numbers on either of the axes (I use axes in the traditional sense, not the matplotlib nomenclature!). An issue I have come across is where matplotlib adjusts the x(y)ticklabels by subtracting a value N, then adds N at the end of the axis.This may be vague, but the following simplified example highlights the issue, with '6.18' being the offending value of N:The three things I would like to know are:Instead of hiding each element, you can hide the whole axis:Or, you can set the ticks to an empty list:In this second option, you can still use  and  to add labels to the axes.If you want to hide just the axis text keeping the grid lines:Doing  or  will also hide the grid lines.Somewhat of an old thread but, this seems to be a faster method using the latest version of matplotlib:set the major formatter for the x-axisIf you are like me and don't always retrieve the axes,  when plotting the figure, then a simple solution would be to do I was not actually able to render an image without borders or axis data based on any of the code snippets here (even the one accepted at the answer). After digging through some API documentation, I landed on this code to render my imageI used the tick_params call to basically shut down any extra information that might be rendered and I have a perfect graph in my output file :). Hope this helps!
Python

I'm starting to learn Python and I've come across generator functions, those that have a yield statement in them.  I want to know what types of problems that these functions are really good at solving.Generators give you lazy evaluation. You use them by iterating over them, either explicitly with 'for' or implicitly by passing it to any function or construct that iterates. You can think of generators as returning multiple items, as if they return a list, but instead of returning them all at once they return them one-by-one, and the generator function is paused until the next item is requested.Generators are good for calculating large sets of results (in particular calculations involving loops themselves) where you don't know if you are going to need all results, or where you don't want to allocate the memory for all results at the same time. Or for situations where the generator uses  generator, or consumes some other resource, and it's more convenient if that happened as late as possible.Another use for generators (that is really the same) is to replace callbacks with iteration. In some situations you want a function to do a lot of work and occasionally report back to the caller. Traditionally you'd use a callback function for this. You pass this callback to the work-function and it would periodically call this callback. The generator approach is that the work-function (now a generator) knows nothing about the callback, and merely yields whenever it wants to report something. The caller, instead of writing a separate callback and passing that to the work-function, does all the reporting work in a little 'for' loop around the generator.For example, say you wrote a 'filesystem search' program. You could perform the search in its entirety, collect the results and then display them one at a time. All of the results would have to be collected before you showed the first, and all of the results would be in memory at the same time. Or you could display the results while you find them, which would be more memory efficient and much friendlier towards the user. The latter could be done by passing the result-printing function to the filesystem-search function, or it could be done by just making the search function a generator and iterating over the result.If you want to see an example of the latter two approaches, see os.path.walk() (the old filesystem-walking function with callback) and os.walk() (the new filesystem-walking generator.) Of course, if you really wanted to collect all results in a list, the generator approach is trivial to convert to the big-list approach:One of the reasons to use generator is to make the solution clearer for some kind of solutions.The other is to treat results one at a time, avoiding building huge lists of results that you would process separated anyway. If you have a fibonacci-up-to-n function like this:You can more easily write the function as this:The function is clearer. And if you use the function like this:in this example, if using the generator version, the whole 1000000 item list won't be created at all, just one value at a time. That would not be the case when using the list version, where a list would be created first.See the \"Motivation\" section in .A non-obvious use of generators is creating interruptible functions, which lets you do things like update UI or run several jobs \"simultaneously\" (interleaved, actually) while not using threads.Buffering. When it is efficient to fetch data in large chunks, but process it in small chunks, then a generator might help:The above lets you easily separate buffering from processing. The consumer function can now just get the values one by one without worrying about buffering.I find this explanation which clears my doubt. Because there is a possibility that person who don't know  also don't know about The return statement is where all the local variables are destroyed and the resulting value is given back (returned) to the caller.  Should the same function be called some time later, the function will get a fresh new set of variables.But what if the local variables aren't thrown away when we exit a function?  This implies that we can  where we left off.  This is where the concept of  are introduced and the  statement resumes where the  left off.So that's the difference between return and yield statements in Python.  So Generators are a simple and powerful tool for creating iterators. They are written like regular functions but use the yield statement whenever they want to return data. Each time next() is called, the generator resumes where it left-off (it remembers all the data values and which statement was last executed).The simple explanation:\nConsider a  statementA lot of the time, all the items in  doesn't need to be there from the start, but can be generated on the fly as they're required. This can be a lot more efficient in both Other times, you don't even know all the items ahead of time. For example:You have no way of knowing all the user's commands beforehand, but you can use a nice loop like this if you have a generator handing you commands:With generators you can also have iteration over infinite sequences, which is of course not possible when iterating over containers.I have found that generators are very helpful in cleaning up your code and by giving you a very unique way to encapsulate and modularize code.  In a situation where you need something to constantly spit out values based on its own internal processing and when that something needs to be called from anywhere in your code (and not just within a loop or a block for example), generators are  feature to use.An abstract example would be a fibonacci number generator that does not live within a loop and when it is called from anywhere will always return the next number in sequence:Now you have two fibonacci number generator objects which you can call from anywhere in your code and they will always return ever larger fibonacci numbers in sequence as follows:The lovely thing about generators is that they encapsulate state without having to go through the hoops of creating objects.  One way of thinking about them is as \"functions\" which remember their internal state.I got the fibonacci example from  and with a little imagination, you can come up with a lot of other situations where generators make for a great alternative to for-loops and other traditional iteration constructs.Lets say you have 100 million domains in your MySQL table and you would like to update alexa rank for each domain.First thing you need is to select your domain names from the database. Lets say your database name is  and table name is If you use  its going to return 100 million rows which is going to  consume lot of memory. So your server might crashSo you decided to run the program in batches. Let say our batch size is 1000.In our first batch we will query the first 1000 rows, check alexa rank for each domain and update the database row. In our second batch we will work on the next 1000 rows. In our third batch it will be from 2001 to 3000 and so on.Now we need a generator function which generates our batches. Here is our generator functionAs you can see our function keep ing the results. If you used the keyword  instead of , then the whole function will be ended once it reaches returnIf a function uses the keyword  then its a generator.Now you can iterate like thisMy favorite uses are \"filter\" and \"reduce\" operations.Let's say we're reading a file, and only want the lines which begin with \"##\".We can then use the generator function in a proper loopThe reduce example is similar.  Let's say we have a file where we need to locate blocks of  lines.  [Not HTML tags, but lines that happen to look tag-like.]Again, we can use this generator in a proper for loop.The idea is that a generator function allows us to filter or reduce a sequence, producing a another sequence one value at a time.A practical example where you could make use of a generator is if you have some kind of shape and you want to iterate over its corners, edges or whatever. For my own project (source code ) I had a rectangle:Now I can create a rectangle and loop over its corners:Instead of  you could have a method  and call that with . It's just more elegant to use  since then we can use the class instance name directly in the  expression.Basically avoiding call-back functions when iterating over input maintaining state.See  and  for an overview of what can be done using generators.Some good answers here, however, I'd also recommend a complete read of the python  which helps explain some of the more potent use-cases of generators.I use generators when our web server is acting as a proxy:Since the send method of a generator has not been mentioned here is an example:It shows the possibility to send a value to a running generator\nA more advanced course on generators in the video below (including yield from explination, generators for parallel processing, escaping recursion limit etc.)Piles of stuff. Any time you want to generate a sequence of items, but don't want to have to 'materialize' them all into a list at once. For example, you could have a simple generator that returns prime numbers:You could then use that to generate the products of subsequent primes:These are fairly trivial examples, but you can see how it can be useful for processing large (potentially infinite!) datasets without generating them in advance, which is only one of the more obvious uses.
Python

Is there a built-in or standard library method in Python to calculate the arithmetic mean (average) of a list of numbers?I am not aware of anything in the standard library. However, you could use something like:In numpy, there's .NumPy has a  which is an arithmetic mean. Usage is as simple as this:In Python 3.4, there is a new  module. You can now use :For 3.1-3.3 users, the original version of the module is available on PyPI under the name . Just change  to .You don't even need numpy or scipy...Use scipy:Instead of casting to float you can do followingor using lambdaI always supposed  is omitted from the builtins/stdlib because it is as simple asand any caveats would be .Notable caveats:
Python

What I understand from reading the documentation is that Python has a separate namespace for functions, and if I want to use a global variable in that function, I need to use .I'm using Python 2.7 and I tried this little testIt seems things are working fine even without . I was able to access global variable without any problem.Am I missing anything? Also, following is from Python documentation:While formal parameters and class definition make sense to me, I'm not able to understand the restriction on for loop control target and function definition.The keyword  is only useful to change or create global variables in a local context, although creating global variables is seldom considered a good solution.The above will give you:While if you use the  statement, the variable will become available \"outside\" the scope of the function, effectively becoming a global variable.So the above code will give you:In addition, due to the nature of python, you could also use  to declare functions, classes or other objects in a local context. Although I would advise against it since it causes nightmares if something goes wrong or needs debugging.While you can access global variables without the  keyword, if you want to assign to them you have to use the  keyword. For example:In your case, you're just accessing the list .This is the difference between accessing the name and  it within a scope.If you're just looking up a variable to read its value, you've got access to global as well as local scope.However if you assign to a variable who's name isn't in local scope, you are  that name into this scope (and if that name also exists as a global, you'll hide that). If you want to be able to assign to the global name, you need to tell the parser to use the global name rather than bind a new local name - which is what the 'global' keyword does.Binding anywhere within a block causes the name everywhere in that block to become bound, which can cause some rather odd looking consequences (e.g. UnboundLocalError suddenly appearing in previously working code).The other answers answer your question. Another important thing to know about names in Python is that they are either local or global on a per-scope basis.Consider this, for example:You can probably guess that the  statement will be assigning to a local variable and not affect the value of the same variable declared outside the  function. You may be more surprised to discover that  The statement  inside the function produces an The reason is that Python has noticed that, elsewhere in the function, you assign the name , and also  is nowhere declared . That makes it a local variable. But when you try to print it, the local name hasn't been defined yet. Python in this case  to looking for the name as a global variable, as some other languages do. Essentially, you cannot access a global variable if you have defined a local variable of the same name  in the function.This tripped me up many times, and I hope to avoid you tripping over the same thing.Accessing a name and assigning a name are different. In your case, you are just accessing a name.If you assign to a variable within a function, that variable is assumed to be local unless you declare it global. In the absence of that, it is assumed to be global.Example:Any variable declared outside of a function is assumed to be global, it's only when declaring them from inside of functions (except constructors) that you must specify that the variable be global.It means that you should not do the following:Global makes the variable \"Global\"This makes 'x' act like a normal variable outside the function. If you took the global out then it would give an error since it cannot print a variable inside a function.I think global variables are great and easier to follow than \"return\", however I am only using small programs and just learning but can see it's value.
Python

I am trying to create a SlugField in Django.I created this simple model:I then do this:I was expecting b-b-b-bYou will need to use the slugify function. You can call  automatically by overriding the  method:Be aware that the above will cause your URL to change when the  field is edited, which . It may be preferable to generate the slug only once when you create a new object:There is corner case with some utf-8 charactersExample:This can be solved with A small correction to Thepeer's answer: To override  function in model classes, better add arguments to it:Otherwise,  will result in a  error (unexpected argument).If you're using the admin interface to add new items of your model, you can set up a  in your  and utilize  to automate entering of a slug:Here, when the user enters a value in the admin form for the  field, the  will be automatically populated with the correct slugified . In most cases the slug should not change, so you really only want to calculate it on first save:If you don't want to set the slugfield to Not be editable, then I believe you'll want to set the Null and Blank properties to False.  Otherwise you'll get an error when trying to save in Admin.So a modification to the above example would be::Use prepopulated_fields in your admin class:I'm using Django 1.7Create a SlugField in your model like this:Then in  define ;
Python

I was wondering how to check whether a variable is a class (not an instance!) or not.I've tried to use the function  to do this, but I don't know what type would a class will have.For example, in the following codeI tried to substitute  \"\" with , but I realized that  is a keyword in python.Even better: use the  function.The inspect.isclass is probably the best solution, and it's really easy to see how it's actually implementedReturn  if  is class and  if not.class Foo: is called old style class and class X(object): is called new style class. Check this  . New style is recommended. Read about \"\"That's a little hackish, but an option if you don't want to avoid imports:There are some working solutions here already, but here's another one:
Python

I am looking over  but just can't seem to figure out how to do this as it's not working. I need to check if the current site user is logged in (authenticated), and am trying:despite being sure that the user is logged in, it returns just:I'm able to do other requests (from the first section in the url above), such as:which returns a successful response. is a function. You should call it likeAs Peter Rowell pointed out, what may be tripping you up is that in the default Django template language, you don't tack on parenthesis to call functions. So you may have seen something like this in template code:However, in Python code, it is indeed a method in the  class.:  is now an attribute in Django 1.10. The method still exists for backwards compatibility, but will be removed in Django 2.0.Following block should work: 
Python

I want to change the key of an entry in a Python dictionary.Is there a straightforward way to do this?Easily done in 2 steps:Or in 1 step:which will raise  if  is undefined. Note that this  delete .if you want to change all the keys:if you want to change single key:\n   You can go with any of the above suggestion.pop'n'freshIn python 2.7 and higher, you can use dictionary comprehension:\nThis is an example I encountered while reading a CSV using a DictReader. The user had suffixed all the column names with ':'to get rid of the trailing ':' in the keys:Since keys are what dictionaries use to lookup values, you can't really change them. The closest thing you can do is to save the value associated with the old key, delete it, then add a new entry with the replacement key and the saved value. Several of the other answers illustrate different ways this can be accomplished.No direct way to do this, but you can delete-then-assignor do mass key changes:If you have a complex dict, it means there is a dict or list within the dict:You can associate the same value with many keys, or just remove a key and re-add a new key with the same value.For example, if you have keys->values:there's no reason you can't add  or remove  and add I haven't seen this exact answer:You can even do this to object attributes. \nMake them into a dictionary by doing this:Then you can manipulate the object attributes like you would a dictionary:
Python

I have the following string: How can I get the last four characters and store them in a string using Python?Like this:This slices the string's last 4 characters. The \"-\" before the 4 signals it starts from the end. Since it's before the \":\", it'll be the start of the string. If it were after the \":\", the string would end in 4 chars before actual end.See the Python docs for more information in slicing.See : 
Python

How are \"keyword arguments\" different from regular arguments? Can't all arguments be passed as  instead of using positional syntax?there are two related concepts, both called \"keyword arguments\".On the calling side, which is what other commenters have mentioned, you have the ability to specify some function arguments by name. You have to mention them after all of the arguments without names (positional arguments), and there must be default values for any parameters which were not mentioned at all.The other concept is on the function definition side: You can define a function that takes parameters by name -- and you don't even have to specify what those names are. These are pure keyword arguments, and can't be passed positionally. The syntax isAny keyword arguments you pass into this function will be placed into a dictionary named kwargs. You can examine the keys of this dictionary at run-time, like this:There is one last language feature where the distinction is important. Consider the following function:The  argument will store all of the positional arguments passed to , with no limit to how many you can provide.The  argument will store any keyword arguments:And of course, you can use both at the same time:These features are rarely used, but occasionally they are very useful, and it's important to know which arguments are positional or keywords.Using keyword arguments is the same thing as normal arguments except order doesn't matter. For example the two functions calls below are the same:They have no keywords before them. The order is important!They have keywords in the front. They can be in any order!You should also know that if you use default arguments and neglect to insert the keywords, then the order will then matter!There are two ways to assign argument values to function parameters, both are used.Note that  have the option to use positional arguments.If  don't use positional arguments, then -- yes -- everything  wrote turns out to be a keyword argument.When  call a function you make a decision to use position or keyword or a mixture.  You can choose to do all keywords if you want.  Some of us do not make this choice and use positional arguments.I'm surprised that no one seems to have pointed out that one can pass a dictionary of keyed argument parameters, that satisfy the formal parameters, like so.I'm surprised no one has mentioned the fact that you can mix positional and keyword arguments to do sneaky things like this using  and  ():This allows you to use arbitrary keyword arguments that may have keys you don't want to define upfront.Using  you can have both required and non-required keyword :: (default value defined for 'b') (no default value defined for 'b'):This can help in cases where you have a many similar arguments next to each other especially when of the same type, in that case I prefer using named arguments or I create a custom class if arguments belong together.
Python

this is i saw in someone's code: Using these magic methods (, ) allows you to implement objects which can be used easily with the  statement. The idea is that it makes it easy to build code which needs some 'cleandown' code executed (think of it as a  block). .A useful example could be a database connection object (which then automagically closes the connection once the corresponding 'with'-statement goes out of scope):As explained above, use this object with the  statement (you may need to do  at the top of the file if you're on Python 2.5). has a nice writeup as well.If you know what  are then you need nothing more to understand  and  magic methods. Lets see a very simple example.In this example I am opening  with help of  function. The  block ensures that even if an unexpected exception occurs  will be closed.Now I am opening same file with  statement:If you look at the code, I  didn't close the file & there is no  block. Because  statement automatically closes   . You can even check it by calling  attribute -- which returns .This is because the file objects (fp in my example) returned by  function has two built-in methods  and . It is  also known as context manager.  method is called at the start of  block and   method is called at the end.  Note:  statement only works with objects that support the context mamangement protocol i.e. they have  and  methods. A class which implement both methods is known as context manager class.Now lets define our own  class.I hope now you have basic understanding of both  and  magic methods.I found it oddly hard to locate the python docs for  and  methods by Googling, so to help others here is the link:I was hoping for a clear description of the  method arguments. This is lacking but we can deduce them...Presumably  is the class of the exception.It says you should not re-raise the passed-in exception. This suggests to us that one of the arguments might be an actual Exception instance ...or maybe you're supposed to instantiate it yourself from the type and value?We can answer by looking at this article:\n...so clearly  is an Exception instance.And presumably  is a Python traceback object.
Python

I want to override the  method on a class to do something fancy but I don't want to break the default behavior.What's the correct way to do this?Overriding  should be fine --  is only called as a last resort i.e. if there are no attributes in the instance that match the name. For instance, if you access , then  will only be called if  has no attribute called . If the attribute is one you don't want to handle, raise :However, unlike ,  will be called first (only works for new style classes i.e. those that inherit from object). In this case, you can preserve default behaviour like so:See .To extend Michael answer, if you want to maintain the default behavior using , you can do it like so:  Now the exception message is more descriptive:
Python

I'm pulling data out of a Google doc, processing it, and writing it to a file (that eventually I will paste into a Wordpress page).It has some non-ASCII symbols. How can I convert these safely to symbols that can be used in HTML source? Currently I'm converting everything to Unicode on the way in, joining it all together in a Python string, then doing: There is an encoding error on the last line: This Python runs without an error:But then if I open the actual text file, I see lots of symbols like:Maybe I need to write to something other than a text file? Deal exclusively with unicode objects as much as possible by decoding things to unicode objects when you first get them and encoding them as necessary on the way out.If your string is actually a unicode object, you'll need to convert it to a unicode-encoded string object before writing it to a file:When you read that file again, you'll get a unicode-encoded string that you can decode to a unicode object:In Python 2.6+, you could  that is default () on Python 3:It might be more convenient if you need to write the text incrementally (you don't need to call  multiple times). Unlike  module,  module has a proper universal newlines support.The file opened by  is a file that takes  data, encodes it in  and writes it to the file. However, what you try to write isn't ; you take  and encode it in  . That's what the  method does, and the result of encoding a unicode string is a bytestring (a  type.)You should either use normal  and encode the unicode yourself, or (usually a better idea) use  and  encode the data yourself.Use  from the  module:Best practice, in general, use  for writing to files (we don't even have to worry about byte-order with utf-8).utf-8 is the most modern and univerally usable encoding - it works in all web browsers, most text-editors (see your settings if you have issues) and most terminals/shells.On Windows, you might try  if you're limited to viewing output in Notepad (or another limited viewer).And just open it with the context manager and write your unicode characters out:Here's an example that attempts to map every possible character up to three bits wide (4 is the max, but that would be going a bit far) from the digital representation (in integers) to an encoded printable output, along with its name, if possible (put this into a file called ):This should run in the order of about a minute, and you can view the data file, and if your file viewer can display unicode, you'll see it. Information about the categories can be found . Based on the counts, we can probably improve our results by excluding the Cn and Co categories, which have no symbols associated with them.It will display the hexadecimal mapping, , symbol (unless can't get the name, so probably a control character), and the name of the symbol. e.g.I recommend  on unix or cygwin (don't print/cat the entire file to your output):e.g. will display similar to the following lines which I sampled from it using Python 2 (unicode 5.2):My Python 3.5 from Anaconda has unicode 8.0, I would presume most 3's would.Save this to file: foo.py:Run it and pipe output to file:Open tmp.txt and look inside, you see this:Thus you have saved unicode e with a obfuscation mark on it to a file.That error arises when you try to encode a non-unicode string: it tries to decode it, assuming it's in plain ASCII. There are two possibilities:
Python

I have two existing dictionaries, and I wish to 'append' one of them to the other. By that I mean that the key,values of the other dictionary should be made into the first dictionary. For example:I think this all can be achieved through a  loop (maybe?), but is there some method of dictionaries or any other module that saves this job for me? The actual dictionaries I'm using are really big...You can door, if you don't want  to be modified, make a copy first:Note that if extra and orig have overlapping keys, the final value will be taken from extra. For example,Assuming that you do not want to change , you can either do a copy and update like the other answers, or you can create a new dictionary in one step by passing all items from both  dictionaries into the dict constructor:Or without itertools:Note that you only need to pass the result of  into  on Python 3, on 2.x  already returns a list so you can just do .As a more general use case, say you have a larger list of dicts that you want to combine into a single dict, you could do something like this: looks like it will do what you want...Perhaps, though, you don't want to update your original dictionary, but work on a copy:The most pythonic (and slightly faster) way to accomplish this is by:Or, depending on the problem to solve, maybe:There is the .update() method :)The answer I want to give is \"use collections.ChainMap\", but I just discovered that it was only added in Python 3.3: You can try to crib the class from the 3.3 source though: Here is a less feature-full Python 2.x compatible version (same author): Instead of expanding/overwriting one dictionary with another using dict.merge, or creating an additional copy merging both, you create a lookup chain that searches both in order. Because it doesn't duplicate the mappings it wraps ChainMap uses very little memory, and sees later modifications to any sub-mapping. Because order matters you can also use the chain to layer defaults (i.e. user prefs > config > env).A three-liner to combine or merge two dictionaries:This creates a new dictionary  without modifying  and .Note: If a key has different values in  and , then  overrides .
Python

What is the most efficient way to shift a list in python? \nRight now I have something like this:Is there a better way?A  is optimized for pulling and pushing on both ends. They even have a dedicated  method. What about just using ?It depends on what you want to have happen when you do this:You might want to change your:to:Numpy can do this using the  command:If you just want to iterate over these sets of elements rather than construct a separate data structure, consider using iterators to construct a generator expression:This also depends on if you want to shift the list in place (mutating it), or if you want the function to return a new list.  Because, according to my tests, something like this is at least twenty times faster than your implementation that adds two lists:In fact, even adding a  to the top of that to operate on a copy of the list passed in is still twice as fast.Various implementations with some timing at Simplest way I can think of:                                        I think you are looking for this:If efficiency is your goal, (cycles? memory?) you may be better off looking at the array module: Arrays do not have the overhead of lists.  As far as pure lists go though, what you have is about as good as you can hope to do.Possibly a ringbuffer is more suitable. It is not a list, although it is likely that it can behave enough like a list for your purposes.The problem is that the efficiency of a shift on a list is O(n), which becomes significant for large enough lists.Shifting in a ringbuffer is simply updating the head location which is O(1)For an immutable implementation, you could use something like this:I take this cost model as a reference:Your method of slicing the list and concatenating two sub-lists are linear-time operations. I would suggest using pop, which is a constant-time operation, e.g.:I don't know if this is 'efficient', but it also works:EDIT: Hello again, I just found a big problem with this solution!\nConsider the following code:The shift_classlist() method executes the same code as my x.insert(0,x.pop())-solution, otherlist is a list indipendent from the class. After passing the content of otherlist to the MyClass.classlist list, calling the shift_classlist() also changes the otherlist list:CONSOLE OUTPUT:I use Python 2.7. I don't know if thats a bug, but I think it's more likely that I missunderstood something here.Does anyone of you know why this happens?I have similar thing. For example, to shift by two...Another alternative:The following method is O(n) in place with constant auxiliary memory:Note that in python, this approach is horribly inefficient compared to others as it can't take advantage of native implementations of any of the pieces.for similar functionality as shift in other languages:
Python

I have terminal access to a VPS running centos 5.9 and default python 2.4.3 installed. I also installed python 2.7.3 via these commands: (I used  instead of )then I installed node.js from source via these commands:The problem is, when I use  and try to install a node.js package which requires python > 2.4.3 I get this error:how should I ?You can use  option to npm like so:or set it to be used always:Npm will in turn pass this option to node-gyp when needed.(note: I'm the one who opened an issue on Github to have this included in the docs, as there were so many questions about it ;-) )set python to python2.7 before running npm installLinux:Windows:For Windows users something like this should work:Ok, so you've found a solution already. Just wanted to share what has been useful to me so many times;I have created  alias which helps me switch python.Execute  before you run . The switch stays in effect until you quit the terminal, afterwards  is set back to system default.You can make use of this technique for any other command/tool as well.
Python

Why is  faster than ? I am using CPython 3.5.2.I tried changing the power I raised by to see how it acts, and for example if I raise x to the power of 10 or 16 it's jumping from 30 to 35, but if I'm raising by  as a float, it's just moving around 24.1~4.I guess it has something to do with float conversion and powers of 2 maybe, but I don't really know.I noticed that in both cases powers of 2 are faster, I guess since those calculations are more native/easy for the interpreter/computer. But still, with floats it's almost not moving.   Python 3  objects are a full fledged object designed to support an arbitrary size; due to that fact,  (see how all variables are declared as  type in ). This also makes their exponentiation a lot more  and  since, you need to play around with the  array it uses to represent its value to perform it. ( -- See:  for more on s.) Python  objects, on the other hand,  to a C  type (by using ) and operations can be performed .  because, after checking for relevant edge-cases, it allows Python to  () to handle the actual exponentiation:where  and  are our original s as C s.The previous fact  the discrepancy between Python 2 and 3, so, I thought I'd address this comment too because it is interesting.In Python 2, you're using the old  object that differs from the  object in Python 3 (all  objects in 3.x are of  type). In 2, there's a distinction that depends on the value of the object (or, if you use the suffix ):The  you see here , it gets safely converted into a C   (The  also hints the compiler to put 'em in a register if it can do so, so that  make a difference):this allows for a good speed gain. To see how sluggish s are in comparison to s, if you wrapped the  name in a  call in Python 2 (essentially forcing it to use  as in Python 3), the speed gain disappears:Take note that, though the one snippet transforms the  to  while the other does not (as pointed out by @pydsinger), this cast is not the contributing force behind the slowdown. The implementation of  is. (Time the statements solely with  to see).This is CPython's peephole optimizer folding the constants for you. You get the same exact timings either case since there's no actual computation to find the result of the exponentiation, only loading of values:Identical byte-code is generated for  with the only difference being that the  loads the float  instead of the int .If we look at the bytecode, we can see that the expressions are purely identical. The only difference is a type of a constant that will be an argument of . So it's most certainly due to an  being converted to a floating point number down the line.Update: let's take a look at  in the CPython source code: calls , which is too long to paste here, so .It calls the  slot of , passing  as an argument.Finally, in  at line 686 of  we see that arguments are converted to a C  right before the actual operation:
Python

How to convert real numpy array to int numpy array?\nTried using map directly to array but it did not work.Use the  method.Some numpy functions for how to control the rounding: , ,, . depending how  u wish to round the floats, up, down, or to the nearest int. To make one of this in to int, or one of the  other types in numpy,  (as answered by BrenBern): you can use :If you're not sure your input is going to be a Numpy array, you can use  with  instead of :If the input array already has the correct dtype,  avoids the array copy while  does not (unless you specify ):
Python

I need help with setting the limits of y-axis on matplotlib. Here is the code that I tried, unsuccessfully.With the data I have for this plot, I get y-axis limits of 20 and 200. However, I want the limits 20 and 250.Try this . Works for subplots too .Your code works also for me. However, another workaround can be to get the plot's axis and then change only the y-values:This should work.  Your code works for me, like for Tam\u00e1s and Manoj Govindan.  It looks like you could try to update Matplotlib.  If you can't update Matplotlib (for instance if you have insufficient administrative rights), maybe using a different backend with  could help.To add to @Hima's answer, if you want to modify a current x or y limit you could use the following.I find this particularly useful when I want to zoom out or zoom in just a little from the default plot settings.
Python

After you train a model in Tensorflow: I am improving my answer to add more details for saving and restoring models. In(and after) Tensorflow version 0.11:  This and some more advanced use-cases have been explained very well here.In( and After) TensorFlow version 0.11.0RC1, you can save and restore your model directly by calling  and  according to For TensorFlow version < 0.11.0RC1:The checkpoints that are saved contain values for the s in your model, not the model/graph itself, which means that the graph should be the same when you restore the checkpoint.Here's an example for a linear regression where there's a training loop that saves variable checkpoints and an evaluation section that will restore variables saved in a prior run and compute predictions. Of course, you can also restore variables and continue training if you'd like.Here are the  for s, which cover saving and restoring. And here are the  for the .There are two parts to the model, the model definition, saved by  as  in the model directory and the numerical values of tensors, saved into checkpoint files like .The model definition can be restored using , and the weights are restored using .However,  uses special collection holding list of variables that's attached to the model Graph, and this collection is not initialized using import_graph_def, so you can't use the two together at the moment (it's on our roadmap to fix). For now, you have to use approach of Ryan Sepassi -- manually construct a graph with identical node names, and use  to load the weights into it.(Alternatively you could hack it by using by using , creating variables manually, and using  for each variable, then using )You can also take this easier way.Step.1 - Initialize all your variablesStep.2 - Save the list inside Model Saver and Save itStep. 3 - Restore the modelStep. 4 - Check VariableWhile running in different python instance, useAs Yaroslav said, you can hack restoring from a graph_def and checkpoint by importing the graph, manually creating variables, and then using a Saver.I implemented this for my personal use, so I though I'd share the code here.Link: (This is, of course, a hack, and there is no guarantee that models saved this way will remain readable in future versions of TensorFlow.)If it is an internally saved model, you just specify a restorer for all variables asand use it to restore variables in a current session:For the external model you need to specify the mapping from the its variable names to your variable names. You can view the model variable names using the command The inspect_checkpoint.py script can be found in './tensorflow/python/tools' folder of the Tensorflow source.To specify the mapping, you can use my , which contains a set of classes and scripts to train and retrain different models. It includes an example of retraining ResNet models, located  In most cases, saving and restoring from disk using a  is your best option:You can also save/restore the graph structure itself (see the  for details). By default, the  saves the graph structure into a  file. You can call  to restore it. It restores the graph structure and returns a  that you can use to restore the model's state:However, there are cases where you need something much faster. For example, if you implement early stopping, you want to save checkpoints every time the model improves during training (as measured on the validation set), then if there is no progress for some time, you want to roll back to the best model.  If you save the model to disk every time it improves, it will tremendously slow down training. The trick is to save the variable states to , then just restore them later:A quick explanation: when you create a variable , TensorFlow automatically creates an assignment operation  to set the variable's initial value. Instead of creating placeholders and extra assignment ops (which would just make the graph messy), we just use these existing assignment ops. The first input of each assignment op is a reference to the variable it is supposed to initialize, and the second input () is the initial value. So in order to set any value we want (instead of the initial value), we need to use a  and replace the initial value. Yes, TensorFlow lets you feed a value for any op, not just for placeholders, so this works fine.Added the  code example.You can also check out  in , which offers  and  methods that can help you easily manage your models. It has parameters that you can also control how frequently you want to back up your model. Here's my simple solution for the two basic cases differing on whether you want to load the graph from file or build it during runtime.This answer holds for Tensorflow 0.12+ (including 1.0). Otherwise Tensorflow will make the names unique itself and they'll be thus different from the names stored in the file. It's not a problem in the previous technique, because the names are \"mangled\" the same way in both loading and saving.As described in issue :instead of If you use  as the default session, you don't need to add extra code to do save/restore things. Just pass a checkpoint dir name to MonitoredTrainingSession's constructor, it will use session hooks to handle these. 
Python

Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not?I found the functions bisect_left/right in the , but they still return a position even if the item is not in the list. That's perfectly fine for their intended usage, but I just want to know if an item is in the list or not (don't want to insert anything).I thought of using  and then checking if the item at that position is equal to what I'm searching, but that seems cumbersome (and I also need to do bounds checking if the number can be larger than the largest number in my list). If there is a nicer method I'd like to know about it. To clarify what I need this for: I'm aware that a dictionary would be very well suited for this, but I'm trying to keep the memory consumption as low as possible. My intended usage would be a sort of double-way look-up table. I have in the table a list of values and I need to be able to access the values based on their index. And also I want to be able to find the index of a particular value or None if the value is not in the list.Using a dictionary for this would be the fastest way, but would (approximately) double the memory requirements.I was asking this question thinking that I may have overlooked something in the Python libraries. It seems I'll have to write my own code, as Moe suggested.Why not look at the code for bisect_left/right and adapt it to suit your purpose.like this:This is a little off-topic (since Moe's answer seems complete to the OP's question), but it might be worth looking at the complexity for your whole procedure from end to end.  If you're storing thing in a sorted lists (which is where a binary search would help), and then just checking for existence, you're incurring (worst-case, unless specified):Whereas with a , you're incurringThe thing a sorted list really gets you are \"next\", \"previous\", and \"ranges\" (including inserting or deleting ranges), which are O(1) or O(|range|), given a starting index.  If you aren't using those sorts of operations often, then storing as sets, and sorting for display might be a better deal overall.   incurs very little additional overhead in python.  It might be worth mentioning that the bisect docs now provide searching examples:\n(Raising ValueError instead of returning -1 or None is more pythonic \u2013 list.index() does it, for example. But of course you can adapt the examples to your needs.)Simplest is to use  and check one position back to see if the item is there:I agree that  using the bisect module is the correct approach.  He did not mention one important detail in his answer.From the   The bisection module does not require the search array to be precomputed ahead of time.  You can just present the endpoints to the  instead of it using the defaults of  and .Even more important for my use, looking for a value X such that the error of a given function is minimized.  To do that, I needed a way to have the bisect_left's algorithm call my computation instead.  This is really simple.Just provide an object that defines  as For example, we could use the bisect algorithm to find a square root with arbitrary precision!This is right from the manual:8.5.1. Searching Sorted ListsThe above bisect() functions are useful for finding insertion points but can be tricky or awkward to use for common searching tasks. The following five functions show how to transform them into the standard lookups for sorted lists:So with the slight modification your code should be:If you just want to see if it's present, try turning the list into a dict:On my machine, \"if n in l\" took 37 seconds, while \"if n in d\" took 0.4 seconds.While there's no explicit binary search algorithm in Python, there is a module -  - designed to find the insertion point for an element in a sorted list using a binary search. This can be \"tricked\" into performing a binary search. The biggest advantage of this is the same advantage most library code has - it's high-performing, well-tested and just works (binary searches in particular can be  - particularly if edge cases aren't carefully considered).For basic types like Strings or ints it's pretty easy - all you need is the  module and a sorted list:You can also use this to find duplicates:Obviously you could just return the index rather than the value at that index if desired.For custom types or objects, things are a little bit trickier: you have to make sure to implement rich comparison methods to get bisect to compare correctly.This should work in at least Python 2.7 -> 3.3This one is:Using a dict wouldn't like double your memory usage unless the objects you're storing are really tiny, since the values are only pointers to the actual objects:In that example, 'foo' is only stored once.  Does that make a difference for you?  And exactly how many items are we talking about anyway?This code works with integer lists in a recursive way. Looks for the simplest case scenario, which is: list length less than 2. It means the answer is already there and  a test is performed to check for the correct answer.\nIf not, a middle value is set and tested to be the correct, if not bisection is performed by calling again the function, but setting middle value as the upper or lower limit, by shifting it to the left or rightDave Abrahams' solution is good. Although I have would have done it minimalistic:Check out the examples on Wikipedia I guess this is much better and effective. please correct me :) . Thank youI needed binary search in python and generic for Django models. In Django models, one model can have foreign key to another model and I wanted to perform some search on the retrieved models objects. I wrote following function you can use this.
Python

I'm having trouble parsing html elements with \"class\" attribute using Beautifulsoup. The code looks like thisI get an error on the same line \"after\" the script finishes. How do I get rid or this error?You can refine your search to only find those divs with a given class using BS3:From the documentation:Which in this case would be:It would also work for:Specific to BeautifulSoup 3:Will find all of these:Update: 2016\nIn the latest version of beautifulsoup, the method 'findAll' has been renamed to \n'find_all'. Hence the answer will be A straight forward way would be :Make sure you take of the casing of , its not Try to check if the div has a class attribute first, like this:This works for me to access the class attribute (on beautifulsoup 4, contrary to what the documentation says). The KeyError comes a list being returned not a dictionary.This worked for me:You can easily find by one class, but if you want to find by the intersection of two classes, it's a little more difficult,From the  (emphasis added):To be clear, this selects only the p tags that are both strikeout and body class. To find for the intersection of  in a set of classes (not the intersection, but the union), you can give a list to the  keyword argument (as of 4.1.2):Also note that findAll has been renamed from the camelCase to the more Pythonic .
Python

When I run the following command:I get this error:Any ideas how to fix this?The  says that python-ldap is based on OpenLDAP, so you need to have the development files (headers) in order to compile the Python module. If you're on Ubuntu, the package is called .::To install python-ldap successfully with pip, following development libraries are needed (package names taken from ubuntu environment):  On CentOS/RHEL 6, you need to install:and yum will also install  as a dependency.  Then you can run:In Ubuntu it looks like this :Windows: I completely agree with the accepted answer, but digging through the comments took a while to get to the meat of what I needed.  I ran across this specific problem with Reviewboard on Windows using the Bitnami.  To give an answer for windows then, I used this link mentioned in the comments:Then, executed the following commands (because I had python 2.7 and a 32bit install at that)On Fedora 22, you need to do this instead:On openSUSE you need to install the packages , ,  and .On OSX, you need the xcode CLI tools.  Just open a terminal and run:As a general solution to install Python packages with binary dependencies [1] on Debian/Ubuntu:You'll have to check the  versus PyPI. In this case they're the same.Obviously doesn't work if the Python package is not in the Ubuntu repos.[1] I learnt this trick when trying to  on Ubuntu.In FreeBSD 11:
Python

I need to add leading zeros to integer to make a string with defined quantity of digits ($cnt).\nWhat the best way to translate this simple function from PHP to Python:Is there a function that can do this?You can use the  method to pad a string with zeros:The standard way is to use format string modifiers. These format string methods are available in most programming languages (via the sprintf function in c for example) and are a handy tool to know about.which will output an string of length 5.Edit: In Python2.6 and above, there is also:See: You most likely just need to format your integer:For example,Python 2.6 allows this:You have at least two options:If on Python >2.5, see a third option in clorz's answer.For Python 3 and beyond:\nstr.zfill() is still the most readable optionBut it is a good idea to look into the new and powerful str.format(), what if you want to pad something that is not 0?A straightforward conversion would be (again with a function):This function takes  and converts it to a string, and adds zeros in the beginning only and only if the length is too short:To sum it up - build-in:  is good enough, but if someone is curious on how to implement this by hand, here is one more example.Python 3.6 f-strings allows us to add leading zeros easily:Have a look at  about.Just for the culture, on PHP, you have the function  which makes exactly the job of your function .This is my Python function:Initially, find the digits in the number of Cases /Folders. According to the length of the maximum / highest number of Cases / Folder, a format is created and added as suffix. For example. No of Cases = 9. Case_1. Case_2...Case_9 are generated. For No of Cases = 99, Case_01, Case_02...Case_99.. for 999, Case_001, Case_002....Case_999 and so on. Hope it helps
Python

How would I compare two dates to see which is later, using Python?For example, I want to check if the current date is past the last date in this list I am creating, of holiday dates, so that it will send an email automatically, telling the admin to update the holiday.txt file.Use the  method and the operator  and its kin. will return . will return . will return .see the .Use Let's say you have the initial dates as strings like these:\n\nYou can do the following:\n and  to convert them to python's date format. Then, the comparison is obvious:\n will return \n will return 
Python

new to Python and had a question about dictionaries. I have a dictionary that I declared in a particular order and want to keep it in that order all the time. The keys/values can't really be kept in order based on their value, I just want it in the order that I declared it.So if I have the dictionary:It isn't in that order if I view it or iterate through it, is there any way to make sure Python will keep the explicit order that I declared the keys/values in?Using Python 2.6contains If the values are  (or any other immutable object), you can also use:Rather than explaining the theoretical part, I'll give a simple example.From Python 3.6 onwards, the standard  type maintains insertion order by default.Definingwill result in a dictionary with the keys in the order listed in the source code.This was achieved by using a simple array with integers for the sparse hash table, where those integers index into another array that stores the key-value pairs (plus the calculated hash). That latter array just happens to store the items in insertion order, and the whole combination actually uses less memory than the implementation used in Python 3.5 and before. See the  for details.This is still considered an implementation detail; future versions of Python  make it mandatory that  preserves order. See the :python dictionaries are unordered.  If you want an ordered dictionary, try .Note that OrderedDict was introduced into the standard library in python 2.7.  If you have an older version of python, you can find recipes for ordered dictionaries on .Dictionaries will use an order that makes searching efficient, and you cant change that,You could just use a list of objects (a 2 element tuple in a simple case, or even a class), and append items to the end. You can then use linear search to find items in it.Alternatively you could create or use a different data structure created with the intention of maintaining order.I came across this post while trying to figure out how to get OrderedDict to work. PyDev for Eclipse couldn't find OrderedDict at all, so I ended up deciding to make a tuple of my dictionary's key values as I would like them to be ordered. When I needed to output my list, I just iterated through the tuple's values and plugged the iterated 'key' from the tuple into the dictionary to retrieve my values in the order I needed them.example:It's a tad cumbersome, but I'm pressed for time and it's the workaround I came up with.note: the list of lists approach that somebody else suggested does not really make sense to me, because lists are ordered and indexed (and are also a different structure than dictionaries).You can't really do what you want with a dictionary. You already have the dictionary created. I found there was no way to keep in order once it is already created. What I did was make a json file instead with the object:I used:then used:to verify.Generally, you can design a class that behaves like a dictionary, mainly be implementing the methods , , ,  and some more.  That class can have any behaviour you like, for example prividing a sorted iterator over the keys ...I had a similar problem when developing a Django project. I couldn't use OrderedDict, because I was running an old version of python, so the simple solution was to use Django's SortedDict class:if you would like to have a dictionary  in a specific order, you can also create a list of lists, where the first item will be the key, and the second item will be the value\nand will look like this\nexample 
Python

I recently came across this syntax, I am unaware of the difference. I would appreciate it if someone could tell me the difference.The answer is explained .To quote:Practically-speaking, there is not much difference since custom comparison operators are rare.  But you should use  as a general rule.In this case, they are the same.  is a singleton object (there only ever exists one ). checks to see if the object is the same object, while == just checks if they are equivalent.For example:But since there is only one , they will always be the same, and  will return True.If you use numpy,will give you error when numpy does elementwise comparison
Python

Is there a way to get  attributes/methods/fields/etc. of an object in Python? is  to what I want, but it doesn't work unless an object has a , which isn't always true (e.g. it's not true for a , a , etc.).Use the built-in function .What you probably want is .The catch is that classes are able to override the special  method, which causes  to return whatever the class wants (though they are encouraged to return an accurate list, this is not enforced). Furthermore, some objects may implement dynamic attributes by overriding , may be RPC proxy objects, or may be instances of C-extension classes. If your object is one these examples, they may not have a   be able to provide a comprehensive list of attributes via : many of these objects may have so many dynamic attrs it doesn't won't actually know  it has until you try to access it. In the short run, if  isn't sufficient, you could write a function which traverses  for an object, then  for all the classes in ; though this will only work for normal python objects. In the long run, you may have to use duck typing + assumptions - if it looks like a duck, cross your fingers, and hope it has .I use :
Python

I am getting the  error. Any idea how I can fix this?You need to use something like .See  for more information on iterating through dictionaries, such as using , across python versions.\nSince python 3 iteritems() is . User items() instead.For Python 3.x  has been removed. Use  instead.You want to use . This returns an iterator over the dictionary, which gives you a tuple(key, value)Your problem was that you were looping over fields, which returns the keys of the dictionary.
Python

I'd like to create a file with path  using python. I've been using  where . I've looked for a non-directory version of , but I haven't been able to find anything. Is there a tool like this to create a file without opening it, or using system or popen/subprocess? There is  (). The system call to create a file is actually  with the  flag. So no matter how, you'll always open the file.So the easiest way to simply create a file without truncating it in case it exists is this:Actually you could omit the  since the refcounting GC of CPython will close it immediately after the  statement finished - but it's cleaner to do it explicitely and relying on CPython-specific behaviour is not good either.In case you want 's behaviour (i.e. update the mtime in case the file exists):You could extend this to also create any directories in the path that do not exist:Of course there IS a way to create files without opening. It's as easy as calling .  The only drawback is that this call requires root privileges on OSX.
Python

Is there any reason to do anything more complicated than one of these two lines when you want to clear a list in Python?The reason I ask is that I just saw this in some running code:Clearing a list in place will affect all other references of the same list.For example, this method doesn't affect other references:But this one does:You could also do:There is a very simple way to delete a python list. Use .For example:This may be useful for large lists, but for small list it should be negligible.: As  Algorias, it doesn't  matter.Note that is equivalent toThere are two cases in which you might want to clear a list:In case 1 you just go on with the assigment:In case 2 the  statement would reduce the reference count to the list object the name  points at. If the list object is only pointed by the name  at, the reference count would be 0, and the object would be freed for garbage collection.Will delete the values of that list variable Will delete the variable itself from memory If you're clearing the list, you, obviously, don't need the list anymore. If so, you can just delete the entire list by simple del method.But in case, you need it again, you can reinitialize it. Or just simply clear its elements by To clear a list  in Python 3.3+ you can also use , which is consistent with the interfaces of other mutable containers (such as ,  or ).another solution that works fine is to create empty list as a reference empty list.for example you have a list as   . To clear it just make the following:this will make  an empty list just like the .
Python

Is there a way to widen the display of output in either interactive or script-execution mode?Specifically, I am using the describe() function on a Pandas .  When the  is 5 columns (labels) wide, I get the descriptive statistics that I want.  However, if the  has any more columns, the statistics are suppressed and something like this is returned:The \"8\" value is given whether there are 6 or 7 columns.  What does the \"8\" refer to?I have already tried dragging the IDLE window larger, as well as increasing the \"Configure IDLE\" width options, to no avail.My purpose in using Pandas and describe() is to avoid using a second program like STATA to do basic data manipulation and investigation.Thanks.Python/IDLE 2.7.3\nPandas 0.8.1\nNotepad++ 6.1.4 (UNICODE)\nWindows Vista SP2  As @bmu , pandas auto detects (by default) the size of the display area, a summary view will be used when an object repr does not fit on the display. You mentioned resizing the IDLE window, to no effect. If you do  does it fit on the IDLE window?The terminal size is determined by , this returns a tuple containing the  of the display. Does the output match the size of your IDLE window? There might be an issue (there was one before when running a terminal in emacs).Note that it is possible to bypass the autodetect,  will never switch to summary view if number of rows, columns does not exceed the given limits. is depracted. Instead, use . Like:Here is the help:Try this:From the documentation:See: You can adjust pandas print options with .However this will not work in all cases as pandas detects your console width and it will only use  if the output fits in the console (see the docstring of ). \nIn this case you can explicitly call  as answered by .With version 0.10 the way wide dataframes are printed :Further more the API for setting pandas options changed:If you want to set options temporarily for display one large df, you can use :Option values are restored automatically when you exit the  block. You can use  to force it to show the whole table.  (You can use  like this for any DataFrame.  The result of  is just a DataFrame itself.)The 8 is the number of rows in the DataFrame holding the \"description\" (because  computes 8 statistics, min, max, mean, etc.).You can set the output display to match your current terminal width:Set column max width using:This particular statement sets max width to 800px, per column.According to the , if you're running on a terminal (ie not iPython notebook, qtconsole or IDLE), it's a 2-liner to have Pandas auto-detect your screen width and adapt on the fly with how many columns it shows:
Python

I was doing a fun project: Solving a Sudoku from an input image using OpenCV (as in Google goggles etc). And I have completed the task, but at the end I found a little problem for which I came here.I did the programming using Python API of OpenCV 2.3.1.Below is what I did :And the method worked well.Check out Performing the step 4 on this image gives the result below:The red line drawn is the original contour which is the true outline of sudoku boundary.The green line drawn is approximated contour which will be the outline of warped image.Which of course, there is difference between green line and red line at the top edge of sudoku. So while warping, I am not getting the original boundary of the Sudoku. How can I warp the image on the correct boundary of the Sudoku, i.e. the red line OR how can I remove the difference between red line and green line? Is there any method for this in OpenCV?I have a solution that works, but you'll have to translate it to OpenCV yourself. It's written in Mathematica.The first step is to adjust the brightness in the image, by dividing each pixel with the result of a closing operation:The next step is to find the sudoku area, so I can ignore (mask out) the background. For that, I use connected component analysis, and select the component that's got the largest convex area:By filling this image, I get a mask for the sudoku grid:Now, I can use a 2nd order derivative filter to find the vertical and horizontal lines in two separate images:I use connected component analysis again to extract the grid lines from these images. The grid lines are much longer than the digits, so I can use caliper length to select only the grid lines-connected components. Sorting them by position, I get 2x10 mask images for each of the vertical/horizontal grid lines in the image:Next I take each pair of vertical/horizontal grid lines, dilate them, calculate the pixel-by-pixel intersection, and calculate the center of the result. These points are the grid line intersections:The last step is to define two interpolation functions for X/Y mapping through these points, and transform the image using these functions:All of the operations are basic image processing function, so this should be possible in OpenCV, too. The spline-based image transformation might be harder, but I don't think you really need it. Probably using the perspective transformation you use now on each individual cell will give good enough results.Nikie's answer solved my problem, but his answer was in Mathematica. So I thought I should give its OpenCV adaptation here. But after implementing I could see that OpenCV code is much bigger than nikie's mathematica code. And also, I couldn't find interpolation method done by nikie in OpenCV ( although it can be done using scipy, i will tell it when time comes.)Result :Result :Result :Result :Of course, this one is not so good.Result :Here, nikie does some kind of interpolation, about which I don't have much knowledge. And i couldn't find any corresponding function for this OpenCV. (may be it is there, i don't know). Check out this SOF which explains how to do this using SciPy, which I don't want to use : So, here I took 4 corners of each sub-square and applied warp Perspective to each.For that, first we find the centroids.But resulting centroids won't be sorted. Check out below image to see their order:So we sort them from left to right, top to bottom.Now see below their order :Finally we apply the transformation and create a new image of size 450x450.Result :The result is almost same as nikie's, but code length is large. May be, better methods are available out there, but until then, this works OK.Regards\nARK.You could try to use some kind of grid based modeling of you arbitrary warping. And since the sudoku already is a grid, that shouldn't be too hard.So you could try to detect the boundaries of each 3x3 subregion and then warp each region individually. If the detection succeeds it would give you a better approximation.
Python

My python script uses subprocess to call a linux utility that is very noisy.  I want to store all of the output to a log file and show some of it to the user.  I thought the following would work, but the output doesn't show up in my application until the utility has produced a significant amount of output.The behavior I really want is for the filter script to print each line as it is received from the subprocess.  Sorta like what  does but with python code.What am I missing?  Is this even possible?If a  is added to fake_utility.py, the code has the desired behavior in python 3.1.  I'm using python 2.6.  You would think that using  would work the same as py3k, but it doesn't.Here is the minimal working code.It's been a long time since I last worked with Python, but I think the problem is with the statement , which reads the entire input before iterating over it. The solution is to use  instead:Of course you still have to deal with the subprocess' buffering.Note:  the solution with an iterator should be equivalent to using , except for the read-ahead buffer, but (or exactly because of this) the proposed change did produce different results for me (Python 2.5 on Windows XP).Indeed, if you sorted out the iterator then buffering could now be your problem. You could tell the python in the sub-process not to buffer its output.becomes I have needed this when calling python from within python.Bit late to the party, but was surprised not to see what I think is the simplest solution here:You want to pass these extra parameters to :Then you can iterate as in your example.  (Tested with Python 3.5)The following modification of R\u00f4mulo's answer works for me on Python 2 and 3 (2.7.12 and 3.6.1):All you need to do is run subprocess.call():\nutil.py:fake_util.py:Running ./util.py now produces output as it is generated:
Python

Which types of objects fall into the domain of \"subscriptable\"?It basically means that the object implements the  method. In other words, it describes objects that are \"containers\", meaning they contain other objects. This includes lists, tuples, and dictionaries.Off the top of my head, the following are the only built-ins that are subscriptable:But mipadi's answer is correct; any class that implements __getitem__ is subscriptableA scriptable object is an object that records the operations done to it and it can store them as a \"script\" which can be replayed.For example, see: Now, if Alistair didn't know what he asked and really meant \"subscriptable\" objects (as edited by others), then (as mipadi also answered) this is the correct one:A subscriptable object is any object that implements the  special method (think lists, dictionaries).I got this , what i was doing is So using \"[\" is causing error[Producing subscriptable error] , it should be 
Python

I am looking for any resources that gives examples of Best Practices, Design patterns and the SOLID principles using Python.  Some overlap in theseAnother resource is by example at the .  A good number do not follow best practices but you can find some patterns in there that are usefulTypein a Python console.Although this is usually treated as a (fine!) joke, it contains a couple of valid python-specific axioms.Bruce Eckel's \"\" leans heavily on Design Patterns You can get started  and .  For a more in depth look at design pattners you should look at .  The source code is not in Python, but it doesn't need to be for you to understand the patterns. Something you can use to simplify your code when calling attributes on objects that might or might not exist is to use the  (to which I was introduced in ).This object just eats the lack of attribute error, and you can avoid checking for their existence.It's nothing more thanWith this, if you do  it won't explode, but just silently become the equivalent of .Normally you'd do something likeWith this, you just do:and forget about it. Beware that extensive use of the  object can potentially hide bugs in your code.You may also wish to read this  (select the .pdf file), which discusses Design Patterns in dynamic object oriented languages (i.e. Python). To quote the page:
Python

What is the best way to compare two instances of some object for equality in Python? I'd like to be able to do something likeExample:To further clarify the question. I'd like to compare by attribute values, and to make a more generic solution than Should the  method look something like this?As usual with Python, it's  :It outputs:N.B : be aware that before Python 3.0, you are more likely to use  instead of , working the same way.You override the  in your object.Implement the  method in your class; something like this:Edit: if you want your objects to compare equal if and only if they have equal instance dictionaries:As a summary : When comparing instances of objects, the  function is called.If the == operator is not working for you by default, you can always redefine the  function for the object.Edit:As has been pointed out, the  function is deprecated since 3.0.\nInstead you should use the  methods.I tried the initial example (see 7 above) and it did not work in ipython. Note that cmp(obj1,obj2) returns a \"1\" when implemented using two identical object instances. Oddly enough when I modify one of the attribute values and recompare, using  cmp(obj1,obj2) the object continues to return a \"1\".  (sigh...)Ok, so what you need to do is iterate two objects and compare each attribute using the == sign.Instance of a class when compared with == comes to non-equal. The best way is to ass the  function to your class which will do the stuff. If you want to do comparison by the content you can simply use cmp(obj1,obj2)In your case cmp(doc1,doc2) It will return -1 if the content wise they are same.
Python

Model:views.py:On the template, when I call person.gender, I get 'M' or 'F' instead of 'Male' or 'Female'.\nHow to display the value ('Male' or 'Female') instead of the code(M/F)?It looks like you were on the right track -  is most certainly what you want:In templates, you don't include () in the name of a method. Do the following:you can use BooleanField instead of CharField,\n and in model:I've recently moved beyond Django, so I'm more familiar with Jinja2 templating, but here we go:Note that it is stored in the database as 'M' and 'F'Psuedo:Actual:For something more complex with more choices it might be worth writing some logic to search through the CATEGORY_CHOICES tuple of tuples.  As of now, with two choices for gender, I don't see that being the case.also see: 
Python

In C# there's a  (written as ) that allows for easy (short) null checking during assignment:Is there a python equivalent?I know that I can do:But is there an even shorter way (where I don't need to repeat )?Ok, it must be clarified how the  operator works. It is a boolean operator, so it works in a boolean context. If the values are not boolean, they are converted to boolean for the purposes of the operator.Note that the  operator does not return only  or . Instead, it returns the first operand if the first operand evaluates to true, and it returns the second operand if the first operand evaluates to false.In this case, the expression  returns  if it is  or evaluates to true when converted to boolean. Otherwise, it returns . For most cases, this will serve for the very same purpose of C\u266f's null-coalescing operator, but keep in mind:If you use your variable  to hold something that is either a reference to the instance of a class or  (as long as your class does not define members  and ), it is secure to use the same semantics as the null-coalescing operator.In fact, it may even be useful to have this side-effect of Python. Since you know what values evaluates to false, you can use this to trigger the default value without using  specifically (an error object, for example).strictly,otherwise s=False will become \"default value\", which may not be what was intended.If you want to make this shorter, tryHere's a function that will return the first argument that isn't None:reduce() might needlessly iterate over all the arguments even if the first argument is not None, so you can also use this version:In addition to Juliano's answer about behavior of \"or\": \nit's \"fast\"So sometimes it's might be a useful shortcut for things likeThe two functions below I have found to be very useful when dealing with many variable testing cases. 
Python

I am using python 3.2.1 and I can't import the  module. I use \n and it works but i can't use it with 's  like this:I get the following error:and when i write  it says there is no such module.From :.A possibly useful method of fixing some Python 2 code to also work in Python 3 (caveat emptor):On Python 3  expects a bytes stream. Use the following:Thank you OP for your question, and Roman for your answer. I had to search a bit to find this; I hope the following helps others.See: dtype=\"|Sx\", where x = any of { 1, 2, 3, ...}:\"The |S1 and |S2 strings are data type descriptors; the first means the array holds strings of length 1, the second of length 2. ...\"In my case I have used :You can use the  from the  module:In order to make examples from \nwork with Python 3.5.2, you can rewrite as follows :The reason for the change may be that the content of a file is in data (bytes) which do not make text until being decoded somehow.  may be a better name than .try thisfrom StringIO import StringIOx=\"1 3\\n 4.5 8\"  numpy.genfromtxt(StringIO(x))
Python

I'm making a website where users can log on and download files, using the  (based on ) which uses Python (2.6 in my case).I need to get the IP address of users when they log on (for logging purposes). \nDoes anyone know how to do this? Surely there is a way to do it with Python?See the documentation on  and then get from this same Request object, the attribute .For more information see the .Actually, what you will find is that when simply getting the following will get you the server's address: If you want the clients IP address, then use the following:Proxies can make this a little tricky, make sure to check out  () if you are using one. Take a look at request.environ in your particular environment. With nginx I will sometimes do something like this:When proxies, such as nginx, forward addresses, they typically include the original IP somewhere in the request headers. . Again, review the documentation about ProxyFix before implementing. Your solution may vary based on your particular environment.The user's IP address can be retrieved using the following snippet: uses this method:
Python

I ran into a problem while working with Selenium. For my project, I have to use Chrome. However, I can't connect to that browser after launching it with Selenium.For some reason, Selenium can't find Chrome by itself. This is what happens when I try to launch Chrome without including a path:To solve this problem, I then included the Chromium path in the code that launches Chrome. However, the interpreter fails to find a socket to connect to:I also tried solving the problem by launching chrome with:However, this did not work either.PS. Here's some information about my system:You need to make sure the standalone ChromeDriver binary (which is different than the Chrome browser binary) is either in your path or available in the webdriver.chrome.driver environment variable.see  for full information on how wire things up.Edit:Right, seems to be a bug in the Python bindings wrt reading the chromedriver binary from the path  the environment variable. Seems if chromedriver is not in your path you have to pass it in as an argument to the constructor.An easier way to get going (assuming you already have  installed, which you should, if not, go do that first and let homebrew make your life better) is to just run the following command:That should put the chromedriver in your path and you should be all set. For windows Download webdriver from:ordownload the latest chromedriver from Paste the chromedriver.exe file in  \"C:\\Python27\\Scripts\" Folder.This should work now.For windows, please have the  placed under For Windows' IDE:If your path doesn't work, you can try to add the  to your project, like in this project structure.Then you should load the  in your main file. As for me, I loaded the  in . means  upper directory means the directory where the  is locatedHope this will be helpful.
Python

My code just scrapes a web page, then converts it to Unicode.But I get a :So I assume that means the HTML contains some wrongly-formed attempt at Unicode somewhere. Can I just drop whatever code bytes are causing the problem instead of getting an error?Can we get the actual value used for ?In addition, we usually encounter this problem here when we are trying to  an already encoded byte string. So you might try to decode it first as inAs an example:Fails withWhile:Succeeds without error. Do note that \"windows-1252\" is something I used as an . I got this from chardet and it had 0.5 confidence that it is right! (well, as given with a 1-character-length string, what do you expect) You should change that to the encoding of the byte string returned from  to what applies to the content you retrieved.Another problem I see there is that the  string method returns the modified string and does not modify the source in place. So it's kind of useless to have  as html is not the encoded string from html.encode (if that is what you were originally aiming for).As Ignacio suggested, check the source webpage for the actual encoding of the returned string from . It's either in one of the Meta tags or in the ContentType header in the response. Use that then as the parameter for .Do note however that it should not be assumed that other developers are responsible enough to make sure the header and/or meta character set declarations match the actual content. (Which is a PITA, yeah, I should know, I  one of those before).Decode the string you get back, using either the charset in the the appropriate  tag in the response or in the  header, then encode.As an extension to Ignacio Vazquez-Abrams' answerIt is sometimes desirable to remove accents from characters and print the base form. This can be accomplished withYou may also want to translate other characters (such as punctuation) to their nearest equivalents, for instance the RIGHT SINGLE QUOTATION MARK unicode character does not get converted to an ascii APOSTROPHE when encoding.Although there are more efficient ways to accomplish this. See this question for more details Use  - it even converts weird characters to ascii instantly, and even converts Chinese to phonetic ascii.then:I use this helper function throughout all of my projects. If it can't convert the unicode, it ignores it. This ties into a django library, but with a little research you could bypass it.I no longer get any unicode errors after using this.For broken consoles like  and HTML output you can always use:This will preserve all the non-ascii chars while making them printable in pure ASCII  in HTML.: . The only valid use case for this is printing to a non-unicode console or easy conversion to HTML entities in an HTML context. And finally, if you are on windows and use cmd.exe then you can type  to enable utf-8 output (works with Lucida Console font). You might need to add .You wrote \"\"\"I assume that means the HTML contains some wrongly-formed attempt at unicode somewhere.\"\"\"The HTML is NOT expected to contain any kind of \"attempt at unicode\", well-formed or not. It must of necessity contain Unicode characters encoded in some encoding, which is usually supplied up front ... look for \"charset\". You appear to be assuming that the charset is UTF-8 ... on what grounds? The \"\\xA0\" byte that is shown in your error message indicates that you may have a single-byte charset e.g. cp1252.If you can't get any sense out of the declaration at the start of the HTML, try using  to find out what the likely encoding is.Why have you tagged your question with \"regex\"? after you replaced your whole question with a non-question:If you have a string , you can use the  method for strings to convert encoding types.For more information about handling ASCII and unicode in Python, this is a really useful site: Works for meI think the answer is there but only in bits and pieces, which makes it difficult to quickly fix the problem such as Let's take an example, Suppose I have file which has some data in the following form ( containing ascii and non-ascii chars )1/10/17, 21:36 - Land : Welcome \u00ef\u00bf\u00bd\u00ef\u00bf\u00bdand we want to ignore and preserve only ascii characters. This code will do:and type(rline) will give you Looks like you are using python 2.x. \nPython 2.x defaults to ascii and it doesn\u2019t know about Unicode. Hence the exception.Just paste the below line after shebang, it will work
Python

Can someone explain this (straight from the - emphasis mine):Why would  and  return floats when they are by definition supposed to calculate integers?Well this got some very good arguments as to why they  return floats, and I was just getting used to the idea, when  pointed out that they in fact  return ints in Python 3...The range of floating point numbers usually exceeds the range of integers. By returning a floating point value, the functions can return a sensible value for input values that lie outside the representable range of integers.Consider: If  returned an integer, what should  return?Now, while Python's integers are now arbitrary precision, it wasn't always this way. The standard library functions are thin wrappers around the equivalent C library functions.As pointed out by other answers, in python they return floats probably because of historical reasons to prevent overflow problems. However, they return integers in python 3.You can find more information in .Because python's math library is a thin wrapper around the C math library which returns floats.The source of your confusion is evident in your comment:The point of the ceil and floor operations is to round floating-point data to .  Not to do a type conversion.  Users who need to get  values can do an explicit conversion following the operation.Note that it would not be possible to implement a round to integral value as trivially if all you had available were a ceil or float operation that returned an integer.  You would need to first check that the input is within the representable integer range, then call the function; you would need to handle NaN and infinities in a separate code path.Additionally, you must have versions of ceil and floor which return floating-point numbers if you want to conform to .Before Python 2.4, an integer couldn't hold the full range of truncated real numbers.Because the range for floats is greater than that of integers -- returning an integer could overflowThis is a very interesting question! As a float requires some bits to store the exponent (=) any floating point number greater than  will always be an integral value! At the other extreme a float with a negative exponent will give one of ,  or . This makes the discussion of  versus  moot because these functions will simply return the original number whenever the number is outside the range of the integer type.  The python functions are wrappers of the  function and so this is really a deficiency of the  functions where they should have returned an integer and forced the programer to do the range// check before calling ceil/floor.Thus the logical answer is the only time these functions are useful they would return a value within integer range and so the fact they return a float is a  and you are very smart for realizing this!Maybe because other languages do this as well, so it is generally-accepted behavior. (For good reasons, as shown in the other answers)Otherwise, you couldn't do that.If  would return integer in Python 2, this would return , not  you meant. In Python 3, it's safe, as  is always floating point division.
Python

Why is 'cls' used instead of 'self'?\nAny help appreciatedThe distinction between  and  is defined in  . As Adrien said, this is not a mandatory. It's a coding style.  says:It's used in case of a class method. Check  for further details.EDIT: As clarified by Adrien, it's a convention. You can actually use anything but  and  are used ().
Python

What must I do to use my objects of a custom type as keys in a Python dictionary (where I don't want the \"object id\" to act as the key) , e.g. I'd want to use MyThing's as keys that are considered the same if name and location are the same.\nFrom C#/Java I'm used to having to override and provide an equals and hashcode method, and promise not to mutate anything the hashcode depends on.What must I do in Python to accomplish this ? Should I even ? (In a simple case, like here, perhaps it'd be better to just place a (name,location) tuple as key - but consider I'd want the key to be an object)You need to add , note  and  :The Python  defines these requirements on key objects, i.e. they must be .An alternative in Python 2.6 or above is to use  -- it saves you writing any special methods:You override  if you want special hash-semantics, and  or  in order to make your class usable as a key. Objects who compare equal need to have the same hash value.Python expects  to return an integer, returning  is not recommended :) User defined classes have  by default that calls , as you noted.There is some extra tips from the .:
Python

What event system for Python do you use? I'm already aware of , but I was wondering what else can be found, or is commonly used?I'm not interested in event managers that are part of large frameworks, I'd rather use a small bare-bones solution that I can easily extend.Wrapping up the various event systems that are mentioned in the answers here:The most basic style of event system is the 'bag of handler methods', which is a simple implementation of the .  Basically, the handler methods (callables) are stored in an array and are each called when the event 'fires'.The disadvantage of these event systems is that you can only register the handlers on the actual Event object (or handlers list).\nSo at registration time the event already needs to exist.That's why the second style of event systems exists: the .\nHere, the handlers don't register on an event object (or handler list), but on a central dispatcher.  Also the notifiers only talk to the dispatcher.  What to listen for, or what to publish is determined by 'signal', which is nothing more than a name (string).Note:  is not an 'event system' in the above sense.  It's a thread synchronization system where one thread waits until another thread 'signals' the Event object.I've been doing it this way:However, like with everything else I've seen, there is no auto generated pydoc for this, and no signatures, which really sucks.We use an EventHook as suggested from Michael Foord in his :Just add EventHooks to your classes with:We add the functionality to remove all listener from an object to Michaels class and ended up with this:I use . It's the most bare bones you can imagine. :-)\nIn fact, here is the complete source code:Note that you can't send messages between processes, for example. It's not a messaging system, just an event system, nothing more, nothing less.I found this small script on . It seems to have just the right simplicity/power ratio I'm after. Peter Thatcher is the author of following code (no licensing is mentioned).You may have a look at  (). Its a small single-file (~250 loc) approach\n\"providing namespaces, wildcards and TTL\".Here's a basic example:I made a variation of Longpoke's minimalistic approach that also ensures the signatures for both callees and callers:I created an  class (code at the end). The syntax is the following:Here is an Example:Output:EventManger Code:Here is a minimal design that should work fine. What you have to do is to simply inherit  in a class and afterwards use  to listen for a specific event. Whenever that specific event is fired anywhere in the code (ie. ), the corresponding callback will fire.Example:If I do code in pyQt I use QT sockets/signals paradigm, same is for djangoIf I'm doing async I/O I use native select moduleIf I'm usign a SAX python parser I'm using event API provided by SAX. So it looks like I'm victim of underlying API :-)Maybe you should ask yourself what do you expect from event framework/module. My personal preference is to use Socket/Signal paradigm from QT. more info about that can be found Here's another  for consideration. It seems a viable choice for more demanding applications.
Python

I am using PyCharm on Windows. I am not getting the settings to change the maximum line length to 79 characters. I see that it is 120 characters by default. Where can I change it to 79 characters? I searched in the settings but didn't find.Here is screenshot of my Pycharm. Required settings is in following path: For File >> Settings >> Editor >> Code Style: Right margin (columns) Take a look at other options in that tab, they're very helpfulYou can even set a separate  for HTML. Under the specified path:File >> Settings >> Editor >> Code Style >> HTML >> Other Tab >> Right margin (columns)This is very useful because generally HTML and JS may be usually long in one line than Python. :) 
Python

I have a dataframe df :Then I want to drop rows with certain sequence numbers which indicated in a list, suppose here is  then left:How or what function can do that ?Use  and pass it a Series of index labels:Note that it may be important to use the \"inplace\" command when you want to do the drop in line. Because your original question is not returning anything, this command should be used.\nYou can also pass to  the  (instead of Series of index labels):Which is equivalent to:If the DataFrame is huge, and the number of rows to drop is large as well, then simple drop by index  takes too much time. In my case, I have a multi-indexed DataFrame of floats with , and I need to remove  rows from it. The fastest method I found is, quite counterintuitively, to  the remaining rows.Let  be an array of positional indexes to drop ( in the question).In my case this took , while the simple  took  and consumed a lot of memory. The resulting DataFrame is the same.In a comment to @theodros-zelleke's answer, @j-jones asked about what to do if the index is not unique.  I had to deal with such a situation.  What I did was to rename the duplicates in the index before I called , a la:where  is a function I defined that went through the elements of index and renamed the duplicates.  I used the same renaming pattern as  uses on columns, i.e., , where  is the name of the row and  is how many times it has occurred previously.
Python

Reading the Python cookbook at the minute and currently looking at generators. I'm finding it hard to get my head round.As I come from a Java background, is there a Java equivalent? The book was speaking about 'Producer / Consumer', however when I hear that I think of threading.Can anyone explain what a generator is and why you would use it? Without quoting any books, obviously (unless you can find a decent, simplistic answer direct from a book). Perhaps with examples, if you're feeling generous!A  is simply a function which returns an object on which you can call , such that for every call it returns some value, until it raises a  exception, signaling that all values have been generated. Such an object is called an .Normal functions return a single value using , just like in Java. In Python, however, there is an alternative, called . Using  anywhere in a function makes it a generator. Observe this code:As you can see,  is a function which yields  and . Every call to  yields a single value, until all values have been yielded.  loops call  in the background, thus:Likewise there are , which provide a means to succinctly describe certain common types of generators:Note that generator expressions are much like :Observe that a generator object is generated , but its code is  run all at once. Only calls to  actually execute (part of) the code. Execution of the code in a generator stops once a  statement has been reached, upon which it returns a value. The next call to  then causes execution to continue in the state in which the generator was left after the last . This is a fundamental difference with regular functions: those always start execution at the \"top\" and discard their state upon returning a value.There are more things to be said about this subject. It is e.g. possible to  data back into a generator (). But that is something I suggest you do not look into until you understand the basic concept of a generator.Now you may ask: why use generators? There are a couple of good reasons:\u00a0\u00a0  in the above examples  is a function which calls the method  on the given object. In Python <=2.6 one uses a slightly different technique, namely  instead of . Python 2.7 has  call  so you need not use the following in 2.7:A generator is effectively a function that returns (data) before it is finished, but it pauses at that point, and you can resume the function at that point.and so on.  The (or one) benefit of generators is that because they deal with data one piece at a time, you can deal with large amounts of data; with lists, excessive memory requirements could become a problem.   Generators, just like lists, are iterable, so they can be used in the same ways:Note that generators provide another way to deal with infinity, for exampleThe generator encapsulates an infinite loop, but this isn't a problem because you only get each answer every time you ask for it.Generators could be thought of as shorthand for creating an iterator.  They behave like a Java Iterator.  Example:Hope this helps/is what you are looking for.As many other answers are showing, there are different ways to create a generator.  You can use the parentheses syntax as in my example above, or you can use yield.  Another interesting feature is that generators can be \"infinite\" -- iterators that don't stop:First of all the term  originally was somewhat ill-defined in Python, leading to lots of confusion. What you probably mean are  and  (see ). Then in Python there are also  (which return a generator object),  (which are iterators) and  (which are evaluated to a generator object). According to  it seems that the official terminology is now that  is short for \"generator function\". In the past the documentation defined the terms inconsistently, but fortunately this has been fixed.It might still be a good idea to be precise and avoid the term \"generator\" without further specification.There is no Java equivalent.Here is a bit of a contrived example:There is a loop in the generator that runs from 0 to n, and if the loop variable is a multiple of 3, it yields the variable.During each iteration of the for loop the generator is executed. If it is the first time the generator executes, it starts at the beginning, otherwise it continues from the previous time it yieldedThe only thing I can add to Stephan202's answer is a recommendation that you take a look at David Beazley's PyCon '08 presentation \"Generator Tricks for Systems Programmers,\" which is the best single explanation of the how and why of generators that I've seen anywhere.  This is the thing that took me from \"Python looks kind of fun\" to \"This is what I've been looking for.\"  It's at .It helps to make a clear distinction between the function foo, and the generator foo(n):foo is a function. \nfoo(6) is a generator object.The typical way to use a generator object is in a loop:The loop printsThink of a generator as a resumable function.  behaves like  in the sense that values that are yielded get \"returned\" by the generator. Unlike return, however, the next time the generator gets asked for a value, the generator's function, foo, resumes where it left off -- after the last yield statement -- and continues to run until it hits another yield statement. Behind the scenes, when you call  the generator object bar is defined for you to have a  attribute.You can call it yourself to retrieve values yielded from foo:When foo ends (and there are no more yielded values), calling  throws a StopInteration error.I like to describe generators, to those with a decent background in programming languages and computing, in terms of stack frames.In many languages, there is a stack on top of which is the current stack \"frame\".  The stack frame includes space allocated for variables local to the function including the arguments passed in to that function.  When you call a function, the current point of execution (the \"program counter\" or equivalent) is pushed onto the stack, and a new stack frame is created.  Execution then transfers to the beginning of the function being called.With regular functions, at some point the function returns a value, and the stack is \"popped\".  The function's stack frame is discarded and execution resumes at the previous location.When a function is a generator, it can return a value  the stack frame being discarded, using the yield statement.  The values of local variables and the program counter within the function are preserved.  This allows the generator to be resumed at a later time, with execution continuing from the yield statement, and it can execute more code and return another value.Before Python 2.5 this was all generators did.  Python 2.5 added the ability to pass values back  to the generator as well.  In doing so, the passed-in value is available as an expression resulting from the yield statement which had temporarily returned control (and a value) from the generator.The key advantage to generators is that the \"state\" of the function is preserved, unlike with regular functions where each time the stack frame is discarded, you lose all that \"state\".  A secondary advantage is that some of the function call overhead (creating and deleting stack frames) is avoided, though this is a usually a minor advantage.I believe the first appearance of iterators and generators were in the Icon programming language, about 20 years ago.You may enjoy , which lets you wrap your head around them without concentrating on the syntax (since Icon is a language you probably don't know, and Griswold was explaining the benefits of his language to people coming from other languages).After reading just a few paragraphs there, the utility of generators and iterators might become more apparent.This post will use  as a tool to build up to explaining the usefulness of . This post will feature both C++ and Python code. Fibonacci numbers are defined as the sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ....Or in general: This can be transferred into a C++ function extremely easily: But if you want to print the first 6 Fibonacci numbers, you will be recalculating a lot of the values with the above function.  For example: , but  also recalculates .  The higher the value you want to calculate, the worse off you will be. So one may be tempted to re-write the above by keeping track of the state in .But this is very ugly, and it complicates our logic in , it would be better to not have to worry about state in our  function.We could return a  of values and use an  to iterate over that set of values, but this requires a lot of memory all at once for a large number of return values. So back to our old approach, what happens if we wanted to do something else besides print the numbers? We'd have to copy and paste the whole block of code in  and change the output statements to whatever else we wanted to do.\nAnd if you copy and paste code, then you should be shot.  You don't want to get shot do you?To solve these problems, and to avoid getting shot, we may re-write this block of code using a callback function.  Every time a new Fibonacci number is encountered, we would call the callback function.This is clearly an improvement, your logic in  is not as cluttered, and you can do anything you want with the Fibonacci numbers, simply define new callbacks.But this is still not perfect.  What if you wanted to only get the first 2 Fibonacci numbers, and then do something, then get some more, then do something else. Well we could go on like we have been, and we could start adding state again into , allowing GetFibNumbers to start from an arbitrary point.\nBut this will further bloat our code, and it already looks too big for a simple task like printing Fibonacci numbers.We could implement a producer and consumer model via a couple threads.  But this complicates the code even more.Instead let's talk about generators.Python has a very nice language feature that solves problems like these called generators. A generator allows you to execute a function, stop at an arbitrary point, and then continue again where you left off.\nEach time returning a value.Consider the following code that uses a generator: Which gives us the results:The  statement is used in conjuction with Python generators.  It saves the state of the function and returns the yeilded value.  The next time you call the next() function on the generator, it will continue where the yield left off.This is by far more clean than the callback function code.  We have cleaner code, smaller code, and not to mention much more functional code (Python allows arbitrarily large integers).
Python

This is a question I have wondered about for quite some time, yet I have never found a suitable solution. If I run a script and I come across, let's say an IndexError, python prints the line, location and quick description of the error and exits. Is it possible to automatically start pdb when an error is encountered? I am not against having an extra import statement at the top of the file, nor a few extra lines of code.You can use  to print the exceptions traceback. Then use  to extract the traceback and finally call  with that tracebackIf you want to start an interactive command line with  using the locals of the frame where the exception originated you can doIf you don't provide the  flag then you'll need to enter 'c' (for Continue) when execution begins. Then it will run to the error point and give you control there.Use the following module:Name it  (or whatever you like) and put it somewhere in your python path.Now, at the start of your script, just add an .This isn't the debugger, but probably just as useful(?)I know I heard Guido mention this in a speech somewhere.I just checked python -?, and if you use the -i command you can interact where your script stopped.So given this script:You can get this output!To be honest I haven't used this, but I should be, seems very useful. has a command for toggling this behavior: . It does exactly what you described, maybe even a bit more (giving you more informative backtraces with syntax highlighting and code completion). It's definitely worth a try!IPython makes this simple on the command line:can be rewritten toOr, similarly, if calling a module:can be rewritten toNote the  to stop IPython from reading the script's arguments as its own.This also has the advantage of invoking the enhanced IPython debugger (ipdb) instead of pdb.You can put this line in your code:More info: To have it run without having to type c at the beginning use:Pdb has its own command line arguments: -c c will execute c(ontinue) command at start of execution and the program will run uninterrupted until the error.Put a breakpoint inside the constructor of topmost exception class in the hierarchy, and most of the times you will see where the error was raised.Putting a breakpoint means whatever you want it to mean : you can use an IDE, or , or whateverIf you are running a module:And now you want to enter  when an exception occurs, do this:(or  your ). The  is needed so that the module is found in the path, since you are running the  module now.If you are using the IPython environment, you can just use the %debug and the shell will take you back to the offending line with the ipdb environment for inspections etc. Another option as pointed above is to use the iPython magic %pdb which effectively does the same.
Python

Is there a way to set up a global variable inside of a module? When I tried to do it the most obvious way as appears below, the Python interpreter said the variable  did not exist.And after importing the module in a different fileAnd the traceback was: Any ideas? I'm trying to set up a singleton by using a module, as per  recommendation.Here is what is going on.First, the only global variables Python really has are module-scoped variables.  You cannot make a variable that is truly global; all you can do is make a variable in a particular scope.  (If you make a variable inside the Python interpreter, and then import other modules, your variable is in the outermost scope and thus global within your Python session.)All you have to do to make a module-global variable is just assign to a name.Imagine a file called foo.py, containing this single line:Now imagine you import it.However, let's suppose you want to use one of your module-scope variables as a global inside a function, as in your example.  Python's default is to assume that function variables are local.  You simply add a  declaration in your function, before you try to use the global.By the way, for this example, the simple  test is adequate, because any string value other than an empty string will evaluate true, so any actual database name will evaluate true.  But for variables that might contain a number value that might be 0, you can't just say ; in that case, you should explicitly test for  using the  operator.  I modified the example to add an explicit  test.  The explicit test for  is never wrong, so I default to using it.Finally, as others have noted on this page, two leading underscores signals to Python that you want the variable to be \"private\" to the module.  If you ever do an , Python will not import names with two leading underscores into your name space.  But if you just do a simple  and then say  you will see the \"private\" variables in the list, and if you explicitly refer to  Python won't care, it will just let you refer to it.  The double leading underscores are a major clue to users of your module that you don't want them rebinding that name to some value of their own.It is considered best practice in Python not to do , but to minimize the coupling and maximize explicitness by either using  or by explicitly doing an import like .EDIT: If, for some reason, you need to do something like this in a very old version of Python that doesn't have the  keyword, there is an easy workaround.  Instead of setting a module global variable directly, use a mutable type at the module global level, and store your values inside it.In your functions, the global variable name will be read-only; you won't be able to rebind the actual global variable name.  (If you assign to that variable name inside your function it will only affect the local variable name inside the function.)  But you can use that local variable name to access the actual global object, and store data inside it.You can use a  but your code will be ugly:A  is better.  But the most convenient is a class instance, and you can just use a trivial class:(You don't really need to capitalize the database name variable.)I like the syntactic sugar of just using  rather than ; it seems the most convenient solution in my opinion.  But the  solution works fine also.With a  you can use any hashable value as a key, but when you are happy with names that are valid identifiers, you can use a trivial class like  in the above. The technique described here is the same as in , , that no artificial helper object is created to explicitly scope variables. .Think of it like  for the  instead of the current instance !, you can import  as often on as many clients as you want, manipulating the same, universal state:I have used this recipe to create simple and lightweight    ever since I found it. As an additional bonus I find it quite pythonic overall as it nicely fits Pythons policy of .Steveha's answer was helpful to me, but omits an important point (one that I think wisty was getting at). The global keyword is not necessary if you only access but do not assign the variable in the function.If you assign the variable without the global keyword then Python creates a new local var -- the module variable's value will now be hidden inside the function.  Use the global keyword to assign the module var inside a function.Pylint 1.3.1 under Python 2.7 enforces NOT using global if you don't assign the var.For this, you need to declare the variable as global. However, a global variable is also accessible from  the module by using . Add this as the first line of your module:You are falling for a subtle quirk. You cannot re-assign module-level variables inside a python function. I think this is there to stop people re-assigning stuff inside a function by accident. You can access the module namespace, you just shouldn't try to re-assign. If your function assigns something, it automatically becomes a function variable - and python won't look in the module namespace.You can do:but you cannot re-assign  inside a function. One workaround:Note, I'm not re-assigning , I'm just modifying its contents.
Python

How do I retrieve the exit code when using Python's  module and the  method?Relevant code:Should I be doing this another way? will set the  attribute when it's done(*). Here's the relevant documentation section:So you can just do (I didn't test it but it should work):(*) This happens because of the way it's implemented: after setting up threads to read the child's streams, it just calls . You should first make sure that the process has completed running and the return code has been read out using the  method. This will return the code. If you want access to it later, it's stored as  in the  object. . The child process will be blocked If it writes to standard output/error, and/or reads from standard input, and there are no peers.
Python

I'm new to Python, so this is probably a simple scoping question. The following code in a Python file (module) is confusing me slightly:In other languages I've worked in, this code would throw an exception, as the  variable is local to the  statement and should not exist outside of it. But this code executes, and prints 1. Can anyone explain this behavior? Are all variables created in a module global/available to the entire module?Python variables are scoped to the innermost function or module; control blocks like  and  blocks don't count. (IIUC, this is also how JavaScript's -declared variables work.)Scope in python follows this order:()Notice that  and other looping/branching constructs are not listed - only classes, functions, and modules provide scope in Python, so anything declared in an  block has the same scope as anything decleared outside the block. Variables aren't checked at compile time, which is why other languages throw an exception. In python, so long as the variable exists at the time you require it, no exception will be thrown.Yes, they're in the same \"local scope\", and actually code like this is common in Python:Note that  isn't declared or initialized before the condition, like it would be in C or Java, for example.Unlike languages such as C, a Python variable is in scope for the whole of the function (or class, or module) where it appears, not just in the innermost \"block\".  It is as though you declared  at the top of the function (or class, or module), except that in Python you don't have to declare variables.Note that the existence of the variable  is checked only at runtime -- that is, when you get to the  statement.  If  didn't equal  then you would get an exception: .As Eli said, Python doesn't require variable declaration. In C you would say:but in Python declaration is implicit, so when you assign to x it is automatically declared. It's because Python is dynamically typed - it wouldn't work in a statically typed language, because depending on the path used, a variable might be used without being declared. This would be caught at compile time in a statically typed language, but with a dynamically typed language it's allowed.The only reason that a statically typed language is limited to having to declare variables outside of  statements in because of this problem. Embrace the dynamic!Yes. It is also true for  scope. But not functions of course.In your example: if the condition in the  statement is false,  will not be defined though.you're executing this code from command line therefore  conditions is true and  is set. Compare:
Python

I want to send a value for  while requesting a webpage using Python Requests.  I am not sure is if it is okay to send this as a part of the header, as in the code below:The debug information isn't showing the headers being sent during the request.Is it acceptable to send this information in the header?  If not, how can I send it?The  should be specified as a field in the header.Here is a , and you'd probably be interested in , which includes .The simplest way to do what you want is to create a dictionary and specify your headers directly, like so:The above clobbers all the default headers that  specifies, which, as of version , is specified in the source code as:If you want to use the default headers and combine it with your own, you can do this:
Python

I'm using Python's logging module to log some debug strings to a file which works pretty well. Now in addition, I'd like to use this module to also print the strings out to stdout. How do I do this? In order to log my strings to a file I use following code:and then call a logger function likeThank you for some help here!Just get a handle to the root logger and add the StreamHandler. The StreamHandler writes to stderr. Not sure if you really need stdout over stderr, but this is what I use when I setup the Python logger and I also add the FileHandler as well. Then all my logs go to both places (which is what it sounds like you want).You could also add a Formatter to it so all your log lines have a common header.ie:Prints to the format of:Adding a StreamHandler without arguments goes to stderr instead of stdout. If some other process has a dependency on the stdout dump (i.e. when writing an NRPE plugin), then make sure to specify stdout explicitly or you might run into some unexpected troubles.Here's a quick example reusing the assumed values and LOGFILE from the question:Either run  with  as the argument prior to setting up any other handlers or logging any messages, or manually add a  that pushes messages to stdout to the root logger (or any other logger you want, for that matter).For 2.7, try the following:  
Python

How would I create a list with values between 2 values I put in? \nFor example, following list is generated for values between 11 and 16:Use . In Python 2.x it returns a list so all you need is,In Python 3.x it's a iterator so you need to convert it to a list,: Second number is exclusive so here it needs to be  = EDIT:To response to the question about incrementing by  the easiest option would probably be to use 's ,You seem to be looking for :For incrementing by  instead of , say:Try:That is a list in Python 2.x and behaves mostly like a list in Python 3.x.  If you are running Python 3 and need a list that you can modify, then use: Use list comprehension in python. Since you want 16 in the list too.. Use x2+1. Range function excludes the higher limit in the function.assuming you want to have a range between x to yuse list for 3.x supportIf you are looking for range like function which works for float type, then here is a very good .Output:
Python

This seems rather obvious, but I can't seem to figure out how do I convert an index of data frame to a column?For example:To,either:or, :so, if you have a multi-index frame with 3 levels of index, like:and you want to convert the 1st () and 3rd () levels in the index into columns, you would do:For MultiIndex you can extract its subindex using where  is the name of the subindex.
Python

I am getting a response from the rest is an Epoch time format likeI want to convert that epoch seconds in MySQL format time so that I could store the differences in my MySQL database.I tried:The above result is not what I am expecting. I want it be like Please suggest how can I achieve this?Also,\nWhy I am getting  forTo convert your time value (float or int) to a formatted string, use:You can also use :This is what you needPlease input a  instead of an  and that other  should go away.Try this:Also in MySQL, you can  like:For your 2nd question, it is probably because  is a string.  You can convert it to numeric like: This is a little more wordy but it comes from date command in unix.First a bit of info in epoch from to understand how epoch should be.just ensure the arg you are passing to  is integer.
Python

In python, is there a difference between calling  and assigning  to a dictionary? If yes, what is it?\nExample:If you have another variable also referring to the same dictionary, there is a big difference:This is because assigning  creates a new, empty dictionary and assigns it to the  variable. This leaves  pointing at the old dictionary with items still in it. However,  clears the same dictionary that  and  both point at. will create a new instance for  but all other references will still point to the old contents. \n will reset the contents, but all references to the same instance will still be correct.In addition to the differences mentioned in other answers, there also is a speed difference.  d = {} is over twice as fast:In addition to @odano 's answer, it seems using  is faster if you would like to clear the dict for many times.The result is:As an illustration for the things already mentioned before:One thing not mentioned is scoping issues. Not a great example, but here's the case where I ran into the problem:The solution is to replace  with If someone thinks up a more practical example, feel free to edit this post. methods are always useful if the original object is not in scope:Re-assigning the dictionary would create a new object and wouldn't modify the original one.
Python

I know that I can use something like  to get a substring in Python, but what does the 3 mean in ?it means 'nothing for the first argument, nothing for the second, and jump by three'. It gets every third item of the sequence sliced.\n is what you want. New in Python 2.3Python sequence slice addresses can be written as a[start:end:step] and any of start, stop or end can be dropped.   is every third element of the sequence. is a sequence of each -th item in the entire sequence.Example:The syntax is:So you can do: is, , \"slice of s from i to j with step k\".  When  and  are absent, the whole sequence is assumed and thus  means \"every k-th item\".First, let's initialize a list:Let's take every 3 item from :Let's take every 3 item from :Let's take every 3 item from :Let's take every 3 item from :When slicing in Python the third parameter is the step. As others mentioned, see  for a nice overview.With this knowledge,  just means that you have not specified any start or end indices for your slice. Since you have specified a step, , this will take every third entry of  starting at the first index. For example:The third parameter is the step.  So [::3] would return every 3rd element of the list/string.Python uses the :: to separate the End, the Start, and the Step value.It depends on what class you are using it on exactly because:We can then open up slice objects as:This is notably used in Numpy to slice multi-dimensional arrays in any direction.Of course, any sane API should use  with the usual \"every 3\" semantic.This visual example will show you how to a neatly select elements in a NumPy Matrix (2 dimensional array) in a pretty entertaining way (I promise). (Caution: this is a NumPy array specific example with the aim of illustrating the a use case of \"double colons\"  for jumping of elements in multiple axes. This example does not cover native Python data structures like ).Say we have a NumPy matrix that looks like this:Say for some reason, your boss wants you to select the following elements:\"But How???\"... Read on! (We can do this in a 2-step approach)Specify the \"start index\" and \"end index\" in both row-wise and column-wise directions.In code:Notice now we've just obtained our subset, with the use of simple start and end indexing technique. Next up, how to do that \"jumping\"... (read on!)We can now specify the \"jump steps\" in both row-wise and column-wise directions (to select elements in a \"jumping\" way) like this:In code (note the double colons):We have just selected all the elements as required! :)Now we know the concept, we can easily combine step 1 and step 2 into one consolidated step - for compactness:Done!
Python

I am creating a program that will download a .jar (java) file from a web server, by reading the URL that is specified in the .jad file of the same game/application. I'm using Python 3.2.1I've managed to extract the URL of the JAR file from the JAD file (every JAD file contains the URL to the JAR file), but as you may imagine, the extracted value is type() string. Here's the relevant function:However I always get an error saying that the type in the function above has to be bytes, and not string. I've tried using the URL.encode('utf-8'), and also bytes(URL,encoding='utf-8'), but I'd always get the same or similar error.So basically my question is how to download a file from a server when the URL is stored in a string type?If you want to obtain the contents of a web page into a variable, just  the response of :The easiest way to download and save a file is to use the  function:But keep in mind that  is considered  and might become deprecated (not sure why, though).So the most  way to do this would be to use the  function to return a file-like object that represents an HTTP response and copy it to a real file using .If this seems too complicated, you may want to go simpler and store the whole download in a  object and then write it to a file. But this works well only for small files.It is possible to extract  (and maybe other formats) compressed data on the fly, but such an operation probably requires the HTTP server to support random access to the file.I use  package whenever I want something related to HTTP requests because its API is very easy to start with:first, install then the code:I hope I understood the question right, which is:  how to download a file from a server when the URL is stored in a string type?I download files and save it locally using the below code:
Python

I was going through the tensorflow api docs . In tensorflow docs they used a keyword called . What is it? In a lot of methods in the api docs it is written like, Now what it is written is that  are only . Well why keep a different name like ? I almost thought that it was . . Another thing is that there are two methods i could not differentiate. They wereWhat are the differences between them? The docs are not clear to me. I know what  does. But not the other. An example will be really helpful.Logits simply means that the function operates on the unscaled output of earlier layers and that the relative scale to understand the units is linear.  It means, in particular, the sum of the inputs may not equal 1, that the values are  probabilities (you might have an input of 5). produces just the result of applying the  to an input tensor.  The softmax \"squishes\" the inputs so that sum(input) = 1;  it's a way of normalizing.  The shape of output of a softmax is the same as the input - it just normalizes the values.  The outputs of softmax  be interpreted as probabilities.In contrast,  computes the cross entropy of the result after applying the softmax function (but it does it all together in a more mathematically careful way).  It's similar to the result of:The cross entropy is a summary metric - it sums across the elements.  The output of  on a shape  tensor is of shape  (the first dimension is treated as the batch).If you want to do optimization to minimize the cross entropy, AND you're softmaxing after your last layer, you should use  instead of doing it yourself, because it covers numerically unstable corner cases in the mathematically right way.  Otherwise, you'll end up hacking it by adding little epsilons here and there.(Edited 2016-02-07: If you have single-class labels, where an object can only belong to one class, you might now  consider using  so that you don't have to convert your labels to a dense one-hot array.  This function was added after release 0.6.0.)Suppose you have two tensors, where  contains computed scores for each class (for example, from y = W*x +b) and  contains one-hot encoded true labels. If you interpret the scores in  as unnormalized log probabilities, then they are .Additionally, the total cross-entropy loss computed in this manner:is essentially equivalent to the total cross-entropy loss computed with the function :In the output layer of your neural network, you will probably compute an array that contains the class scores for each of your training instances, such as from a computation . To serve as an example, below I've created a  as a 2 x 3 array, where the rows correspond to the training instances and the columns correspond to classes. So here there are 2 training instances and 3 classes.Note that the values are not normalized (i.e. the rows don't add up to 1). In order to normalize them, we can apply the softmax function, which interprets the input as unnormalized log probabilities (aka ) and outputs normalized linear probabilities. It's important to fully understand what the softmax output is saying. Below I've shown a table that more clearly represents the output above. It can be seen that, for example, the probability of training instance 1 being \"Class 2\" is 0.619. The class probabilities for each training instance are normalized, so the sum of each row is 1.0.So now we have class probabilities for each training instance, where we can take the argmax() of each row to generate a final classification. From above, we may generate that training instance 1 belongs to \"Class 2\" and training instance 2 belongs to \"Class 1\". Are these classifications correct? We need to measure against the true labels from the training set. You will need a one-hot encoded  array, where again the rows are training instances and columns are classes. Below I've created an example  one-hot array where the true label for training instance 1 is \"Class 2\" and the true label for training instance 2 is \"Class 3\".Is the probability distribution in  close to the probability distribution in ? We can use  to measure the error.We can compute the cross-entropy loss on a row-wise basis and see the results. Below we can see that training instance 1 has a loss of 0.479, while training instance 2 has a higher loss of 1.200. This result makes sense because in our example above,  showed that training instance 1's highest probability was for \"Class 2\", which matches training instance 1 in ; however, the prediction for training instance 2 showed a highest probability for \"Class 1\", which does not match the true class \"Class 3\".What we really want is the total loss over all the training instances. So we can compute:We can instead compute the total cross entropy loss using the  function, as shown below. Note that  and  produce essentially equivalent results with some small differences in the very final digits. However, you might as well use the second approach: it takes one less line of code and accumulates less numerical error because the softmax is done for you inside of .tf.nn.softmax computes the forward propagation through a softmax layer. You use it during evaluation of the model when you compute the probabilities that the model outputs.tf.nn.softmax_cross_entropy_with_logits computes the cost for a softmax layer. It is only used during training. The logits are the unnormalized log probabilities output the model (the values output before the softmax normalization is applied to them).
Python

I'm currently working on a computation in python shell. What I want to have is Matlab style listout where you can see all the variables that have been defined up to a point (so I know which names I've used, their values and such).Is there a way, and how can I do that?Couple of things you could use:If this is an option for you, you might want to look at :To get a list of all currently defined variables, type :You can type  for more detail:There are a wealth of other functions available - basically it is the Python interpreter on steroids. One convenient one is  command, which lets you save variables between sessions (kind of like a super easy )If you have a few minutes, check out I am in no way associated with the team behind IPython, just a satisfied user.To get the names:To get the values:vars() also takes an optional argument to find out which vars are defined within an object itself. As RedBlueThing and analog said:Using the interactive shell (version 2.6.9), after creating variables  and , running  givesrunning  givesRunning  gives exactly the same answer as  in this case.I haven't gotten into any modules, so all the variables are available as both local and global variables.   and  list the values of the variables as well as the names;  only lists the names.If I import a module and run  or  inside the module,  still gives only a small number of variables; it adds  to the variables listed above.  and  also list the same variables, but in the process of printing out the dictionary value for , it lists a far larger number of variables: built-in functions, exceptions, and types such as \"\", rather than just the brief  as shown above.For more about  see  at New Mexico Tech or  at ibiblio.org.For more about  and  see  at Dive Into Python and a page about  at New Mexico Tech.[Comment:  @Kurt:  You gave a link to  but that answer has a mistake in it. The problem there is:   in that example will always return . You do get a list of the variables, which answers the question, but with incorrect types listed beside them.  This was not obvious in your example because all the variables happened to be strings anyway; however, what it's returning is the type of the name of the variable instead of the type of the variable.  To fix this: instead of  use . I apologize for posting a comment in the answer section but I don't have comment posting privileges, and the other question is closed.]print locals()edit continued from comment.To make it look a little prettier when printing:That should give you a more vertical printout.keep in mind dir() will return all current imports,  variables.if you just want your variables, I would suggest a naming scheme that is easy to extract from dir, such as varScore, varNames, etc.that way, you can simply do this:if you want to list all variables, but exclude imported modules and variables such as:you can use something like so:as you can see, it will show the variable \"imports\" though, because it is a variable (well, a tuple). A quick workaround is to add the word \"imports\" into the imports tuple itself!In my Python 2.7 interpreter, the same  command that exists in MATLAB exists in Python. It shows the same details as the MATLAB analog (variable name, type, and value/data).In the Python interpreter,  lists all variables in the \"interactive namespace\".globals(), locals(), vars(), and dir() may all help you in what you want.a bit more smart (python 3) way:This has to be defined in the interactive shell.import os, a = 10, import sys, MyWho()  then gives['a', 'MyWho', 'sys', 'os']
Python

According to :However, if I define two files:and:when i run  it prints out  without giving any exception. Is diveintopython wrong, or did I misunderstand something? And is there some way to  define a module's function as private?In Python, \"privacy\" depends on \"consenting adults'\" levels of agreement - you can't  it (any more than you can in real life;-).  A single leading underscore means you're not  to access it \"from the outside\" --  leading underscores (w/o trailing underscores) carry the message even more forcefully... but, in the end, it still depends on social convention and consensus: Python's introspection is forceful enough that you can't  every other programmer in the world to respect you wish.((Btw, though it's a closely held secret, much the same holds for C++: with most compilers, a simple  line before ing your  file is all it takes for wily coders to make hash of your \"privacy\"...!-))There may be confusion between  and .A  starts with \nSuch a element is not copied along when using the  form of the import command;  it is however imported if using the  syntax  ()\nSimply remove one underscore from the a.__num of the question's example and it won't show in modules that import a.py using the  syntax.A  starts with   (aka dunder i.e. d-ouble under-score) \nSuch a variable has its name \"mangled\" to include the classname etc.\nIt can still be accessed outside of the class logic, through the mangled name.\nAlthough the name mangling can serve as a mild prevention device against unauthorized access, its main purpose is to prevent possible name collisions with class members of the ancestor classes. \nSee Alex Martelli's funny but accurate reference to  as he describes the convention used in regards to these variables.This question was not fully answered, since module privacy is not purely conventional, and since using  may or may not recognize module privacy, depending on how it is used.If you define private names in a module, those names  be imported into any script that uses the syntax, 'import module_name'. Thus, assuming you had correctly defined in your example the module private, _num, in a.py, like so....you would be able to access it in b.py with the module name symbol:To import only non-privates from a.py, you must use the  syntax:For the sake of clarity, however, it is better to be explicit when importing names from modules, rather than importing them all with a '*':Python allows for private  members with the double underscore prefix.  This technique doesn't work at a module level so I am thinking this is a mistake in Dive Into Python.Here is an example of private class functions:Python has three modes via., private, public and protected .While importing a module only public mode is accessible .So private and protected modules cannot be called from outside of the module i.e., when it is imported .
Python

I've been wondering this for some time. As the title say, which is faster, the actual function or simply raising to the half power?This is not a matter of premature optimization. This is simply a question of how the underlying code actually works. What is the theory of how Python code works?I sent Guido van Rossum an email cause I really wanted to know the differences in these methods.As per comments, I've updated the code:Now the  function is directly in a local argument, meaning it has the fastest lookup possible.  The python version seems to matter here. I used to think that  would be faster, since when python parses \"i**.5\" it knows, syntactically, which method to call ( or some variant), so it doesn't have to go through the overhead of lookup that the  variant does. But I might be wrong: 0.191000 vs. 0.224000 0.195000 vs. 0.139000Also psyco seems to deal with  better: 0.109000 vs. 0.043000 0.128000 vs. 0.067000Table results produced on machine:To reproduce results:How many square roots are you really performing?  Are you trying to write some 3D graphics engine in Python?  If not, then why go with code which is cryptic over code that is easy to read?  The time difference is would be less than anybody could notice in just about any application I could forsee.  I really don't mean to put down your question, but it seems that you're going a little too far with premature optimization.Here's some timings (Python 2.5.2, Windows):This test shows that  is slightly faster than .For the Python 3.0 the result is the opposite: is always faster than  on another machine (Ubuntu, Python 2.6 and 3.1):In these micro-benchmarks, math.sqrt will be slower, because of the slight time it takes to lookup the sqrt in the math namespace. You can improve it slightly with Even then though, running a few variations through timeit, show a slight (4-5%) performance advantage for \"x**.5\"interestingly, doingsped it up even more, to within 1% difference in speed, with very little statistical significance.I will repeat Kibbee, and say that this is probably a premature optimization.Most likely math.sqrt(x), because it's optimized for square rooting.Benchmarks will provide you the answer you are looking for.using Claudiu's code, on my machine even with \"from math import sqrt\" x**.5 is faster but using psyco.full() sqrt(x) becomes much faster, at least by 200%In python 2.6 the   function uses the C  function and the  functions uses the C  function.In glibc compiler the implementation of  is quite complex and it is well optimized for various exceptional cases. For example, calling C  simply calls the  function.The difference in speed of using  or  is caused by the wrappers used around the C functions and the speed strongly depends on optimization flags/C compiler used on the system. Here are the results of Claudiu's algorithm on my machine. I got different results:For what it's worth (see Jim's answer). On my machine, running python 2.5:Someone commented about the \"fast Newton-Raphson square root\" from Quake 3... I implemented it with ctypes, but it's super slow in comparison to the native versions. I'm going to try a few optimizations and alternate implementations.Here's another method using struct, comes out about 3.6x faster than the ctypes version, but still 1/10 the speed of C.You might want to benchmark the  as well. Shouldn't take much to convert to Python.Claudiu's results differ from mine. I'm using Python 2.6 on Ubuntu on an old P4 2.4Ghz machine... Here's my results:sqrt is consistently faster for me... Even Codepad.org NOW seems to agree that sqrt, in the local context, is faster (). Codepad seems to be running Python 2.5 presently. Perhaps they were using 2.4 or older when Claudiu first answered?In fact, even using math.sqrt(i) in place of arg(i), I still get better times for sqrt. In this case timeit2() took between 0.53 and 0.55 seconds on my machine, which is still better than the 0.56-0.60 figures from timeit1.I'd say, on modern Python, use math.sqrt and definitely bring it to local context, either with somevar=math.sqrt or with from math import sqrt.What would be even faster is if you went into math.py and copied the function \"sqrt\" into your program. It takes time for your program to find math.py, then open it, find the function you are looking for, and then bring that back to your program. If that function is faster even with the \"lookup\" steps, then the function itself has to be awfully fast. Probably will cut your time in half. IN summary:
Python

What is python-3 using instead of PIL for manipulating Images?The \"friendly PIL fork\" . Check out the  for support matrix and so on.Christoph Gohlke managed to build PIL (for Windows only) for python versions up to 3.3: I tried his version of PIL with Python 3.2, and image open/create/pixel manipulation/save all work.Qt works very well with graphics. In my opinion it is more versatile than PIL.You get all the features you want for graphics manipulation, but there's also vector graphics and even support for real printers. And all of that in one uniform API, .To use Qt you need a Python binding for it:  or .\nThey both support Python 3.Here is a simple example that loads a JPG image, draws an antialiased circle of radius  at coordinates  with the color of the pixel that was at those coordinates and saves the modified image as a PNG file:But please note that this solution is quite 'heavyweight', because Qt is a large framework for making GUI applications.As of March 30, 2012, I have tried and failed to get the sloonz fork on GitHub to open images.  I got it to compile ok, but it didn't actually work.  I also tried building gohlke's library, and it compiled also but failed to open any images.  Someone mentioned PythonMagick above, but it only compiles on Windows.  See .PIL was last updated in 2009, and while it's website says they are working on a Python 3 port, it's been 3 years, and the mailing list has gone cold.To solve my Python 3 image manipulation problem, I am using  to execute ImageMagick shell commands.  This method works.See .You can use my package  on Python 3. It is numpy-based rather than PIL based.The original PIL author planned to port to Python 3. Check this message in the mailing list: However, for the last 3 years, there has been no further work by the original author.As to what you can use NOW, I've no idea. I'm sticking with Python 2.6 until 3.0 has more widespread support from third-party libraries.Maybe you could do the image work in some other language.You want the , here is how to install it on Python 3:If that does not work for you (it should), try normal :
Python

What is the pythonic way of writing the following code?I have a vague memory that the explicit declaration of the  loop can be avoided and be written in the  condition. Is this true?Though not widely known,  also accepts a tuple. You don't need to loop.Just use:Take an extension from the file and see if it is in the set of extensions:Using a set because time complexity for lookups in sets is O(1) ().I have this:
Python

I see a lot on converting a  string to an  object in Python, but I want to go the other way.\nI've got  and I would like to convert it to string like .You can use  to help you format your date.E.g.,will yield:More information about formatting see  and  objects (and  as well) support a , and there are two ways to access it:So your example could look like:orFor completeness' sake: you can also directly access the attributes of the object, but then you only get the numbers:The time taken to learn the mini-language is worth it.For reference, here are the codes used in the mini-language:You could use simple string formatting methods: can be used as well:Output:Another option:String concatenation, , can be used to build the string.You can convert datetime to string.Output --> 5/23/2017
Python

How do I use a progress bar when my script is doing some task that is likely to take time?For example, a function which takes some time to complete and returns  when done. How can I display a progress bar during the time the function is being executed?Note that I need this to be in real time, so I can't figure out what to do about it. Do I need a  for this? I have no idea.Right now I am not printing anything while the function is being executed, however a progress bar would be nice. Also I am more interested in how this can be done from a code point of view.There are specific libraries () but maybe something very simple would do:Note: this progressbar is a fork of  which hasn't been maintained in years.With  you can add a progress meter to your loops in a second:The above suggestions are pretty good, but I think most people just want a ready made solution, with no dependencies on external packages, but is also reusable. I got the best points of all the above, and made it into a function, along with a test cases.To use it, just copy the lines under \"def update_progress(progress)\" but not the test script. Don't forget to import sys. Call this whenever you need to display or update the progress bar.This works by directly sending the \"\\r\" symbol to console to move cursor back to the start. \"print\" in python does not recongise the above symbol for this purpose, hence we need 'sys'This is what the result of the test script shows (The last progress bar animates):for a similar application (keeping track of the progress in a loop) I simply used the :Their example goes something like this,Try progress from .The result will be a bar like the following:I really like the , as it is very simple to use.For the most simple case, it is just:The appearance can be customized and it can display the estimated remaining time. For an example use the same code as above but with:I've just made a simple progress class for my needs after searching here for a equivalent solution. I tough I might a well post it.Example :Will print the following:Use this library:  ().Usage:Have fun!Many of the answers above rely on external packages, but I also think (as some above stated) that most people just want a ready made solution. The code bellow can be adapted to fit your needs by customizing the string part. It is simpler and works without the need of a second thread to update the bar. Some packages above do that. A second thread can be a problem for example for a ipython notebook.The code bellow only works with iterators that provide a length (i.e. len(iterator) must be defined).Example:Output:...... can be any iterable object with a , e.g.  ['a', 'b', 'c']` works just fine.If your work can't be broken down into measurable chunks, you could call your function in a new thread and time how long it takes:You can obviously increase the timing precision as required.Here's a short solution that builds the loading bar programmatically (you must decide how long you want it).I like this .Starts with simple example and moves onto a multi-threaded version. Works out of the box. No 3rd party packages required.The code will look something like this:Or here is example to use threads in order to run the spinning loading bar while the program is running:You should link the progress bar to the task at hand (so that it measures the progress :D). For example, if you are FTPing a file, you can tell ftplib to grab a certain size buffer, let's say 128K, and then you add to your progress bar whatever percentage of the filesize 128k represents. If you are using the CLI, and your progress meter is 20 characters long, you would add one character when 1/20th of the file had transferred.@Massagran: It works well in my programs. Furthermore, we need to add a counter to indicate the loop times. This counter plays as the argument of the method .\nFor example: read all lines of a test file and treat them on something. Suppose that the function  do not concern in the variable .The variable  controls the status of  via the method 
Python

I'm unsure about (1).As for (2), I believe Python flushes to stdout after every new line.  But, if you overload stdout to be to a file, does it flush as often?For file operations, Python uses the operating system's default buffering unless you configure it do otherwise.  You can specify a buffer size, unbuffered, or line buffered.For example, the open function takes a buffer size argument.\"The optional buffering argument specifies the file\u2019s desired buffer size: \" You can also force flush the buffer to a file programmatically with the  method.I have found this useful when tailing an output file with .I don't know if this applies to python as well, but I think it depends on the operating system that you are running.On Linux for example, output to terminal flushes the buffer on a newline, whereas for output to files it only flushes when the buffer is full (by default).  This is because it is more efficient to flush the buffer fewer times, and the user is less likely to notice if the output is not flushed on a newline in a file.  You might be able to auto-flush the output if that is what you need.EDIT:  I think you would auto-flush in python this way (based \nfrom )You can also check the default buffer size by calling the read only DEFAULT_BUFFER_SIZE attribute from io module.Here is another approach, up to the OP to choose which one he prefers.When including the code below in the .py file before any other code, messages printed with  and any errors will no longer be logged to Ableton's Log.txt but to separate files on your disk:(for Mac, change  to the name of your user folder. On Windows the path to your user folder will have a different format)When you open the files in a text editor that refreshes its content when the file on disk is changed (example for Mac: TextEdit does not but TextWrangler does), you will see the logs being updated in real-time.
Python

My Django unit tests take a long time to run, so I'm looking for ways to speed that up. I'm considering installing an , but I know that has its downsides too. Of course, there are things I could do with my code, but I'm looking for a structural fix. Even running a single test is slow since the database needs to be rebuilt / south migrated every time. So here's my idea...Since I know the test database will always be quite small, why can't I just configure the system to always keep the entire test database in RAM? Never touch the disk at all. How do I configure this in Django?  I'd prefer to keep using  since that's what I use in production, but if \u00a03 or something else makes this easy, I'd go that way.Does SQLite or MySQL have an option to run entirely in memory? It should be possible to configure a RAM disk and then configure the test database to store its data there, but I'm not sure how to tell Django / MySQL to use a different data directory for a certain database, especially since it keeps getting erased and recreated each run. (I'm on a Mac FWIW.)If you set your database engine to sqlite3 when you run your tests, .I'm using code like this in my  to set the engine to sqlite when running my tests:Or in Django 1.2:And finally in Django 1.3 and 1.4:(The full path to the backend isn't strictly necessary with Django 1.3, but makes the setting forward compatible.)You can also add the following line, in case you are having problems with South migrations:I usually create a separate settings file for tests and use it in test command e.g.It has two benefits:MySQL supports a storage engine called \"MEMORY\", which you can configure in your database config () as such:Note that the MEMORY storage engine doesn't support blob / text columns, so if you're using  this won't work for you.I can't answer your main question, but there are a couple of things that you can do to speed things up.Firstly, make sure that your MySQL database is set up to use InnoDB. Then it can use transactions to rollback the state of the db before each test, which in my experience has led to a massive speed-up. You can pass a database init command in your settings.py (Django 1.2 syntax):Secondly, you don't need to run the South migrations each time. Set  in your settings.py and the database will be created with plain syncdb, which will be much quicker than running through all the historic migrations.You can do double tweaking:I'm using both tricks and I'm quite happy.How to set up it for MySQL on Ubuntu:Beware, it's just for testing, after reboot your database from memory is lost!Extending on Anurag's answer I simplified the process by creating the same test_settings and adding the following to manage.pyseems cleaner since sys is already imported and manage.py is only used via command line, so no need to clutter up settingsAnother approach: have another instance of MySQL running in a tempfs that uses a RAM Disk. Instructions in this blog post:.Advantages: 
Python

I am looking to format a number like 188518982.18 to \u00a3188,518,982.18 using Python.How can I do this?See the  module.This does currency (and date) formatting.Not quite sure why it's not mentioned more online (or on this thread), but the  package (and Django utilities) from the Edgewall guys is awesome for currency formatting (and lots of other i18n tasks).  It's nice because it doesn't suffer from the need to do everything globally like the core Python locale module.The example the OP gave would simply be:My locale settings seemed incomplete, so I had too look beyond this SO answer and found: OS-independentJust wanted to share here.If you are using OSX and have yet to set your locale module setting this first answer will not work you will receive the following error:To remedy this you will have to do use the following:Oh, that's an interesting beast.I've spent considerable time of getting that right, there are three main issues that differs from locale to locale:\n - currency symbol and direction\n - thousand separator\n - decimal pointI've written my own rather extensive implementation of this which is part of the kiwi python framework, check out the LGPL:ed source here:The code is slightly Linux/Glibc specific, but shouldn't be too difficult to adopt to windows or other unixes.Once you have that installed you can do the following:Which will then give you:orDepending on the currently selected locale.The main point this post has over the other is that it will work with older versions of python. locale.currency was introduced in python 2.5.This is an ancient post, but I just implemented the following solution which:Code:Output:And for the original poster, obviously, just switch  for I've come to look at the same thing and found  not really used it yet but maybe a mix of the two would be goodA lambda for calculating it inside a function, with help from and then,#printing  the variable 'Total:' in a format that looks like this '9,348.237'where the '{:7,.3f}' es the number of spaces for formatting the number in this case is a million with 3 decimal points.\nThen you add the '.format(zum1).  The zum1 is tha variable that has the big number for the sum of all number in my particular program.  Variable can be anything that you decide to use.
Python

Edit: Since it appears that there's either no solution, or I'm doing something so non-standard that nobody knows - I'll revise my question to also ask: What is the best way to accomplish logging when a python app is making a lot of system calls?My app has two modes.  In interactive mode, I want all output to go to the screen as well as to a log file, including output from any system calls.  In daemon mode, all output goes to the log.  Daemon mode works great using os.dup2().  I can't find a way to \"tee\" all output to a log in interactive mode, without modifying each and every system call.In other words, I want the functionality of the command line 'tee' for any output generated by a python app, .To clarify: To redirect all output I do something like this, and it works great:The nice thing about this is that it requires no special print calls from the rest of the code.  The code also runs some shell commands, so it's nice not having to deal with each of their output individually as well.Simply, I want to do the same, except  instead of redirect.At first blush, I thought that simply reversing the dup2's should work.  Why doesn't it?  Here's my test: The file \"a.log\" should be identical to what was displayed on the screen.Since you're comfortable spawning external processes from your code, you could use  itself.  I don't know of any Unix system calls that do exactly what  does.You could also emulate  using the  package (or use  if you're using Python 2.5 or earlier).I had this same issue before and found this snippet very useful:from:   I would spin up a small class to write to two places at once...This is obviously quick-and-dirty.  Some notes:These are all straightforward enough that I'm comfortable leaving them as exercises for the reader.  The key insight here is that  just calls a \"file-like object\" that's assigned to .What you really want is  module from standard library.  Create a logger and attach two handlers, one would be writing to a file and the other to stdout or stderr.See   for detailsI wrote a  implementation in Python that should work for most cases, and it works on Windows also.Also, you can use it in combination with  module from Python if you want.(Ah, just re-read your question and see that this doesn't quite apply.)Here is a sample program that makes uses the .  This logging module has been in all versions since 2.3.  In this sample the logging is configurable by command line options.  In quite mode it will only log to a file, in normal mode it will log to both a file and the console.As described elsewhere, perhaps the best solution is to use the logging module directly:However, there are some (rare) occasions where you  to redirect stdout. I had this situation when I was extending django's runserver command which uses print: I didn't want to hack the django source but needed the print statements to go to a file.This is a way of redirecting stdout and stderr away from the shell using the logging module:You should only use this LogFile implementation if you really cannot use the logging module directly.Here is another solution, which is more general than the others -- it supports splitting output (written to ) to any number of file-like objects. There's no requirement that  itself is included.NOTE: This is a proof-of-concept. The implementation here is not complete, as it only wraps  of the file-like objects (e.g. ), leaving out members/properties/setattr, etc.  However, it is probably good enough for most people as it currently stands.What I like about it, other than its generality, is that it is clean in the sense it doesn't make any direct calls to , , , etc.To complete John T answer: I added an  and  method to use it as a context manager with the 'with' keyword, which gives this codeIt can then be used asanother solution using logging module:I know this question has been answered repeatedly, but for this I've taken the main answer from  answer and modified it so it contains the suggested flush and followed its linked revised version. I've also added the enter and exit as mentioned in  answer for use with the with statement. In addition, the  mentions to flush files using  so I've added that as well. I don't know if you  need that but its there.You can then use itor None of the answers above really seems to answer the problem posed.  I know this is an old thread, but I think this problem is a lot simpler than everyone is making it:Now this will repeat everything to the normal sys.stderr handler and your file.  Create another class  for .As per a request by @user5359531 in the comments under @John T's , here's a copy of the referenced post to the revised version of the linked discussion in that answer:I'm writing a script to run cmd-line scripts.  ( Because in some cases, there just is no viable substitute for a Linux command -- such as the case of rsync. )What I really wanted was to use the default python logging mechanism in every case where it was possible to do so, but to still capture any error when something went wrong that was unanticipated.This code seems to do the trick.  It may not be particularly elegant or efficient ( although it doesn't use string+=string, so at least it doesn't have that particular potential bottle-\nneck ).  I'm posting it in case it gives someone else any useful ideas.Obviously, if you're not as subject to whimsy as I am, replace LOG_IDENTIFIER with another string that you're not like to ever see someone write to a log.
Python

I want to run a script, which basicly shows things like:Now, at the moment, I use print to print the whole line AFTER the function has succeeded. However, I now want it to print \"Installing xxx...\" first, and AFTER the function has run, to add the \"DONE\" tag; but on the same line.Any ideas?You can use the  statement to do this without importing .The comma on the end of the  line prevents  from issuing a new line (you should note that there will be an extra space at the end of the output).\nSince the above does not work in Python 3, you can do this instead (again, without importing ):The print function accepts an  parameter which defaults to . Setting it to an empty string prevents it from issuing a new line at the end of the line.You can simply use this:and the output will beno need to overkill by . Pay attention to comma symbol at the end.\n to remove the newline insert at the end. Read more by Use  and . In this way, you have to add the new line by hand with  if you want to recreate the print functionality. I think that it might be unnecessary to use curses just for this. You must use backspace '' or ('') char to go back on previous position in console outputPython 3:This code will count from 0% to 100% on one line. Final value will be:Additional info about flush in this case here: None of the answers worked for me since they all paused until a new line was encountered. I wrote a simple helper:To test it: \"hello \" will first print out and flush to the screen before the sleep. After that you can use standard print.   will print without return carriagePrint has an optional end argument, it is what printed in the end.\nThe default is newline but you can change it to empty string. eg: print(\"hello world!\", end=\"\")If you want to overwrite the previous line (rather than continually adding to it), you can combine  with   at the end of the print statement. For example,will count 0 to 9, replacing the old number in the console. The  will print on the same line as the last counter, 9.In your case for the OP, this would allow the console to display percent complete of the install as a \"progress bar\", where you can define a begin and end character position, and update the markers in between.Just in case you have pre-stored the values in an array, you can call them in the following format:I found this solution, and it's working on Python 2.7
Python

I have a list with numeric strings, like so:I would like to convert every list element to integer, so it would look like this:I could do it using a loop, like so:Does it have to be so ugly? I'm sure there is a more pythonic way to do this in a one line of code. Please help me out.This is what list comprehensions are for:In Python 2.x another approach is to use :Note: in Python 3.x  returns a map object which you can convert to a list if you want:just a point,the list comprehension is more natural, whileis faster. Useful read: If you are intending on passing those integers to a function or method, consider this example:This construction is intentionally remarkably similar to list comprehensions mentioned by adamk. Without the square brackets, it's called a , and is a very memory-efficient way of passing a list of arguments to a method. A good discussion is available here: Another way,Another way to make it in Python 3:
Python

Lets say I have an numpy array a:And I would like to add a column of zeros to get array b:How can I do this easily in numpy?I think a more straightforward solution and faster to boot is to do the following:And timings: and \nare useful alternatives to  and ,\nwith square brackets [] instead of round ().\nA couple of examples:(The reason for square brackets [] instead of round ()\nis that Python expands e.g. 1:4 in square --\nthe wonders of overloading.)Use :While writing the question I came up with one way, using hstackAny other (more elegant solutions) welcome!I think:is more elegant.What I find most elegant is the following:An advantage of  is that it also allows you to insert columns (or rows) at other places inside the array. Also instead of inserting a single value you can easily insert a whole vector, for instance doublicate the last column:Which leads to:For the timing,  might be slower than JoshAdel's solution: also worksI like JoshAdel's answer because of the focus on performance. A minor performance improvement is to avoid the overhead of initializing with zeros, only to be overwritten. This has a measurable difference when N is large, empty is used instead of zeros, and the column of zeros is written as a separate step:A bit late to the party, but nobody posted this answer yet, so for the sake of completeness: you can do this with list comprehensions, on a plain Python array:I was also interested in this question and compared the speed ofwhich all to the same thing for any input vector . WithI foundLooks like / is what you want if you're looking for speed.Assuming  is a (100,3) ndarray and  is a (100,) ndarray  can be used as follows:The trick is to use This converts  to a (100, 1) 2D array.now gives
Python

I have to search through a list and replace all occurrences of one element with another. So far my attempts in code are getting me nowhere, what is the best way to do this?For example, suppose my list has the following integersand I need to replace all occurrences of the number 1 with the value 10 so the output I need is Thus my goal is to replace all instances of the number 1 with the number 10.Try using a  and the .List comprehension works well--and looping through with enumerate can save you some memory (b/c the operation's essentially be doing in place).There's also functional programming...see usage of :If you have several values to replace, you can also use a dictionary:The following is a very direct methodThis method works. Comments are welcome. Hope it helps :)
Python

This is a slightly.. vain question, but BuildBot's output isn't particularly nice to look at..For example, compared to....and others,  looks rather.. archaicI'm currently playing with Hudson, but it is very Java-centric (although with , I found it easier to setup than BuildBot, and produced more info)Basically: is there any Continuous Integration systems aimed at python, that produce lots of shiny graphs and the likes? Since this time the Jenkins project has replaced Hudson as the community version of the package. The original authors have moved to this project as well. Jenkins is now a standard package on Ubuntu/Debian, RedHat/Fedora/CentOS, and others. The following update is still essentially correct. The starting point to do this with  is different. After trying a few alternatives, I think I'll stick with Hudson.  was nice and simple, but quite limited. I think  is better suited to having numerous build-slaves, rather than everything running on a single machine like I was using it.Setting Hudson up for a Python project was pretty simple:That's all that's required. You can setup email notifications, and  are worth a look. A few I'm currently using for Python projects:You might want to check out  and .  You can have it run your unit tests, and coverage checks with this command:That'll be helpful if you want to go the Jenkins route, or if you want to use another CI server that has support for JUnit test reporting.Similarly you can capture the output of pylint using the Don't know if it would do :  is made by the guys who write Trac and is integrated with Trac.  is the CI tool used by Apache. It is written in Python.We've had great success with  as our CI server and using nose as our test runner.   gives you count pass/fail, readable display for failed test( that can be E-Mailed).  You can even see details of the test failures while you stack is running.  If of course supports things like running on multiple machines, and it's much simpler to setup and maintain than buildbot.Buildbot's waterfall page can be considerably prettified. Here's a nice example Atlassian's  is also definitely worth checking out.  The entire Atlassian suite (JIRA, Confluence, FishEye, etc) is pretty sweet.I guess this thread is quite old but here is my take on it with hudson:I decided to go with pip and set up a repo (the painful to get working but nice looking eggbasket), which hudson auto uploads to with a successful tests. Here is my rough and ready script for use with a hudson config execute script like: /var/lib/hudson/venv/main/bin/hudson_script.py -w $WORKSPACE -p my.package -v $BUILD_NUMBER, just put in **/coverage.xml, pylint.txt and nosetests.xml in the config bits:When it comes to deploying stuff you can do something like:And then people can develop stuff using:This stuff assumes you have a repo structure per package with a setup.py and dependencies all set up then you can just check out the trunk and run this stuff on it.I hope this helps someone out.------update---------I've added epydoc which fits in really nicely with hudson. Just add javadoc to your config with the html folderNote that pip doesn't support the -E flag properly these days, so you have to create your venv separatelyanother one :  is a hosted tool for pythonIf you're considering hosted CI solution, and doing open source, you should look into  as well - it has very nice integration with GitHub.  While it started as a Ruby tool, they have  a while ago.Signal is another option. You can know more about it and watch a video also .I would consider  - it has great Python support, and very pretty output.continuum's  now is able to trigger builds from github and can compile for linux, osx and windows ( 32 / 64 ). the neat thing is that it really allows you to closely couple distribution and continuous integration. That's crossing the t's and dotting the I's of Integration. The site, workflow and tools are really polished and AFAIK conda is the most robust and pythonic way to distributing complex python modules, where you need to wrap  distribute C/C++/Fotran libraries.We have used bitten quite a bit.  It is pretty and integrates well with Trac, but it is a pain in the butt to customize if you have any nonstandard workflow.  Also there just aren't as many plugins as there are for the more popular tools.  Currently we are evaluating Hudson as a replacement.Check . As  explains, it uses Docker for every build. Thanks to that, you can configure whatever you like inside your Docker image, including Python.Little disclaimer, I've actually had to build a solution like this for a client that wanted a way to automatically test and deploy  code on a git push plus manage the issue tickets via git notes. This also lead to my work on the .One could easily just setup a bare node system that has a build user and manage their build through , , /, and . One could even go a step further and use ansible and celery for distributed builds with a gridfs/nfs file store.Although, I would not expect anyone other than a Graybeard UNIX guy or Principle level engineer/architect to actually go this far. Just makes for a nice idea and potential learning experience since a build server is nothing more than a way to arbitrarily execute scripted tasks in an automated fashion.
Python

Is there a way to specify the running directory of command in python's  ?For example:My python script is located in Is is possible to run  in the directory  ?  How do I set the working directory for subprocess?  to set the Current Working Directory; you'll also want to escape your backslashes (), or use  so that the backslashes aren't interpreted as escape sequences by Python.  The way you have it written, the  part will be translated to a .So, your new line should look like:To use your Python script path as cwd,  and define cwd using this:
Python

Why does this code not input integers?  Everything on the web says to use , but I read on Stack Overflow (on a thread that did not deal with integer input) that  was renamed to  in Python 3.x.There were two functions to get user input, called  and . The difference between them is,  doesn't evaluate the data and returns as it is, in string form. But,  will evaluate whatever you entered and the result of evaluation will be returned. For example,The data  is evaluated and the result is . When it evaluates the expression , it detects that you are adding two numbers and so the result will also be of the same  type. So, the type conversion is done for free and  is returned as the result of  and stored in  variable. You can think of  as the  composed with an  call. you should be careful when you are using  in Python 2.x. I explained why one should be careful when using it, in .But,  doesn't evaluate the input and returns as it is, as a string.Python 3.x's  and Python 2.x's  are similar and  is not available in Python 3.x. To answer your question, since Python 3.x doesn't evaluate and convert the data type, you have to explicitly convert to s, with , like thisYou can accept numbers of any base and convert them directly to base-10 with the  function, like thisThe second parameter tells what is the base of the numbers entered and then internally it understands and converts it. If the entered data is wrong it will throw a .Apart from that, your program can be changed a little bit, like thisYou can get rid of the  variable by using  and . : Python doesn't expect  at the end of the line :)In Python 3.x,  was renamed to  and the Python 2.x  was removed.  This means that, just like ,  in Python 3.x always returns a string object.To fix the problem, you need to explicitly make those inputs into integers by putting them in :Also, Python does not need/use semicolons to end lines.  So, having them doesn't do anything positive. (Python 3) and  (Python 2)  return strings. Convert the result to integer explicitly with .Pro tip: semi-colons are not needed in Python.For multiple integer in a single line,  might be better.If the number is already known, (like 2 integers), you can useMultiple questions require input for several integers on single line.  The best way is to input the whole string of numbers one one line and then split them to integers.Python 3.x has  function which returns always string.So you must convert to \n\nIn python 2.x  and  functions always return string so you must convert them to int too.I encountered a problem of taking integer input while solving a problem on , where two integers - separated by space - should be read from one line.While  is sufficient for a single integer, I did not find a direct way to input two integers.  I tried this:Now I use num1 and  num2 as integers.  Hope this helps.Yes, in python 3.x,  is replaced with . In order to revert to old behavior of  use: This will let python know that entered input is integerConvert to integers:Similarly for floating point numbers:While in your example,  does the trick in any case, 's  is worth consideration since that makes sure your code works for both Python 2 and 3  disables Python2's default behaviour of  trying to be \"clever\" about the input data type ( basically just behaves like ).Taking int as input in python:\nwe take a simple string input using:now we want int as input.so we typecast this string to int. simply using:
Python

I'm thinking about putting the virtualenv for a Django web app I am making inside my git repository for the app. It seems like an easy way to keep deploy's simple and easy. Is there any reason why I shouldn't do this?I'm totally new to virtualenv, so there is a good chance this is a really stupid question.I use  to get the packages I need into a  file and add that to my repository.  I tried to think of a way of why you would want to store the entire virtualenv, but I could not.I used to do the same until I started using libraries that are compiled differently depending on the environment such as PyCrypto. My PyCrypto mac wouldn't work on Cygwin wouldn't work on Ubuntu.It becomes an utter nightmare to manage the repository.Either way I found it easier to manage the pip freeze & a requirements file than having it all in git. It's cleaner too since you get to avoid the commit spam for thousands of files as those libraries get updated...  Storing the virtualenv directory inside git will, as you noted, allow you to deploy the whole app by just doing a git clone (plus installing and configuring Apache/mod_wsgi).  One potentially significant issue with this approach is that on Linux the full path gets hard-coded in the venv's activate, django-admin.py, easy_install, and pip scripts.  This means your virtualenv won't entirely work if you want to use a different path, perhaps to run multiple virtual hosts on the same server.  I think the website may actually work with the paths wrong in those files, but you would have problems the next time you tried to run pip.The solution, already given, is to store enough information in git so that during the deploy you can create the virtualenv and do the necessary pip installs.  Typically people run  to get the list then store it in a file named requirements.txt.  It can be loaded with .  RyanBrady already showed how you can string the deploy statements in a single line:  Personally, I just put these in a shell script that I run after doing the git clone or git pull.Storing the virtualenv directory also makes it a bit trickier to handle pip upgrades, as you'll have to manually add/remove and commit the files resulting from the upgrade.  With a requirements.txt file, you just change the appropriate lines in requirements.txt and re-run .  As already noted, this also reduces \"commit spam\".I think one of the main problems which occur is that the virtualenv might not be usable by other people. Reason is that it always use absolute path's. So if you virtualenv was for example in  it will assume the same for all other people using this repository (it must be exactly the same absolute path). You can't presume people using the same directory structure as you.Better practice is that everybody is setting up their own environment (be it with or without virtualenv) and installing libraries there. That also makes you code more usable over different platforms (Linux/Windows/Mac), also because virtualenv is installed different in each of them.If you know which operating systems your application will be running on, I would create one virtualenv for each system and include it in my repository. Then I would make my application detect which system it is running on and use the corresponding virtualenv.The system could e.g. be identified using the  module.In fact, this is what I do with an in-house application I have written, and to which I can quickly add a new system's virtualenv in case it is needed. This way, I do not have to rely on that pip will be able to successfully download the software my application requires. I will also not have to worry about compilation of e.g.  which I use.If you do not know which operating system your application may run on, you are probably better off using  as suggested in other answers here.If you just setting up development env, then use pip freeze file, caz that makes the git repo clean.Then if doing production deployment, then checkin the whole venv folder. That will make your deployment more reproducible, not need those libxxx-dev packages, and avoid the internet issues.So there are two repos. One for your main source code, which includes a requirements.txt. And a env repo, which contains the whole venv folder. 
Python

I have form with one input for email and two submit buttons to subscribe and unsubscribe from newsletter:I have also class form:I must write my own clean_email method and I need to know by which button was form submited. But the value of submit buttons aren't in  dictionary.\nCould I get values of buttons otherwise?You can use  in the  method to access the POST data before validation. It should contain a key called  or  depending on which button was pressed.Eg:You can also do like this, It's an old question now, nevertheless I had the same issue and found a solution that works for me: I wrote MultiRedirectMixin.one url to the same view! \nlike so!
Python

I've read every other google source and SO thread, with nothing working. installed on . Download, extracting, and then trying to install PyCrypto results in So I install MinGW and tack that on the install line as the compiler of choice. But then I get the error How in the world do I get around this? I've tried using pip, which gives the same result. I found a prebuilt PyCrypto 2.3 binary and installed that, but it's nowhere to be found on the system (not working).Any ideas?If you don't already have a C/C++ development environment installed that is compatible with the Visual Studio binaries distributed by Python.org, then you should stick to installing only pure Python packages or packages for which a Windows binary is available.Fortunately, there are PyCrypto binaries available for Windows:\n\nAs @Udi suggests in the comment below, the following command also installs  and can be used in  as well:Notice to choose the relevant link for your setup from If you're looking for builds for Python 3.5, see Microsoft has recently recently released a standalone, dedicated . If you're using Python 2.7, simply install that compiler and Setuptools 6.0 or later, and most packages with C extensions will now compile readily. is part of the Visual C++ compiler, you need that to install what you are trying to install. Don't even try to deal with MingGW if your Python was compiled with Visual Studio toolchain and vice versa. Even the  of the Microsoft tool chain is important. Python compiled with VS 2008 won't work with extensions compiled with VS 2010!You have to compile PyCrypto with the same compiler that the version of Python was compiled with. Google for  because that is the root of your problem,  As far as I know the following is still true. This was posted in the link above in June, 2010 referring to trying to build extensions with VS 2010 Express against the Python installers available on python.org.For VS2010:For VS2012:then Call:, python finally agreed for a binary disribution called  which allows to install even binary extensions on Windows without having a compiler with simple . There is a  with their status. Pycrypto is not there yet, but lxml, PySide and Scrapy for example. : . It is a  fork with new features and it supports wheel. It replaces  (see ) is an almost-compatible fork of PyCrypto with Windows wheels available on .You can install it with a simple:The website includes instructions to build it from sources with the Microsoft compilers too.I have managed to get  to compile by using  and . This presumes that you have  or  installed.Here's how I did it:1) Install . For the sake of this explanation, let's assume it's installed in . When using the installer, which I recommend, select the C++ compiler  MSYS should install with 2) Add  to your . If you aren't familiar,  is very helpful.3) From the search bar, run  and the MSYS terminal will open. For those familiar with , it works in a similar fashion.4) From within the MSYS terminal  should run without error after this.  It's possible to build PyCrypto using the Windows 7 SDK toolkits. There are two versions of the Windows 7 SDK. The original version (for .Net 3.5) includes the VS 2008 command-line compilers. Both 32- and 64-bit compilers can be installed.The first step is to compile  to provide fast arithmetic. I've documented the process I use in the  library. Detailed instructions for building mpir using the SDK compiler can be found at The key steps to use the SDK compilers from a DOS prompt are:1) Run either vcvars32.bat or vcvars64.bat as appropriate.2) At the prompt, execute \"set MSSdk=1\"3) At the prompt, execute \"set DISTUTILS_USE_SDK=1\"This should allow \"python setup.py install\" to succeed assuming there are no other issues  with the C code. But I vaaguely remember that I had to edit a couple of PyCrypto files to enable mpir and to find the mpir libraries but I don't have my Windows system up at the moment. It will be a couple of days before I'll have time to recreate the steps. If you haven't reported success by then, I'll post the PyCrypto steps. The steps will assume you were able to compile mpir.I hope this helps. For those of you looking for python 3.4 I found a  with an installer that just works. Here are the direct links for  and To install Pycrypto in Windows,Try this in Command Prompt,Set path=C:\\Python27\\Scripts (i.e path where easy_install is located)Then execute the following,easy_install pycryptoTry this,Download Pycrypto from \"\"Then change your current path to downloaded path using your terminal and user should be root:Eg: root@xyz-virtual-machine:~/pycrypto-2.6.1#Then execute the following using the terminal:python setup.py installIt's worked for me. Hope works for all..This probably isn't the optimal solution but you might download and install the free Visual C++ Express package from MS. This will give you the C++ compiler you need to compile the PyCrypto code.This error  occurs because the install script didn't find the  command.You only need to .(N.B: Note that MinGW comes with MSYS so )For example, if we are in folder \nOptional: you might need to clean before you re-run the script:You need to install msys package under MinGW and add following entries in your PATH env variable.Then run your command from normal windows command prompt.Due to weird legal reasons, binaries are not published the normal way. Voidspace is normally the best second source. But since quite some time, voidspace maintainer did not update. \nUse the zip from [Try just using:or:Source: 
Python

I need some help on declaring a regex. My inputs are like the following:The required output is:I've tried this:I've also tried this (but it seems like I'm using the wrong regex syntax):I dont want to hard-code the  from 1 to 99 . . .This tested snippet should do it: Here's a commented version explaining how it works:Regexes are  But I would strongly recommend spending an hour or two studying the basics. For starters, you need to learn which characters are special:  which need to be escaped (i.e. with a backslash placed in front - and the rules are different inside and outside character classes.) There is an excellent online tutorial at: . The time you spend there will pay for itself many times over. Happy regexing! does fixed replacements. Use  instead.The easiest wayI would go like this (regex explained in comments):If you want to learn more about regex I recomend to read  by  Jan Goyvaerts and Steven Levithan.replace method of string objects does not accept regular expressions but only fixed strings (see documentation: ).You have to use  module:don't have to use regular expression (for your sample string)
Python

I need to remove all special characters, punctuation and spaces from a string so that I only have letters and numbers.This can be done without :You can use :If you insist on using , other solutions will do fine. However note that if it can be done without using a regular expression, that's the best way to go about it.Here is a regex to match a string of characters that are not a letters or numbers:Here is the Python command to do a regex substitution:Shorter way  :If you want spaces between words and numbers substitute '' with ' 'you can add more special character and that will be replaced by '' means nothing i.e they will be removed.I think just  worksThe most generic approach is using the 'categories' of the unicodedata table which classifies every single character. E.g. the following code filters only printable characters based on their category:Look at the given URL above for all related categories. You also can of course filter\nby the punctuation categories.After seeing this, I was interested in expanding on the provided answers by finding out which executes in the least amount of time, so I went through and checked some of the proposed answers with  against two of the example strings:The above results are a product of the lowest returned result from an average of:  can be 3x faster than .Assuming you want to use a regex and you want/need Unicode-cognisant 2.x code that is 2to3-ready:Use translate:Caveat: Only works on ascii strings.and you shall see your result as 'askhnlaskdjalsdk
Python

Is there any short way to achieve what the APT () command line interface does in Python?I mean, when the package manager prompts a yes/no question followed by , the script accepts  or  (defaults to  as hinted by the capital letter).The only thing I find in the official docs is  and ...I know it's not that hard to emulate, but it's annoying to rewrite :|As you mentioned, the easiest way is to use . There is no built-in way to do this. From :Usage example:I'd do it this way:There is a function  in Python's standard library: You can use it to check user's input and transform it to  or  value.A very simple (but not very sophisticated) way of doing this for a single choice would be:You could also write a simple (slightly improved) function around this:as mentioned by @Alexander Artemenko, here's a simple solution using strtoboolI know this has been answered a bunch of ways and this may not answer OP's specific question (with the list of criteria) but this is what I did for the most common use case and it's far simpler than the other responses:You can also use .Shamelessly taken from the README:I modified fmark's answer to by python 2/3 compatible more pythonic.See  if you are interested in something with more error handlingYou could try something like the code below to be able to work with choices from the variable 'accepted' show here:Here is the code ..on 2.7, is this too non-pythonic?it captures any variation of Yes at least.Doing the same with python 3.x, where  doesn't exist:How about this: This is what I use:This is how I'd do it.OutputHere's my take on it, I simply wanted to abort if the user did not affirm the action.You can use 's  method.This will print:Should work for  on Linux, Mac or Windows.Docs: 
Python

I have a  as part of an object, and wish to encode this to a JSON string which should look like . I don't care about precision on the client side, so a float is fine.Is there a good way to serialize this? JSONDecoder doesn't accept Decimal objects, and converting to a float beforehand yields  which is wrong, and will be a big waste of bandwidth.How about subclassing ?Then use it like so: and higher has native support for Decimal type:Note that  is  by default:So:Hopefully, this feature will be included in standard library.I would like to let everyone know that I tried Micha\u0142 Marczyk's answer on my web server that was running Python 2.6.5 and it worked fine. However, I upgraded to Python 2.7 and it stopped working. I tried to think of some sort of way to encode Decimal objects and this is what I came up with:This should hopefully help anyone who is having problems with Python 2.7. I tested it and it seems to work fine. If anyone notices any bugs in my solution or comes up with a better way, please let me know.I tried switching from simplejson to builtin json for GAE 2.7, and had issues with the decimal. If default returned str(o) there were quotes (because _iterencode calls _iterencode on the results of default), and float(o) would remove trailing 0.If default returns an object of a class that inherits from float (or anything that calls repr without additional formatting) and has a custom __repr__ method, it seems to work like I want it to. can not be exactly represented in IEEE floats, it will always come as , e.g. try  , you can read more about it here:  \n  So if you don't want float, only option you have to send it as string, and to allow automatic conversion of decimal objects to JSON, do something like this:In my Flask app, Which uses python 2.7.11, flask alchemy(with 'db.decimal' types), and Flask Marshmallow ( for 'instant' serializer and deserializer), i had this error, every time i did a GET or POST. The serializer and deserializer, failed to convert  Decimal types into any JSON identifiable format. I did a  \"pip install simplejson\", then \nJust by addingthe serializer and deserializer starts to purr again. I did nothing else...\nDEciamls are displayed as '234.00' float format.This is what I have, extracted from our classWhich passes unittest:My $.02!I extend a bunch of the JSON encoder since I am serializing tons of data for my web server. Here's some nice code. Note that it's easily extendable to pretty much any data format you feel like and will reproduce 3.9 as Makes my life so much easier...this can be done by adding in , but I was hoping for a better solution
Python

I want to do something similar to this:But this is not supported by python lists\nWhat is the best way of doing it?Use a list comprehension:If you want to use the  infix syntax, you can just do:you can then use it like: But if you don't absolutely need list properties (for example, ordering), just use sets as the other answers recommend.Use Or you might just have x and y be sets so you don't have to do any conversions.That is a \"set subtraction\" operation. Use the set data structure for that.In Python 2.7:Output:if duplicate and ordering items are problem :For many use cases, the answer you want is:This is a hybrid between  and .aaronasterling's version does  item comparisons for each element in , so it takes quadratic time. quantumSoup's version uses sets, so it does a single constant-time set lookup for each element in \u2014but, because it converts   and  into sets, it loses the order of your elements.By converting only  into a set, and iterating  in order, you get the best of both worlds\u2014linear time, and order preservation.*However, this still has a problem from quantumSoup's version: It requires your elements to be hashable. That's pretty much built into the nature of sets.** If you're trying to, e.g., subtract a list of dicts from another list of dicts, but the list to subtract is large, what do you do?If you can decorate your values in some way that they're hashable, that solves the problem. For example, with a flat dictionary whose values are themselves hashable:If your types are a bit more complicated (e.g., often you're dealing with JSON-compatible values, which are hashable, or lists or dicts whose values are recursively the same type), you can still use this solution. But some types just can't be converted into anything hashable.If your items aren't, and can't be made, hashable, but they are comparable, you can at least get log-linear time (, which is a lot better than the  time of the list solution, but not as good as the  time of the set solution) by sorting and using :If your items are neither hashable nor comparable, then you're stuck with the quadratic solution.Try this.Looking up values in sets are faster than looking them up in lists:I believe this will scale slightly better than:Both preserve the order of the lists.This example subtracts two lists:
Python

Why such structuregives an error ?Default argument values are evaluated at function define-time, but  is an argument only available at function call time. Thus arguments in the argument list cannot refer each other.It's a common pattern to default an argument to  and add a test for that in code:For cases where you also wish to have the option of setting 'b' to None:
Python

I'm wondering if there's any way to tell pip, specifically in a requirements file, to install a package with both a minimum version () and a maximum version which should never be installed (theoretical api: ).I ask because I am using a third party library that's in active development. I'd like my pip requirements file to specify that it should always install the most recent minor release of the 0.5.x branch, but I don't want pip to ever try to install any newer major versions (like 0.6.x) since the API is different.  This is important because even though the 0.6.x branch is available, the devs are still releasing patches and bugfixes to the 0.5.x branch, so I don't want to use a static  line in my requirements file.Is there any way to do that?You can do:And  will look for the best match, assuming the version is at least 0.2, and less than 0.3.This also applies to pip .  See the full details on version specifiers in .
Python

In python 2.7, we got the  available.Now, I know the pro and cons of the following:What are  (and the like) for? What are their benefits? How does it work? What is a view after all?I read that the view is always reflecting the changes from the dictionary. But how does it behave from the perf and memory point of view? What are the pro and cons?Dictionary views are essentially what their name says:  on the keys and values (or items) of a dictionary.  Here is an excerpt from the  for Python\u00a03:(The Python\u00a02 equivalent uses  and .)This example shows the : the keys view is  a copy of the keys at a given point in time, but rather a simple window that shows you the keys; if they are changed, then what you see through the window does change as well.  This feature can be useful in some circumstances (for instance, one can work with a view on the keys in multiple parts of a program instead of recalculating the current list of keys each time they are needed).One advantage is that  at, say, the keys uses only  and requires , as there is no creation of a list of keys (Python\u00a02, on the other hand, often unnecessarily creates a new list, as quoted by Rajendran T, which takes memory and time in an amount proportional to the length of the list).  To continue the window analogy, if you want to see a landscape behind a wall, you simply make an opening in it (you build a window); copying the keys into a list would correspond to instead painting a copy of the landscape on your wall\u2014the copy takes time, space, and does not update itself.To summarize, views are simply\u2026 views (windows) on your dictionary, which show the contents of the dictionary even after it changes.  They offer features that differ from those of lists: a list of keys contain a  of the dictionary keys at a given point in time, while a view is dynamic and is much faster to obtain, as it does not have to copy any data (keys or values) in order to be created.The view methods return a list(not a copy of the list, compared to ,  and ), so it is more lightweight, but reflects the current contents of dictionary.From As you mentioned  returns a copy of the dictionary\u2019s list of (key, value) pairs which is wasteful and  returns an iterator over the dictionary\u2019s (key, value) pairs.Now take the following example to see the difference between an interator of dict and a view of dictWhereas a view simply shows you what's in the dict. It doesn't care if it changed:A view is simply a what the dictionary looks like now. After deleting an entry  would have been out-of-date and  would have thrown an error.Just from reading the docs I get this impression:So I guess the key usecase is if you're keeping a dictionary around and repeatedly iterating over its keys/items/values with modifications in between. You could just use a view instead, turning  into . But if you're just iterating over the dictionary once, I think the iter- versions are still preferable.
Python

I've recently moved over to using IPython notebooks as part of my workflow.  However, I've not been successful in finding a way to import .py files into the individual cells of an open IPython notebook so that they can edited, run and then saved. Can this be done?I've found  in the documentation which tells me how to import .py files as new notebooks but this falls short of what I want to achieve.Any suggestions would be much appreciated,\nthanks in advance.A text file can be loaded in a notebook cell with the magic command .If you execute a cell containing:the content of  will be loaded in the next cell. You can edit and execute it as usual.To save the cell content back into a file add the cell-magic  at the beginning of the cell and run it. Beware that if a file with the same name already exists .To see the help for any magic command add a : like  or .For general help on magic functions type \"%magic\"\nFor a list of the available magic functions, use %lsmagic. For a description\nof any of them, type %magic_name?, e.g. '%cd?'.: Starting from IPython 3 (now Jupyter project), the notebook has a text editor that can be used as a more convenient alternative to load/edit/save text files.  Beside the cell magic commands, IPython notebook (now Jupyter notebook) is so cool that it allows you to use any unix command right from the cell (this is also equivalent to using the  cell magic command).To run a unix command from the cell, just precede your command with  mark. for example:Also, see  for further explanation with examples.\nHope this helps.Drag and drop a Python file in the Ipython notebooks \"home\" notebooks table, click upload. This will create a new notebook with only one cell containing your .py file contentElse copy/paste from your favorite editor ;)I have found it satisfactory to use ls and cd within ipython notebook to find the file. Then type cat your_file_name into the cell, and you'll get back the contents of the file, which you can then paste into the cell as code.
Python

I keep important settings like the hostnames and ports of development and production servers in my version control system. But I know that it's  to keep  (like private keys and database passwords) in a VCS repository.But passwords--like any other setting--seem like they should be versioned. So what  the proper way to keep passwords version controlled?I imagine it would involve keeping the  in their own \"secrets settings\" file and having  file encrypted and version controlled. But what technologies? And how to do this properly? Is there a better way entirely to go about it?I ask the question generally, but in my specific instance I would like to store secret keys and passwords for a  site using  and .Also, an  solution would do something magical when I push/pull with git--e.g., if the encrypted passwords file changes a script is run which asks for a password and decrypts it into place.You're exactly right to want to encrypt your sensitive settings file while still maintaining the file in version control. As you mention, the best solution would be one in which Git will transparently encrypt certain sensitive files when you push them so that locally (i.e. on any machine which has your certificate) you can use the settings file, but Git or Dropbox or whoever is storing your files under VC does not have the ability to read the information in plaintext.This gist  shows a tutorial on how to use the Git's smudge/clean filter driver with openssl to transparently encrypt pushed files. You just need to do some initial setup.You'll basically be creating a  folder containing 3 bash scripts,which are used by Git for decryption, encryption, and supporting Git diff. A master passphrase and salt (fixed!) is defined inside these scripts and you MUST ensure that .gitencrypt is never actually pushed.\nExample  script:Similar for  and . See Gist.Your repo with sensitive information should have a .gitattribute file (unencrypted and included in repo) which references the .gitencrypt directory (which contains everything Git needs to encrypt/decrypt the project transparently) and which is present on your local machine. contents:Finally, you will also need to add the following content to your  fileNow, when you push the repository containing your sensitive information to a remote repository, the files will be transparently encrypted. When you pull from a local machine which has the .gitencrypt directory (containing your passphrase), the files will be transparently decrypted.I should note that this tutorial does not describe a way to only encrypt your sensitive settings file. This will transparently encrypt the entire repository that is pushed to the remote VC host and decrypt the entire repository so it is entirely decrypted locally. To achieve the behavior you want, you could place sensitive files for one or many projects in one sensitive_settings_repo. You could investigate how this transparent encryption technique works with Git submodules  if you really need the sensitive files to be in the same repository.The use of a fixed passphrase could theoretically lead to brute-force vulnerabilities if attackers had access to many encrypted repos/files. IMO, the probability of this is very low. As a note at the bottom of this tutorial mentions, not using a fixed passphrase will result in local versions of a repo on different machines always showing that changes have occurred with 'git status'.Heroku pushes  for settings and secret keys:With Foreman and  files Heroku provide an enviable toolchain to export, import and synchronise environment variables.Personally, I believe it's wrong to save secret keys alongside code. It's fundamentally inconsistent with source control, because the keys are for services . The one boon would be that a developer can clone HEAD and run the application without any setup. However, suppose a developer checks out a historic revision of the code. Their copy will include last year's database password, so the application will fail against today's database.With the Heroku method above, a developer can checkout last year's app, configure it with today's keys, and run it successfully against today's database. The cleanest way in my opinion is to use environment variables. You won't have to deal with  files for example, and the project state on the production environment would be the same as your local machine's. I recommend reading 's config chapter, the others too if you're interested.   An option would be to put project-bound credentials into an encrypted container (TrueCrypt or Keepass) and push it.Interesting question btw. I just found this:  which looks very promising for automatic encryptionI suggest using configuration files for that and to not version them.You can however version examples of the files.I don't see any problem of sharing development settings. By definition it should contain no valuable data. was recently released by StackExchange and while I have yet to use it, it seems to exactly address the problems and support the features requested in this question.From the description on :I think GnuPG is the best way to go - it's already used in one git-related project (git-annex) to encrypt repository contents stored on cloud services. GnuPG (gnu pgp) provides a  strong key-based encryption.Now if your 'mypassword' file did not change then encrypting it will result with same ciphertext and it won't be added to the index (no redundancy). Slightest modification of mypassword results in radically different ciphertext and mypassword.gpg in staging area differs a lot from the one in repository, thus will be added to the commit. Even if the attacker gets a hold of your gpg key he still needs to bruteforce the password. If the attacker gets an access to remote repository with ciphertext he can compare a bunch of ciphertexts, but their number won't be sufficient to give him any non-negligible advantage.Later on you can use .gitattributes to provide an on-the-fly decryption for quit git diff of your password.Also you can have separate keys for different types of passwords etc.No, just don't, even if it's your private repo and you never intend to share it, don't.You should create a local_settings.py put it on VCS ignore and in your settings.py do something likeIf your secrets settings are that versatile, I am eager to say you're doing something wrongThis is the best way to manage a set of sane defaults for the config you checkin without requiring the config be complete, or contain things like hostnames and credentials.  There are a few ways to override default configs.Environment variables (as others have already mentioned) are one way of doing it.The best way is to look for an external config file that overrides the default config values.  This allows you to manage the external configs via a configuration management system like Chef, Puppet or Cfengine.  Configuration management is the standard answer for the management of configs separate from the codebase so you don't have to do a release to update the config on a single host or a group of hosts. Encrypting creds is not always a best practice, especially in a place with limited resources.  It may be the case that encrypting creds will gain you no additional risk mitigation and simply add an unnecessary layer of complexity.  Make sure you do the proper analysis before making a decision.Usually, i seperate password as a config file. and make them dist.And when i run , put the real password in  that copied.ps. when you work with git or hg. you can ignore  files to make  or Encrypt the passwords file, using for example GPG. Add the keys on your local machine and on your server. Decrypt the file and put it outside your repo folders.I use a passwords.conf, located in my homefolder. On every deploy this file gets updated. No, private keys and passwords do not fall under revision control. There is no reason to  burden everyone with read access to your repository with knowing sensitive service credentials used in production, when most likely not all of them should have access to those services.Starting with Django 1.4, your Django projects now ship with a  module that defines the  and it's a perfect place to start enforcing the use of a  settings module that contains site-specific configurations. This settings module is ignored from revision control, but it's presence is required when running your project instance as a WSGI application, typical for production environments. This is how it should look like:Now you can have a  module who's owner and group can be configured so that only authorized personnel and the Django processes can read the file's contents.If you need VCS for your secrets you should at least keep them in a second repository seperated from you actual code. So you can give your team members access to the source code repository and they won't see your credentials. Furthermore host this repository somewhere else (eg. on your own server with an encrypted filesystem, not on github) and for checking it out to the production system you could use something like .Another approach could be to completely avoid saving secrets in version control systems and instead use a tool like , a secret storage with key rolling and auditing, with an API and embedded encryption.Since asking this question I have settled on a solution, which I use when developing small application with a small team of people.git-crypt uses GPG to transparently encrypt files when their names match certain patterns. For intance, if you add to your  file......then a file like  will always be pushed to remote repos with encryption, but remain unencrypted on your local file system.If I want to add a new GPG key (a person) to your repo which can decrypt the protected files then run . This creates a new commit. The new user will be able to decrypt subsequent commits.You could use EncFS if your system provides that. Thus you could keep your encrypted data as a subfolder of your repository, while providing your application a decrypted view to the data mounted aside. As the encryption is transparent, no special operations are needed on pull or push. It would however need to mount the EncFS folders, which could be done by your application based on an password stored elsewhere outside the versioned folders (eg. environment variables).
Python

Why in this millenium should Python  specify a maximum line length of 79 characters?Pretty much every code editor under the sun can handle longer lines.  What to do with wrapping should be the choice of the content consumer, not the responsibility of the content creator.Are there any (legitimately) good reasons for adhering to 79 characters in this age?Much of the value of PEP-8 is to stop people arguing about inconsequential formatting rules, and get on with writing good, consistently formatted code. Sure, no one really thinks that 79 is optimal, but there's no obvious gain in changing it to 99 or 119 or whatever your preferred line length is. I think the choices are these: follow the rule and find a worthwhile cause to battle for, or provide some data that demonstrates how readability and productivity vary with line length. The latter would be extremely interesting, and would have a good chance of changing people's minds I think.Keeping your code human readable not just machine readable. A lot of devices still can only show 80 characters at a time. Also it makes it easier for people with larger screens to multi-task by being able to set up multiple windows to be side by side.Readability is also one of the reasons for enforced line indentation.I believe those who study typography would tell you that 66 characters per a line is supposed to be the most readable width for length. Even so, if you need to debug a machine remotely over an ssh session, most terminals default to 80 characters, 79 just fits, trying to work with anything wider becomes a real pain in such a case. You would also be suprised by the number of developers using vim + screen as a day to day environment.I am a programmer who has to deal with a lot of code on a daily basis. Open source and what has been developed in house.As a programmer, I find it useful to have many source files open at once, and often organise my desktop on my (widescreen) monitor so that two source files are side by side. I might be programming in both, or just reading one and programming in the other.I find it dissatisfying and frustrating when one of those source files is >120 characters in width, because it means I can't comfortably fit a line of code on a line of screen. It upsets formatting to line wrap.I say '120' because that's the level to which I would get annoyed at code being wider than. After that many characters, you should be splitting across lines for readability, let alone coding standards.I write code with 80 columns in mind. This is just so that when I do leak over that boundary, it's not such a bad thing.Printing a monospaced font at default sizes is (on A4 paper) 80 columns by 66 lines.79 characters (well, actually 72 characters) is where most text-based email readers linewrap.  So code cut-and-pasted into an email is a lot more readable.because if you push it beyond the 80th column it means that either you are writing a very long and complex line of code that does too much (and so you should refactor), or that you indented too much (and so you should refactor).Here's why I like the 80-character with: at work I use Vim and work on two files at a time on a monitor running at, I think, 1680x1040 (I can never remember).  If the lines are any longer, I have trouble reading the files, even when using word wrap.  Needless to say, I hate dealing with other people's code as they love long lines.Since whitespace has semantic meaning in Python, some methods of word wrapping could produce incorrect or ambiguous results, so there needs to be some limit to avoid those situations.  An 80 character line length has been standard since we were using teletypes, so 79 characters seems like a pretty safe choice.I agree with Justin.  To elaborate, overly long lines of code are harder to read by humans  and some people might have console widths that only accommodate 80 characters per line.  The style recommendation is there to ensure that the code you write can be read by as many people as possible on as many platforms as possible and as comfortably as possible.
Python

I need your help about matplotlib. Yes, I did not forget calling the pyplot.show().It returns  as the output.There is nothing to happen. No error message. No new window. Nothing. I install  by using pip and I didn't take any error messages. Details:I use,If I set my backend to  in ,\nthen I can reproduce your symptoms:~/.matplotlib/matplotlibrc:Note that the file  may not be in directory . In this case, the following code shows where it is:If you edit  and change the backend to something like , you should see a plot. You can list all the backends available on your machine withIt should return a list like:Reference:I ran into the exact same problem on Ubuntu 12.04, because I installed matplotlib (within a virtualenv) usingTo make long story short, my advice is: don't try to install matplotlib using pip or by hand; let a real package manager (e.g. apt-get / synaptic) install it and all its dependencies for you.Unfortunately, matplotlib's backends (alternative methods for actually rendering your plots) have all sorts of dependencies that pip will not deal with.  Even worse, it fails silently; that is,  appears to install matplotlib successfully.  But when you try to use it (e.g. ), no plot window will appear.  I tried all the different backends that people on the web suggest (Qt4Agg, GTK, etc.), and they all failed (i.e. when I tried to import matplotlib.pyplot, I get  because it's trying to import some dependency that's missing).  I then researched how to install those dependencies, but it just made me want to give up using pip (within virtualenv) as a viable installation solution for any package that has non-Python package dependencies.  The whole experience sent me crawling back to apt-get / synaptic (i.e. the Ubuntu package manager) to install software like matplotlib.  That worked perfectly.  Of course, that means you can only install into your system directories, no virtualenv goodness, and you are stuck with the versions that Ubuntu distributes, which may be way behind the current version...%matplotlib inlineFor me working with notebook, adding the above line before the plot works.For future reference,I have encountered the same problem -- pylab was not showing under ipython.  The problem was fixed by changing ipython's config file {ipython_config.py}.  In the config fileI changed 'auto' to 'qt' and now I see graphsJust type:See  at 23:30 ! is used because of my import:  as pltI'm using python2.7 on a mac with iTerm2.I had to install matplotlib from source to get this to work. The key instructions (from ) are:By changing the backend, as @unutbu says, I just ran into loads more problems with all the different backends not working either.Adding the following two lines before importing pylab seems to work for me What solved my problem was just using the below two lines in ipython notebook at the topAnd it worked. I'm using Ubuntu16.04 and ipython-5.1Be sure to have this startup script enabled :\n( Preferences > Console > Advanced Options ) If the standard PYTHONSTARTUP is enabled you won't have an interactive plotSimilar to @Rikki, I solved this problem by upgrading  with . If you can't upgrade uninstalling and reinstalling may work.For Ubuntu 12.04:
Python

I'm basically looking for a python version of Given a list of lists, I need a new list that gives all the possible combinations of items between the lists.The number of lists is unknown, so I need something that works for all cases. Bonus points for elegance!you need :The most elegant solution is to use  in python 2.6.If you aren't using Python 2.6, the docs for itertools.product actually show an equivalent function to do the product the \"manual\" way:I hope you find that as elegant as I did when I first encountered it.Numpy can do it:Nothing wrong with straight up recursion for this task, and if you need a version that works with strings, this might fit your needs:
Python

I could use some pseudo-code, or better, Python.  I am trying to implement a rate-limiting queue for a Python IRC bot, and it partially works, but if someone triggers less messages than the limit (e.g., rate limit is 5 messages per 8 seconds, and the person triggers only 4), and the next trigger is over the 8 seconds (e.g., 16 seconds later), the bot sends the message, but the queue becomes full and the bot waits 8 seconds, even though it's not needed since the 8 second period has lapsed.Here the , if you want just to drop messages when they arrive too quickly (instead of queuing them, which makes sense because the queue might get arbitrarily large):There are no datastructures, timers etc. in this solution and it works cleanly :) To see this, 'allowance' grows at speed 5/8 units per seconds at most, i.e. at most five units per eight seconds. Every message that is forwarded deducts one unit, so you can't send more than five messages per every eight seconds.Note that  should be an integer, i.e. without non-zero decimal part, or the algorithm won't work correctly (actual rate will not be ). E.g.  does not work because  will never grow to 1.0. But  works fine.Use this decorator @RateLimited(ratepersec) before your function that enqueues.Basically, this checks if 1/rate secs have passed since the last time and if not, waits the remainder of the time, otherwise it doesn't wait. This effectively limits you to rate/sec. The decorator can be applied to any function you want rate-limited.In your case, if you want a maximum of 5 messages per 8 seconds, use @RateLimited(0.625) before your sendToQueue function.A Token Bucket is fairly simple to implement.Start with a bucket with 5 tokens.Every 5/8 seconds: If the bucket has less than 5 tokens, add one.Each time you want to send a message: If the bucket has \u22651 token, take one token out and send the message. Otherwise, wait/drop the message/whatever.(obviously, in actual code, you'd use an integer counter instead of real tokens and you can optimize out the every 5/8s step by storing timestamps)Reading the question again, if the rate limit is fully reset each 8 seconds, then here is a modification:Start with a timestamp, , at a time long ago (e.g., at the epoch). Also, start with the same 5-token bucket.Strike the every 5/8 seconds rule.Each time you send a message: First, check if  \u2265 8 seconds ago. If so, fill the bucket (set it to 5 tokens). Second, if there are tokens in the bucket, send the message (otherwise, drop/wait/etc.). Third, set  to now.That should work for that scenario.I've actually written an IRC bot using a strategy like this (the first approach). Its in Perl, not Python, but here is some code to illustrate:The first part here handles adding tokens to the bucket. You can see the optimization of adding tokens based on time (2nd to last line) and then the last line clamps bucket contents to the maximum (MESSAGE_BURST)$conn is a data structure which is passed around. This is inside a method that runs routinely (it calculates when the next time it'll have something to do, and sleeps either that long or until it gets network traffic). The next part of the method handles sending. It is rather complicated, because messages have priorities associated with them.That's the first queue, which is run no matter what. Even if it gets our connection killed for flooding. Used for extremely important things, like responding to the server's PING. Next, the rest of the queues:Finally, the bucket status is saved back to the $conn data structure (actually a bit later in the method; it first calculates how soon it'll have more work)As you can see, the actual bucket handling code is very small \u2014 about four lines. The rest of the code is priority queue handling. The bot has priority queues so that e.g., someone chatting with it can't prevent it from doing its important kick/ban duties.to block processing until the message can be sent, thus queuing up further messages,  antti's beautiful solution may also be modified like this:it just waits until enough allowance is there to send the message. to not start with two times the rate, allowance may also initialized with 0.Keep the time that the last five lines were sent.  Hold the queued messages until the time the fifth-most-recent message (if it exists) is a least 8 seconds in the past (with last_five as an array of times):One solution is to attach a timestamp to each queue item and to discard the item after 8 seconds have passed. You can perform this check each time the queue is added to.This only works if you limit the queue size to 5 and discard any additions whilst the queue is full.If someone still interested, I use this simple callable class in conjunction with a timed LRU key value storage to limit request rate per IP. Uses a deque, but can rewritten to be used with a list instead.How about this:I needed a variation in Scala. Here it is:Here is how it can be used:Just a python implementation of a code from accepted answer.
Python

Suppose you have three objects you acquire via context manager, for instance A lock, a db connection and an ip socket.\nYou can acquire them by:But is there a way to do it in one block? something likeFurthermore, is it possible, given an array of unknown length of objects that have context managers, is it possible to somehow do:If the answer is \"no\", is it because the need for such a feature implies bad design, or maybe I should suggest it in a pep? :-P, you can use :is equivalent to:Note that this isn't exactly the same as normally using nested , because , , and  will all be called initially, before entering the context managers. This will not work correctly if one of these functions may raise exceptions, but will work for the examples in the question., syntax has been added for this, and  has been deprecated:, you can also enter an unknown-length list of context managers by using :This allows you to create the context managers as you are adding them to the , which prevents the possible problem with .The first part of your question is possible in .The second part of your question is solved with  in .
Python

I've got a timedelta. I want the days, hours and minutes from that - either as a tuple or a dictionary... I'm not fussed.I must have done this a dozen times in a dozen languages over the years but Python usually has a simple answer to everything so I thought I'd ask here before busting out some nauseatingly simple (yet verbose) mathematics.Mr Fooz raises a good point.I'm dealing with \"listings\" (a bit like ebay listings) where each one has a duration. I'm trying to find the time left by doing Am I right in saying that wouldn't account for DST? If not, what's the simplest way to add/subtract an hour?If you have a  value ,  already gives you the \"days\" you want.  values keep fraction-of-day as seconds (not directly hours or minutes) so you'll indeed have to perform \"nauseating simple mathematics\", e.g.:This is a bit more compact, you get the hours, minutes and seconds in two lines.As for DST, I think the best thing is to convert both  objects to seconds. This way the system calculates DST for you.I don't understand how about thisYou get minutes and seconds of a minute as a float.timedeltas have a  and  attribute .. you can convert them yourself with ease.
Python

I am trying to pass a list as an argument to a command line program. Is there an  option to pass a list as option?Script is called like belowUse the  option. takes 1 or more arguments,  takes zero or more.Let's take a look in more detail at some of the different ways one might try to do this, and the end result.Here is the output you can expect::: I don't mean in general.. I mean using quotes to  is not what you want. I prefer passing a delimited string which I parse later in the script. The reasons for this are; the list can be of any type  or , and sometimes using  I run into problems if there are multiple optional arguments and positional arguments.Then,or,will work fine. The delimiter can be a space, too, which would though enforce quotes around the argument value like in the example in the question.Additionally to , you might want to use  if you know the list in advance:If you are intending to make a single switch take multiple parameters, then you use . If your example '-l' is actually taking integers:ProducesIf you specify the same argument multiple times, the default action () replaces the existing data.The alternative is to use the  action:Which producesOr you can write a custom handler/action to parse comma-separated values so that you could doUsing  in argparse's add_argument methodI use nargs='' to the option to pick defaults if I am not passing any explicit argumentsIncluding a code snippet as example: The below sample code is written in python3. By changing the print statement format, can run in python2Note: I am collecting multiple string arguments that gets stored in the list - opts.alist\nIf you want list of integers, change the type parameter on parser.add_argument to int
Python

I'm trying to use the sort feature when querying my mongoDB, but it is failing.  The same query works in the MongoDB console but not here.  Code is as follows:The error I get is as follows:I found a link elsewhere that says I need to place a 'u' infront of the key if using pymongo, but that didn't work either.  Anyone else get this to work or is this a bug., in pymongo, takes  and  as parameters.So if you want to sort by, let's say,  then you should You can try this:This also works:I'm using this in my code, please comment if i'm doing something wrong here, thanks.Python uses key,direction. You can use the above way.So in your case you can do this
Python

Assuming  is a Python dictionary, what's the best, most elegant, most \"pythonic\" way of refactoring code like this:Like this:You can also use the  like so:You can pass any ordinary function instead of lambda:While  is a nice idiom, it's slower than  (and slower than  if presence of the key in the dictionary can be expected most of the time):For multiple different defaults try this:There is a method in python dictionaries to do this: However this method sets the value of  to  if key  is not already defined, unlike what the question asked.(this is a late answer)An alternative is to subclass the  class and implement the  method, like this:Examples:
Python

I know that Python does not support method overloading, but I've run into a problem that I can't seem to solve in a nice Pythonic way.I am making a game where a character needs to shoot a variety of bullets, but how do I write different functions for creating these bullets? For example suppose I have a function that creates a bullet travelling from point A to B with a given speed. I would write a function like this:But I want to write other functions for creating bullets like:And so on with many variations. Is there a better way to do it without using so many keyword arguments cause its getting kinda ugly fast. Renaming each function is pretty bad too because you get either , , or .To address some answers:Python does support \"method overloading\" as you present it. In fact, what you just describe is trivial to implement in Python, in so many different ways, but I would go with:In the above code,  is a plausible default value for those arguments, or . You can then call the method with only the arguments you are interested in, and Python will use the default values. You could also do something like this:Another alternative is to directly hook the desired function directly to the class or instance:Yet another way is to use an abstract factory pattern:You can use \"roll-your-own\" solution for function overloading. This one is copied from  about multimethods (because there is little difference between mm and overloading in python):The usage would beMost restrictive limitations  are:What you are asking for, is called . See  language examples which demonstrates different types of dispatches.However, before looking at that, we'll first tackle why  is not really what you want in python.First one needs to understand the concept of overloading and why it's not applicable to python.Python is a  typed language, so the concept of overloading simply does not apply to it. However, all is not lost, since we can create such  at run-time:So we should be able to do  in python or, as it is alternatively called, .The multimethods are also called :Python does not support this out of the box. But, as it happens, there is an excellent python package called  that does exactly that. Here is how we might use  package to implement your methods:A possible option is to use the multipledispatch module as detailed here:\nInstead of doing this:You can do this:With the resulting usage:This type of behaviour is typically solved (in OOP languages) using Polymorphism. Each type of bullet would be responsible for knowing how it travels. For instance:Pass as many arguments to the c_function that exist, then do the job of determining which c function to call based on the values in the initial c function. So, python should only ever be calling the one c function. That one c function looks at the arguments, and then can delegate to other c functions appropriately.You're essentially just using each subclass as a different data container, but by defining all the potential arguments on the base class, the subclasses are free to ignore the ones they do nothing with.When a new type of bullet comes along, you can simply define one more property on the base, change the one python function so that it passes the extra property, and the one c_function that examines the arguments and delegates appropriately. Doesn't sound too bad I guess.In Python 3.4 was added .Here is short API description from PEP.To define a generic function, decorate it with the @singledispatch decorator. Note that the dispatch happens on the type of the first argument. Create your function accordingly:To add overloaded implementations to the function, use the register() attribute of the generic function. This is a decorator, taking a type parameter and decorating a function implementing the operation for that type:I think your basic requirement is to have a C/C++ like syntax in python with the least headache possible.  Although I liked Alexander Poluektov's answer it doesn't work for classes.  The following should work for classes.  It works by distinguishing by the number of non keyword arguments (but doesn't support distinguishing by type):And it can be used simply like this:Output:Either use multiple keyword arguments in the definition, or create a  hierarchy whose instances are passed to the function.I think aclass hierarchy with the associated polymorphism is the way to go. You can effectively overload the base class constructor by using a metaclass so that calling the base class results in the creation of the appropriate subclass object. Below is some sample code to illustrate the essence of what I mean.Use keyword arguments with defaults. E.g.In the case of a straight bullet versus a curved bullet, I'd add two functions:  and .By passing keyword args, overloading methods is tricky in python. However, there could be usage of passing the dict, list or primitive variables.I have tried something for my use cases, this could help here to understand people to overload the methods.Let's take your example:a class overload method with call the methods from different class.pass the arguments from remote class:OR \nSo, handling is being achieved for list, Dictionary or primitive variables from method overloading.try it out for your codes.
Python

There is a lot of documentation on how to serialize a Model QuerySet but how do you just serialize to JSON the fields of a Model Instance?You can easily use a list to wrap the required object and that's all what django serializers need to correctly serialize it, eg.:To avoid the array wrapper, remove it before you return the response:I found this interesting post on the subject too:It uses django.forms.models.model_to_dict, which looks like the perfect tool for the job.If you're dealing with a list of model instances the best you can do is using , it gonna fit your need perfectly. However, you are to face an issue with trying to serialize a  object, not a  of objects. That way, in order to get rid of different hacks, just use Django's  (if I'm not mistaken,  relies on it, too): You now just need one straight  call to serialize it to json:That's it! :)It sounds like what you're asking about involves serializing the data structure of a Django model instance for interoperability.  The other posters are correct: if you wanted the serialized form to be used with a python application that can query the database via Django's api, then you would wan to serialize a queryset with one object.  If, on the other hand, what you need is a way to re-inflate the model instance somewhere else without touching the database or without using Django, then you have a little bit of work to do.Here's what I do:First, I use  for the conversion.  It happened to be what I found first, but it might not be the best.  My implementation depends on one of its features, but there should be similar ways with other converters.Second, implement a  method on all models that you might need serialized.  This is a magic method for , but it's probably something you're going to want to think about no matter what implementation you choose.  The idea is that you return an object that is directly convertible to  (i.e. an array or dictionary).  If you really want to do this automatically:This will not be helpful to you unless you have a completely flat data structure (no , only numbers and strings in the database, etc.).  Otherwise, you should seriously think about the right way to implement this method.Third, call  and you have what you want.If you're asking how to serialize a single object from a model and you  you're only going to get one object in the queryset (for instance, using objects.get), then use something like:which would get you something of the form:I solved this problem by adding a serialization method to my model:Here's the verbose equivalent for those averse to one-liners: is an ordered list of model fields which can be accessed from instances and from the model itself.I return the dict of my instanceso it return something like {'field1':value,\"field2\":value,....}how about this way:or exclude anything you don't want.Here's my solution for this, which allows you to easily customize the JSON as well as organize related recordsFirstly implement a method on the model. I call is  but you can call it whatever you like, e.g.:Then in the view I do:It doesn't seem you can serialize an instance, you'd have to serialize a QuerySet of one object.I run out of the  release of django, so this may not be in earlier versions.To serialize and deserialze, use the following:Use list, it will solve problemStep1:Step2:Step3:
Python

I would like to increase the width of the ipython notebook in my browser. I have a high-resolution screen, and I would like to expand the cell width/size to make use of this extra space.Thanks!edit: 5/2017I now use jupyterthemes: and this command:which sets the width to 100% with a nice theme.That  solution didn't actually work on my IPython, however luckily someone suggested a working solution for new IPythons:Create a file  (iPython) or  (Jupyter) with contentThen restart iPython/Jupyter notebooks. Note that this will affect all notebooks.If you don't want to change your default settings, and you only want to change the width of the current notebook you're working on, you can enter the following into a cell:To get this to work with jupyter (version 4.0.6) I created  containing:You can set the CSS of a notebook by calling a stylesheet from any cell. As an example, take a look at the .In particular, creating a file containingshould give you a starting point. However, it may be necessary to also adjust e.g  to deal with markdown as well as code cells.If that file is  then add a cell containing:This will apply all the stylings, and, in particular, change the cell width.I recommend using . This way you can override css for all notebooks, without adding any code to notebooks. \nWe don't like to change configuration in .ipython/profile_default, since  we are running a shared Jupyter server for the whole team.I made a  style specifically for vertically-oriented high-res screens, that makes cells wider and adds a bit of empty-space in the bottom, so you can position the last cell in the centre of the screen.\n\nYou can, of course, modify my css to your liking, if you have a different layout, or you don't want extra empty-space in the end.Last but not least, Stylish is a great tool to have in your toolset, since you can easily customise other sites/tools to your liking (e.g. Jira, Podio, Slack, etc.)
Python

I am looking for a function that takes as input two lists, and returns the , and the significance of the correlation.You can have a look at :The Pearson correlation can be calculated with numpy's .If you don't feel like installing scipy, I've used this quick hack, slightly modified from :(Edited for correctness.)The following code is a straight-up interpretation of :Test:returnsThis agrees with Excel, ,  (also ), which return 0.981980506 and 0.9819805060619657, and 0.98198050606196574, respectively.:: Fixed a bug pointed out by a commenter.An alternative can be a native scipy function from  which calculates:And here is an example:will return you: Rather than rely on numpy/scipy, I think my answer should be the easiest to code and  in calculating the Pearson Correlation Coefficient (PCC) .The  of PCC is basically to show you how  the two variables/lists are. \nIt is important to note that the PCC value ranges .\nA value between 0 to 1 denotes a positive correlation.\nValue of 0 = highest variation (no correlation whatsoever).\nA value between -1 to 0 denotes a negative correlation.Hmm, many of these responses have long and hard to read code...I'd suggest using numpy with its nifty features when working with arrays:Here is an implementation for pearson correlation based on sparse vector. The vectors here are expressed as a list of tuples expressed as (index, value). The two sparse vectors can be of different length but over all vector size will have to be same. This is useful for text mining applications where the vector size is extremely large due to most features being bag of words and hence calculations are usually performed using sparse vectors. Unit tests:You can do this with , too:This givesThis is a implementation of Pearson Correlation function using numpy:Here's a variant on mkh's answer that runs much faster than it, and scipy.stats.pearsonr, using numba.You can take a look at this article. This is a well-documented example for calculating correlation based on historical forex currency pairs data from multiple files using pandas library (for Python), and then generating a heatmap plot using seaborn library.You may wonder how to interpret your probability in the context of looking for a correlation in a particular direction (negative or positive correlation.)  Here is a function I wrote to help with that.  It might even be right!It's based on info I gleaned from  and , thanks to other answers posted here.
Python

I have a dictionary of points, say:I want to create a new dictionary with all the points whose x and y value is smaller than 5, i.e. points 'a', 'b' and 'd'.According to the , each dictionary has the  function, which returns a list of   tuple:So I have written this:Is there a more elegant way? I was expecting Python to have some super-awesome  function...Nowadays, in Python 2.7 and up, you can use a dict comprehension:And in Python 3:You could choose to call  instead of  if you're in Python 2 and  may have a  of entries. may be overkill if you know for sure each point will always be 2D only (in that case you might express the same constraint with an ) but it will work fine;-).I think that Alex Martelli's answer is definitely the most elegant way to do this, but just wanted to add a way to satisfy your want for a super awesome  method in a Pythonic sort of way:Basically we create a class that inherits from , but adds the filter method. We do need to use  for the the filtering, since using  while destructively iterating will raise exception.
Python

What are the relative merits / downsides of various Python bundles (EPD / Anaconda) vs. a manual install?I have installed EPD academic, and I have no issues with it. It provides more packages that I think I will ever need, and it is very easy to update using enpkg enstaller. The EPD academic licence requires yearly renewal however and the free version does not do updates as easily.At the moment I really only use a handful of packages such as , , , , ,  and their respective dependencies. For such limited use am I better off with manual install and  or do the bundles offer anything over and above this?: Nowadays I always recommend Anaconda. It includes lots of Python packages for scientific computing, data science, web development, etc. It also provides a superior environment tool, , which allows to easily switch between environments, even between Python 2 and 3. It is also updated very quickly as soon as a new version of a package is released, and you can just do  to update it.:On Windows, what is complicated is to compile the math packages, so I think a manual install is a viable option only if you are interested only in , without other packages.Therefore better chose either EPD (now Canopy) or Anaconda.Anaconda has around 270 packages, including the most important for most scientific applications and data analysis, that is, , , , , , .\nSo if this is enough for you, I would choose Anaconda.Instead, if you are interested in other packages, and even more if you use any of the Enthought packages ( for example is very useful for realtime data visualization), then EPD/Canopy is probably a better choice. The Academic version has a larger number of packages in the base install, and many more in the repository. Anaconda also includes Chaco.I have tried various Windows distributions in the last year, trying to find one sutable for my work environment (behind a proxy, but without access to proxy configuration).Here is my feedback from experience:\nWe had a license of EPD, but it was old and we were unable to update becasue of the weird proxy situation. In order to add some packages (such as recent version of ), I compiled from source. To update  and , I used the precompiled installer from , but it would sometimes screw up compatibility. I loved having a fully configured  and , and it simply worked out of the box.After a while, I tried installing the free version of Canopy, but it lacks Cython and py2exe and some specific advanced packaged I needed, so I never really used it.\nSome of my colleagues bought the full Canopy license, but we're still not sure how they're going to update...\nNot wanting to struggle with licenses, I installed Python(x,y) at home. The only downside I noticed right now is that the standard installation requires you to select which packages you want. It's both a good and a bad point, because I can't be sure that my clients will have the exact same configuration as I do when I install. (The Enthought tool suite can be installed in Python(x,y).)\nAfter using Python(x,y) for a while, I just noticed I installed the 32 bit version. Although it is not clear on their website, it seems they don't have a 64 bit version as of July 2015. I'm going to uninstall it and get a 64 bit distribution.\nWhen I first wrote this, Anaconda didn't seem to have enough packages yet. A couple of years later, it seems much better, I'm going to give it a try!\nIn order to avoid version compatibility issues with our old EPD version, I ended up using manual Python installation and adding additional packages from the LFD website linked above. It works great, but I would still suggest Canopy to a new user who requires advanced packages (like  or ). If you go for Canopy, get the full licence (Academic or purchased). Else, go with Python(x,y), it will end up being the same.\nNo need for a distribution. It's all relatively recent (+/- 6 months is tolerable) and pre-compiled. You just need to execute  and it's there! Most advanced packages are there as well.The other answers cover the ground quite nicely, so I just want to remark on one particular aspect that nobody has mentioned yet. It is probably fairly niche, but it  potentially make or break Anaconda or Canopy for some people under Linux systems:Anaconda Python builds use the UCS4 Unicode mode, whereas Enthought Canopy uses UCS2.What this means in practical terms is that if you rely on any extensions which you cannot compile yourself for whatever reason (e.g. pre-compiled proprietary libraries), if they happen not to be built for a Python version with the same mode, you may sooner or later run into errors that look something like .According to , UCS4 seems to currently be more popular and recommended. Also, the whole UCS compatibility issues seem to only affect 2.x and < 3.3 versions.I used Anaconda for years and liked it quite a bit. Unfortunately,  (now ) is unavailable without the enterprise edition. I want to use Jupyter notebooks in the classroom, so I switched to Canopy. It seems easy enough to install all of the packages we need. Admittedly, we haven't tested them all.
Python

I'm just curious if anyone knows if there's good reason why django's orm doesn't call 'full_clean' on a model unless it is being saved as part of a model form.  (NOTE: quote updated for Django 1.6... previous django docs had a caveat about ModelForms as well.)Are there good reasons why people wouldn't want this behavior? I'd think if you took the time to add validation to a model, you'd want that validation run every time the model is saved.I know how to get everything to work properly, I'm just looking  for an explanation.AFAIK, this is because of backwards compatibility. There are also problems with ModelForms with excluded fields, models with default values, pre_save() signals, etc.Sources you might be intrested in:Because of the compatibility considering, the auto clean on save is not enabled in django kernel.If we are starting a new project and want the default  method on Model could clean automatically, we can use the following signal to do clean before every model was saved. The simpliest way to call the  method is just to override  method in your :Instead of inserting a piece of code that declares a receiver, we can use an app as  section in Before that, you may need to install  using PyPI:
Python

I guess it could be something like , but that is more like a frozen-keys dict (a half-frozen dict). Isn't it?A \"frozendict\" should be a frozen dictionary, it should have , , , etc., and support , , etc.Python doesn't have a builtin frozendict type. It turns out this wouldn't be useful too often (though it would still probably be useful more often than  is).The most common reason to want such a type is when memoizing function calls for functions with unknown arguments. The most common solution to store a hashable equivalent of a dict (where the values are hashable) is something like . This depends on the sorting not being a bit insane. Python cannot positively promise sorting will result in something reasonable here. (But it can't promise much else, so don't sweat it too much.)You could easily enough make some sort of wrapper that works much like a dict. It might look something likeIt should work great:Curiously, although we have the seldom useful  in python, there's still no frozen mapping.  The idea was rejected in .  So the python 2 solution to this:Still seems to be the somewhat lame:In python3 you have the option of :Now the default config  be updated dynamically, but remain immutable where you want it to be immutable by passing around the proxy instead.  So changes in the  will update  as expected, but you can't write to the mapping proxy object itself.  Admittedly it's not quite the same thing as an \"immutable, hashable dict\" - but it's a decent substitute given the same kind of use cases for which we might want a frozendict.    Assuming the keys and values of the dictionary are themselves immutable (e.g. strings) then:Here is the code I've been using.  I subclassed frozenset.  The advantages of this are the following.Update Jan 21 2015:  The original piece of code I posted in 2014 used a for-loop to find a key that matched.  That was incredibly slow.  Now I've put together an implementation which takes advantage of frozenset's hashing features.  Key-value pairs are stored in special containers where the  and  functions are based on the key only.  This code has also been formally unit-tested, unlike what I posted here in August 2014.MIT-style license.I think of frozendict everytime I write a function like this:Yes, this is my second answer, but it is a completely different approach.  The first implementation was in pure python.  This one is in Cython.  If you know how to use and compile Cython modules, this is just as fast as a regular dictionary.  Roughly .04 to .06 micro-sec to retrieve a single value.This is the file \"frozen_dict.pyx\"Here's the file \"setup.py\"If you have Cython installed, save the two files above into the same directory.  Move to that directory in the command line.And you should be done.There appears to be a nearly trivial solution that the other answers have missed. The most trivial answer ought to be something likeexcept that  is a read-only attribute in , so we have to override it:You can add a  method to your class in the same way that @MikeGraham's answer suggests.You can make the class even more immutable by having  and  raise errors, especially the latter one. Alternatively, you could define an empty  attribute on the class. None of this is strictly necessary, however, since user-defined attributes will not affect the result of :Another thing to keep in mind is that you can always modify a dict defined like this if you are willing to jump through the hoops:will bypass the frozenness. Whether this is a bug or a feature is for you to decide.The main disadvantage of  is that it needs to be specified before it is used, so it's less convenient for single-use cases.However, there is a practical workaround that can be used to handle many such cases. Let's say that you want to have an immutable equivalent of the following dict:This can be emulated like this:It's even possible to write an auxiliary function to automate this:Of course this works only for flat dicts, but it shouldn't be too difficult to implement a recursive version.Another option is the  class from the  package.You may use  from  package as:As per the :
Python

In Python 2.5.2, the following code raises a TypeError:If I replace the  with , it will work. What's the explanation for this?The reason is that super() only operates on new-style classes, which in the 2.x series means extending from object.In addition, don't use super() unless you have to. It's not the general-purpose \"right thing\" to do with new-style classes that you might suspect.There are times when you're expecting multiple inheritance and you might possibly want it, but until you know the hairy details of the MRO, best leave it alone and stick to:I tried the various X.a() methods; however, they seem to require an instance of X in order to perform a(), so I did X().a(self), which seems more complete than the previous answers, at least for the applications I've encountered. It doesn't seem to be a good way of handling the problem as there is unnecessary construction and destruction, but it works fine.My specific application was Python's cmd.Cmd module, which is evidently not a NewStyle object for some reason.Final Result:In case none of the above answers mentioned it clearly. Your parent class needs to inherit from \"object\", which would essentially turn it into a new style class. 
Python

I'm starting new Google App Engine application and currently considering two frameworks:  and . I'm rather satisfied with built-in webapp framework that I've used for my previous App Engine application, so I think webapp2 will be even better and I won't have any problems with it.However, there are a lot of good reviews of Flask, I really like its approach and all the things that I've read so far in the documentation and I want to try it out. But I'm a bit concerned about limitations that I can face down the road with Flask.So, the question is -  By \"problem\" I mean something that I can't work around in several lines of code (or any reasonable amount of code and efforts) or something that is completely impossible.And as a follow-up question: are there any killer-features in Flask that you think can blow my mind and make me use it despite any problems that I can face? I'm the author of tipfy and webapp2.A big advantage of sticking with webapp (or its natural evolution, webapp2) is that you don't have to create your own versions for existing SDK handlers for your framework of your choice.For example,  uses a webapp handler. To use it in a pure Flask view, using werkzeug.Request and werkzeug.Response, you'll need to implement deferred for it (like I did  for tipfy).The same happens for other handlers: blobstore (Werkzeug still doesn't support range requests, so you'll need to use WebOb even if you create your own handler -- see ), mail, XMPP and so on, or others that are included in the SDK in the future.And the same happens for libraries created with App Engine in mind, like , which is based on webapp and would need a port or adapter to work with other frameworks, if you don't want to mix webapp and your-framework-of-choice handlers in the same app.So, even if you choose a different framework, you'll end a) using webapp in some special cases or b) having to create and maintain your versions for specific SDK handlers or features, if you'll use them.I much prefer Werkzeug over WebOb, but after over one year porting and maintaining versions of the SDK handlers that work natively with tipfy, I realized that this is a lost cause -- to support GAE for the long term, best is to stay close to webapp/WebOb. It makes support for SDK libraries a breeze, maintenance becomes a lot easier, it is more future-proof as new libraries and SDK features will work out of the box and there's the benefit of a large community working around the same App Engine tools.A specific webapp2 defense is summarized . Add to those that  and is  and you have a good set of compelling reasons to go for it. Also, webapp2 has a big chance to be included in a future SDK release (this is extra-official, don't quote me :-) which will push it forward and bring new developers and contributions.That said, I'm a big fan of Werkzeug and the Pocoo guys and borrowed a lot from Flask and others (web.py, Tornado), but -- and, you know, I'm biased -- the above webapp2 benefits should be taken into account.Your question is extremely broad, but there appears to be no big problems using Flask on Google App Engine.This mailing list thread links to several templates:And here is a tutorial specific to the Flask / App Engine combination:Also, see , , and  for issues people have had with Flask and Google App Engine.I think google app engine officially supports flask framework. There is a sample code and tutorial here -> For me the decision for webapp2 was easy when I discovered that flask is not an object-oriented framework (from the beginning), while webapp2 is a pure object oriented framework. webapp2 uses Method Based Dispatching as standard for all RequestHandlers (as flask documentation calls it and implements it since V0.7 in MethodViews). While in flask MethodViews are an add-on it is a core design principle for webapp2. So your software design will look different using both frameworks. Both frameworks use nowadays jinja2 templates and are fairly feature identical. I prefer to add security checks to a base-class RequestHandler and inherit from it. This is also good for utility functions, etc. As you can see for example in link [3] you can override methods to prevent dispatching a request.If you are an OO-person, or if you need to design a REST-server, I would recommend webapp2 for you. If you prefer simple functions with decorators as handlers for multiple request-types, or you are uncomfortable with OO-inheritance then choose flask. I think both frameworks avoid the complexity and dependencies of much bigger frameworks like pyramid.I didn't try webapp2 and found that tipfy was a bit difficult to use since it required setup scripts and builds that configure your python installation to other than default. F\u00f6r these and other reasons I havn't made my largest project depend on a framework and I use the plain webapp instead, add the library called beaker to get session capability and django already has builtin translations for words common to many usecases so when building a localized application django was the right choice for my largest project. The 2 other frameworks I actually deployed with projects to a production environment were GAEframework.com and web2py and generally it seems that adding a framework which changes its template engine could lead to incompatibilities between old and new versions. So my experience is that I'm being reluctant to adding a framework to my projects unless they solve the more advanced use cases (file upload, multi auth, admin ui are 3 examples of more advanced use cases that no framework for gae at the moment handles well. 
Python

The typical ConfigParser generated file looks like:Now, is there a way to index lists like, for instance:Related question: ? Thanks in advanceThere is nothing stopping you from packing the list into a delimited string and then unpacking it once you get the string from the config.  If you did it this way your config section would look like:It's not pretty but it's functional for most simple lists.Also a bit late, but maybe helpful for some.\nI am using a combination of ConfigParser and JSON:just read it with:You can even break lines if your list is long (thanks @peter-smit):Of course i could just use JSON, but i find config files much more readable, and the [DEFAULT] Section very handy.Coming late to this party, but I recently implemented this with a dedicated section in a config file for a list:and using  to get an iterable list of path items, like so:Hope this helps other folk Googling this question ;)One thing a lot of people don't know is that multi-line configuration-values are allowed. For example:The value of  will now be:Which you easily can split with the splitlines method (don't forget to filter empty items).If we look to a big framework like Pyramid they are using this technique:Myself, I would maybe extend the ConfigParser if this is a common thing for you:Note that there are a few things to look out for when using this techniqueIf you want to  pass in a list then you can use:For example configuration:The code is:output:I landed here seeking to consume this...The answer is to split it on the comma and strip the spaces:To get a  list result:It may not answer the OP's question exactly but might be the simple answer some people are looking for.This is what I use for lists:config file content: code : it work for stringsin case of numbers config content:code:thanks.Only primitive types are supported for serialization by config parser. I would use JSON or YAML for that kind of requirement.I faced the same problem in the past. If you need more complex lists, consider creating your own parser by inheriting from ConfigParser. Then you would overwrite the get method with that:With this solution you will also be able to define dictionaries in your config file.But be careful! This is not as safe: this means anyone could run code through your config file. If security is not an issue in your project, I would consider using directly python classes as config files. The following is much more powerful and expendable than a ConfigParser file:So now my  file, which could look like this:Can be parsed into fine-grained-enough objects for my small project.This is for very quick parsing of simple configs, you lose all ability to fetch ints, bools, and other types of output without either transforming the object returned from , or re-doing the parsing job accomplished by the Parser class elsewhere.
Python

What is the difference between Numpy's  and  functions? When should you use one rather than the other? They seem to generate identical output for all the inputs I can think of.The  is:So it is like , except it has fewer options, and .  has  by default. I think the main difference is that  (by default) will make a copy of the object, while  will not unless necessary.The difference can be demonstrated by this example:Hope this helps!The differences are mentioned quite clearly in the documentation of  and . The differences lie in the argument list and hence the action of the function depending on those parameters. The function definitions are :and The following arguments are those that may be passed to  and   as mentioned in the documentation :
Python

I'm trying to test a complicated javascript interface with Selenium (using the Python interface, and across multiple browsers).  I have a number of buttons of the form:I'd like to be able to search for buttons based on \"My Button\" (or non-case-sensitive, partial matches such as \"my button\" or \"button\")I'm finding this amazingly difficult, to the extent to which I feel like I'm missing something obvious.  The best thing I have so far is:This is case-sensitive, however.  The other thing I've tried is iterating through all the divs on the page, and checking the element.text property.  However, every time you get a situation of the form:div.outer also has \"My Button\" as the text.  To fix THAT, I've tried looking to see if div.outer is the parent of div.inner, but couldn't figure out how to do that (element.get_element_by_xpath('..') returns an element's parent, but it tests not equal to div.outer).  Also, iterating through all the elements on the page seems to be really slow, at least using the Chrome webdriver.Ideas?Edit: This question came out a little vague.  Asked (and answered) a more specific version here: Try the following:you could try an xpath like:You can also use it with Page Object Pattern, e.g:@FindBy(xpath = \"//*[contains(text(), 'Best Choice')]\")WebElement buttonBestChoice;Try this. Its very easy:This really worked for me in selenium web driver.
Python

I'm trying to use Sphinx to document a 5,000+ line project in Python. It has about 7 base modules. As far as I know, In order to use autodoc I need to write code like this for each file in my project:This is way too tedious because I have many files. It would be much easier if I could just specify that I wanted the 'mods' package to be documented. Sphinx could then recursively go through the package and make a page for each submodule.Is there a feature like this? If not I could write a script to make all the .rst files, but that would take up a lot of time.You can check this  that I've made. I think it can help you.This script parses a directory tree looking for python modules and packages and creates ReST files appropriately to create code documentation with Sphinx. It also creates a modules index.This script is now part of Sphinx 1.1 as .I do not know whether Sphinx had had  extension at the time original question was asked, but for now it is quite possible to set up automatic generation of that kind without using  or similar script. Below there are settings which work for one of my projects.In conclusion, there is no need to keep  directory under version control. Also, you may name it anything you want and place it anywhere in the source tree (putting it below  will not work, though).In each package, the  file can have  components for each part of the package.Then you can  and it mostly does what you want.Maybe what you're looking for is  and this .
Python

I am having trouble with some of pandas functionalities. How do I check what is my installation version?Check :Pandas also provides a utility function, , which reports the version of its dependencies as well:open the console and type the code below.Code:Output:Run:You should get a list of packages (including panda) and their versions, e.g.:
Python

Here's the simplest way to explain this. Here's what I'm using:Here's what I want:The reason is that I want to split a string into tokens, manipulate it, then put it back together again.If you are splitting on newline, use .(Not a general solution, but adding this here in case someone comes here not realizing this method existed.)You can also split a string with an array of strings instead of a regular expression, like this:If one wants to split string while keeping separators by regex without capturing group:If one assumes that regex is wrapped up into capturing group:Both ways also will remove empty groups which are useless and annoying in most of the cases.
Python

In Flask, How do I extract parameters from a URL? \nHow can I extract named parameters from a URL using flask and python?When the user accesses this URL running on my flask app, I want the web service to be able to handle the parameters specified after the question mark:Use  to get parsed contents of query string:
Python

What is the name of the method to override the  operator (subscript notation) for a class in Python?You need to use the .And if you're going to be setting values you'll need to implement the  too, otherwise this will happen:To fully overload it you also need to implement the and  methods.I almost forgot... if you want to completely emulate a list, you also need .There are all documented in You are looking for the  method. See , section 3.4.6
Python

In other words, what's the sprintf equivalent to pprint?  The  module has a command named , for just that purpose.From the documentation:Example:Assuming you really do mean  from the ,  then you want\nthe  method.If you just mean  , then you want Are you looking for ?Something like this:
Python

I'm building a simple helper script for work that will copy a couple of template files in our code base to the current directory. I don't, however, have the absolute path to the directory where the templates are stored. I do have a relative path from the script but when I call the script it treats that as a path relative to the current working directory. Is there a way to specify that this relative url is from the location of the script instead?In the file that has the script, you want to do something like this:This will give you the absolute path to the file you're looking for.  Note that if you're using setuptools, you should probably use its  instead.:  I'm responding to a comment here so I can paste a code sample.  :-)I'm assuming you mean the  script when you mention running the file directly.  If so, that doesn't appear to be the case on my system (python 2.5.1 on OS X 10.5.7):However, I do know that there are some quirks with  on C extensions.  For example, I can do this on my Mac:However, this raises an exception on my Windows machine.you need  (sample below adds the parent directory to your path)As mentioned in the accepted answer I just want to add thatIt should be something likeThe accepted answer can be misleading in some cases , please refer to  link for detailsSee \nAs initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. Use this path as the root folder from which you Consider my code:Instead of using as in the accepted answer, it would be more robust to use:because using __file__ will return the file from which the module was loaded, if it was loaded from a file, so if the file with the script is called from elsewhere, the directory returned will not be correct. These answers give more detail:  and This code will return the absolute path to the main script.This will work even in a module.Hi first of all you should understand functions  and  In short  makes a  to . And if the path provided is itself a absolute path then the function returns the same path.similarly  makes a  to . And if the path provided is itself a relative path then the function returns the same path.:suppose i have a file  which contains list of input files to be processed by my python script.D:\\conc\\input1.dicD:\\conc\\input2.dicD:\\Copyioconc\\input_file_list.txtIf you see above folder structure,  is present in  folder and the files to be processed by the python script are present in  folderBut the content of the file  is as shown below:..\\conc\\input1.dic..\\conc\\input2.dicAnd my python script is present in  drive.And the relative path provided in the  file are relative to the path of  file.So when python script shall executed the current working directory (use  to get the path)As my relative path is relative to , that is , i have to change the current working directory to .So i have to use , so the current working directory shall be .Now to get the files  and , i will read the lines \"..\\conc\\input1.dic\" then shall use the command  (to change relative path to absolute path. Here as current working directory is \"D:\\Copyofconc\", the file \".\\conc\\input1.dic\" shall be accessed relative to \"D:\\Copyofconc\")so  shall be \"D:\\conc\\input1.dic\"An alternative which works for me: What worked for me is using . Then I specified the  directory I needed to go. For example I just needed to go up one directory.I'm not sure if this applies to some of the older versions, but I believe Python 3.3 has native relative path support.For example the following code should create a text file in the same folder as the python script:(note that there shouldn't be a forward or backslash at the beginning if it's a relative path)
Python

I am using Python 2.x.My editor gives me a 'warning' underline when I compare , but no warning when I use .  I did a test in the Python shell and determined both are valid syntax, but my editor seems to be saying that  is preferred. Is this the case, and if so, why?Use  when you want to check against an object's  (e.g. checking to see if  is ).  Use  when you want to check  (e.g. Is  equal to ?).You can have custom classes where  will return e.g: checks for object .  There is only 1 object , so when you do , you're checking whether they actually are the same object (not just  objects) In other words,  is a check for equivalence (which is defined from object to object) whereas  checks for object identity: is generally preferred when comparing arbitrary objects to singletons like  because it is faster and more predictable.  always compares by object identity, whereas what  will do depends on the exact type of the operands and even on their ordering.This recommendation is supported by , which  that \"comparisons to singletons like None should always be done with  or , never the equality operators.\"PEP 8 defines that it is better to use the is operator when comparing singletons.
Python

I want to move away from PHP a little and learn Python. In order to do web development with Python I'll need a framework to help with templating and other things. I have a non-production server that I use to test all of web development stuff on. It is a Debian 7.1 LAMP stack that runs MariaDB instead of the common MySQL-server package.Yesterday I installed Django and created my first project called . I have not changed any settings yet.Here is my first big piece of confusion. In the tutorial I followed the guy installed Django, started his first project, restarted Apache, and Django just worked from then on. He went to his browser and went to the Django default page with no problems.Me however, I have to cd into my firstweb folder and runAnd it works. No problem. But I'm wondering if it is supposed to work like this, and if this will cause problems down the line?My  is that I want to set it up so it uses my MySQL database. I go into my settings.py under /firstweb/firstweb and I see ENGINE and NAME but I'm not sure what to put here.And then in the USER, PASSWORD, and HOST areas is this my database and its credentials? If I am using  can I just put  in the HOST area? is simple to add. In your  dictionary, you will have an entry like this:You also have the option of utilizing MySQL , as of Django 1.7. You can accomplish this by setting your  array like so:You also need to create the  file with similar settings from aboveWith this new method of connecting in Django 1.7, it is important to know the order connections are established:If you are just testing your application on your local machine, you can useAdding the  argument allows machines other than your own to access your development application. Once you are ready to deploy your application, I recommend taking a look at the chapter on  on the Mysql default character set is often not utf-8, therefore make sure to create your database using this sql:  If you are using  your  line should look like this:To the very first please run the below commands to install python dependencies otherwise python runserver command will throw error.Then configure the settings.py file as defined by #Andy and at the last execute :Have fun..!! As all said above, you can easily install xampp first from \nThen follow the instructions as:Actually, there are many issues with different environments, python versions, so on. You might also need to install python dev files, so to 'brute-force' the installation I would run all of these:You should be good to go with the accepted answer. And can remove the unnecessary packages if that's important to you.If you are using python3.x then Run below commandThen change setting.py likeAndy's answer helps but if you have concern on exposing your database password in your django setting, I suggest to follow django official configuration on mysql connection: Quoted here as: To replace 'HOST': '127.0.0.1' in setting, simply add it in my.cnf:Another OPTION that is useful, is to set your storage engine for django, you might want it in your setting.py:sudo apt-get install python-dev python3-devsudo apt-get install libmysqlclient-devpip install MySQL-pythonpip install pymysqlpip install mysqlclientYou must create a MySQL database first. Then go to  file and edit the  dictionary with your MySQL credentials:Here is a complete installation guide for setting up Django to use MySQL on a virtualenv:
Python

I have about 10million values that I need to put in some type of look up table, so I was wondering which would be more efficient a  or ?I know you can do something like this for both:andMy thought is the dict will be faster and more efficient.Thanks for your help. \nLittle more info on what I'm trying to do.  .  I'm making a look up table to see if a value calculated has all ready been calculated.  \nEfficiency for look up. \nThere are no values assosiated with the value...so would a  be better?Lookups in lists are O(n), lookups in dictionaries are amortized O(1), with regard to the number of items in the data structure. If you don't need to associate values, use sets.Both dictionaries and sets use hashing and they use much more memory than only for object storage. According to A.M. Kuchling in , the implementation tries to keep the hash 2/3 full, so you might waste quite some memory. If you do not add new entries on the fly (which you do, based on your updated question), it might be worthwhile to sort the list and use binary search. This is O(log n), and is likely to be slower for strings, impossible for objects which do not have a natural ordering.A dict is a hash table, so it is really fast to find the keys. So between dict and list, dict would be faster. But if you don't have a value to associate, it is even better to use a set. It is a hash table, without the \"table\" part.EDIT: for your new question, YES, a set would be better. Just create 2 sets, one for sequences ended in 1 and other for the sequences ended in 89. I have sucessfully solved this problem using sets. is exactly what you want.  O(1) lookups, and smaller than a dict.I did some benchmarking and it turns out that dict is faster than both list and set for large data sets, running python 2.7.3 on an i7 CPU on linux:As you can see, dict is considerably faster than list and about 3 times faster than set. In some applications you might still want to choose set for the beauty of it, though. And if the data sets are really small (< 1000 elements) lists perform pretty well. if data are unique set() will be the most efficient, but of two - dict (which also requires uniqueness, oops :)You want a dict.  For (unsorted) lists in Python, the \"in\" operation requires O(n) time---not good when you have a large amount of data.  A dict, on the other hand, is a hash table, so you can expect O(1) lookup time.  As others have noted, you might choose a set (a special type of dict) instead, if you only have keys rather than key/value pairs.Related:You don't actually need to store 10 million values in the table, so it's not a big deal either way.Hint: think about how large your result can be after the first sum of squares operation. The largest possible result will be much smaller than 10 million...
Python

Many third-party Python modules have an attribute which holds the version information for the module (usually something like  or ), however some do not.Particular examples of such modules are libxslt and libxml2.I need to check that the correct version of these modules are being used at runtime. Is there a way to do this?A potential solution wold be to read in the source at runtime, hash it, and then compare it to the hash of the known version, but that's nasty. Is there a better solutions?I'd stay away from hashing.  The version of libxslt being used might contain some type of patch that doesn't effect your use of it.  As an alternative, I'd like to suggest that you don't check at run time (don't know if that's a hard requirement or not).  For the python stuff I write that has external dependencies (3rd party libraries), I write a script that users can run to check their python install to see if the appropriate versions of modules are installed.  For the modules that don't have a defined 'version' attribute, you can inspect the interfaces it contains (classes and methods) and see if they match the interface they expect.  Then in the actual code that you're working on, assume that the 3rd party modules have the interface you expect.Use . Anything installed from PyPI at least should have a version number.Some ideas:You can use to see the installed packages in requirements format.
Python

Hay, I'm trying to save a object to my database, but it's throwing a MultiValueDictKeyError error.The problems lies within the form, the is_private is represented by a checkbox. If the check box is NOT selected, obvously nothing is passed. This is where the error gets chucked.How do i properly deal with this exception, and catch it? The line isThankUse the MultiValueDict's  method. This is also present on standard dicts and is a way to fetch a value while providing a default if it does not exist.Generally,Choose what is best for you:If  key is present in request.POST the  variable will be equal to it, if not, then it will be equal to False.You get that because you're trying to get a key from a dictionary when it's not there. You need to test if it is in there first.try:or depending on the values you're using.Why didn't you try to define  in your models as ?
Python

I don't understand how looping over a dictionary or set in python is done by 'arbitrary' order.I mean, it's a programming language so everything in the language must be 100% determined, correct? Python must have some kind of algorithm that decides which part of the dictionary or set is chosen, 1st, second and so on. What am I missing?The order is not arbitrary, but depends on the insertion and deletion history of the dictionary or set, as well as on the specific Python implementation. For the remainder of this answer, for 'dictionary', you can also read 'set'; sets are implemented as dictionaries with just keys and no values.Keys are hashed, and hash values are assigned to slots in a dynamic table (it can grow or shrink based on needs). And that mapping process can lead to collisions, meaning that a key will have to be slotted in a  slot based on what is already there.Listing the contents loops over the slots, and so keys are listed in the order they  reside in the table.Take the keys  and , for example, and lets assume the table size is 8 slots. In Python 2.7,  is ,  is . Modulo 8, that means these two keys are slotted in slots 3 and 4 then:This informs their listing order:All slots except 3 and 4 are empty, looping over the table first lists slot 3, then slot 4, so  is listed before . and , however, have hash values that are exactly 8 apart and thus map to the exact same slot, :Their order now depends on which key was slotted first; the second key will have to be moved to a next slot:The table order differs here, because one or the other key was slotted first.The technical name for the underlying structure used by CPython (the most commonly used Python implemenation) is a , one that uses open addressing. If you are curious, and understand C well enough, take a look at the  for all the (well documented) details. You could also watch this  about how CPython  works, or pick up a copy of , which includes a chapter on the implementation written by Andrew Kuchling.Note that as of Python 3.3, a random hash seed is used as well, making hash collisions unpredictable to prevent certain types of denial of service (where an attacker renders a Python server unresponsive by causing mass hash collisions). This means that the order of a given dictionary is then  dependent on the random hash seed for the current Python invocation.Other implementations are free to use a different structure for dictionaries, as long as they satisfy the documented Python interface for them, but I believe that all implementations so far use a variation of the hash table.CPython 3.6 introduces a   implementation that maintains insertion order, and is faster and more memory efficient to boot. Rather than keep a large sparse table where each row references the stored hash value, and the key and value objects, the new implementation adds a smaller hash  that only references indices in dense table (one that only contains as many rows as there are actual key-value pairs), and it is the dense table that happens to list the contained items in order. See the . Note that this is considered an , Python-the-language does not specify that other implementations have to retain order.Python 2.7 and newer also provides an , a subclass of  that adds an additional data structure to record key order. At the price of some speed and extra memory, this class remembers in what order you inserted keys; listing keys, values or items will then do so in that order. It uses a doubly-linked list stored in an additional dictionary to keep the order up-to-date efficiently. See the . Note that the  type is still unordered.If you wanted an ordered set, you can install the ; it works on Python 2.5 and up.This is more a response to  before it was closed as a duplicate.The others are right: don't rely on the order. Don't even pretend there is one.That said, there is  thing you can rely on:That is, the order is .Understanding why there is a  order requires understanding a few things:From the top:A  is a method of storing random data with really fast lookup times.It has a backing array:We shall ignore the special dummy object, which exists only to make removes easier to deal with, because we won't be removing from these sets.In order to have really fast lookup, you do some magic to calculate a hash from an object. The only rule is that two objects which are equal have the same hash. (But if two objects have the same hash they can be unequal.)You then make in index by taking the modulus by the array length:This makes it really fast to access elements.Hashes are only most of the story, as  and  can result in the same number. In that case, several different strategies can try and resolve the conflict. CPython uses \"linear probing\" 9 times before doing complicated things, so it will look  for up to 9 places before looking elsewhere.CPython's hash sets are stored like this:So when you create an array the backing store is length 8. When it is 5 full and you add an element, it will briefly contain 6 elements.  so this triggers a resize, and the backing store quadruples to size 32.Finally,  just returns  for numbers (except  which is special).So, let's look at the first one: is 10, so the backing store is at least 15(+1) . The relevant power of 2 is 32. So the backing store is:We haveso these insert as:So we would expect an order likewith the 1 or 33 that isn't at the start somewhere else. This will use linear probing, so we will either have:orYou might expect the 33 to be the one that's displaced because the 1 was already there, but due to the resizing that happens as the set is being built, this isn't actually the case. Every time the set gets rebuilt, the items already added are effectively reordered.Now you can see whymight be in order. There are 14 elements, so the backing store is at least 21+1, which means 32:1 to 13 hash in the first 13 slots. 20 goes in slot 20.55 goes in slot  which is 23:If we chose 50 instead, we'd expectAnd lo and behold: is implemented quite simply by the looks of things: it traverses the list and pops the first one.\"Arbitrary\" isn't the same thing as \"non-determined\".What they're saying is that there are no useful properties of dictionary iteration order that are \"in the public interface\". There almost certainly are many properties of the iteration order that are fully determined by the code that currently implements dictionary iteration, but the authors aren't promising them to you as something you can use. This gives them more freedom to change these properties between Python versions (or even just in different operating conditions, or completely at random at runtime) without worrying that your program will break.Thus if you write a program that depends on  of dictionary order, then you are \"breaking the contract\" of using the dictionary type, and the Python developers are not promising that this will always work, even if it appears to work for now when you test it. It's basically the equivalent of relying on \"undefined behaviour\" in C.The other answers to this question are excellent and well written.  The OP asks \"how\" which I interpret as \"how do they get away with\" or \"why\".The Python documentation says  are not ordered because the Python dictionary implements the  .  As they say In other words, a computer science student cannot assume that an associative array is ordered.  The same is true for sets in  and  Implementing a dictionary using a hash table is an  that is interesting in that it has the same properties as associative arrays as far as order is concerned.Python use  for storing the dictionaries, so there is no order in dictionaries or other iterable objects that use hash table.But regarding the indices of items in a hash object, python calculate the indices based on following code :Therefor, as the hash value of integers is the integer itself the index  is based on the number ( is a constant) so the index calculated by  between  and the number itself (expect for -1 which it's hash is -2) , and for other objects with their hash value. consider the following example with  that use hash-table :For number  we have : That actually it's : in this case  is  or . And for  :And for  :For more details about python hash function its good to read the following quotes from  :
Python

I'm trying to build two functions using PyCrypto that accept two parameters: the message and the key, and then encrypt/decrypt the message.I found several links on the web to help me out, but each one of them has flaws: uses os.urandom, which is discouraged by PyCrypto.Moreover, the key I give to the function is not guaranteed to have the exact length expected. What can I do to make that happen ?Also, there are several modes, which one is recommended? I don't know what to use :/Finally, what exactly is the IV? Can I provide a different IV for encrypting and decrypting, or will this return in a different result?Here's what I've done so far:Here is my implementation and works for me with some fixes and enhances the alignment of the key and secret phrase with 32 bytes and iv to 16 bytes:You may need the following two functions to pad(when do encryption) and unpad(when do decryption) when the length of input is not a multiple of BLOCK_SIZE.So you're asking the length of key? You can use the md5sum of the key rather than use it directly.More, according to my little experience of using PyCrypto, the IV is used to mix up the output of a encryption when input is same, so the IV is chosen as a random string, and use it as part of the encryption output, and then use it to decrypt the message.And here's my implementation, hope it will be useful for you:You can get a passphrase out of an arbitrary password by using a cryptographic hash function ( Python's builtin ) like SHA-1 or SHA-256. Python includes support for both in its standard library:You can truncate a cryptographic hash value just by using  or  and it will retain its security up to the length you specify.For someone who would like to use urlsafe_b64encode and urlsafe_b64decode, here are the version that're working for me (after spending some time with the unicode issue)For the benefit of others, here is my decryption implementation which I got to by combining the answers of @Cyril and @Marcus.  This assumes that this coming in via HTTP Request with the encryptedText quoted and base64 encoded.Another take on this (heavily derived from solutions above) butIt's little late but i think this will be very helpful. No one mention about use  scheme like PKCS#7 padding. You can use it instead the previous functions to pad(when do encryption) and unpad(when do decryption).i will provide the full Source Code below.
Python

I want to put output information of my program to a folder. if given folder does not exist, then the program should create a new folder with folder name as given in the program. Is this possible? If yes, please let me know how.Suppose I have given folder path like  and  folder doesn't exist then program should create  folder and should put output information in the  folder.You can create a folder with \nand use  to see if it already exists:If you're trying to make an installer:  does a lot of work for you.You probably want  as it will create intermediate directories as well, if needed.Have you tried os.mkdir?You might also try this little code snipped:makedirs creates multiple levels of directories, if needed.
Python

I am trying to create a graphical spectrum analyzer in python.I am currently reading 1024 bytes of a 16 bit dual channel 44,100 Hz sample rate audio stream and averaging the amplitude of the 2 channels together.  So now I have an array of 256 signed shorts.  I now want to preform a fft on that array, using a module like numpy, and use the result to create the graphical spectrum analyzer, which, to start will just be 32 bars.I have read the wikipedia articles on Fast Fourier Transform and Discrete Fourier Transform but I am still unclear of what the resulting array represents.  This is what the array looks like after I preform an fft on my array using numpy:I am wondering what exactly these numbers represent and how I would convert these numbers into a percentage of a height for each of the 32 bars.  Also, should I be averaging the 2 channels together?The array you are showing is the Fourier Transform coefficients of the audio signal. These coefficients can be used to get the frequency content of the audio. The FFT is defined for complex valued input functions, so the coefficients you get out will be imaginary numbers even though your input is all real values. In order to get the amount of power in each frequency, you need to calculate the magnitude of the FFT coefficient for each frequency. This is  just the real component of the coefficient, you need to calculate the square root of the sum of the square of its real and imaginary components. That is, if your coefficient is a + b*j, then its magnitude is sqrt(a^2 + b^2).Once you have calculated the magnitude of each FFT coefficient, you need to figure out which audio frequency each FFT coefficient belongs to. An N point FFT will give you the frequency content of your signal at N equally spaced frequencies, starting at 0. Because your sampling frequency is 44100 samples / sec. and the number of points in your FFT is 256, your frequency spacing is 44100 / 256 = 172 Hz (approximately)The first coefficient in your array will be the 0 frequency coefficient. That is basically the average power level for all frequencies. The rest of your coefficients will count up from 0 in multiples of 172 Hz until you get to 128. In an FFT, you only can measure frequencies up to half your sample points. Read these links on the  and  if you are a glutton for punishment and need to know why, but the basic result is that your lower frequencies are going to be replicated or  in the higher frequency buckets. So the frequencies will start from 0, increase by 172 Hz for each coefficient up to the N/2 coefficient, then decrease by 172 Hz until the N - 1 coefficient.That should be enough information to get you started. If you would like a much more approachable introduction to FFTs than is given on Wikipedia, you could try . It was very helpful for me.So that is what those numbers represent. Converting to a percentage of height could be done by scaling each frequency component magnitude by the sum of all component magnitudes. Although, that would only give you a representation of the relative frequency distribution, and not the actual power for each frequency. You could try scaling by the maximum magnitude possible for a frequency component, but I'm not sure that that would display very well. The quickest way to find a workable scaling factor would be to experiment on loud and soft audio signals to find the right setting.Finally, you should be averaging the two channels together if you want to show the frequency content of the entire audio signal as a whole. You are mixing the stereo audio into mono audio and showing the combined frequencies. If you want two separate displays for right and left frequencies, then you will need to perform the Fourier Transform on each channel separately.Although this thread is years old, I found it very helpful. I just wanted to give my input to anyone who finds this and are trying to create something similar.As for the division into bars this should not be done as antti suggest, by dividing the data equally based on the number of bars. The most useful would be to divide the data into octave parts, each octave being double the frequency of the previous. (ie. 100hz is one octave above 50hz, which is one octave above 25hz). Depending on how many bars you want, you divide the whole range into 1/X octave ranges.\nBased on a given center frequency of A on the bar, you get the upper and lower limits of the bar from:To calculate the next adjoining center frequency you use a similar calculation:You then average the data that fits into these ranges to get the amplitude for each bar.For example:\nWe want to divide into 1/3 octaves ranges and we start with a center frequency of 1khz.Given 44100hz and 1024 samples (43hz between each data point) we should average out values 21 through 26. ( 890.9 / 43 = 20.72 ~ 21 and 1122.5 / 43 = 26.10 ~ 26 )(1/3 octave bars would get you around 30 bars between ~40hz and ~20khz).\nAs you can figure out by now, as we go higher we will average a larger range of numbers. Low bars typically only include 1 or a small number of data points. While the higher bars can be the average of hundreds of points. The reason being that 86hz is an octave above 43hz... while 10086hz sounds almost the same as 10043hz.what you have is a sample whose length in time is 256/44100 = 0.00580499 seconds. This means that your frequency resolution is 1 / 0.00580499 = 172 Hz. The 256 values you get out from Python correspond to the frequencies, basically, from 86 Hz to 255*172+86 Hz = 43946 Hz. The numbers you get out are complex numbers (hence the \"j\" at the end of every second number).EDITED: FIXED WRONG INFORMATIONYou need to convert the complex numbers into amplitude by calculating the sqrt(i + j) where i and j are the real and imaginary parts, resp.If you want to have 32 bars, you should as far as I understand take the average of four successive amplitudes, getting 256 / 4 = 32 bars as you want.
Python

Is there a built-in function that can round like this:I don't know of a standard function in Python, but this works for me:It is easy to see why the above works.  You want to make sure that your number divided by 5 is an integer, correctly rounded.  So, we first do exactly that (), and then since we divided by 5, we multiply by 5 as well.  The final conversion to  is because  returns a floating-point value in Python.I made the function more generic by giving it a  parameter, defaulting to 5.For rounding to non-integer values, such as 0.05:I found this useful since I could just do a search and replace in my code to change \"round(\" to \"myround(\", without having to change the parameter values.It's just a matter of scaling    Removing the 'rest' would work:If the value is aready an integer:As a function:round(x[, n]): values are rounded to the closest multiple of 10 to the power minus n. So if n is negative...Since 10 = 5 * 2, you can use integer division and multiplication with 2, rather than float division and multiplication with 5.0. Not that that matters much, unless you like bit shiftingModified version of divround :-)Sorry, I wanted to comment on Alok Singhai's answer, but it won't let me due to a lack of reputation =/Anyway, we can generalize one more step and go:This allows us to use non-integer bases, like  or any other fractional base.I realise I'm late to the party, but it seems that this solution has not been mentioned:It does not use multiplication and will not convert from/to floats.Rounding to the nearest multiple of 10:As you can see, it works for both negative and positive numbers. Ties (e.g. -15 and 15) will always be rounded upwards.Similar example that rounds no the nearest multiple of 5, demonstrating that it also behaves as expected for a different \"base\":What about this:In case someone needs \"financial rounding\" (0.5 rounds always up):As per documentation other rounding options are:By default Python uses ROUND_HALF_EVEN as it has some statistical advantages (the rounded results are not biased).**next multiple of 5 **consider 51 need to converted to 55You can \u201ctrick\u201d  into rounding off instead of rounding down by adding  to the \nnumber you pass to .
Python

I have data, in which I want to find number of NaN, so that if it is less than some threshold, I will drop this columns. I looked, but didn't able to find any function for this. there is count_values(), but it would be slow for me, because most of values are distinct and I want count of NaN only.You can use the  method and then sum to count the nan values. For one column:For several columns, it also works:You could subtract the total length from the  of non-nan values:You should time it on your data. For small Series got a 3x speed up in comparison with the  solution.Since pandas 0.14.1 my suggestion  to have a keyword argument in the value_counts method has been implemented:if you are using Jupyter Notebook, How about....oror, are there anywhere NaNs in the data, if yes, where?if its just counting nan values in a pandas column here is a quick wayBased on the second and most voted answer we can easily define a function that gives us a dataframe to preview the missing values and the % of missing values in each column:Used the solution proposed by @sushmit in my code. \nA possible variation of  the same can also be -\n\nAdvantage of this is that it returns the result for each of the columns in the df henceforth.You can use value_counts method and print values of np.nanbased to the answer that was given and some improvements this is my approach 
Python

So I tried the \"evil\" thing Ned Deily mentioned in his answer . Now I have that the type True is now always False. How would I reverse this within the interactive window?Thing to not do:Since True has now been completely overridden with False, there doesn't seem to be an obvious way to back-track. Is there a module that True comes from that I can do something like:You can simply  your custom name to set it back to the default:This works:but fails if  has been fiddled with as well. Therefore this is better:as  cannot be reassigned.These also evaluate to  regardless of whether  has been reassigned to , , , , etc:Another way:For completeness: Kevin mentions that you could also fetch the real  from :But that  can also be overriden:So better to go with one of the other options.Just do this:Or, because booleans are essentially integers:Solutions that use no object literals but are as durable as . Of course, you can define False once True is defined, so I'll supply solutions as half pairs.
Python

I am trying to plot some data from a camera in real time using OpenCV. However the real-time plotting (using matplotlib) doesn't seem to be working.I've isolated the problem into this simple example:I would expect this example to plot 1000 points individually. What actually happens is that the window pops up with the first point showing (ok with that), then waits for the loop to finish before it populates the rest of the graph.Any thoughts why I am not seeing points populated one at a time?Here's the working version of the code in question (requires at least version Matplotlib 1.1.0 from 2011-11-14):Note some of the changes: The while loop at the end is to keep the window up after all data is plotted.If you're interested in realtime plotting, I'd recommend looking into . In particular, using  to avoid redrawing the background on every frame can give you substantial speed gains (~10x):Output: is probably not the best choice for this.  What I would do is use  instead.  You also might want to include a small time delay (e.g., ) in the loop so that you can see the plots happening.  If I make these changes to your example it works for me and I see each point appearing one at a time.None of the methods worked for me.\nBut I have found this\nAll you need is to addand than you could see the new plot.I know I'm a bit late to answer this question. Nevertheless, I've made some code a while ago to plot live graphs, that I would like to share:Just try it out. Copy-paste this code in a new python-file, and run it. You should get a beautiful, smoothly moving graph:The problem seems to be that you expect  to show the window and then to return. It does not do that. The program will stop at that point and only resume once you close the window. You should be able to test that: If you close the window and then another window should pop up.To resolve that problem just call  once after your loop. Then you get the complete plot. (But not a 'real-time plotting')You can try setting the keyword-argument  like this:  once at the beginning and then use  to update.Here is a version that I got to work on my system.The drawnow(makeFig) line can be replaced with a makeFig(); plt.draw() sequence and it still works OK.I know this question is old, but there's now a package available called  on GitHub as \"python-drawnow\". This provides an interface similar to MATLAB's drawnow -- you can  update a figure.An example for your use case:python-drawnow is a thin wrapper around  but provides the ability to confirm (or debug) after figure display.If you want draw and not freeze your thread as more point are drawn you should use plt.pause() not time.sleep()im using the following code to plot a series of xy coordinates.
Python

Is there a way to upgrade the version of python used in a virtualenv (e.g. if a bugfix release comes out)?I could  then remove the directory and  but this requires a lot of reinstallation of large libraries, for instance numpy which I use a lot. I can see this is an advantage when upgrading from e.g. 2.6 -> 2.7, but what about 2.7.x -> 2.7.y?ThanksDid you see ? If I haven't misunderstand that answer, you may try to create a new virtualenv on top of the old one. You just need to know which python is going to use your virtualenv (you will need to see your virtualenv version). If your virtualenv is installed with the same python version of the old one and upgrading your virtualenv package is not an option, you may want to read  in order to install a virtualenv with the python version you want.I've tested this approach (the one that create a new virtualenv on top of the old one) and it worked fine for me. I think you may have some problems if you change from python 2.6 to 2.7 or 2.7 to 3.x but if you just upgrade inside the same version (staying at 2.7 as you want) you shouldn't have any problem, as all the packages are held in the same folders for both python versions (2.7.x and 2.7.y packages are inside your_env/lib/python2.7/).If you change your virtualenv python version, you will need to install all your packages again for that version (or just link the packages you need into the new version packages folder, i.e: your_env/lib/python_newversion/site-packages) I changed the answer 5 months after I originally answered. The following method is more convenient and robust. it also fixes the  exception when you do  in a virtual environment after upgrading Python to v2.7.8. Currently, .If you're using Homebrew Python on OS X, first  all virtualenv, then upgrade Python:Run the following commands ( is path of your virtual environment):Finally, re-create your virtual environment:By doing so, old Python core files and standard libraries (plus  and ) are removed, while the custom libraries installed in  are preserved and working, as soon as they are in pure Python. Binary libraries may or may not need to be reinstalled to function properly.This worked for me on 5 virtual environments with Django installed.BTW, if  is not working afterwards, try this:If you happen to be using the venv module that comes with Python 3.3+, it supports an  option. \nPer the :I wasn't able to create a new virtualenv on top of the old one.  But there are tools in pip which make it much faster to re-install requirements into a brand new venv.  Pip can build each of the items in your requirements.txt into a wheel package, and store that in a local cache.  When you create a new venv and run pip install in it, pip will automatically use the prebuilt wheels if it finds them.  Wheels install much faster than running setup.py for each module.My ~/.pip/pip.conf looks like this:I install wheel (), then run .  This stores the built wheels in the wheel-dir in my pip.conf.From then on, any time I pip install any of these requirements, it installs them from the wheels, which is pretty quick.  I moved my home directory from one mac to another (Mountain Lion to Yosemite) and didn't realize about the broken virtualenv until I lost hold of the old laptop. I had the virtualenv point to Python 2.7 installed by  and since Yosemite came with Python 2.7, I wanted to update my virtualenv to the system python. When I ran  on top of the existing directory, I was getting  error. By trial and error, I worked around this issue by removing a few links and fixing up a few more manually. This is what I finally did (similar to what @Rockalite did, but simpler):After this, I was able to just run virtualenv on top of the existing directory.I'm adding an answer for anyone using Doug Hellmann's excellent  specifically since the existing answers didn't do it for me.Some context:Directions:Let's say your existing project is named  and is currently running Python 2 (), though the commands are the same whether upgrading from 2.x to 3.x, 3.6.0 to 3.6.1, etc.  I'm also assuming you're currently inside the activated virtual environment.1. Deactivate and remove the old virtual environment:Note that if you've added any custom commands to the hooks (e.g., ) you'd need to save those before removing the environment.2. Stash the real project in a temp directory:3. Create the new virtual environment (and project dir) and activate:4. Replace the empty generated project dir with real project, change back into project dir:5. Re-install dependencies, confirm new Python version, etc:If this is a common use case, I'll consider opening a PR to add something like  /  to virtualenvwrapper.
Python

When initializing a dictionary with  Pycharm's code inspector generates a warning, sayingIf I rewrite it  the warning goes away. Since  already  a dictionary literal, I'm pretty sure the message is erroneous. Furthermore, it seems like both  and  are valid and Pythonic. This related question seems to conclude that the choice is just a matter of style/preference:\nWhy would Pycharm complain about ?Mac nailed it. The warning actually applied to multiple lines, not just the one that was flagged.Pycharm seems to look for a sequence of consecutive statements where you initialize a dictionary and then set values in the dictionary. For example, this will trigger the warning:But this code will not:I think pycharm will trigger the error if you have something like:as you could have writtenBTW: The fact that the error goes away if you use the function doesn't necessarily mean that pycharm believes  is a literal. It could just mean that it doesn't complain for:HTH!
Python

I am getting TransactionManagementError when trying to save a Django User model instance and in its post_save signal, I'm saving some models that have the user as the foreign key. The context and error is pretty similar to this question\nHowever, in this case, the error occurs .It works well in manual testing, but unit tests fails.Is there anything that I'm missing?views.pysignal.pytests.pyTraceback:I ran into this same problem myself. This is caused by a quirk in how transactions are handled in the newer versions of Django coupled with a unittest that intentionally triggers an exception.I had a unittest that checked to make sure a unique column constraint was enforced by purposefully triggering an IntegrityError exception:In Django 1.4, this works fine. However, in Django 1.5/1.6, each test is wrapped in a transaction, so if an exception occurs, it breaks the transaction until you explicitly roll it back. Therefore, any further ORM operations in that transaction, such as my , will fail with that  exception.Like caio mentioned in the comments, the solution is to capture your exception with  like:That will prevent the purposefully-thrown exception from breaking the entire unittest's transaction.Since @mkoistinen never made , an answer, I'll post his suggestion so people won't have to dig through comments.From the : A TransactionTestCase may call commit and rollback and observe the effects of these calls on the database.I was getting this error on running unit tests in my create_test_data function using django 1.9.7.  It worked in earlier versions of django.It looked like this:My solution was to use update_or_create instead:I had the same issue, while testing and went searching google and stackoverflow.In My Case I was doing thisso converting it toRemoved that error.
Python

Having spent a decent amount of time watching both the  and  tags on SO, the impression that I get is that  questions are less likely to contain reproducible data. This is something that the R community has been pretty good about encouraging, and thanks to guides like , newcomers are able to get some help on putting together these examples. People who are able to read these guides and come back with reproducible data will often have much better luck getting answers to their questions.How can we create good reproducible examples for  questions? Simple dataframes can be put together, e.g.:But many example datasets need more complicated structure, e.g.:For datasets that are hard to mock up using a few lines of code, is there an equivalent to R's  that allows you to generate copy-pasteable code to regenerate your datastructure?This is to mainly to expand on @AndyHayden's answer by providing examples of how you can create sample dataframes.  Pandas and (especially) numpy give you a variety of tools for this such that you can generally create a reasonable facsimile of any real dataset with just a few lines of code.After importing numpy and pandas, be sure to provide a random seed if you want folks to be able to exactly reproduce your data and results.Here's an example showing a variety of things you can do.  All kinds of useful sample dataframes could be created from a subset of this:This produces:Some notes:In addition to taking subsets of the above code, you can further combine the techniques to do just about anything.  For example, here's a short example that combines  and  to create sample ticker data for 4 stocks covering the same dates:Now we have a sample dataset with 100 lines (25 dates per ticker), but we have only used 4 lines to do it, making it easy for everyone else to reproduce without copying and pasting 100 lines of code.  You can then display subsets of the data if it helps to explain your question:My best advice for asking questions would be to play on the psychology of the people who answer questions.  Being one of those people, I can give insight into why I answer certain questions and why I don't answer others.I'm motivated to answer questions for several reasonsAll my purest intentions are great and all, but I get that satisfaction if I answer 1 question or 30.   for which questions to answer has a huge component of point maximization.I'll also spend time on interesting problems but that is few and far between and doesn't help an asker who needs a solution to a non-interesting question.  Your best bet to get me to answer a question is to serve that question up on a platter ripe for me to answer it with as little effort as possible.  If I'm looking at two questions and one has code I can copy paste to create all the variables I need... I'm taking that one!  I'll come back to the other one if I have time, maybe.Make it easy for the people answering questions.I like points (I mentioned that above).  But those points aren't really really my reputation.  My real reputation is an amalgamation of what others on the site think of me.  I strive to be fair and honest and I hope others can see that.  What that means for an asker is, we remember the behaviors of askers.  If you don't select answers and upvote good answers, I remember.  If you behave in ways I don't like or in ways I do like, I remember.  This also plays into which questions I'll answer.Anyway, I can probably go on, but I'll spare all of you who actually read this. One of the most challenging aspects of responding to SO questions is the time it takes to recreate the problem (including the data).  Questions which don't have a clear way to reproduce the data are less likely to be answered.  Given that you are taking the time to write a question and you have an issue that you'd like help with, you can easily help yourself by providing data that others can then use to help solve your problem.The instructions provided by @Andy for writing good Pandas questions are an excellent place to start.  For more information, refer to  and how to create .  After taking the time to write your question and any sample code, try to read it and provide an 'Executive Summary' for your reader which summarizes the problem and clearly states the question.:Depending on the amount of data, sample code and error stacks provided, the reader needs to go a long way before understanding what the problem is.  Try restating your question so that the question itself is on top, and then provide the necessary details.:Sometimes just the head or tail of the DataFrame is all that is needed.  You can also use the methods proposed by @JohnE to create larger datasets that can be reproduced by others.  Using his example to generate a 100 row DataFrame of stock prices:If this was your actual data, you may just want to include the head and/or tail of the dataframe as follows (be sure to anonymize any sensitive data):You may also want to provide a description of the DataFrame (using only the relevant columns).  This makes it easier for others to check the data types of each column and identify other common errors (e.g. dates as string vs. datetime64 vs. object):If your DataFrame has a multiindex, you must first reset before calling .  You then need to recreate the index using :Here is my version of  - the standard R tool to produce reproducible reports - for Pandas s.\nIt will probably fail for more complex frames, but it seems to do the job in simple cases:now,  that this produces a much more verbose output than , e.g.,vsfor  above, but it preserves column types. \nE.g., in the above test case,because  is  and  is .
Python

Both function return the same list.\nThen what is the need of two different functions performing same job.The difference is that flatten always returns a copy and ravel returns a view of the original array whenever possible. This isn't visible in the printed output, but if you modify the array returned by ravel, it may modify the entries in the original array. If you modify the entries in an array returned from flatten this will never happen. ravel will often be faster since no memory is copied, but you have to be more careful about modifying the array it returns.As explained  a key difference is that  is a method of an ndarray object and hence can only be called for true numpy arrays. In contrast  is a library-level function and hence can be called on any object that can successfully be parsed. For example  will work on a list of ndarrays, while flatten is not available for that type of object.@IanH also points out important differences with memory handling in his answer.
Python

I need to lock a file for writing in Python. It will be accessed from multiple Python processes at once. I have found some solutions online, but most fail for my purposes as they are often only Unix based or Windows based.Alright, so I ended up going with the code I wrote  (). I can use it in the following fashion:There is a cross-platform file locking module here: Although as Kevin says, writing to a file from multiple processes at once is something you want to avoid if at all possible.If you can shoehorn your problem into a database, you could use SQLite.  It supports concurrent access and handles its own locking.I prefer  \u2014 Platform-independent file lockingCoordinating access to a single file at the OS level is fraught with all kinds of issues that you probably don't want to solve.Your best bet is have a separate process that coordinates read/write access to that file.Locking is platform and device specific, but generally, you have a few options:For all these methods, you'll have to use a spin-lock (retry-after-failure) technique for acquiring and testing the lock.  This does leave a small window for mis-synchronization, but its generally small enough to not be an major issue.If you're looking for a solution that is cross platform, then you're better off logging to another system via some other mechanism (the next best thing is the NFS technique above).  Note that sqlite is subject to the same constraints over NFS that normal files are, so you can't write to an sqlite database on a network share and get synchronization for free.Locking a file is usually a platform-specific operation, so you may need to allow for the possibility of running on different operating systems. For example:I have been looking at several solutions to do that and my choice has been\nIt's powerful and relatively well documented. It's based on fasteners.Other solutions:I found a simple and worked(!)  from grizzled-python.Simple use os.open(..., O_EXCL) + os.close() didn't work on windows.I have been working on a situation like this where I run multiple copies of the same program from within the same directory/folder and logging errors.  My approach was to write a \"lock file\" to the disc before opening the log file. The program checks for the presence of the \"lock file\" before proceeding, and waits it's turn if the \"lock file\" exists.Here is the code:EDIT---\nAfter thinking over some of the comments about stale locks above I edited the code to add a check for staleness of the \"lock file.\"  Timing several thousand iterations of this function on my system gave and average of 0.002066... seconds from just before:to just after:so I figured I will start with 5 times that amount to indicate staleness and monitor the situation for problems.Also, as I was working with the timing, I realized that I had a bit of code  that was not really necessary:which I had immediately following the open statement, so I have removed it in this edit.Kernel-level file locking is an extremly complex subject, since different types of locks have very different semantic, and the main lock of unix systems (fcntl) has horrible flaws.But I've just released a python library which deals with the issue in a very portable way. It can achieve shared/exclusive file record locking in a system-wide manner, and provides workaround for fcntl flaws.Enjoy RSFile - You may find  very useful. It can be used to lock a file or for locking mechanisms in general and can be accessed from multiple Python processes at once. If you simply  want to lock a file here's how it works: 
Python

Every day I love python more and more. Today, I was writing some code like:I had to do something N times. But each time didn't depend on the value of  (index variable).\nI realized that I was creating a variable I never used (), and I thought \"There surely is a more pythonic way of doing this without the need for that useless index variable.\"So... the question is: do you know how to do this simple task in a more (pythonic) beautiful way?A slightly faster approach than looping on  is:Use the _ variable, as I learned when I asked this , for example:I just use , it's straight to the point. It's going to generate the entire list for huge numbers in Python 2, but if you're using Python 3 it's not a problem.since function is first-class citizen, you can write small wrapper (from Alex answers)then you can pass function as argument.Assume that you've defined  as a function, and you'd like to perform it  times.\nMaybe you can try the following:The _ is the same thing as x. However it's a python idiom that's used to indicate an identifier that you don't intend to use. In python these identifiers don't takes memor or allocate space like variables do in other languages.  It's easy to forget that.  They're just names that point to objects, in this case an integer on each iteration.What about a simple while loop?You already have the variable; why not use it?
Python

I am trying to save a csv to a folder after making some edits to the file. Every time I use  the csv file has a separate column of indexes. I want to avoid printing the index to csv.I tried: And to save the file...However, I still got the unwanted index column. How can I avoid this when I save my files?Use .There are two ways to handle the situation where we do not want the index to be stored in csv file.
Python

Is there a generally accepted way to do this?  Is this acceptable:The correct way to do it is to provide a docstring. That way,  will also spit out your comment.That's three double quotes to open the comment and another three double quotes to end it. You can also use any valid Python string. It doesn't need to be multiline and double quotes can be replaced by single quotes. See: Use a docstring, as others have already written. You can even go one step further and add a  to your docstring, making automated testing of your functions a snap.Use a :Oh boy! Consider a can of worms opened :)The principles of good commenting are fairly subjective, but here are some guidlines:Read about using  in your python code.As per the Python Docstring Conventions:There will be no golden rule, but rather provide comments that mean something to the other developers on your team (if you have one) or even to yourself when you come back to it six months down the road.I would go for a documentation practice that integrates with a Documentation tool such as .  The first step is to use a :I would go a step further than just saying \"use a docstring\". Pick a documentation generation tool, such as pydoc or epydoc (I use epydoc in pyparsing), and use the markup syntax recognized by that tool.  Run that tool often while you are doing your development, to identify holes in your documentation.  In fact, you might even benefit from writing the docstrings for the members of a class  implementing the class.
Python

I have a script reading in a csv file with very huge fields:However, this throws the following error on some csv files:The csv file might contain very huge fields, therefore increase the : works for Python 2.x and 3.x.  would only work with Python 2.x ()As Geoff pointed out, the code above might result in the following error: . \nTo circumvent this, you could use the following  code:This could be because your CSV file has embedded single or double quotes. If your CSV file is tab-delimited try opening it as:For Python 3.4 I found this code and it works for me:
Python

the following code worked until today when I imported from a Windows machine and got this error:How can I fix this issue?It'll be good to see the csv file itself, but this might work for you, give it a try, replace:with:Or, open a file with  and pass it to , like:Or, use , like this:I realize this is an old post, but I ran into the same problem and don't see the correct answer so I will give it a tryPython Error:Caused by trying to read Macintosh (pre OS X formatted) CSV files. These are text files that use CR for end of line. If using MS Office make sure you select either plain  format or .  as save-as type. My preferred EOL version would be LF (Unix/Linux/Apple), but I don't think MS Office provides the option to save in this format.For Mac OS X, save your CSV file in \"Windows Comma Separated (.csv)\" format.If this happens to you  (as it did to me):Try to run  on your windows imported files firstThis worked for me on OSX.This is an error that I faced. I had saved .csv file in MAC OSX.While saving, save it as \"Windows Comma Separated Values (.csv)\" which resolved the issue.
Python

I was looking for an elegant way to change a specified column name in a .play data ...The most elegant solution I have found so far ...I was hoping for a simple one-liner ... this attempt failed ...Any hints gratefully received.A one liner does exist:Following is the docstring for the  method.Since  argument is available, you don't need to copy and assign the original data frame back to itself, but do as follows:What about?
Python

Someone suggested I use an ORM for a project I'm designing but I'm having trouble finding information on what it is or how it works. Can anyone give me a brief explanation or a link as to where I can learn more about it? (ORM) is a technique that lets you query and manipulate data from a database using an object-oriented paradigm. When talking about ORM, most people are referring to a  that implements the Object-Relational Mapping technique, hence the phrase \"an ORM\".An ORM library is a completely ordinary library written in your language of choice that encapsulates the code needed to manipulate the data, so you don't use SQL anymore; you interact directly with an object in the same language you're using.For example, here is a completely imaginary case with a pseudo language:You have a book class, you want to retrieve all the books of which the author is \"Linus\". Manually, you would do something like that:With an ORM library, it would look like this:The mechanical part is taken care of automatically via the ORM library.Well, use one. Whichever ORM library you choose, they all use the same principles. There are a lot of ORM libraries around here:If you want to try an ORM library in Web programming, you'd be better off using an entire framework stack like:Do not try to write your own ORM, unless you are trying to learn something. This is a gigantic piece of work, and the old ones took a lot of time and work before they became reliable.Sure.ORM stands for  \"Object to Relational Mapping\" where In applications where you don't use a ORM framework you do this by hand. Using an ORM framework would allow you do reduce the boilerplate needed to create the solution.So let's say you have this object.and the tableUsing an ORM framework would allow you to map that object with a db record automagically and write something like:And have the employee inserted into the DB.An ORM (Object Relational Mapper) is a piece/layer of software that helps map your code Objects to your database.Some handle more aspects than others...but the purpose is to take some of the weight of the Data Layer off of the developer's shoulders.Here's a brief clip from Martin Fowler (Data Mapper):The first chapter of the Hibernate book  has an excellent overview of general ORM concepts and discusses motivation and design of ORMs. Highly recommended, even if you don't work with Java. is a great option for those using python.Like all acronyms it's ambiguous, but I assume they mean  -- a way to cover your eyes and make believe there's no SQL underneath, but rather it's all objects;-). Not really true, of course, and not without problems -- the always colorful Jeff Atwood has described ORM as ;-). But, if you know little or no SQL, and have a pretty simple / small-scale problem, they can save you time!-)This is a huge topic. Pick up a good hibernate book and it should explain ORM in detail before getting to the nitty gritty hibernate material.DALMP   could be a good one for php/mysql currently supporting many caches backends like redis/memcache/apcObject Model is concerned with the following three concepts\nData Abstraction\nEncapsulation\nInheritance\nThe relational model used the basic concept of a relation or table.\nObject-relational mapping (OR mapping) products integrate object programming language capabilities with relational databases.
Python

How do I get the probability of a string being similar to another string in Python?I want to get a decimal value like:etc.Preferably with standard Python and library.e.g.There is a built in.Using it:I think maybe you are looking for an algorithm describing the distance between strings. Here are some you may refer to:   is a  that implements Levenshtein distance in python, with some helper functions to help in certain situations where you may want two distinct strings to be considered identical. For example:You can create a function like:Package  includes Levenshtein distance:
Python

I am using jinja2, and I want to call a python function as a helper, using a similar syntax as if I were calling a macro. jinja2 seems intent on preventing me from making a function call, and insists I repeat myself by copying the function into a template as a macro.    Is there any straightforward way to do this?  And, is there any way to import a whole set of python functions and have them accessible from jinja2, without going through a whole lot of rigamarole (such as writing an extension)?For those using Flask, put this in your :and in your template call it with I know this post is quite old, but there are better methods of doing this in the newer versions of Flask using context processors.The above can be used in a Jinja2 template with Flask like so:(Which outputs )The above when used like so:(Which outputs the input price with the currency symbol)Or, without decorators, and manually registering the function:Filters applied with the above two methods can be used like this:I think jinja deliberately makes it difficult to run 'arbitrary' python within a template. It tries to enforce the opinion that less logic in templates is a good thing.You can manipulate the global namespace within an  instance to add references to your functions. It must be done  you load any templates. For example:Will output:Works with Jinja2 version 2.7.3Use a lambda to connect the template to your main codeThen you can seamlessly call the function in the templateTo call a python function from Jinja2, you can use custom filters which work similarly as the globals:\nIt's quite simple and useful.\nIn a file myTemplate.txt, I wrote:And in a python script:
Python

I have two dictionaries, but for simplification, I will take these two:Now, I want to compare whether each  pair in  has the same corresponding value in . So I wrote this:And it works since a  is returned and then compared for equality.My questions:Is this correct? Is there a  way to do this? Better not in speed, I am talking about code elegance.UPDATE: I forgot to mention that I have to check how many  pairs are equal. If you want to know how many values match in both the dictionaries, you should have said that :) Maybe something like this:What you want to do is simply  What you do is not a good idea, because the items in a dictionary are not supposed to have any order. You might be comparing  with  (same dictionaries, different order).For example, see this:The difference is only one item, but your algorithm will see that  items are differentI'm new to python but I ended up doing something similar to @mouadThe XOR operator () should eliminate all elements of the dict when they are the same in both dicts.Just use:@mouad 's answer is nice if you assume both dictionaries just contain simple values. However if you have dictionaries that contain dictionaries you'll get an exception as dictionaries are not hashable.Off the top of my head, something like this might work:Note that I'm not yet happy about the line:as the values of these could be objects. It would be nice to be able to check if the two objects were implementing a comparable interface.To check if two dictionaries are equal, simply use:Yet another possibility, up to the last note of the OP, is to compare the hashes ( or ) of the dicts dumped as JSON. The way hashes are constructed guarantee that if they are equal, the source strings are equal as well. This is very fast and mathematically sound. Here's another option:So as you see the two id's are different. But the  seem to do the trick:In PyUnit there's a method which compares dictionaries beautifully. I tested it using the following two dictionaries, and it does exactly what you're looking for.I'm not recommending importing  into your production code. My thought is the source in PyUnit could be re-tooled to run in production. It uses  which \"pretty prints\" the dictionaries. Seems pretty easy to adapt this code to be \"production ready\".
Python

What is the difference between  and  in Numpy? And where can I find the implementations in the numpy source code?Well,  is just a convenience function to create an , it is not a class itself.  You can also create an array using , but it is not the recommended way.  From the docstring of :  Most of the meat of the implementation is in C code, , but you can start looking at the ndarray interfaces here: is a function that returns a .  There is no object type numpy.array.
Python

I am writing a Python (Python 3.3) program to send some data to a webpage using POST method.  Mostly for debugging process I am getting the page result and displaying it on the screen using  function.The code is like this:the   method returns a  element encoding the page (which is a well formated UTF-8 document)  It seemed okay until I stopped using IDLE GUI for Windows and used the Windows console instead.  The returned page has a U+2014 character (em-dash) which the print function translates well in the Windows GUI (I presume Code Page 1252) but does not in the Windows Console (Code Page 850).  Given the  default behavior I get the following error:I could fix it using this quite ugly code:Now it replace the offending character \"\u2014\" with a .  Not the ideal case (a hyphen should be a better replacement) but good enough for my purpose.There are several things I do not like from my solution.The problem is not the emdash (I can think of several ways to solve that particularly problem) but I need to write robust code.  I am feeding the page with data from a database and that data can come back.  I can anticipate many other conflicting cases: an '\u00c1' U+00c1 (which is possible in my database) could translate into CP-850 (DOS/Windows Console encodign for Western European Languages) but not into CP-437 (encoding for US English, which is default in many Windows instalations).So, the question:Is there a nicer solution that makes my code agnostic from the output interface encoding?I see three solutions to this:Based on Dirk St\u00f6cker's answer, here's a neat wrapper function for Python 3's print function. Use it just like you would use print.As an added bonus, compared to the other answers, this won't print your text as a bytearray ('b\"content\"'), but as normal strings ('content'), because of the last decode step.For debugging purposes, you could use .To display text, always print Unicode. Don't hardcode the character encoding of your environment such as  inside your script. To decode the http response, see .To print Unicode to Windows console, you could .I dug deeper into this and found the best solutions are here.In my case I solved \"UnicodeEncodeError: 'charmap' codec can't encode character \"original code:New code:If you use Python 3.6 (possibly 3.5 or later), it doesn't give that error to me anymore.  I had a similar issue, because I was using v3.4, but it went away after I uninstalled and reinstalled. If you are using Windows command line to print the data, you should use This worked for me!
Python

In Python, the where and when of using string concatenation versus string substitution eludes me. As the string concatenation has seen large boosts in performance, is this (becoming more) a stylistic decision rather than a practical one?For a concrete example, how should one handle construction of flexible URIs:Edit: There have also been suggestions about joining a list of strings and for using named substitution. These are variants on the central theme, which is, which way is the Right Way to do it at which time? Thanks for the responses!Concatenation is (significantly) faster according to my machine. But stylistically, I'm willing to pay the price of substitution if performance is not critical. Well, and if I need formatting, there's no need to even ask the question... there's no option but to use interpolation/templating.Don't forget about named substitution:\"As the string concatenation has seen large boosts in performance...\"If performance matters, this is good to know.However, performance problems I've seen have never come down to string operations.  I've generally gotten in trouble with I/O, sorting and O()  operations being the bottlenecks.Until string operations are the performance limiters, I'll stick with things that are obvious.  Mostly, that's substitution when it's one line or less, concatenation when it makes sense, and a template tool (like Mako) when it's large.  The cost of string concatenation is proportional to the length of the result.  Looping leads you straight to the land of N-squared.  Some languages will optimize concatenation to the most recently allocated string, but it's risky to count on the compiler to optimize your quadratic algorithm down to linear.  Best to use the primitive (?) that takes an entire list of strings, does a single allocation, and concatenates them all in one go.What you want to concatenate/interpolate and how you want to format the result should drive your decision. Also, know that Python 2.6 introduces a new version of string interpolation, called :String templating is slated to eventually replace %-interpolation, but that won't happen for quite a while, I think.I was just testing the speed of different string concatenation/substitution methods out of curiosity. A google search on the subject brought me here. I thought I would post my test results in the hope that it might help someone decide....After running , I found that the % method was about twice as fast as the others on these small strings. The concat method was always the slowest (barely). There were very tiny differences when switching the positions in the  method, but switching positions was always at least .01 slower than the regular format method.Sample of test results:I ran these because I do use string concatenation in my scripts, and I was wondering what the cost was. I ran them in different orders to make sure nothing was interfering, or getting better performance being first or last. On a side note, I threw in some longer string generators into those functions like  and regular concat was almost 3 times as fast (1.1 vs 2.8) as using the  and  methods. I guess it depends on the strings, and what you are trying to achieve. If performance really matters, it might be better to try different things and test them. I tend to choose readability over speed, unless speed becomes a problem, but thats just me. SO didn't like my copy/paste, i had to put 8 spaces on everything to make it look right. I usually use 4.Remember, stylistic decisions  practical decisions, if you ever plan on maintaining or debugging your code :-)  There's a famous quote from Knuth (possibly quoting Hoare?): \"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.\"As long as you're careful not to (say) turn a O(n) task into an O(n) task, I would go with whichever you find easiest to understand..I use substitution wherever I can. I only use concatenation if I'm building a string up in say a for-loop.Actually the correct thing to do, in this case (building paths) is to use . Not string concatenation or interpolation
Python

I know that artificial benchmarks are evil. They can show results only for very specific narrow situation. I don't assume that one language is better than the other because of the some stupid bench. However I wonder why results is so different. Please see my questions at the bottom.Benchmark is simple math calculations to find pairs of prime numbers which differs by 6 (so called )\nE.g. sexy primes below 100 would be: \nRunning: all except Factor was running in VirtualBox (Debian unstable amd64 guest, Windows 7 x64 host)\nCPU: AMD A4-3305M[*1] - I'm afraid to imagine how much time will it takeC:Ruby:Scala:Scala opimized  (the same idea like in Clojure optimization):Clojure:Clojure optimized :PythonFactorBash(zsh):Rough answers:Most important optimisation in the Clojure code would be to use typed primitive maths within , something like:With this improvement, I get Clojure completing 10k in 0.635 secs (i.e. the second fastest on your list, beating Scala) note that you have printing code inside your benchmark in some cases - not a good idea as it will distort the results, especially if using a function like  for the first time causes initialisation of IO subsystems or something like that!I'll answer just #2, since it's the only one I've got anything remotely intelligent to say, but for your Python code, you're creating an intermediate list in , whereas you're using  in your  in Ruby which is just iterating.If you change your  to:they're on par.I could optimize the Python further, but my Ruby isn't good enough to know when I've given more of an advantage (e.g., using  makes Python win on my machine, but I don't remember if the Ruby range you used creates an entire range in memory or not). Without being too silly, making the Python code look like:which doesn't change much more, puts it at 1.5s for me, and, with being extra silly, running it with PyPy puts it at .3s for 10K, and 21s for 100K.Here's a fast Clojure version, using the same basic algorithms:It runs about 20x faster than your original on my machine. And here's a version that leverages the new reducers library in 1.5 (requires Java 7 or JSR 166):This runs about 40x faster than your original. On my machine, that's 100k in 1.5 seconds.You can make the Scala a lot faster by modifying your  method toNot quite as concise but the program runs in 40% of the time! We cut out the superfluous  and anonymous  objects, the Scala compiler recognizes the tail-recursion and turns it into a while-loop, which the JVM can turn into more or less optimal machine code, so it shouldn't be too far off the C version.See also: Here is my scala version in both parallel and no-parallel, just for fun:\n(In my dual core compute, the parallel version takes 335ms while the no-parallel version takes 655ms)EDIT: According to 's suggestion, I have changed my code to avoid the effects of IO and jvm warmup:The result shows in my compute:Never mind the benchmarks; the problem got me interested and I made some fast tweaks.  This uses the  decorator, which memoizes a function; so when we call  we basically get that prime check for free.  This change cuts the work roughly in half.  Also, we can make the  calls step through just the odd numbers, cutting the work roughly in half again.This requires Python 3.2 or newer to get , but could work with an older Python if you install a Python recipe that provides .  If you are using Python 2.x you should really use  instead of .The above took only a very short time to edit.  I decided to take it one step further, and make the primes test only try prime divisors, and only up to the square root of the number being tested.  The way I did it only works if you check numbers in order, so it can accumulate all the primes as it goes; but this problem was already checking the numbers in order so that was fine.On my laptop (nothing special; processor is a 1.5 GHz AMD Turion II \"K625\") this version produced an answer for 100K in under 8 seconds.The above code is pretty easy to write in Python, Ruby, etc. but would be more of a pain in C.You can't compare the numbers on this version against the numbers from the other versions without rewriting the others to use similar tricks.  I'm not trying to prove anything here; I just thought the problem was fun and I wanted to see what sort of easy performance improvements I could glean.Don't forget Fortran!  (Mostly joking, but I would expect similar performance to C).  The statements with exclamation points are optional, but good style. ( is a comment character in fortran 90)I couldn't resist to do a few of the most obvious optimizations for the C version which made the 100k test now take 0.3s on my machine (5 times faster than the C version in the question, both compiled with MSVC 2010 /Ox).Here is the identical implemention in Java:With Java 1.7.0_04 this runs almost exactly as fast as the C version. Client or server VM doesn't show much difference, except that JIT training seems to help the server VM a bit (~3%) while it has almost no effect with the client VM. The output in Java seems to be slower than in C. If the output is replaced with a static counter in both versions, the Java version runs a little faster than the C version.These are my times for the 100k run:and the 1M run (16386 results):While this does not really answer your questions, it shows that small tweaks can have a noteworthy impact on performance. So to be able to really compare languages you should try to avoid all algorithmic differences as much as possible.It also gives a hint why Scala seems rather fast. It runs on the Java VM and thus benefits from its impressive performance.In Scala try using Tuple2 instead of List, it should go faster. Just remove the word 'List' since (x, y) is a Tuple2.Tuple2 is specialized for Int, Long and Double meaning it won't have to box/unbox those raw datatypes. . List isn't specialized. .Here's the code for the Go (golang.org) version:It ran just as fast as the C version.\nIntel Core 2 Duo T6500 2.1GHz, 2MB L2 cache, 800MHz FSB.\n4GB RAM The 100k version:  With 1000000 (1M instead of 100K):   But I think that it would be fair to use Go's built in multithreading capabilities and compare that version with the regular C version (without multithreading), just because it's almost too easy to do multithreading with Go.Update: I did a parallel version using Goroutines in Go:The parallelized version completed in 1.706 seconds. It used less than 1.5 Mb RAM. Fixed with a call to Update: I ran the paralellized version up to 1M numbers.  With 1000000 (1M instead of 100K):    The 100k version:   Based on , I wrote a scala version using recursion, and I improved on it by only going to the sqrt instead of x/2 for the prime check function. I get ~250ms for 100k, and ~600ms for 1M. I went ahead and went to 10M in ~6s.I also went back and wrote a CoffeeScript (V8 JavaScript) version, which gets ~15ms for 100k, 250ms for 1M, and 6s for 10M, by using a counter (ignoring I/O). If I turn on the output it takes ~150ms for 100k, 1s for 1M, and 12s for 10M. Couldn't use tail recursion here, unfortunately, so I had to convert it back into loops.Just for the fun of it, here is a parallel Ruby version. On my 1.8GHz Core i5 MacBook Air, the performance results are:It looks like the JVM's JIT is giving Ruby a nice performance boost in the default case, while true multithreading helps JRuby perform 50% faster in the threaded case. What's more interesting is that JRuby 1.7 improves the JRuby 1.6 score by a healthy 17%!The answer to your question #1 is that Yes, the JVM is incredably fast and yes static typing helps.The JVM should be faster than C in the long run, possibly even faster than \"Normal\" assembly language--Of course you can always hand optimize assembly to beat anything by doing manual runtime profiling and creating a separate version for each CPU, you just have to be amazingly good and knowledgable.The reasons for Java's speed are: The JVM can analyze your code while it runs and hand-optimize it--for instance, if you had a method that could be statically analyzed at compile time to be a true function and the JVM noticed that you were often calling it with the same parameters, it COULD actually eliminate the call completely and just inject the results from the last call (I'm not sure if Java actually does this exactly, but it doest a lot of stuff like this). Due to static typing, the JVM can know a lot about your code at compile time, this lets it pre-optimize quite a bit of stuff.  It also lets the compiler optimize each class individually without knowledge of how another class is planning to use it.  Also Java doesn't have arbitrary pointers to memory location, it KNOWS what values in memory may and may not be changed and can optimize accordingly.Heap allocation is MUCH more efficient than C, Java's heap allocation is more like C's stack allocation in speed--yet more versatile.  A lot of time has gone into the different algroithims used here, it's an art--for instance, all the objects with a short lifespan (like C's stack variables) are allocated to a \"known\" free location (no searching for a free spot with enough space) and are all freed together in a single step (like a stack pop). The JVM can know quirks about your CPU architecture and generate machine code specifically for a given CPU.The JVM can speed your code long after you shipped it.  Much like moving a program to a new CPU can speed it up, moving it to a new version of the JVM can also give you huge speed performances taylored to CPUs that didn't even exist when you initially compiled your code, something c physically cannot do without a recomiple.By the way, most of the bad rep for java speed comes from the long startup time to load the JVM (Someday someone will build the JVM into the OS and this will go away!) and the fact that many developers are really bad at writing GUI code (especially threaded) which caused Java GUIs to often become unresponsive and glitchy.  Simple to use languages like Java and VB have their faults amplified by the fact that the capibilities of the average programmer tends to be lower than more complicated languages.
Python

I am setting out to do a side project that has the goal of translating code from one programming language to another. The languages I am starting with are PHP and Python (Python to PHP should be easier to start with), but ideally I would be able to add other languages with (relative) ease. The plan is:Then I believe I can start outputting code. . I'll still have to review the generated code and fix problems. Ideally the translator should flag problematic translations.Before you ask \"What the hell is the point of this?\" The answer is... It'll be an interesting learning experience. If you have any insights on how to make this less daunting, please let me know.I am more interested in knowing what kinds of patterns I could enforce on the code to make it easier to translate (ie: IoC, SOA ?) the code than how to do the translation.I've been  to do general purpose program manipulation (with language translation being a special case) since 1995, supported by a strong team of computer scientists.  DMS provides generic parsing, AST building, symbol tables, control and data flow analysis, application of translation rules, regeneration of source text with comments, etc., all parameterized by explicit definitions of computer languages.The amount of machinery you need to do this  is vast (especially if you want to be able to do this for multiple languages in a general way), and then you need reliable parsers for languages with unreliable definitions (PHP is perfect example of this).There's nothing wrong with you thinking about building a language-to-language translator or attempting it, but I think you'll find this a much bigger task for real languages than you expect.  We have some 100 man-years invested in just DMS, and another 6-12 months in each \"reliable\" language definition (including the one we painfully built for PHP), much more for nasty languages such as C++.  It will be a \"hell of a learning experience\"; it has been for us.  (You might find the technical Papers section at the above website interesting to jump start that learning).People often attempt to build some kind of generalized machinery by starting with some piece of technology with which they are familiar, that does a part of the job. (Python ASTs are great example).  The good news, is that part of the job is done.  The bad news is that machinery has a zillion assumptions built into it, most of which you won't discover until you try to wrestle it into doing something else.  At that point you find out the machinery is wired to do what it originally does, and will really, really resist your attempt to make it do something else. (I suspect trying to get the Python AST to model PHP is going to be a lot of fun).The reason I started to build DMS originally was to build foundations that had very few such assumptions built in.   It has some that give us headaches.  So far, no black holes. (The hardest part of my job over the last 15 years is to try to prevent such assumptions from creeping in).Lots of folks also make the mistake of assuming that if they can parse (and perhaps get an AST), they are well on the way to doing something complicated.  One of the hard lessons is that you need symbol tables and flow analysis to do good program analysis or transformation.   ASTs are necessary but not sufficient.  This is the reason that Aho&Ullman's compiler book doesn't stop at chapter 2.  (The OP has this right in that he is planning to build additional machinery beyond the AST).  For more on this topic, see .The remark about \"I don't need a perfect translation\" is troublesome.  What weak translators do is convert the \"easy\" 80% of the code, leaving the hard 20% to do by hand.  If the application you intend to convert are pretty small, and you only intend to convert it once well, then that 20% is OK. If you want to convert many applications (or even the same one with minor changes over time), this is not nice.  If you attempt to convert 100K SLOC then 20% is 20,000 original lines of code that are hard to translate, understand and modify in the context of another 80,000 lines of translated program you already don't understand.  That takes a huge amount of effort.  At the million line level, this is simply impossible in practice.  (Amazingly there are people that distrust automated tools and insist on translating million line systems by hand; that's even  and they normally find out painfully with long time delays, high costs and often outright failure.)What you have to shoot for to translate large-scale systems is high nineties percentage  conversion rates, or it is likely that you can't complete the manual part of the translation activity.Another key consideration is size of code to be translated.  It takes a lot of energy to build a working, robust translator, even with good tools.  While it seems sexy and cool to build a translator instead of simply doing a manual conversion, for small code bases (e.g., up to about 100K SLOC in our experience) the economics simply don't justify it. Nobody likes this answer, but if you really have to translate just 10K SLOC of code, you are probably better off just biting the bullet and doing it.  And yes, that's painful.I consider our tools to be extremely good (but then, I'm pretty biased).   And it is still very hard to build a good translator; it takes us about 1.5-2 man-years and we know how to use our tools.  The difference is that with this much machinery, we  considerably more often than we fail.My answer will address the specific task of parsing Python in order to translate it to another language, and not the higher-level aspects which Ira addressed well in his answer.In short: The  module, available since Python 2.6 is much more suitable for your needs, since it gives you a ready-made AST to work with. I've written an  last year, but in short, use the  method of  to parse Python source code into an AST. The  module will give you a parse tree, not an AST. . Now, since Python's ASTs are quite detailed, given an AST the front-end job isn't terribly hard. I suppose you can have a simple prototype for some parts of the functionality ready quite quickly. However, getting to a complete solution will take more time, mainly because the semantics of the languages are different. A simple subset of the language (functions, basic types and so on) can be readily translated, but once you get into the more complex layers, you'll need heavy machinery to emulate one language's core in another. For example consider Python's generators and list comprehensions which don't exist in PHP (to my best knowledge, which is admittedly poor when PHP is involved).To give you one final tip, consider the  tool created by the Python devs to translate Python 2 code to Python 3 code. Front-end-wise, it has most of the elements you need to translate Python to . However, since the cores of Python 2 and 3 are similar, no emulation machinery is required there.Writing a translator isn't impossible, especially considering that Joel's Intern If you want to do one language, it's easy. If you want to do more, it's a little more difficult, but not too much. The hardest part is that, while any turing complete language can do what another turing complete language does, built-in data types can change what a language does phenomenally.For instance:takes a  of C++ code to duplicate (ok, well you can do it fairly short with some looping constructs, but still).That's a bit of an aside, I guess. Have you ever written a tokenizer/parser based on a language grammar? You'll probably want to learn how to do that if you haven't, because that's the main part of this project. What I would do is come up with a basic Turing complete syntax - something fairly similar to Python  . Then you create a lexer/parser that takes a language grammar (perhaps using ), and based on the grammar, compiles the language into your intermediate language. Then what you'll want to do is do the reverse - create a parser from your language into target languages based on the grammar.The most obvious problem I see is that at first you'll probably create  inefficient code, especially in more powerful* languages like Python.But if you do it this way then you'll probably be able to figure out ways to optimize the output as you go along. To summarize:*by powerful I mean that this takes 4 lines:Show me another language that can do something like that in 4 lines, and I'll show you a language that's as powerful as Python.There are a couple answers telling you not to bother. Well, how helpful is that? You want to learn? You can learn. This is compilation. It just so happens that your target language isn't machine code, but another high-level language. This is done all the time.There's a relatively easy way to get started. First, go get  (if you want to work in PHP) or some such and go through the example code. Next, you can write a lexical analyzer using a sequence of regular expressions and feed tokens to the parser you generate. Your semantic actions can either output code directly in another language or build up some data structure (think objects, man) that you can massage and traverse to generate output code.You're lucky with PHP and Python because in many respects they are the same language as each other, but with different syntax. The hard part is getting over the semantic differences between the grammar forms and data structures. For example, Python has lists and dictionaries, while PHP only has assoc arrays.The \"learner\" approach is to build something that works OK for a restricted subset of the language (such as only print statements, simple math, and variable assignment), and then progressively remove limitations. That's basically what the \"big\" guys in the field all did.Oh, and since you don't have static types in Python, it might be best to write and rely on PHP functions like \"python_add\" which adds numbers, strings, or objects according to the way Python does it.Obviously, this can get much bigger if you let it.I will second @EliBendersky point of view regarding using ast.parse instead of parser (which I did not know about before). I also warmly recommend you to review his blog. I used ast.parse to do Python->JavaScript translator (@). I've come up with Pythonium design by  reviewing other implementations and trying them on my own. I forked Pythonium from  which I also started, It's actually a complete rewrite . The overall design is inspired from PyPy and  paper.Everything I tried, from beginning to the best solution, even if it looks like Pythonium marketing it really isn't (don't hesitate to tell me if something doesn't seem correct to the netiquette):I never actually succeed at running Pyjamas #fail and never tried to read the code #fail again. But in my mind PyJamas was doing API->API tranlation (or framework to framework) and not Python to JavaScript translation. The JavaScript framework consume data that is already in the page or data from the server. Python code is only \"plumbing\". After that I discovered  that pyjamas was actually a real python->js translator. Still I think it's possible to do API->API (or framework->framework) translation and that's basicly what I do in Pythonium but at lower level. Probably Pyjamas use the same algorithm as Pythonium...Then I discovered brython fully written in Javascript like Skulpt, no need for compilation and lot of fluff... but written in JavaScript.Since the initial line written in the course of this project, I knew about PyPy, even the JavaScript backend for PyPy. Yep, you can, if you find it, directly generate a Python interpreter in JavaScript from PyPy. People say, it was a disaster. I read no where why. But I think the reason is that the intermediate language they use to implement the interpreter, RPython, is a subset of Python tailored to be translated to C (and maybe asm). Ira Baxter says you always make assumptions when you build something and probably you fine tune it to be the best at what it's meant to do in the case of PyPy: Python->C translation. Those assumptions might not be relevant in another context worse they can infere overhead otherwise said direct translation will most likely always be better.Having the interpreter written in Python sounded like a (very) good idea. But I was more interested in a compiler for performance reasons also it's actually more easy to compile Python to JavaScript than interpret it.I started PythonJS with the idea of putting together a subset of Python that I could easily translate to JavaScript. At first I didn't even bother to implement OO system because of past experience. The subset of Python that I achieved to translate to JavaScript are:This seems like a lot but actually very narrow compared to full blown semantic of Python. It's really JavaScript with a Python syntax. The generated JS is perfect ie. there is no overhead, it can not be improved in terms of performance by further editing it. If you can improve the generated code, you can do it from the Python source file too. Also, the compiler did not rely on any JS tricks that you can find in .js written by , so it's very readable.The direct descendant of this part of PythonJS is the Pythonium Veloce mode. The full implementation can be found @  793 SLOC + around 100 SLOC of shared code with the other translator.An adapted version of pystones.py can be translated in Veloce mode cf. After having setup basic Python->JavaScript translation I choosed another path to translate full Python to JavaScript. The way of glib doing object oriented class based code except the target language is JS so you have access to arrays, map-like objects and many other tricks and all that part was written in Python. IIRC there is no javascript code written by in Pythonium translator. Getting single inheritance is not difficult here are the difficult parts making Pythonium fully compliant with Python:This part is factored in  It's written in Python compatible with Python Veloce.The actual compliant translator  doesn't generate JavaScript code directly and most importantly doesn't do ast->ast transformation. I tried the ast->ast thing and ast even if nicer than cst is not nice to work with even with ast.NodeTransformer and more importantly I don't need to do ast->ast.Doing python ast to python ast in my case at least would maybe be a performance improvement since I sometime inspect the content of a block before generating the code associated with it, for instance:So I don't really visit each node once for each phase of the translation.The overall process can be described as:Python builtins are written in Python code (!), IIRC there is a few restrictions related to bootstraping types, but you have access to everything that can translate Pythonium in compliant mode. Have a look at Reading JS code generated from pythonium compliant can be understood but source maps will greatly help.The valuable advice I can give you in the light of this experience are kind old farts:With Python Veloce mode only, I'm very happy! But along the way I discovered that what I was really looking for was liberating me and others from Javascript but more importantly being able to  in a comfortable way. This lead me to Scheme, DSL, Models and eventually domain specific models (cf. ).About what Ira Baxter response:The estimations are not helpful at all. I took me more or less 6 month of free time for both PythonJS and Pythonium. So I can expect more from full time 6 month. I think we all know what 100 man-year in an enterprise context can mean and not mean at all...When someone says something is hard or more often impossible, I answer that \"it only takes time to find a solution for a problem that is impossible\" otherwise said nothing is impossible except if it's proven impossible in this case a math proof...If it's not proven impossible then it leaves room for imagination:andorIt's not just optimistic thinking. When I started Python->Javascript everybody was saying it was impossible. PyPy impossible. Metaclasses too hard. etc... I think that the only revolution that brings PyPy over Scheme->C paper (which is 25 years old) is some automatic JIT generation (based hints written in the RPython interpreter I think).Most people that say that a thing is \"hard\" or \"impossible\" don't provide the reasons. C++ is hard to parse? I know that, still they are (free)  C++ parser. Evil is in the detail? I know that. Saying it's impossible alone is not helpful, It's even worse than \"not helpful\" it's discouraging, and some people mean to discourage others. I heard about this question via .What would be perfection ? That's how you define next goal and maybe reach the overall goal.I see no patterns that can not be translated from one language to another language at least in a less than perfect way. Since language to language translation is possible, you'd better aim for this first. Since, I think according to , translation between two computer languages is a tree or DAG isomorphism. Even if we already know that they are both turing complete, so...Framework->Framework which I better visualize as API->API translation might still be something that you might keep in mind as a way to improve the generated code. E.g: Prolog as very specific syntax but still you can do Prolog like computation by describing the same graph in Python... If I was to implement a Prolog to Python translator I wouldn't implement unification in Python but in a C library and come up with a \"Python syntax\" that is very readable for a Pythonist. In the end, syntax is only \"painting\" for which we give a meaning (that's why I started scheme). Evil is in the detail of the language and I'm not talking about the syntax. The concepts that are used in the language  hook (you can live without it) but required VM features like tail-recursion optimisation can be difficult to deal with. You don't care if the initial program doesn't use tail recursion and even if there is no tail recursion in the target language you can emulate it using greenlets/event loop. For target and source languages, look for:From this will emerge:You will also probably be able to know what will be translated to fast and slow code.There is also the question of the stdlib or any library but there is no clear answer, it depends of your goals.Idiomatic code or readable generated code have also solutions...Targeting a platform like PHP is much more easy than targeting browsers since you can provide C-implementation of slow and/or critical path.Given you first project is translating Python to PHP, at least for the PHP3 subset I know of, customising veloce.py is your best bet. If you can implement veloce.py for PHP then probably you will be able to run the compliant mode... Also if you can translate PHP to the subset of PHP you can generate with php_veloce.py it means that you can translate PHP to the subset of Python that veloce.py can consume which would mean that you can translate PHP to Javascript. Just saying...You can also have a look at those libraries:Also you might be interested by this blog post (and comments): You could take a look at the , which translates Vala (a C#-like language) into C.
Python

Let's say that I have a class Suit and four subclasses of suit: Heart, Spade, Diamond, Club.I have a method which receives a suit as a parameter, which is a class object, not an instance. More precisely, it may receive only one of the four values: Heart, Spade, Diamond, Club. How can I make an assertion which ensures such a thing? Something like:I'm using Python 3.You can use  like this .  You can use  if you have an instance, or  if you have a class. Normally thought its a bad idea. Normally in Python you work out if an object is capable of something by attempting to do that thing to it.The  boolean function returns true if the given subclass  is indeed a subclass of the superclass .You can use the builtin issubclass. But type checking is usually seen as unneccessary because you can use duck-typing.Using issubclass seemed like a clean way to write loglevels. It kinda feels odd using it... but it seems cleaner than other options. 
Python

I am running PyLint on a Python project. PyLint makes many complaints about being unable to find numpy members. How can I avoid this while avoiding skipping membership checks.From the code:Which, when ran, I get the expected:However, pylint gives me this error:For versions, I am using pylint 1.0.0 (astroid 1.0.1, common 0.60.0) and trying to work with numpy 1.8.0 .I had the same issue here, even with the latest versions of all related packages (, , ).The following solution worked like a charm: I added  to the list of ignored modules by modifying my  file, in the  section:Depending on the error, you might also need to add the following line (still in the ):In recent versions of pylint you can add  to your pylint command. They had fixed this problem in an earlier version in an unsafe way. Now if you want them to look more carefully at a package outside of the standard library, you must explicitly whitelist it. I was getting the same error for a small numpy project I was working on and decided that ignoring the numpy modules would do just fine. I created a  file with:and following paduwan's and j_houg's advice I modified the following sectors:andand it \"fixed\" my issue.Since this is the top result in google and it gave me the impression that you have to ignore those warnings in all files:The problem has actually been fixed in the sources of pylint/astroid last month \nbut are not yet in the Ubuntu packages. To get the sources, justwhereby the last step will most likely require a  and of course you need mercurial to clone.If using  with Don Jayamanne's excellent , add a user setting to whitelist numpy:There have been many different bugs reported about this over the past few years i.e. I'd suggest disabling for the lines where the complaints occur.Probably, it's confused with numpy's abstruse method of methods import. Namely,  is in fact , imported in numpy with statementin turn imported withand in numeric you'll findI guess I would be confused in place of PyLint! See  for PyLint side of view.This seems to work on at least Pylint 1.1.0:I had this problem with numpy, scipy, sklearn, nipy, etc., and I solved it by wrapping epylint like so:$ cat epylint.pyThis script simply runs epylint, then scrapes its output to filter out false-positive warnings and errors. You can extend it by added more elif cases.N.B.: If this applies to you, then you'll want to modify your pychechers.sh so it likes like this(Of course, you have to make epylint.py executable first)Here is a link to my .emacs . Hope this is useful to someone.This is the pseudo-solution I have come up with for this problem.Then, in your code, instead of calling  functions as  and  and so on, \nyou would write , , etc. \nAdvantages of this approach vs. other approaches suggested in other answers:The clear disadvantage is that you have to explicitely import every numpy function you use. \nThe approach could be elaborated on further. \nYou could define your own module, call it say,  as followsThen, your application code could import this module only (instead of numpy) as and use the names as usual: ,  etc.The advantage of this is that you will have a single module in which all  related imports are done once and for all, and then you import it with that single line, wherever you want. Still you have to be careful that  does not import names that don\u00b4t exist in  as those errors won't be caught by pylint.  In Extension to j_hougs answer, you can now add the modules in question to this line in .pylintrc, which is already prepared empty on generation:you can generate a sample .pylintrc by doing:and then edit the mentioned lineI had to add this at the top of any file where I use numpy a lot. Just in case someone in eclipse is having trouble with Pydev and pylint...I've been working on a patch to pylint to solve the issue with dynamic members in libraries such as numpy. It adds a \"dynamic-modules\" option which forces to check if members exist during runtime by making a real import of the module. See . There is also a pull request, see link in one of the comments.A little bit of copy paste from the previous answer to summarize what is working (at least for me: debian-jessie)Basic command to run:\n    # ONLY if you do not already have a .pylintrc file in your home\n    $ pylint --generate-rcfile > .pylintrcThen open the file and add the packages you want after  separated by comma. You can have the same behavior using the option  from the command line.If you ignore some packages in the  section that means that  will never show error related to that packages. In practice,  will not tell you anything about those packages.
Python

Recently I wrote a function to generate certain sequences with nontrivial constraints. The problem came with a natural recursive solution. Now it happens that, even for relatively small input, the sequences are several thousands, thus I would prefer to use my algorithm as a generator instead of using it to fill a list with all the sequences.Here is an example. Suppose we want to compute all the permutations of a string with a recursive function. The following naive algorithm takes an extra argument 'storage' and appends a permutation to it whenever it finds one:(Please don't care about inefficiency, this is only an example.)Now I want to turn my function into a generator, i.e. to yield a permutation instead of appending it to the storage list:This code does  work (the function behaves like an empty generator).Am I missing something?\nIs there a way to turn the above recursive algorithm into a generator ?Or without an accumulator:This avoids the -deep recursion, and is in general a nice way to handle generators-inside-generators: allows us to continue progress in another generator by simply ing it, instead of iterating through it and ing each item manually.Python 3.3 will add  to the syntax, which allows for natural delegation to a sub-generator:The interior call to getPermutations -- it's a generator, too.You need to iterate through that with a for-loop (see @MizardX posting, which edged me out by seconds!)
Python

I have a shell that runs CentOS.For a project I'm doing, I need python 2.5+, but centOS is pretty dependent on 2.4.From what I've read, a number of things will break if you upgrade to 2.5.I want to install 2.5 separately from 2.4, but I'm not sure how to do it. So far I've downloaded the source tarball, untarred it, and did a  which is where I want it to end up. Can I now just  ? Or is there more?You could also use the , and then do  to install python 2.6Try epelThe python executable will be available at Now,  command will execute When I've run into similar situations, I generally avoid the package manager, especially if it would be embarrassing to break something, i.e. a production server. Instead, I would go to Activestate and download their binary package:This is installed by running a script which places everything into a folder and does not touch any system files. In fact, you don't even need root permissions to set it up. Then I change the name of the binary to something like apy26, add that folder to the end of the PATH and start coding. If you install packages with or if you use virtualenv and easyinstall, then you have just as flexible a python environment as you need without touching the system standard python.Edits...\nRecently I've done some work to build a portable Python binary for Linux that should run on any distro with no external dependencies. This means that any binary shared libraries needed by the portable Python module are part of the build, included in the tarball and installed in Python's private directory structure. This way you can install Python for your application without interfering with the system installed Python. has a build script which has been thoroughly tested on Ubuntu Lucid 10.04 LTS both 32 and 64 bit installs. I've also built it on Debian Etch but that was a while ago and I can't guarantee that I haven't changed something. The easiest way to do this is you just put your choice of Ubuntu Lucid in a virtual machine, checkout the script with  and then run the script. Once you have it built, use the tarball on any recent Linux distro. There is one little wrinkle with moving it to a directory other than  which is that you have to run the included  to set the interpreter path BEFORE you move the directory. This affects any binaries in All of this is based on building with RUNPATH and copying the dependent shared libraries. Even though the script is in several files, it is effectively one long shell script arranged in the style of /etc/rc.d directories.No, that's it. You might want to make sure you have all optional library headers installed too so you don't have to recompile it later. They are listed in the documentation I think.Also, you can install it even in the standard path if you do . That way it won't override your current default \"python\".No need to do yum or make your own RPM. Build  from source.There can be a  use Add the install path ( by default) to .It will not break  or any other things which are dependent on . provides a YUM repository for python26 RPMs that can co-exist with the 'native' 2.4 that is needed for quite a few admin tools on CentOS.Quick instructions that worked at least for me:If you want to make it easier on yourself, there are CentOS RPMs for new Python versions floating around the net. E.g. see:When you install your python version (in this case it is python2.6) then issue this command to create your :Late to the party, but the OP should have gone with  or , and sidestepped the problem completely.I am currently working on a Centos server, well, toiling away would be the proper term and I can assure everyone that the only way I am able to blink back the tears whilst using the software equivalents of fire hardened spears, is  buildout.  you can always make your own RPM:Missing Dependency: libffi.so.5  is here : for dos that just dont know :=)I unistalled the original version of python (2.6.6) and install 2.7(with option ) but when I tried install something with yum didn't work.So I solved this issue as follow:Done
Python

I need to be able to switch back and forth between Python 2 and 3. How do I do that using Homebrew as I don't want to mess with path and get into trouble.\nRight now I have 2.7 installed through Homebrew.I would use  You can install it:To enable pyenv in your Bash shell, you need to run:To do this automatically for Bash upon startup, add that line to your . Once you have installed pyenv and activated it, you can install different versions of python and choose which one you can use. Example:You can check the versions you have installed with:And you can switch between python versions with the command:Also you can set a python version for the current directory with:You can check by running :You can have both versions installed at the same time.For Python 2.x:For Python 3.x:Now, you will have both the versions installed in your machine. When you want to use version 2, use the  executable. When you want to use version 3, use the  executable.Alternatively, you probably can just enter \"python3\" to run your most current version of python3.x and \"python\" or \"python2\" to run the latest installed 2.x version.
Python

What I'm trying to do would look like this in the command line:How can I get a reference to all the names defined in  from within  itself?Something like this:Just use globals()As previously mentioned, globals gives you a dictionary as opposed to dir() which gives you a list of the names defined in the module.  The way I typically see this done is like this:Also check out the built-in  module.  It can be very handy.
Python

In :I don't understand mro.\nWhat does  do?\nWhat does mro mean?Follow along...:As long as we have single inheritance,  is just the tuple of: the class, its base, its base's base, and so on up to  (only works for new-style classes of course).Now, with  inheritance...:...you also get the assurance that, in , no class is duplicated, and no class comes after its ancestors, save that classes that first enter at the same level of multiple inheritance (like B and C in this example) are in the  left to right.Every attribute you get on a class's instance, not just methods, is conceptually looked up along the , so, if more than one class among the ancestors defines that name, this tells you where the attribute will be found -- in the first class in the  that defines that name. stands for Method Resolution Order.  It returns a list of types the class is derived from, in the order they are searched for methods.This would perhaps show the order of resolution.and response would be The rule is dept first which in this case would mean D, B, A, CPython normally uses a  order when searching inheriting classes\nBut when two classes inherit from the same class, Python removes the first mention of that class from mro.
Python

I'm writing a Django Middleware class that I want to execute only once at startup, to initialise some other arbritary code. I've followed the very nice solution posted by sdolan , but the \"Hello\" message is output to the terminal . E.g.and in my Django settings file, I've got the class included in the  list.But when I run Django using runserver and request a page, I get in the terminalAny ideas why \"Hello world\" is printed twice? Thanks.Don't do it this way.You don't want \"middleware\" for a one-time startup thing.You want to execute code in the top-level .  That module is imported and executed once.file: file: The number one answer does not seem to work anymore, urls.py is loaded upon first request.What has worked lately is to put the startup code in any one of your INSTALLED_APPS .py e.g. When using  ... this gets executed twice, but that is because runserver has some tricks to validate the models first etc ... normal deployments or even when runserver auto reloads, this is only executed once.This question is well-answered in the blog post , which will work for Django >= 1.4.Basically, you can use  to do that, and it will be run only once, when the server starts, but not when you run commands or import a particular module.If it helps someone, in addition to  answer, \"--noreload\" option prevents runserver from executing command on startup twice:But that command won't reload runserver after other code's changes as well.
Python

Python provides a nice method for getting length of an eager iterable,  that is. But I couldn't find anything similar for lazy iterables represented by generator comprehensions and functions. Of course, it is not hard to write something like:But I can't get rid of a feeling that I'm reimplementing a bicycle.(While I was typing the function, a thought struck my mind: maybe there really is no such function, because it \"destroys\" its argument. Not an issue for my case, though).P.S.: concerning the first answers - yes, something like  would work too, but that drastically increases the usage of memory.P.P.S.: re-checked... Disregard the P.S., seems I made a mistake while trying that, it works fine. Sorry for the trouble.There isn't one because you can't do it in the general case - what if you have a lazy infinite generator?  For example:This never terminates but will generate the Fibonacci numbers.  You can get as many Fibonacci numbers as you want by calling .If you really need to know the number of items there are, then you can't iterate through them linearly one time anyway, so just use a different data structure such as a regular list.The easiest way is probably just  where gen is your generator. Or better yet:If it's not iterable, it will throw a .Or, if you want to count something specific in the generator:You can use enumerate() to loop through the generated data stream, then return the last number -- the number of items.I tried to use itertools.count() with itertools.izip() but no luck. This is the best/shortest answer I've come up with:Kamil Kisiel's solution is way better:Use  for a memory efficient purely functional solution:By definition, only a subset of generators will return after a certain number of arguments (have a pre-defined length), and even then, only a subset of these finite generators have a predictable end (accessing the generator can have side-effects which could stop the generator earlier).If you wish to implement length methods for your generator, you have to first define what you consider the \"length\" (is it the total number of elements? the number of remaining elements?), then wrap your generator in a class. Here's an example:Here is how to use it:This is a hack, but if you really want to have  work on a general iterable (consuming it in the way), you can create your own version of .The  function is essentially equivalent to the following (though implementations usually provide some optimizations to avoid the extra lookup):Therefore we can define our  to try that, and if  does not exist, count the number of elements ourselves by consuming the iterable:The above works in Python 2/3, and (as far as I know) should cover every conceivable kind of iterable.Try the  package for a simple solution.  Example:See  for another applied example.I think when considering only length, you should discard the result (content).always does the work for you in this scenario.
Python

When using os.system() it's often necessary to escape filenames and other arguments passed as parameters to commands.  How can I do this?  Preferably something that would work on multiple operating systems/shells but in particular for bash.I'm currently doing the following, but am sure there must be a library function for this, or at least a more elegant/robust/efficient option: I've accepted the simple answer of using quotes, don't know why I didn't think of that; I guess because I came from Windows where ' and \" behave a little differently.Regarding security, I understand the concern, but, in this case, I'm interested in a quick and easy solution which os.system() provides, and the source of the strings is either not user-generated or at least entered by a trusted user (me).This is what I use:The shell will always accept a quoted filename and remove the surrounding quotes before passing it to the program in question. Notably, this avoids problems with filenames that contain spaces or any other kind of nasty shell metacharacter.: If you are using Python 3.3 or later, use  instead of rolling your own. does what you want since python 3.(Use  to support both python 2 and python 3)Perhaps you have a specific reason for using . But if not you should probably be using the . You can specify the pipes directly and avoid using the shell.The following is from :Maybe  is a better shot?Note that pipes.quote is actually broken in Python 2.5 and Python 3.1 and not safe to use--It doesn't handle zero-length arguments.See ; it has been fixed in Python 2.6 and 3.2 and newer.I believe that os.system just invokes whatever command shell is configured for the user, so I don't think you can do it in a platform independent way.  My command shell could be anything from bash, emacs, ruby, or even quake3.  Some of these programs aren't expecting the kind of arguments you are passing to them and even if they did there is no guarantee they do their escaping the same way.: This is an answer for Python 2.7.x.According to the ,  is a way to \"\". (Although it is  and finally exposed publicly in Python 3.3 as the  function.)On ,  is a way to \"\".Here we are, the platform independent way of quoting strings for command lines.Usage:The function I use is:that is: I always enclose the argument in double quotes, and then backslash-quote the only characters special inside double quotes.The real answer is: Don't use  in the first place. Use  instead and supply the unescaped arguments.If you do use the system command, I would try and whitelist what goes into the os.system() call.. For example..The subprocess module is a better option, and I would recommend trying to avoid using anything like os.system/subprocess wherever possible.
Python

I have a model that looks like this:I want select count (just the count) of items for each category, so in SQL it would be as simple as this:Is there an equivalent of doing this \"the Django way\"? Or is plain SQL the only option? I am familiar with the  method in Django, however I don't see how  would fit there.Here, as I just discovered, is how to do this with the Django 1.1 aggregation API:(: Full ORM aggregation support is now included in . True to the below warning about using private APIs, the method documented here no longer works in post-1.1 versions of Django.  I haven't dug in to figure out why; if you're on 1.1 or later you should use the real  anyway.)The core aggregation support was already there in 1.0; it's just undocumented, unsupported, and doesn't have a friendly API on top of it yet.  But here's how you can use it anyway until 1.1 arrives (at your own risk, and in full knowledge that the query.group_by attribute is not part of a public API and could change):If you then iterate over query_set, each returned value will be a dictionary with a \"category\" key and a \"count\" key.You don't have to order by -count here, that's just included to demonstrate how it's done (it has to be done in the .extra() call, not elsewhere in the queryset construction chain).  Also, you could just as well say count(id) instead of count(1), but the latter may be more efficient.Note also that when setting .query.group_by, the values must be actual DB column names ('category_id') not Django field names ('category').  This is because you're tweaking the query internals at a level where everything's in DB terms, not Django terms.Since I was a little confused about how grouping in Django 1.1 works I thought I'd elaborate here on how exactly you go about using it. First, to repeat what Michael said:Note also that you need to !This will select only the categories and then add an annotation called . Depending on the default ordering this may be all you need, . The reason for this is that the fields required for ordering are also selected and make each row unique, so you won't get stuff grouped how you want it. One quick way to fix this is to reset the ordering:This should produce exactly the results you want. To set the name of the annotation you can use:Then you will have an annotation called  in the results.Everything else about grouping was very straightforward to me. Be sure to check out the  for more detailed info.How's this?  (Other than slow.)It has the advantage of being short, even if it does fetch a lot of rows.Edit.The one query version.  BTW, this is often  than SELECT COUNT(*) in the database.  Try it to see.
Python

How do you execute raw SQL in SQLAlchemy?I have a python web app that runs on flask and interfaces to the database through SQLAlchemy. I need a way to run the raw SQL. The query involves multiple table joins along with Inline views. I've tried:But I keep getting gateway errors.Have you tried:or:If you want to use a session (as your question suggests), use its  method directly:The following might be specific to my database driver (psycopg2); I'm not sure. Regardless, it's how I pull out my values.The key point about is the  call. The  part is just something that I find makes my life easier by giving name based access.Furthermore, this is transactional  managing it manually. Say  is a function that creates a session:docs: example:You can get the results of SELECT SQL queries using  and  as shown . You don't have to deal with tupules this way. As an example for a class User having the tablename 'users' you can try, executes the  but doesn't commit it unless you're on autocommit mode. So, inserts and updates wouldn't reflect in the database.To commit after the changes, doHave you tried using  and bind parameters as described ? This can help solve many parameter formatting and performance problems. Maybe the gateway error is a timeout? Bind parameters tend to make complex queries execute substantially faster.
Python

I looked at other questions and can't figure it out... I did the following to install django-debug-toolbar:3 Added INTERNAL_IPS:4 Added debug_toolbar to installed appsI am not getting any errors or anything, and the toolbar doesn't show up on any page, not even admin.I even added the directory of the debug_toolbar templates to my Stupid question, but you didn't mention it, so... What is  set to? It won't load unless it's .If it's still not working, try adding '127.0.0.1' to  as well.This is a last-ditch-effort move, you shouldn't  to do this, but it will clearly show if there's merely some configuration issue or whether there's some larger issue.Add the following to settings.py:That will effectively remove all checks by debug toolbar to determine if it should or should not load itself; it will always just load. Only leave that in for testing purposes, if you forget and launch with it, all your visitors will get to see your debug toolbar too.For explicit configuration, also see the official install docs .EDIT(6/17/2015):Apparently the syntax for the nuclear option has changed. It's now in its own dictionary:Their  use this dictionary.Debug toolbar wants the ip address in request.META['REMOTE_ADDR'] to be set in the INTERNAL_IPS setting. Throw in a print statement in one of your views like such:And then load that page. Make sure that IP is in your INTERNAL_IPS setting in settings.py. Normally I'd think you would be able to determine the address easily by looking at your computer's ip address, but in my case I'm running the server in a Virtual Box with port forwarding...and who knows what happened. Despite not seeing it anywhere in ifconfig on the VB or my own OS, the IP that showed up in the REMOTE_ADDR key was what did the trick of activating the toolbar.If everything else is fine, it could also be that your template lacks an explicit closing  tag\u2014The current stable version 0.11.0 requires the following things to be true for the toolbar to be shown: If you are serving static content make sure you collect the css, js and html by doing: Newer, development versions have added defaults for settings points 2, 3 and 4 which makes life a bit simpler, however, as with any development version it has bugs. I found that the latest version from git resulted in an  error when running through nginx/uwsgi. Either way, if you want to install the latest version from github run:You can also clone a specific commit by doing: I have the toolbar working just perfect. With this configurations:I hope it helpsAdd  to your INTERNAL_IPS on Windows, it is used with vagrant internallyINTERNAL_IPS = (\n    '10.0.2.2',\n)This should work.I had the same problem and finally resolved it after some googling. In INTERNAL_IPS, you need to have the  IP address.I tried everything, from setting , to settings  to my client's IP address, and even configuring Django Debug Toolbar manually (note that recent versions make all configurations automatically, such as adding the middleware and URLs). Nothing worked in a remote development server (though it did work locally).\nThe ONLY thing that worked was configuring the toolbar as follows:This replaces the default method that decides if the toolbar should be shown, and always returns true.Another thing that can cause the toolbar to remain hidden is if it cannot find the required static files.  The debug_toolbar templates use the {{ STATIC_URL }} template tag, so make sure there is a folder in your static files called debug toolbar.The collectstatic management command should take care of this on most installations.I tried the configuration from  and it worked for me:I just modified it by adding  instead of  as mentioned in the , as I'm using Django 1.7.An addition to previous answers:if the toolbar doesn't show up, but it loads in the html (check your site html in a browser, scroll down)the issue can be that debug toolbar static files are not found (you can also see this in your site's access logs then, e.g. 404 errors for /static/debug_toolbar/js/toolbar.js)It can be fixed the following way then (examples for nginx and apache):nginx config:apache config:Or:more on collectstatic here: Or manualy move debug_toolbar folder of debug_toolbar static files to your set static files folderI had to add the following to the project url.py file to get the debug toolbar display. After that debug tool bar is displayed. and higher:Also don't forget to include the debug_toolbar to your middleware.\nThe Debug Toolbar is mostly implemented in a middleware. Enable it in your settings module as follows:\n(django newer versions)Old-style middleware:(need to have _CLASSES keywork in the Middleware)This wasn't the case for this specific author but I just have been struggling with the Debug Toolbar not showing and after doing everything they pointed out, I found out it was a problem with MIDDLEWARE order. So putting the middleware early in the list could work. Mine is first:In my case, it was another problem that hasn't been mentioned here yet: I had GZipMiddleware in my list of middlewares.As the automatic configuration of debug toolbar puts the debug toolbar's middleware at the top, it only gets the \"see\" the gzipped HTML, to which it can't add the toolbar.I removed GZipMiddleware in my development settings. Setting up the debug toolbar's configuration manually and placing the middleware  GZip's should also work.In my case I just needed to remove the python compiled files ()you have to make sure there is a closing  tag in your templates. My problem is that there is no regular html tags in my templates, I just display content in plain text. I solved  it by inheriting every html file from base.html, which has a  tag.For me this was as simple as typing  into the address bar, rather than  which apparently was not matching the INTERNAL_IPS.I got the same problem, I solved it by looking at the Apache's error log.\nI got the apache running on mac os x with mod_wsgi\nThe debug_toolbar's tamplete folder wasn't being loadLog sample:I just add this line to my VirtualHost file:I had the same problem using Vagrant. I solved this problem by adding  to the INTERNAL_IPS as below example. Remembering that  is the IP in my private network in Vagrantfile.I had this problem and had to install the debug toolbar from source.Version 1.4 has a problem where it's hidden if you use PureCSS and apparently other CSS frameworks. is the commit which fixes that.The docs explain how to install from source.For anyone who is using Pycharm 5 - template debug is not working there in some versions. Fixed in 5.0.4, affected vesions - 5.0.1, 5.0.2\nCheck out  Spend A LOT time to find that out. Maybe will help someoneOne stupid thing got me.. that if you use apache wsgi, remember to touch the .wsgi file to force your code recompile. just waste 20 minutes of my time to debug the stupid error :(
Python

How can I download a webpage with a user agent other than the default one on urllib2.urlopen? from everyone's favorite .The short story: You can use  to do this.You can also pass the headers as a dictionary when creating the Request itself, :I  a  a couple weeks ago.There is example code in that question, but basically you can do something like this: (Note the capitalization of  as of , section 14.43.)Or, a bit shorter:For python 3, urllib is split into 3 modules...All these should work in theory, but (with Python 2.7.2 on Windows at least) any time you send a custom User-agent header, urllib2 doesn't send that header.  If you don't try to send a User-agent header, it sends the default Python / urllib2 None of these methods seem to work for adding User-agent but they work for other headers:Another solution in  and Python 2.7:For  you can use:Try this :
Python

Is there any Django function which will let me get an object form the database, or None if nothing matches?Right now I'm using something like:But that's not very clear, and it's messy to have everywhere.In Django  you can use the  Queryset method. It returns the first object matched by the queryset, or None if there is no matching object.Usage:There are two ways to do this;Or you can use a wrapper:Call it like thisTo add some sample code to sorki's answer (I'd add this as a comment, but this is my first post, and I don't have enough reputation to leave comments), I implemented a get_or_none custom manager like so:And now I can do this:You can also try to use django annoying (it has another useful functions!)install it with:Give Foo . It's pretty easy - just put your code into function in custom manager, set custom manager in your model and call it with .If you need generic function (to use it on any model not just that with custom manager) write your own and place it somewhere on your python path and import, not messy any more.Whether doing it via a manager or generic function, you may also want to catch 'MultipleObjectsReturned' in the TRY statement, as the get() function will raise this if your kwargs retrieve more than one object.Building on the generic function:and in the manager:Here's a variation on the helper function that allows you to optionally pass in a  instance, in case you want to get the unique object (if present) from a queryset other than the model's  objects queryset (e.g. from a subset of child items belonging to a parent instance):This can be used in two ways, e.g.:I think that in most cases you can just use:Only if it is not critical that a new entry will be added in Foo table ( other columns will have the None/default values )
Python

So it's a new millennium; Apple has waved their hand; it's now legal to include a Python interpreter in an iPhone (App Store) app.How does one go about doing this? All the existing discussion (unsurprisingly) refers to jailbreaking. (Older question: )My goal here isn't to write a PyObjC app, but to write a regular ObjC app that runs Python as an embedded library. The Python code will then call back to native Cocoa code. It's the \"control logic is Python code\" pattern.Is there a guide to getting Python built in XCode, so that my iPhone app can link it? Preferably a stripped-down Python, since I won't need 90% of the standard library.I can probably figure out the threading and Python-extension API; I've done that on MacOS. But only using command-line compilers, not XCode.It doesn't really matter how you build Python -- you don't need to build it in Xcode, for example -- but what does matter is the product of that build.Namely, you are going to need to build something like libPython.a that can be statically linked into your application.  Once you have a .a, that can be added to the Xcode project for your application(s) and, from there, it'll be linked and signed just like the rest of your app.IIRC (it has been a while since I've built python by hand) the out-of-the-box python will build a libPython.a (and a bunch of other libraries), if you configure it correctly.Of course, your second issue is going to be cross-compiling python for ARM from your  box.  Python is an autoconf based project and autoconf is a pain in the butt for cross-compilation.As you correctly state, making it small will be critical.Not surprising, either, is that you aren't the first person to want to do this, but not for iOS.   Python has been squeezed into devices much less capable than those that run iOS.  I found a thread with a bunch of links when googling about;  it .Also, you might want to join the  list.   While you aren't targeting a PyObjC based application (which, btw, is a good idea -- PyObjC has a long way to go before it'll be iOS friendly), the PyObjC community has been discussing this and Ronald, of anyone, is probably the most knowledgeable person in this particular area.  Note that PyObjC will have to solve the embedded Python on iOS problem prior to porting PyObjC.  Their prerequisite is your requirement, as it were.I've put a very rough script up on github that fetches and builds python2.6.5 for iPhone and simulator.Work in progressSomewhat depressing update nearly 2 years later: (copied from README on github)I also started such a project. It comes with its own simplified compile script so there is no need to mess around with autoconf to get your cross compiled static library. It is able to build a completely dependency-free static library of Python with some common modules. It should be easily extensible.
Python

I can write something myself by finding zero-crossings of the first derivative or something, but it seems like a common-enough function to be included in standard libraries.  Anyone know of one?My particular application is a 2D array, but usually it would be used for finding peaks in FFTs, etc.Specifically, in these kinds of problems, there are multiple strong peaks, and then lots of smaller \"peaks\" that are just caused by noise that should be ignored.  These are just examples; not my actual data:1-dimensional peaks:2-dimensional peaks:The peak-finding algorithm would find the location of these peaks (not just their values), and ideally would find the true inter-sample peak, not just the index with maximum value, probably using  or something.Typically you only care about a few strong peaks, so they'd either be chosen because they're above a certain threshold, or because they're the first  peaks of an ordered list, ranked by amplitude.As I said, I know how to write something like this myself.  I'm just asking if there's a pre-existing function or package that's known to work well.I  and it works decently for the 1-D case, but could be better.sixtenbe  for the 1-D case.I do not think that what you are looking for is provided by SciPy.  I would write the code myself, in this situation.The spline interpolation and smoothing from scipy.interpolate are quite nice and might be quite helpful in fitting peaks and then finding the location of their maximum.I'm looking at a similar problem, and I've found some of the best references come from chemistry (from peaks finding in mass-spec data).  For a good thorough review of peaking finding algorithms read .  This is one of the best clearest reviews of peak finding techniques that I've run across.  (Wavelets are the best for finding peaks of this sort in noisy data.).It looks like your peaks are clearly defined and aren't hidden in the noise.  That being the case I'd recommend using smooth savtizky-golay derivatives to find the peaks (If you just differentiate the data above you'll have a mess of false positives.).  This is a very effective technique and is pretty easy to implemented (you do need a matrix class w/ basic operations).  If you simply find the zero crossing of the first S-G derivative I think you'll be happy.There is a function in scipy named  which sounds like is suitable for your needs, however I don't have experience with it so I cannot recommend..For those not sure about which peak-finding algorithms to use in Python, here a rapid overview of the alternatives: Wanting myself an equivalent to the MatLab  function, I've found that the  from Marcos Duarte is a good catch.Pretty easy to use:Which will give you:Detecting peaks in a spectrum in a reliable way has been studied quite a bit, for example all the work on sinusoidal modelling for music/audio signals in the 80ies. Look for \"Sinusoidal Modeling\" in the literature.If your signals are as clean as the example, a simple \"give me something with an amplitude higher than N neighbours\" should work reasonably well. If you have noisy signals, a simple but effective way is to look at your peaks in time, to track them: you then detect spectral lines instead of spectral peaks. IOW, you compute the FFT on a sliding window of your signal, to get a set of spectrum in time (also called spectrogram). You then look at the evolution of the spectral peak in time (i.e. in consecutive windows).There are standard statistical functions and methods for finding outliers to data, which is probably what you need in the first case. Using derivatives would solve your second. I'm not sure for a method which solves both continuous functions and sampled data, however.First things first, the definition of \"peak\" is vague if without further specifications.  For example, for the following series, would you call 5-4-5 one peak or two?1-2-1-2-1-1-5-4-5-1-1-5-1In this case, you'll need at least two thresholds: 1) a high threshold only above which can an extreme value register as a peak; and 2) a low threshold so that extreme values separated by small values below it will become two peaks.Peak detection is a well-studied topic in Extreme Value Theory literature, also known as \"declustering of extreme values\".  Its typical applications include identifying hazard events based on continuous readings of environmental variables e.g. analysing wind speed to detect storm events.
Python

Copying a shuffled  list ten times takes me about 0.18 seconds: (these are five runs)Copying the unshuffled list ten times takes me about 0.05 seconds:Here's my testing code:I also tried copying with , the results were similar (i.e., big speed difference)Why the big speed difference? I know and understand the speed difference in the famous  example, but here my processing has no decisions. It's just blindly copying the references inside the list, no?I'm using Python 2.7.12 on Windows 10. Tried Python 3.5.2 as well now, the results were almost the same (shuffled consistently around 0.17 seconds, unshuffled consistently around 0.05 seconds). Here's the code for that:The interesting bit is that it depends on the order in which the integers are  created. For example instead of  create a random sequence with :This is as fast as copying your  (first and fast example).However when you shuffle - then your integers aren't in the order they were first created anymore, that's what makes it slow. A quick intermezzo:So when you copy your list you get each item of that list and put it \"as is\" in the new list. When your next item was created shortly after the current one there is a good chance (no guarantee!) that it's saved next to it on the heap. Let's assume that whenever your computer loads an item in the cache it also loads the  next-in-memory items (cache locality). Then your computer can perform the reference count increment for  items on the same cache!With the shuffled sequence it still loads the next-in-memory items but these aren't the ones next-in-list. So it can't perform the reference-count increment without \"really\" looking for the next item. The actual speed depends on what happened before the copy: in what order were these items created and in what order are these in the list.You can verify this by looking at the :Just to show a short excerpt:So these objects are really \"next to each other on the heap\". With  they aren't:Which shows these are not really next to each other in memory:I haven't thought this up myself. Most of the informations can be found in the .This answer is based on the \"official\" CPython implementation of Python. The details in other implementations (Jython, PyPy, IronPython, ...) may be different. Thanks @J\u00f6rgWMittag .When you shuffle the list items, they have worse locality of reference, leading to worse cache performance.You might think that copying the list just copies the references, not the objects, so their locations on the heap shouldn't matter.  However, copying still involves accessing each object in order to modify the refcount.As explained by others, it's not just copying the references but also increases the reference counts inside the objects and thus the objects  accessed and the cache plays a role.Here I just want to add more experiments. Not so much about shuffled vs unshuffled (where accessing one element might miss the cache but get the following elements into the cache so they get hit). But about repeating elements, where later accesses of the same element might hit the cache because the element is still in the cache.Testing a normal range:A list of the same size but with just one element repeated over and over again is faster because it hits the cache all the time:And it doesn't seem to matter what number it is:Interestingly, it gets even faster when I instead repeat the same two or four elements:I guess something doesn't like the same single counter increased all the time. Maybe some  because each increase has to wait for the result of the previous increase, but this is a wild guess.Anyway, trying this for even larger numbers of repeated elements:The output (first column is the number of different elements, for each I test three times and then take the average):So from about 2.8 seconds for a single (repeated) element it drops to about 2.2 seconds for 2, 4, 8, 16, ... different elements and stays at about 2.2 seconds until the hundred thousands. I think this uses my L2 cache (4 \u00d7 256 KB, I have an ).Then over a few steps, the times go up to 3.5 seconds. I think this uses a mix of my L2 cache and my L3 cache (8 MB) until that's \"exhausted\" as well.At the end it stays at around 3.5 seconds, I guess because my caches don't help with the repeated elements anymore.
Python

Django has some good automatic serialization of ORM models returned from DB to JSON format.How to serialize SQLAlchemy query result to JSON format? I tried  but it encodes query object itself.\nI tried  but it returnsIs it really so hard to serialize SQLAlchemy ORM objects to JSON /XML? Isn't there any default serializer for it? It's very common task to serialize ORM query results nowadays.What I need is just to return JSON or XML data representation of SQLAlchemy query result.SQLAlchemy objects query result in JSON/XML format is needed to be used in javascript datagird (JQGrid )You could use something like this:and then convert to JSON using:It will ignore fields that are not encodable (set them to 'None').It doesn't auto-expand relations (since this could lead to self-references, and loop forever).If, however, you'd rather loop forever, you could use:And then encode objects using:This would encode all children, and all their children, and all their children... Potentially encode your entire database, basically. When it reaches something its encoded before, it will encode it as 'None'.Another alternative, probably better, is to be able to specify the fields you want to expand:You can now call it with:To only expand SQLAlchemy fields called 'parents', for example.You could just output your object as a dict:And then you use User.as_dict() to serialize your object.As explained in You can convert a RowProxy to a dict like this:Then serialize that to JSON ( you will have to specify an encoder for things like  values )\nIt's not that hard if you just want one record ( and not a full hierarchy of related records ).I recommend using a recent surfaced library . It allows you to create serializers to represent your model instances with support to relations and nested objects.Have a look at theier . package has an implementation of  Base class for your models.Usage:Now the  model is magically serializable.If your framework is not Flask, you can just For security reasons you should never return all the model's fields. I prefer to selectively choose them.Flask's json encoding now supports UUID, datetime and relationships (and added  and  for flask_sqlalchemy  class). I've updated the encoder as follows:With this I can optionally add a  property that returns the list of fields I wish to encode:I add @jsonapi to my view, return the resultlist and then my output is as follows:It is not so straighforward. I wrote some code to do this. I'm still working on it, and it uses the MochiKit framework. It basically translates compound objects between Python and Javascript using a proxy and registered JSON converters. Browser side for database objects is \nIt needs the basic Python proxy source in .On the Python side there is the base .\nThen finally the SqlAlchemy object encoder in .\nIt also depends on metadata extractors found in the  file.Custom serialization and deserialization. (class method) builds a Model object based on json data. could be called only on instance, and merge all data from json into Model instance. - recursive serialization property is needed to define write only properties (\"password_hash\" for example).Use the  in SQLAlchemy:If you're transferring the object between sessions, remember to detach the object from the current session using .\nTo attach it again, just do .Here is a solution that lets you select the relations you want to include in your output as deep as you would like to go.\nNOTE: This is a complete re-write taking a dict/str as an arg rather than a list. fixes some stuff..so for an example using person/family/homes/rooms... turning it into json all you need isI thought I'd play a little code golf with this one. FYI: I am using  since we have a separately designed schema according to business requirements. I just started using SQLAlchemy today but the documentation states that automap_base is an extension to declarative_base which seems to be the typical paradigm in the SQLAlchemy ORM so I believe this should work.It does not get fancy with following foreign keys per 's solution, but it simply matches columns to values and handles Python types by str()-ing the column values. Our values consist Python datetime.time and decimal.Decimal class type results so it gets the job done.Hope this helps any passers-by!I know this is quite an older post. I took solution given by @SashaB and modified as per my need. I added following things to it:My code is as follows:Hope it helps someone!My take utilizing (too many?) dictionaries:Running with flask (including jsonify) and flask_sqlalchemy to print outputs as JSON.Call the function with jsonify(serialize()).Works with all SQLAlchemy queries I've tried so far (running SQLite3)
Python

What is a good way to find the index of an element in an array in python? \nNote that the array may not be sorted.\nIs there a way to specify what comparison operator to use?The best way is probably to use the list method .index. For the objects in the list, you can do something like:with any special processing you need.You can also use a for/in statement with enumerate(arr)Example of finding the index of an item that has value > 100.From :If you just want to find out if an element is contained in the list or not:Here is another way using list comprehension (some people might find it debatable). It is very approachable for simple tests, e.g. comparisons on object attributes (which I need a lot):Of course this assumes the existence (and, actually, uniqueness) of a suitable element in the list.assuming you want to find a value in a numpy array,\nI guess something like this might work:There is the  method, , but I don't think you can specify a custom comparison operator. It wouldn't be hard to write your own function to do so, though:The index method of a list will do this for you. If you want to guarantee order, sort the list first using . Sorted accepts a cmp or key parameter to dictate how the sorting will happen:Or:I use function for returning index for the matching element (Python 2.6):Then use it via lambda function for retrieving needed element by any required equation e.g. by using element name.If i need to use it in several places in my code i just define specific find function e.g. for finding element by name:And then it is quite easy and readable:I found this by adapting some tutos. Thanks to google, and to all of you ;)A very simple use:P.S. scuse my englishhow's this one?Usage:
Python

If I want to use the results of , which is a  object, with a method that expects a dictionary or mapping-like object (see ), what is the right way to do it?I would think the answer is no:  smells like a convention for implementation, but not for an interface, the way  or  or  seem to be.You can access the namespace's dictionary with :You can modify the dictionary directly if you wish:Yes, it is okay to access the __dict__ attribute.  It is a well-defined, tested, and guaranteed behavior.:If you prefer to have dict-like view of the attributes, you can use the standard Python idiom, :In general, I would say \"no\". However  has struck me as over-engineered, possibly from when classes couldn't inherit from built-in types. On the other hand,  does present a task-oriented approach to argparse, and I can't think of a situation that would call for grabbing the , but the limits of my imagination are not the same as yours.
Python

Is it possible to get some information out of the .pyc file that is generated from a .py file? worked well for me with Python 2.7 to decompile the .pyc bytecode into .py, whereas unpyclib crashed with an exception.For Python 3 and Python 2.7, you can try the more recent .See  for some other comments.Yes, you can get it with  that can be found on .Than you can decompile your .pyc fileYou may try . It's based on Decompyle++ and Uncompyle2.\nIt's supports decompiling python versions 1.0-3.3Note: I am the author of the above tool.Decompyle++ (pycdc) was the only one that worked for me: was suggested in Yes, it is possible.There is a perfect open-source Python (.PYC) decompiler, called Decompyle++  Decompyle++ aims to translate compiled Python byte-code back into valid and human-readable Python source code. \nWhile other projects have achieved this with varied success, Decompyle++ is unique in that it seeks to support byte-code from any version of Python. Online version is available here: \nI have no idea if it's any good, but a quick google search turned up .
Python

Python sorts by byte value by default, which means \u00e9 comes after z and other equally funny things. What is the best way to sort alphabetically in Python?Is there a library for this? I couldn't find anything. Preferrably sorting should have language support so it understands that \u00e5\u00e4\u00f6 should be sorted after z in Swedish, but that \u00fc should be sorted by u, etc. Unicode support is thereby pretty much a requirement.If there is no library for it, what is the best way to do this? Just make a mapping from letter to a integer value and map the string to a integer list with that?IBM's  library does that (and a lot more). It has Python bindings: . : The core difference in sorting between ICU and  is that ICU uses the full  while  uses .The differences between those two algorithms are briefly summarized here: . These are rather exotic special cases, which should rarely matter in practice.I don't see this in the answers. My Application sorts according to the locale using python's standard library. It is pretty easy.Question to Lennart and other answerers: Doesn't anyone know 'locale' or is it not up to this task?Try James Tauber's . It may not do exactly as you want, but seems well worth a look. For a bit more information about the issues, see  by Christopher Lenz.A summary and extended answer: under Python 2, and  will in fact solve the problem, and does a good job, assuming that you have the locale in question installed. I tested it under Windows too, where the locale names confusingly are different, but on the other hand it seems to have all locales that are supported installed by default. doesn't necessarily do this better in practice, it however does way . Most notably it has support for splitters that can split texts in different languages into words. This is very useful for languages that doesn't have word separators. You'll need to have a corpus of words to use as a base for the splitting, because that's not included, though.It also has long names for the locales so you can get pretty display names for the locale, support for other calendars than Gregorian (although I'm not sure the Python interface supports that) and tons and tons of other more or less obscure locale supports. If you want to sort alphabetically and locale-dependent, you can use the  module, unless you have special requirements, or also need more locale dependent functionality, like words splitter.You might also be interested in :Though it is certainly not the most exact way, it is a very simple way to at least get it somewhat right. It also beats locale in a webapp as locale is not threadsafe and sets the language settings process-wide. It also easier to set up than PyICU which relies on an external C library. I uploaded the script to github as the original was down at the time of this writing and I had to resort to web caches to get it:I successfully used this script to sanely sort German/French/Italian text in a plone module.I see the answers have already done an excellent job, just wanted to point out one coding inefficiency in . To apply a selective char-by-char translation to a unicode string s, it uses the code:Python has a much better, faster and more concise way to perform this auxiliary task (on Unicode strings -- the analogous method for byte strings has a different and somewhat less helpful specification!-):The dict you pass to the  method has Unicode ordinals (not strings) as keys, which is why we need that rebuilding step from the original char-to-char . (Values in the dict you pass to translate [as opposed to keys, which must be ordinals] can be Unicode ordinals, arbitrary Unicode strings, or None to remove the corresponding character as part of the translation, so it's easy to specify \"ignore a certain character for sorting purposes\", \"map \u00e4 to ae for sorting purposes\", and the like).In Python 3, you can get the \"rebuilding\" step more simply, e.g.:See  for other ways you can use this  static method in Python 3.The simplest, easiest, and most straightforward way to do this it to make a callout to the Perl library module, , which is  a subclass of the standard  module. All you need do is pass the constructor a locale value of  for Sweden.  (You may not neccesarily appreciate this for Swedish text, but because Perl uses abstract characters, you can use any Unicode code point you please \u2014 no matter the platform or build! Few languages offer such convenience. I mention it because I\u2019ve fighting a losing battle with Java a lot over this maddening problem lately.)The problem is that I do not know how to access a Perl module from Python \u2014 apart, that is, from using a shell callout or two-sided pipe. To that end,  that you can call to do exactly what you have asked for with perfect ease. , with all tailoring options supported!!  And if you have an optional module installed or run Perl 5.13 or better, then you have full access to easy-to-use CLDR locales.  See below.Imagine an input set ordered this way:A default sort by code point yields:which is incorrect by everybody\u2019s book.  Using my script, which uses the Unicode Collation Algorithm, you get this order:That is the default UCA sort.  To get the Swedish locale, call  this way:Here is a better input demo. First, the input set:By code point, that sorts this way:But using the default UCA makes it sort this way:But in the Swedish locale, this way:If you prefer uppercase to sort before lowercase, do this:You can do many other things with . For example, here is how to sort titles in English:You will need Perl 5.10.1 or better to run the script in general. For locale support, you must either install the optional CPAN module . Alternately, you can install a development versions of Perl, 5.13+, which include that module standardly.This is a rapid prototype, so  is mostly un(der)documented. But this is its SYNOPSIS of what switches/options it accepts on the command line:Yeah, ok: that\u2019s really the argument list I use for the call to , but you get the idea. :) If you can figure out how to call Perl library modules from Python directly without calling a Perl script, by all means do so.  I just don\u2019t know how myself.  I\u2019d love to learn how.In the meantime, I believe this script will do what you need done in all its particular \u2014   I now use this for all of text sorting. It  does what I\u2019ve needed for a long, long time. The only downside is that  argument causes performance to go down the tubes, although it\u2019s plenty fast enough for regular, non-locale  sorting.  Since it loads everything in memory, you probably don\u2019t want to use this on gigabyte documents. I use it many times a day, and it sure it great having sane text sorting at last.To implement it you will need to read about \"Unicode collation algorithm\"\nsee\na sample implementation is hereJeff Atwood wrote a good post on , in it he linked to a script which does .It's not a trivial script, by any means, but it does the trick.Lately I've been using zope.ucol () for this task. For example, sorting the german \u00df:zope.ucol also wraps ICU, so would be an alternative to PyICU.It is far from a complete solution for your use case, but you could take a look at the  script from effbot.org. What it basically does is remove all accents from a text. You can use that 'sanitized' text to sort alphabetically. (For a better description see  page.)
Python

I am trying to find out the version of Visual Studio that is used to compile the Python on my computerIt says What I do not understand is this  designation. Does it mean it is compiled with Visual Studio 2005? I cannot find this information on . appears to be Visual C++ 2008 according to  (of all places).  The  indicates 1500 to be the result of the  macro. mentions that The above MSDN link said that 1600 indicates VS2010.Strangely, I wasn't able to find that info about the earlier  values on MSDN.
Python

I can't get my head around Python's  module. My needs are very simple: I just want to log everything to syslog. After reading documentation I came up with this simple test script:But this script does not produce any log records in syslog. What's wrong?Change the line to this:This works for meYou should  use the local host for logging, whether to /dev/log or localhost  through the TCP stack. This allows the fully RFC compliant and featureful system logging daemon to handle syslog. This eliminates the need for the remote daemon to be functional and provides the enhanced capabilities of syslog daemon's such as rsyslog and syslog-ng for instance. The same philosophy goes for SMTP. Just hand it to the local SMTP software. In this case use 'program mode' not the daemon, but it's the same idea. Let the more capable software handle it. Retrying, queuing, local spooling, using TCP instead of UDP for syslog and so forth become possible. You can also [re-]configure those daemons separately from your code as it should be.Save your coding for your application, let other software do it's job in concert.I add a little extra comment just in case it helps anyone because I found this exchange useful but needed this little extra bit of info to get it all working.To log to a specific facility using SysLogHandler you need to specify the facility value.\nSay for example that you have defined:in syslog, then you'll want to use:and you also need to have syslog listening on UDP to use localhost instead of /dev/log.Piecing things together from here and other places, this is what I came up with that works on unbuntu 12.04 and centOS6Create an file in  that ends in .conf and add the following textRestart , reloading did NOT seem to work for the new log files. Maybe it only reloads existing conf files?Then you can use this test program to make sure it actually works.Is your syslog.conf set up to handle facility=user?You can set the facility used by the python logger with the facility argument, something like this:I found  to make it quite easy to get the basic logging behavior you describe:There are other things you could do, too, but even just the first two lines of that will get you what you've asked for as I understand it.From the above script will log to LOCAL0 facility with our custom \"LOG_IDENTIFIER\"...\nyou can use LOCAL[0-7] for local purpose.You can also add a file handler or rotating file handler to send your logs to a local file:\n
Python

I recently installed Python 3.1 and the Pygame module for Python 3.1  When I type import python in the console I get the following error:Please help!It could be due to the architecture of your OS. Is your OS 64 Bit and have you installed 64 bit version of Python? It may help to install both 32 bit version  and , which is available officially only in 32 bit and you won't face this problem.I see that 64 bit pygame is maintained , you might also want to try uninstalling Pygame only and install the 64 bit version on your existing python3.1, if not choose go for both 32-bit version.Looks like the question has been long ago answered but the solution did not work for me.  When I was getting that error, I was able to fix the problem by downloading I had installed Python 32 bit version and psycopg2 64 bit version to get this problem. I installed psycopg2 32 bit version and then it worked.Had this issue on Python 2.7.9, solved by updating to Python 2.7.10 (unreleased when this question was asked and answered).Another possible cause of similar issue could be wrong  in the cx_freeze manifest, trying to load x86 common controls dll in x64 process - should be fixed by this patch:
Python

I am new to Python's logging package and plan to use it for my project. I would like to customize the time format to my taste. Here is a short code I copied from a tutorial:And here is the output:I would like to shorten the time format to just: '', dropping the mili-second suffix. I looked at the Formatter.formatTime, but confused. I appreciate your help to achieve my goal. Thank you.From the  regarding the Formatter class:So changetoUsing logging.basicConfig, the following example works for me:This allows you to format & config all in one line.  A resulting log record looks as follows:2014-05-26 12:22:52.376 CRITICAL historylistener - main: History log failed to startif using logging.config.fileConfig with a configuration file use something like:To add to the other answers, here are the  from Python Documentation.
Python

How do I get the index column name in python pandas?  Here's an example dataframe:What I'm trying to do is get/set the dataframe index title.  Here is what i tried:Anyone know how to do this? You can just get/set the index via its  property should do the trick.Python has a  function that let's you query object attributes.  was helpful here.From version  you can use :The new functionality works well in method chains.You can also rename column names with parameter :If you do not want to create a new row but simply put it in the empty cell then use:Otherwise use:  also give us the column namesUse  to set the index name. Seems this api is available since .
Python

I'm looking for an open source implementation, preferably in python, of  (). Is anyone familiar with such open source implementation I can use?I'm writing an application that searches twitter for some search term, say \"youtube\", and counts \"happy\" tweets vs. \"sad\" tweets. \nI'm using Google's appengine, so it's in python. I'd like to be able to classify the returned search results from twitter and I'd like to do that in python.\nI haven't been able to find such sentiment analyzer so far, specifically not in python. \nAre you familiar with such open source implementation I can use? Preferably this is already in python, but if not, hopefully I can translate it to python.Note, the texts I'm analyzing are VERY short, they are tweets. So ideally, this classifier is optimized for such short texts.BTW, twitter does support the \":)\" and \":(\" operators in search, which aim to do just this, but unfortunately, the classification provided by them isn't that great, so I figured I might give this a try myself.Thanks!BTW, an early demo is  and the code I have so far is  and I'd love to opensource it with any interested developer.With most of these kinds of applications, you'll have to roll much of your own code for a statistical classification task. As Lucka suggested, NLTK is the perfect tool for natural language manipulation in Python, so long as your goal doesn't interfere with the non commercial nature of its license.  However, I would suggest other software packages for modeling.  I haven't found many strong advanced machine learning models available for Python, so I'm going to suggest some standalone binaries that easily cooperate with it.You may be interested in , which can be easily interfaced with Python.  This has been used for classification tasks in various areas of natural language processing.  You also have a pick of a number of different models.  I'd suggest starting with Maximum Entropy classification so long as you're already familiar with implementing a Naive Bayes classifier.  If not, you may want to look into it and code one up to really get a decent understanding of statistical classification as a machine learning task.The University of Texas at Austin computational linguistics groups have held classes where most of the projects coming out of them have used this great tool.  You can look at the course page for  to get an idea of how to make it work and what previous applications it has served.Another great tool which works in the same vein is .  The difference between Mallet is that there's a bit more documentation and some more models available, such as decision trees, and it's in Java, which, in my opinion, makes it a little slower.   is a whole suite of different machine learning models in one big package that includes some graphical stuff, but it's really mostly meant for pedagogical purposes, and isn't really something I'd put into production.Good luck with your task.  The real difficult part will probably be the amount of knowledge engineering required up front for you to classify the 'seed set' off of which your model will learn.  It needs to be pretty sizeable, depending on whether you're doing binary classification (happy vs sad) or a whole range of emotions (which will require even more).  Make sure to hold out some of this engineered data for testing, or run some tenfold or remove-one tests to make sure you're actually doing a good job predicting before you put it out there. And most of all, have fun!  This is the best part of NLP and AI, in my opinion.Good luck with that.Sentiment is enormously contextual, and tweeting culture makes the problem worse because  for most tweets.  The whole point of twitter is that you can leverage the huge amount of shared \"real world\" context to pack meaningful communication in a very short message.If they say the video is bad, does that mean bad, or ?Thanks everyone for your suggestions, they were indeed very useful!\nI ended up using a Naive Bayesian classifier, which I borrowed from . \nI started by feeding it with a list of good/bad keywords and then added a \"learn\" feature by employing user feedback. It turned out to work pretty nice.The full details of my work as in a .Again, your help was very useful, so thank you!I have constructed a word list labeled with sentiment. You can access it from here:You will find a short Python program on my blog: This post displays how to use the word list with single sentences as well as with Twitter.Word lists approaches have their limitations. You will find a investigation of the limitations of my word list in the article \"A new ANEW: Evaluation of a word list for sentiment analysis in microblogs\". That article is available from my homepage.Please note a  is missing from the code (for paedagogic reasons).A lot of research papers indicate that a good starting point for sentiment analysis is looking at adjectives, e.g., are they positive adjectives or negative adjectives. For a short block of text this is pretty much your only option... There are papers that look at entire documents, or sentence level analysis, but as you say tweets are quite short... There is no real magic approach to understanding the sentiment of a sentence, so I think your best bet would be hunting down one of these research papers and trying to get their data-set of positively/negatively oriented adjectives.Now, this having been said, sentiment is domain specific, and you might find it difficult to get a high-level of accuracy with a general purpose data-set.Good luck.I think you may find it difficult to find what you're after. The closest thing that I know of is , which has some  and is available under a limited kind of open-source licence, but is written in Java.Also, sentiment analysis systems are usually developed by training a system on product/movie review data which is significantly different from the average tweet. They are going to be optimised for text with several sentences, all about the same topic. I suspect you would do better coming up with a rule-based system yourself, perhaps based on a lexicon of sentiment terms like .Check out  for an implementation of similar idea with a really beautiful interface (and ).Take a look at . It's written in python, and it uses Naive Bayes classifier with semi-supervised machine learning. The source can be found .Maybe  (based on NLTK and pattern) is the right sentiment analysis tool for you.I came across  a while ago. You could probably use it as a starting point. It also has a lot of modules and addons, so maybe they already have something similar.Somewhat wacky thought: you could try using the Twitter API to download a large set of tweets, and then classifying a subset of that set using emoticons: one positive group for  \":)\", \":]\", \":D\", etc, and another negative group with \":(\", etc.Once you have that crude classification, you could search for more clues with frequency or ngram analysis or something along those lines.It may seem silly, but serious research has been done on this (search for \"sentiment analysis\" and emoticon). Worth a look.  There's a Twitter Sentiment API by TweetFeel that does advanced linguistic analysis of tweets, and can retrieve positive/negative tweets. See For those interested in coding Twitter Sentiment Analyis from scratch, there is a Coursera course \"\" with python code on GitHub (as part of assignment 1 - ). The sentiments are part of the .You can find working solutions, for example . In addition to the AFINN-111 sentiment list, there is a simple implementation of builing a dynamic term list based on frequency of terms in tweets that have a pos/neg score (see ).
Python

In python, how do I check if an object is a generator object?Trying this - gives the error -(I know I can check if the object has a  method for it to be a generator, but I want some way using which I can determine the type of any object, not just generators.)You can use GeneratorType from types:You mean generator functions ? use .if you want a generator object you can use  as pointed out by JAB in his comment.The  function is fine if you want to check for pure generators (i.e. objects of class \"generator\"). However it will return  if you check, for example, a  iterable. An alternative way for checking for a generalised generator is to use this function:I think it is important to make distinction between  and  (generator function's result):calling generator_function won't yield normal result, it even won't execute any code in the function itself, the result will be special object called :so it is not generator function, but generator:and generator function is not generator:just for a reference, actual call of function body will happen by consuming generator, e.g.:See also Don't do this.  It's simply a very, very bad idea.Instead, do this:In the unlikely event that the body of the  loop also has s, there are several choices: (1) define a function to limit the scope of the errors, or (2) use a nested  block.Or (3) something like this to distinguish all of these s which are floating around.Or (4) fix the other parts of your application to provide generators appropriately.  That's often simpler than all of this.If you are using tornado webserver or similar you might have found that server methods are actually generators and not methods. This makes it difficult to call other methods because yield is not working inside the method and therefore you need to start managing pools of chained generator objects. A simple method to manage pools of chained generators is to create a help function such as Now writing chained generators such asProduces outputWhich is probably what you want if your looking to use generators as a thread alternative or similar.
Python

I notice that it is often suggested to use queues with multiple treads, instead of lists and .pop(). Is this because lists are not thread-safe, or for some other reason?Lists themselves are thread-safe. In CPython the GIL protects against concurrent accesses to them, and other implementations take care to use a fine-grained lock or a synchronized datatype for their list implementations. However, while lists  can't go corrupt by attempts to concurrently access, the lists's  is not protected. For example:is not guaranteed to actually increase L[0] by one if another thread does the same thing, because  is not an atomic operation. (Very, very few operations in Python are actually atomic, because most of them can cause arbitrary Python code to be called.) You should use Queues because if you just use an unprotected list, you may get or delete  because of race conditions.To clarify a point in Thomas' excellent answer, it should be mentioned that   thread safe.This is because there is no concern that data being  will be in the same place once we go to  to it. The  operation does not read data, it only writes data to the list. of  operations and whether or not they are thread safe.\nHoping to get an answer regarding the  language construct .
Python

I'm working with Python v2, and I'm trying to find out if you can tell if a word is in a string.I have found some information about identifying if the word is in the string - using .find, but is there a way to do an IF statement. I would like to have something like the following:Thanks for any help.What is wrong with:but keep in mind that this matches a sequence of characters, not necessarily a whole word - for example,  is True. If you only want to match whole words, you ought to use regular expressions:find returns an integer representing the index of where the search item was found.  If it isn't found, it returns -1.If you want to find out whether a whole word is in a space-separated list of words, simply use:This elegant method is also the fastest. Compared to Hugh Bothwell's and daSong's approaches:This small function compares all search words in given text. If all search words are found in text, returns length of search, or  otherwise.Also supports unicode string search.usage:If matching a sequence of characters is not sufficient and you need to match whole words, here is a simple function that gets the job done. It basically appends spaces where necessary and searches for that in the string:This assumes that commas and other punctuations have already been stripped out.You can split string to the words and check the result list.You could just add a space before and after \"word\".This way it looks for the space before and after \"word\".Advanced way to check the exact word, that we need to find in a long string:
Python

I am running a  Python app on a Heroku Cedar dyno. The app returns  to its clients (it's an , really).Once in a while clients get 0-byte responses. It's not me returning them, however. Here is a snippet of my app's log:The first line above is me starting to handle the request. The second line is me returning a value (to Flask -- it's a Flask \"Response\" object).The third line is Gnicorn's, where you can see the Gunicorn got the 200 status and 22 bytes HTTP body (\"\").However, the client got 0 bytes. Here is the Heroku router log:Why does Gunicorn return 22 bytes, but Heroku sees 0, and indeed passes back 0 bytes to the client? Is this a Heroku bug?I know I may be considered a little off the wall here but there is another option.We know that from time to time there is a bug that happens on transit.We know that there is not much we can do right now to stop the problem. If you are only providing the API then stop reading however if you write the client too, keep going.The error is a known case, and known cause. The result of an empty return value means that something went wrong. However the value is available and was fetched, calculated, whatever... My instinct as a developer would be to treat an empty result as an HTTP error and request the data be resent. You could then track the resend requests and see how often this happens.I would suggest (although you strike me as the kind of developer to think of this too) that you count the requests and set a sane value for responding \"network error\" to the user. My instinct would be to retry right away and then to wait a little while before retrying some more.From what you describe the first retry would probably pick up the data properly. Of course this could mean keeping older requests hanging about in cache for a few minutes or running the request a second time depending on what seemed most appropriate.This would also route around any number of other point-to-point networking errors and leave the app far more robust even in the face of connectivity problems.I know our instinct as developers is to fix the known fault but sometimes it is better to work towards a system that is able to operate despite faults. That said it never hurts to log errors and problems and try to fix them anyway.
Python

I am looking for best practices for function/class/module documentation, i.e. comments in the code itself. Ideally I would like a comment template which is both human readable and consumable by Python documentation utilities.I have read the .I understand this part:This sentence needs a bit more explanation:Specifically, I am looking for examples of well-commented functions and classes.You should  and check out the . All the cool kids are doing it.You should . i.e.You should avoid repeating yourself unnecessarily or explaining the eminently obvious. Example of what not to do:If you wanted to describe something non-obvious it would be a different story; for example, that verbose causes messages to occur on  or a  stream. This is not specific to Python, but follows from more hand-wavy ideals such as  and .Try to avoid mentioning specific types if possible (abstract or interface-like types are generally okay). Mentioning  is typically more helpful from a duck typing perspective (i.e. \"iterable\" instead of , or \"mutable ordered sequence\" instead of ). I've seen some code that is very literal and heavy WRT the  and the  function-level documentation, which I've found to be at odds with the duck typing mentality.As Emji said, Django is a good project to follow for clear, consistent style guides.For example, their  even goes as far as describing how they'd like to see documentation.  Specifically they mention:I think the best resource will be Quote:: The official Python documentation generatorThe best way to learn documentation practices is probably to look at the source code of a well known project. Like the .
Python

I'd like to make a Python package containing some  code. I've got the the Cython code working nicely. However, now I want to know how best to package it.For most people who just want to install the package, I'd like to include the  file that Cython creates, and arrange for  to compile that to produce the module. Then the user doesn't need Cython installed in order to install the package.But for people who may want to modify the package, I'd also like to provide the Cython  files, and somehow also allow for  to build them using Cython (so those users  need Cython installed).How should I structure the files in the package to cater for both these scenarios?The . But it doesn't say how to make a single  that handles both the with/without Cython cases.I've done this myself now, in a Python package  ( - EDIT: now ) (I don't expect this to be a popular package, but it was a good chance to learn Cython).This method relies on the fact that building a  file with  (at least with Cython version 0.14) always seems to create a  file in the same directory as the source  file.Here is a cut-down version of  which I hope shows the essentials:I also edited  to ensure that  is included in a source distribution (a source distribution that is created with ):I don't commit  to version control 'trunk' (or 'default' for Mercurial). When I make a release, I need to remember to do a  first, to ensure that  is present and up-to-date for the source code distribution. I also make a release branch, and commit the C file into the branch. That way I have a historical record of the C file that was distributed with that release.Adding to Craig McQueen's answer: see below for how to override the  command to have Cython automatically compile your source files before creating a source distribution.That way your run no risk of accidentally distributing outdated  sources. It also helps in the case where you have limited control over the distribution process e.g. when automatically creating distributions from continuous integration etc.The easiest is to include both but just use the c-file? Including the .pyx file is nice, but it's not needed once you have the .c file anyway. People who want to recompile the .pyx can install Pyrex and do it manually.Otherwise you need to have a custom build_ext command for distutils that builds the C file first. Cython already includes one. What that documentation doesn't do is say how to make this conditional, but Should handle it.Including (Cython) generated .c files are pretty weird. Especially when we include that in git. I'd prefer to use . When Cython is not available, it will build an egg which has built-in Cython environment, and then build your code using the egg.A possible example: Update(2017-01-05):Since , there's no need to use .  is an example to build Cython project from scratch without .The simple hack I came up with:Just install Cython if it could not be imported. One should probably not share this code, but for my own dependencies it's good enough.This is a setup script I wrote which makes it easier to include nested directories inside the build. One needs to run it from folder within a package. Givig structure like this:setup.pyHappy compiling ;) 
Python

Suppose I have written a decorator that does something very generic. For example, it might convert all arguments to a specific type, perform logging, implement memoization, etc.Here is an example:Everything well so far. There is one problem, however. The decorated function does not retain the documentation of the original function:Fortunately, there is a workaround:This time, the function name and documentation are correct:But there is still a problem: the function signature is wrong. The information \"*args, **kwargs\" is next to useless.What to do? I can think of two simple but flawed workarounds:1 -- Include the correct signature in the docstring:This is bad because of the duplication. The signature will still not be shown properly in automatically generated documentation. It's easy to update the function and forget about changing the docstring, or to make a typo. []2 -- Not use a decorator, or use a special-purpose decorator for every specific signature:This works fine for a set of functions that have identical signature, but it's useless in general. As I said in the beginning, I want to be able to use decorators entirely generically.I'm looking for a solution that is fully general, and automatic.So the question is: is there a way to edit the decorated function signature after it has been created?Otherwise, can I write a decorator that extracts the function signature and uses that information instead of \"*kwargs, **kwargs\" when constructing the decorated function? How do I extract that information? How should I construct the decorated function -- with exec?Any other approaches? preserves signatures since Python 3.4: is available  but it does not preserve the signature there:Notice:  instead of .There is a  with  decorator you can use:Then the signature and help of the method is preserved:EDIT: J. F. Sebastian pointed out that I didn't modify  function -- it is fixed now.Take a look at the  module - specifically the  decorator, which solves this problem.This is solved with Python's standard library  and specifically  function, which is designed to \"\". It's behaviour depends on Python version, however, as shown below. Applied to the example from the question, the code would look like:When executed in Python 3, this would produce the following:Its only drawback is that in Python 2 however, it doesn't update function's argument list. When executed in Python 2, it will produce:Second option:$ easy_install wraptwrapt have a bonus, preserve class signature.
Python

I am trying to write a wrapper script for a command line program (svnadmin verify) that will display a nice progress indicator for the operation.  This requires me to be able to see each line of output from the wrapped program as soon as it is output.I figured that I'd just execute the program using , use , then read each line as it came in and act on it accordingly.  However, when I ran the following code, the output appeared to be buffered somewhere, causing it to appear in two chunks, lines 1 through 332, then 333 through 439 (the last line of output)After looking at the documentation on subprocess a little, I discovered the  parameter to , so I tried setting bufsize to 1 (buffer each line) and 0 (no buffer), but neither value seemed to change the way the lines were being delivered.At this point I was starting to grasp for straws, so I wrote the following output loop:but got the same result.Is it possible to get 'realtime' program output of a program executed using subprocess?  Is there some other option in Python that is forward-compatible (not )?I tried this, and for some reason while the codebuffers aggressively, the variantdoes not. Apparently this is a known bug: You can try this:If you use readline instead of read, there will be some cases where the input message is not printed. Try it with a command the requires an inline input and see for yourself.I ran into the same problem awhile back.  My solution was to ditch iterating for the  method, which will return immediately even if your subprocess isn't finished executing, etc.Using pexpect [  ] with non-blocking readlines will resolve this problem. It stems from the fact that pipes are buffered, and so your app's output is getting buffered by the pipe, therefore you can't get to that output until the buffer fills or the process dies.I used this solution to get realtime output on a subprocess. This loop will stop as soon as the process completes leaving out a need for a break statement or possible infinite loop. Complete solution:Real Time Output Issue resolved:\nI did encountered similar issue in Python, while capturing the real time output from c program.  I added \";\" in my C code. It worked for me. Here is the snip the code << C Program >><< Python Program >><< OUTPUT>>\nPrint: Count  1\nPrint: Count  2\nPrint: Count  3Hope it helps.~sairamFound this \"plug-and-play\" function . Worked like a charm!This is what I did:It continuously prints new lines as they are output by the subprocess. 
Python

Python seems to have functions for copying files (e.g. ) and functions for copying directories (e.g. ) but I haven't found any function that handles both. Sure, it's trivial to check whether you want to copy a file or a directory, but it seems like a strange omission.Is there really no standard function that works like the unix  command, i.e. supports both directories and files and copies recursively? What would be the most elegant way to work around this problem in Python?I suggest you first call , and if an exception is thrown, then retry with .Unix  doesn't 'support both directories and files':To make cp copy a directory, you have to manually tell cp that it's a directory, by using the '-r' flag.There is some disconnect here though -  when passed a filename as the source will happily copy just the single file; copytree won't.To add on  and  answers, here's an alternative way of copying files and folders recursively. (Python 3.X)Should it be your first time and you have no idea how to copy files and folders recursively, I hope this helps.The python shutil.copytree method its a mess. I've done one that works correctly: and  are copying files. copies a folder with all the files and all subfolders.  is using  to copy the files.So the analog to  you are saying is the  because  targets and copies a folder and its files/subfolders like . Without the   copies files like  and  do.
Python

I'm having a few issues trying to encode a string to UTF-8. I've tried numerous things, including using  and , but I get the error:This is my string:I don't see what's going wrong, any idea?Edit: The problem is that printing the string as it is does not show properly. Also, this error when I try to convert it:This is to do with the encoding of your terminal not being set to UTF-8.  Here is my terminalOn my terminal the example works with the above, but if I get rid of the  setting then it won't workConsult the docs for your linux variant to discover how to make this change permanent.try:edit: gives , which is correct.so your problem must be at some oter place, possibly if you try to do something with it were there is an implicit conversion going on (could be printing, writing to a stream...)to say more we'll need to see some code.My +1 to mata's comment at  and to the Nick Craig-Wood's demonstration.  You have decoded the string correctly.  The problem is with the  command as it converts the Unicode string to the console encoding, and the console is not capable to display the string.  Try to write the string into a file and look at the result using some decent editor that supports Unicode:Then you will see .If you are working on a  host, look at  on your  PC.When this file contains a line:comment it out with adding  at the head of line. It might help.With this line,  sends language related environment variables of your PC to the  host. It causes  problems.No problems with my terminal. The above answers helped me looking in the right directions but it didn't work for me until I added :As indicated in the comment below, this may lead to undesired results. OTOH it also may just do the trick well enough to get things working and you don't care about losing some characters.It looks like your string is encoded to , so what exactly is the problem?  Or what are you trying to do here..?this works for ubuntu 15.10:I was getting the same type of error, and I found that the console is not capable of displaying the string in another language. Hence I made the below code changes to set default_charset as UTF-8. This is the best answer:\nin linux:so  is OK.i solve that problem changing in the file settings.py with 'ENGINE': 'django.db.backends.mysql',   don\u00b4t use 'ENGINE': 'mysql.connector.django',Just convert the text explicitly to string using . Worked for me.
Python

Python 2.x has two ways to overload comparison operators,  or the \"rich comparison operators\" such as .  Rich comparison operators are simpler to implement each, but you must implement several of them with nearly identical logic.  However, if you can use the builtin  and tuple ordering, then  gets quite simple and fulfills all the comparisons:This simplicity seems to meet my needs much better than overloading all 6(!) of the rich comparisons.  (However, you can get it down to \"just\" 4 if you rely on the \"swapped argument\"/reflected behavior, but that results in a net increase of complication, in my humble opinion.)I understand the , , , etc. operators can be overloaded for other purposes, and can return any object they like.  I am not asking about the merits of that approach, but only about differences when using these operators for comparisons in the same sense that they mean for numbers. As Christopher ,  is disappearing in 3.x. Yep, it's easy to implement everything in terms of e.g.  with a mixin class (or a metaclass, or a class decorator if your taste runs that way).For example:Now your class can define just  and multiply inherit from ComparableMixin (after whatever other bases it needs, if any). A class decorator would be quite similar, just inserting similar functions as attributes of the new class it's decorating (the result might be microscopically faster at runtime, at equally minute cost in terms of memory).Of course, if your class has some particularly fast way to implement (e.g.)  and , it should define them directly so the mixin's versions are not use (for example, that is the case for ) -- in fact  might well be defined to facilitate that as:but in the code above I wanted to keep the pleasing symmetry of only using ;-).\nAs to why  had to go, since we  have  and friends, why keep another, different way to do exactly the same thing around?  It's just so much dead-weight in every Python runtime (Classic, Jython, IronPython, PyPy, ...).  The code that  won't have bugs is the code that isn't there -- whence Python's principle that there ought to be ideally one obvious way to perform a task (C has the same principle in the \"Spirit of C\" section of the ISO standard, btw).This doesn't mean we go out of our way to prohibit things (e.g., near-equivalence between mixins and class decorators for some uses), but it definitely  mean that we don't like to carry around code in the compilers and/or runtimes that redundantly exists just to support multiple equivalent approaches to perform exactly the same task.Further edit: there's actually an even better way to provide comparison AND hashing for many classes, including that in the question -- a  method, as I mentioned on my comment to the question. Since I never got around to writing the PEP for it, you must currently implement it with a Mixin (&c) if you like it:It's a very common case for an instance's comparisons with other instances to boil down to comparing a tuple for each with a few fields -- and then, hashing should be implemented on exactly the same basis. The  special method addresses that need directly.To simplify this case there's a class decorator in Python 2.7+/3.2+, , that can be used to implement what Alex suggests. Example from the docs:This is covered by Also,  goes away in python 3.0.  ( Note that it is not present on  but it IS on  )I tried out the comparable mixin answer above.  I ran into trouble with \"None\".  Here is a modified version that handles equality comparisons with \"None\".  (I saw no reason to bother with inequality comparisons with None as lacking semantics):Inspired by Alex Martelli's  &  answers, I came up with the following mixin.\nIt allows you to implement a single  method, which uses key-based comparisons\nsimilar to , but allows your class to pick the most efficient comparison key based on the type of . (Note that this mixin doesn't help much for objects which can be tested for equality but not order). 
Python

I would like to limit the X and Y axis in matplotlib but for a speific subplot. As I can see\nsubplot figure itself doesn't have any axis property. I want for example to change only the limits for the second plot!You should learn a bit of the OO interface to matplotlib, not just the state machine interface.  Almost all of the  function are thin wrappers that basically do . () return an  () object.  Once you have a referance to the axes object you can plot directly to it, change it's limits, etc.and so on for as many axes as you want.or better, wrap it all up in a loop:
Python

For example, I have a string like this(return value of ):Whatever I did to it, it is always printed with the annoying  before the string:Does anyone have any ideas about how to use it as a normal string or convert it into a normal string? Decode it.To get bytes from string, encode it.If the answer from  didn't work you could also try:
Python

I have found that both of the following work:Should all Python classes extend object? Are there any potential problems with not extending object?In Python 2, not inheriting from  will create an old-style class, which, amongst other effects, causes  to give different results:vs.Also the rules for multiple inheritance are  in ways that I won't even try to summarize here. All good documentation that I've seen about MI describes new-style classes.Finally, old-style classes have disappeared in Python 3, and inheritance from  has become implicit. So, always prefer new style classes unless you need backward compat with old software.In Python 3, classes extend  implicitly, whether you say so yourself or not.In Python 2, there's  classes. To signal a class is new-style, you have to inherit explicitly from . If not, the old-style implementation is used.You generally want a new-style class. Inherit from  explicitly.In python 3 you can create a class in three different ways & internally they are all equal (see examples). It doesn't matter how you create a class, all classes in python 3 inherits from special class called  . The  class   is fundamental class in python and provides lot of functionality like double-underscore methods, descriptors, super() method, property() method etc. Example 1.Example 2.Example 3. Yes, all Python classes should extend (or rather subclass, this is Python here) object. While normally no serious problems will occur, in some cases (as with multiple inheritance trees) this will be important. This also ensures better compatibility with Python 3.in python3 there isn't a differance, but in python2 not extending  gives you an old-style classes; you'd like to use a new-style class over an old-style class.
Python

I get this pep8 warning whenever I use lambda expressions. Are lambda expressions not recommended? If not why?The recommendation in  you are running into is:Assigning lambdas to names basically just duplicates the functionality of  - and in general, it's best to do something a single way to avoid confusion and increase clarity.The legitimate use case for lambda is where you want to use a function without assigning it, e.g:Here is the story, I had a simple lambda function which I was using twice. This is just for the representation, I have faced couple of different versions of this.Now, to keep things DRY, I start to reuse this common lambda. At this point my code quality checker complains about lambda being a named function so I convert it into a function. Now the checker complains that a function has to be bounded by one blank line before and after. Here we have now 6 lines of code instead of original 2 lines with no increase in readability and no increase in being pythonic. At this point the code checker complains about the function not having docstrings. In my opinion this rule better be avoided and broken when it makes sense, use your judgement. Lattyware is absolutely right: Basically  wants you to avoid things likeand instead useHowever, as addressed in a recent  (Aug 2014), statements such as the following are now compliant:Since my PEP-8 checker doesn't implement this correctly yet, I turned off E731 for the time being.I also encountered a situation in which it was even impossible to use a def(ined) function.In this case, I really wanted to make a mapping which belonged to the class. Some objects in the mapping needed the same function. It would be illogical to put the a named function outside of the class. \nI have not found a way to refer to a method (staticmethod, classmethod or normal) from inside the class body. SomeClass does not exist yet when the code is run. So referring to it from the class isn't possible either. 
Python

From my understanding : :  : Now, coming back to python, i am bit confused about this. Every where you can learn that python is an interpreted language but it's not interpreted to the machine code, instead to some intermediate code(like byte-code or IL). So which program then executes the IM code. Please help me understand how is a python script handled and run.  First off, interpreted/compiled is not a property of the language but a property of the implementation. For most languages, most if not all implementations fall in one category, so one might save a few words saying the language is interpreted/compiled too, but it's still an important distinction, both because it aids understanding and because there are quite a few languages with usable implementations of both kinds (mostly in the realm of functional languages, see Haskell and ML). In addition, there are C interpreters and projects that attempt to compile a subset of Python to C or C++ code (and subsequently to machine code).Second, compilation is not restricted to ahead-of-time compilation to native machine code. A compiler is, more generally, a program that converts a program in one programming language into a program in another programming language (arguably, you can even have a compiler with the same input and output language if significant transformations are applied). And JIT compilers compile to native machine code , which can give speed very close to or even better than ahead of time compilation (depending on the benchmark and the quality of the implementations compared).But to stop nitpicking and answer the question you meant to ask: Practically (read: using a somewhat popular and mature implementation), Python is . Not compiled to machine code ahead of time (i.e. \"compiled\" by the restricted and wrong, but alas common definition), \"only\" compiled to , but it's still compilation with at least some of the benefits. For example, the statement  is compiled to a byte stream which, when \"disassembled\", looks somewhat like . This is a simplification, it's actually less readable and a bit more low-level -  you can experiment with the standard library  and see what the real deal looks like. Interpreting this is faster than interpreting from a higher-level representation.That bytecode is either interpreted (note that there's a difference, both in theory and in practical performance, between interpreting directly and first compiling to some intermediate representation and interpret that), as with the reference implementation (CPython), or both interpreted and compiled to optimized machine code at runtime, as with .The CPU can only understand machine code indeed. For interpreted program, the ultimate goal of an interpreter is to \"interpret\" the program code into machine code. However, usually a modern interpreted language does not interpret human code directly because it is too inefficient.The Python interpreter first read the human code and optimize it to some immediate code before interpreting it into machine code. That's why you always need another program to run a Python script unlike in C++ you can run the executable directly. For example c:\\Python27\\python.exe or /usr/bin/python.The answer depends on what implementation of python is being used. If you are using lets say  (The Standard implementation of python) or  (Targeted for integration with java programming language)it is first translated into , and depending on the implementation of python you are using  this .  (Python Virtual Machine) for CPython and  (Java Virtual Machine) for Jython.But lets say you are using  which is another standard CPython implementation. It would use a . Almost, we can say Python is interpreted language. But we are using some part of one time compilation process in python to convert complete source code into byte-code like java language.According to python.org it is an interpreter....... ...
Python

In shells like the interactive python shell, you can usually use the arrow keys to move around in the current line or get previous commands (with arrow-up) etc.But after I ssh into another machine and start  there, I get sessions like:where the last character comes from arrow-up. Or, using arrow-left:How can I fix this?In the regular bash, arrow keys work fine. The weird behavior is just in the interactive python (or perl etc.) shell.Looks like readline is not enabled. Check if  variable is defined, for me it points to  and that file is executed by the python process before going interactive, which setups readline/history handling.Thanks to @chown here is the docs on this: I've solved this issue by installing  package:On OS X, Xcode updates sometimes break . Solution:If the problem still persists, try to remove  using  and install it using :On OS X, I have different problem.When I using system python shell, the keys is no problem, but problem in virtualenv. I'd try to reinstall/upgrade virtualenv/readline and nothing fixed.While I try to  in problem python shell, get this error message:Cause there is  but not , so I make a symbol link:Problem has been solved!Here are the steps which worked for me in ubuntu 12.04 for python 3.3.1) open teminal and write 2) download the source file of python 3.3.2 from 3) extract it and navigate to the Python-3.3.2/ directory in a shell4) execute the following command:On CentOS, I fix this by and then recompile python 3.4.On OpenSUSE, I fix this byfollowing Valerio Crini's answer.Perhaps \"pip3 install readline\" is a general solution. Haven't tried on my CentOS.I fixed this by doing the following:After that I managed to run  successfully which solved the escape characters in my python shell.FYI, I'm using RedHatHave you tried using a different SSH client? Some SSH clients have special, built-in keymappings for different remote processes. I ran into this one a lot with emacs.What client are you using? I'd recommend trying Putty and SecureCRT to compare their behavior.Did you call ssh with the  parameter to tell ssh to allocate a virtual terminal for you?From the man page:Additionally you may also have to set the  environment variable on the server correctly as suggested in another post.How's your env variable $TERM set [a] when things work fine and [b] when they don't?  Env settings are often the key to such problems.Try getting a key code library running on the server. If that does not work try to download a library with read-key ability.I was trying build Python 2.7 on Ubuntu 14.0. You will need libreadline-dev. However, if you get it from apt-get, the current version is 6.3, which is incompatible with Python 2.7 (not sure about Python 3). For example, the data type \"Function\" and \"CPPFunction\", which were defined in previous versions of readline has been removed in 6.3, as reported here:That is to say you need to get the source code of an earlier version of readline. I installed libreadline 5.2 from apt-get for the library, and get the source code of 5.2 for the header files. Put them in /usr/include. Finally the issue has been resolved. If you use Anaconda Python, you can fix this by running:Worked for me!On OS X, using python 3.5 and virtualenvIn the interpreter do: Now arrow keys should work properly. Additional information...Note that as of Oct 1, 2015 - readline has been  (source )Use  instead (see: )If I install readline instead of gnureadline using python 3.5, I receive errors after attempt to import in the interpreter: 
Python

What I want is this behavior:of course, what really happens when I print is:clearly they are sharing the data in class . how do I get separate instances to achieve the behavior I desire?You want this:Declaring the variables inside the class declaration makes them \"class\" members and not instance members. Declaring them inside the  method makes sure that a new instance of the members is created alongside every new instance of the object, which is the behavior you're looking for.You declared \"list\" as a \"class level property\" and not \"instance level property\".  In order to have properties scoped at the instance level, you need to initialize them through referencing with the \"self\" parameter in the  method (or elsewhere depending on the situation).You don't strictly have to initialize the instance properties in the  method but it makes for easier understanding.The accepted answer works but a little more explanation does not hurt. Class attributes do not become instance attributes when an instance is created. They become instance attributes when a value is assigned to them.In the original code no value is assigned to  attribute after instantiation; so it remains a class attribute. Defining list inside  works because  is called after instantiation. Alternatively, this code would also produce the desired output:However, the confusing scenario in the question will never happen to immutable objects such as numbers and strings, because their value cannot be changed without assignment. For example a code similar to the original with string attribute type works without any problem:So to summarize: . This is a good thing because this way you can have static attributes if you never assign a value to an attribute after instantiation.Yes you must declare in the \"constructor\" if you want that the list becomes an object property and not a class property.So nearly every response here seems to miss a particular point.  Class variables  become instance variables as demonstrated by the code below.  By utilizing a metaclass to intercept variable assignment at the class level, we can see that when a.myattr is reassigned, the field assignment magic method on the class is not called.  This is because the assignment .  This behavior has  to do with the class variable as demonstrated by the second class which has no class variables and yet still allows field assignment. Class variables have NOTHING to do with instance variables. They just happen to be in the scope for lookups on instances. Class variables are in fact  on the class object itself.  You can also have  if you want as well because metaclasses themselves are objects too.  Everything is an object whether it is used to create other objects or not, so do not get bound up in the semantics of other languages usage of the word class.  In python, a class is really just an object that is used to determine how to create other objects and what their behaviors will be.  Metaclasses are classes that create classes, just to further illustrate this point. Although the accepted anwer is spot on, I would like to add a bit description.Let's do a small exercise first of all define a class as follows:So what do we have here?Pretty straight forward so far yeah? Now let's start playing around with this class. Let's initialize  this class first:Now do the following:Well,  worked as expected but how the hell did  work? Well it worked because temp is a class attribute. Everything in python is an object. Here A is also an object of class . Thus the attribute temp is an attribute held by the A class and if you change the value of temp through A (and not through an instance of a), the changed value is going to be reflected in all the instance of A class.\nLet's go ahead and do that:Interesting isn't it? And Any Python object is automatically given a  attribute, which contains its list of attributes. Let's investigate what this dictionary contains for our example objects:So how come that we get a defined value of  if it is not even listed for the instance a. Well that's the magic of  method. In Python the dotted syntax automatically invokes this method so when we write , Python executes a.('temp'). That method performs the attribute lookup action, i.e. finds the value of the attribute by looking in different places.The standard implementation of  searches first the internal dictionary () of an object, then the type of the object itself. In this case  executes first  and then Okay now let's use our  method:Well now that we have used self,  gives us a different value from . I think the answers provided are misleading. A property defined inside a class becomes an instance property when the object is instantiated, . So copies of  are made, and  and  are different copies. The reason they seem to be the same is that they are both aliases to the same list. But that is a consequence of the way lists work, not of the way classes work. If you were to do the same thing with numbers instead of lists (or just using += instead of append, which would create a new list) you would see that changing  doesn't affect changing .Defining  inside  works, because the function is called twice, once for each time the object is instantiated, and so, two different lists are created.
Python

While optimising my code I realised the following:and also:I assume it has to do with the way python is implemented in C, but I wonder if anybody would care to explain why is so?The (somewhat unexpected) reason for your results is that Python seems to fold constant expressions involving floating-point multiplication and exponentiation, but not division.  is a different beast altogether since there's no bytecode for it and it involves a function call.On Python 2.6.5, the following code:compiles to the following bytecodes:As you can see, multiplication and exponentiation take no time at all since they're done when the code is compiled. Division takes longer since it happens at runtime. Square root is not only the most computationally expensive operation of the four, it also incurs various  overheads that the others do not (attribute lookup, function call etc).If you eliminate the effect of constant folding, there's little to separate multiplication and division: is actually a little bit faster than , presumably because it's a special case of the latter and can therefore be done more efficiently, in spite of the overheads: Constant expression folding is done by Python's peephole optimizer. The source code () contains the following comment that explains why constant division isn't folded:The  flag enables \"true division\" defined in .
Python

I'm having trouble understanding . From what I understand,  returns the absolute path from which the module was loaded. I'm having problem producing this: I have a  with one statement , running from   returns . running from  returns . Any reasons why?From the  linked by @kindall in a comment to the question:For the rest of this, consider  not to include .So, if you aren't inside the part of  that contains the module, you'll get an . If you are inside the part of  that contains the module, you'll get a .If you load a module in the current directory, and the current directory  in , you'll get an absolute path.If you load a module in the current directory, and the current directory  in , you'll get a relative path. is always absolute . Not sure if it resolves symlinks though.: Except for script that has been executed directly using a relative path. Like this:Late simple example:Under Python-2.*, the second call incorrectly determines the  based on the current directory:As noted by @techtonik, in Python 3.4+, this will work fine since  returns an absolute path.With the help of the of Guido mail provided by @kindall, we can understand the standard import process as trying to find the module in each member of , and file as the result of this lookup (more details in .). So if the module is located in an absolute path in  the result is absolute, but if it is located in a relative path in  the result is relative.Now the  startup file takes care of delivering only absolute path in , except the initial , so if you don't change it by other means than setting the PYTHONPATH (whose path are also made absolute, before prefixing ), you will get always an absolute path, but when the module is accessed through the current directory.Now if you trick sys.path in a funny way you can get anything.As example if you have a sample module  in  with the code:If you go in /tmp you get:When in  in , if you add  your  you get:Even if you add , it will be normalized and the result is the same.But if instead of using  you use directly some funny path\nyou get a result as funny as the cause.Guido explains in the above cited thread, why python do not try to transform all entries in absolute paths:So your path is used .
Python

What's a correct and good way to implement ?I am talking about the function that returns a hashcode that is then used to insert objects into hashtables aka dictionaries.As  returns an integer and is used for \"binning\" objects into hashtables I assume that the values of the returned integer should be uniformly distributed for common data (to minimize collisions).\nWhat's a good practice to get such values? Are collisions a problem?\nIn my case I have a small class which acts as a container class holding some ints, some floats and a string.An easy, correct way to implement  is to use a key tuple. It won't be as fast as a specialized hash, but if you need that then you should probably implement the type in C.Here's an example of using a key for hash and equality:Also, the  has more information, that may be valuable in some particular circumstances.Paul Larson of Microsoft Research studied a wide variety of hash functions. He told me that worked surprisingly well for a wide variety of strings. I've found that similar polynomial techniques work well for computing a hash of disparate subfields.John Millikin proposed a solution similar to this:The problem with this solution is that the . In other words, the hash collides with that of the tuple of its key members. Maybe this does not matter very often in practice?The  suggests to combine the hashes of the sub-components using something like XOR, which gives us this:Bonus: more robust  thrown in there for good measure.Update: as Blckknght points out, changing the order of a, b, and c could cause problems. I added an additional  to capture the order of the values being hashed. This final  can be removed if the values being combined cannot be rearranged (for example, if they have different types and therefore the value of  will never be assigned to  or , etc.).I can try to answer the second part of your question.The collisions will probably result not from the hash code itself, but from mapping the hash code to an index in a collection. So for example your hash function could return random values from 1 to 10000, but if your hash table only has 32 entries you'll get collisions on insertion.In addition, I would think that collisions would be resolved by the collection internally, and there are many methods to resolve collisions. The simplest (and worst) is, given an entry to insert at index i, add 1 to i until you find an empty spot and insert there. Retrieval then works the same way. This results in inefficient retrievals for some entries, as you could have an entry that requires traversing the entire collection to find!Other collision resolution methods reduce the retrieval time by moving entries in the hash table when an item is inserted to spread things out. This increases the insertion time but assumes you read more than you insert. There are also methods that try and branch different colliding entries out so that entries to cluster in one particular spot. Also, if you need to resize the collection you will need to rehash everything or use a dynamic hashing method. In short, depending on what you're using the hash code for you may have to implement your own collision resolution method. If you're not storing them in a collection, you can probably get away with a hash function that just generates hash codes in a very large range. If so, you can make sure your container is bigger than it needs to be (the bigger the better of course) depending on your memory concerns. Here are some links if you're interested more: Wikipedia also has a  of various collision resolution methods: Also, \"\" by Tharp covers alot of collision resolution methods extensively. IMO it's a great reference for hashing algorithms. Depends on the size of the hash value you return. It's simple logic that if you need to return a 32bit int based on the hash of four 32bit ints, you're gonna get collisions.I would favor bit operations. Like, the following C pseudo code:Such a system could work for floats too, if you simply took them as their bit value rather than actually representing a floating-point value, maybe better.For strings, I've got little/no idea.
Python

For example I can point the  to  with my template filename in the context but I think need to send more context details.I need to  know exactly what context to add for each of the password reset and change views.If you take a look at the sources for  you'll see that it uses . The upshot is, you can use Context Processors to modify the context which may allow you to inject the information that you need.The b-list has a good .Edit (I seem to have been confused about what the actual question was):You'll notice that  takes a named parameter called :Check  for more information.... thus, with a urls.py like: will be called for URLs matching  with the keyword argument .Otherwise, you don't need to provide any context as the  view takes care of itself. If you want to see what context you have available, you can trigger a  error and look through the stack trace find the frame with a local variable named . If you want to modify the context then what I said above about context processors is probably the way to go.In summary: what do you need to do to use your own template? Provide a  keyword argument to the view when it is called. You can supply keyword arguments to views by including a dictionary as the third member of a URL pattern tuple.Strongly recommend this article.I just plugged it in and it workedYou just need to wrap the existing functions and pass in the template you want. For example:To see this just have a look at the function declartion of the built in views:You can do the following:Explanation:When the templates are loaded, they are searched in your INSTALLED_APPS variable in settings.py .\nThe order is dictated by the definition's rank in INSTALLED_APPS, so since your app come before 'django.contrib.auth' your template were loaded (reference: ).Motivation of approach:The  says that there only one context variable, .If you're having trouble with login (which is common), the  says there are three context variables:I was using this two lines in the url and the template from the admin what i was changing to my needAnother, perhaps simpler, solution is to add your override template directory to the DIRS entry of the TEMPLATES setting in settings.py.  (I think this setting is new in Django 1.8.  It may have been called TEMPLATE_DIRS in previous Django versions.)Like so:Then put your override template files under .  So the overridden password reset template would be 
Python

I've recently come across a problem which requires at least a basic degree of image processing, can I do this in Python, and if so, with what?The best-known library is .  However if you are simply doing basic manipulation, you are probably better off with the Python bindings for , which will be a good deal more efficient than writing the transforms in Python.Depending on what you mean by \"image processing\", a better choice might be in the numpy based libraries: , , or . All of these work based on numpy arrays, so you can mix and match functions from one library and another.I started the website  which has more information on these.You also have an approach to image processing based on \"standard\" scientific modules:  has a whole package dedicated to image processing: .  Scipy is in effect the standard general numerical calculations package; it is based on the de facto standard array-manipulation module : images can also be manipulated as array of numbers.  As for image display,  (also part of the \"science trilogy\") makes displaying images .SciPy is still actively maintained, so it's a good investment for the future.  Furthermore, SciPy currently runs with Python 3 too, while the Python Imaging Library (PIL) does not.To complete the list: opencv\nThere's also , which might be more suitable depending on your needs.There is actually a wonderful .  It gives you the ability to alter existing images, including anti-aliasing capabilities, and create new images with text and such.  You can also find a  in the PIL handbook provided on the aforementioned site.If you are creating a custom image processing effect, you may find PythonPixels useful.\n\nIt is intended for writing and experimenting with image processing.VIPS should be fast and uses multiple CPUs:\n
Python

I can't seem to figure out how to setup a \"default\" logger for my Django installation. I would like to use Django 1.3's new  setting in .I've looked at the , but it looks to me like they only setup handlers which will do logging for particular loggers. In the case of their example they setup handler for the loggers named 'django','django.request', and 'myproject.custom'.All I want to do is setup a default  which will handle all loggers by default. i.e., if I make a new module somewhere in my project and it is denoted by something like: , I should be able to do this and have all logging goto the rotating file logs.Figured it out...You set the 'catch all' logger by referencing it with the empty string: .As an example, in the following setup I have the all log events getting saved to , with the exception of  log events which will be saved to . Because  is set to  for my  logger, the log event will never reach the the 'catch all' logger.As you said in , Chris, one option to define a default logger is to use the empty string as its key.However, I think the intended way is to define a special logger under the  key of the logging configuration dictionary. I found this in the :Here's the configuration from your answer changed to use the  key:To be fair, I can't see any difference in behaviour between the two configurations. It appears that defining a logger with an empty string key will modify the root logger, because  will return the root logger.The only reason I prefer  over  is that it is explicit about modifying the root logger. In case you were curious,  overrides  if you define both, just because the root entry is processed last.after add:we may change format to: or 
Python

Is there syntax that allows you to expand a list into the arguments of a function call?Example:It exists, but it's hard to search for. I think most people call it the \"\" operator.It's in the documentation as \"\".You'd use it like this: . There's also one for dictionaries:You should use the * operator, like  Read the Python doc .Also, do read this: Try the following:This can be found in the Python docs as .That can be done with:
Python

I'm trying to create a directory if the path doesn't exist, but the ! (not) operator doesn't work. I'm not sure how to negate in Python... What's the correct way to do this?The negation operator in Python is . Therefore just replace your  with .For your example, do this:For your specific example (as Neil said in the comments), you don't have to use the  module, you can simply use  to get the result you need, with added exception handling goodness.Example:Python prefers English keywords to punctuation. Use , i.e. . The same thing goes for  and  which are  and  in Python.try instead:Combining the input from everyone else (use not, no parens, use ) you'd get...
Python

What's the easiest way to play a sound file (.wav) in Python? By easiest I mean both most platform independent and requiring the least dependencies. pygame is certainly an option, but it seems overkill for just sound. can play wav, au and mp3 files.  For Windows, you can use winsound. It's built inYou should be able to use ossaudiodev for linux:(Credit for ossaudiodev: Bill Dandreta )Definitely use  for this. It's kind of a large package, but it is pure python with no extension modules. That will definitely be the easiest for deployment. It's also got great format and codec support.This seems ridiculous and far fetched but you could always use Windows (or whatever OS you prefer) to manage the sound for you!Simple, no extensions, somewhat slow and junky, but working.After the play() command add a delay of say 10 secs or so, it'll workThis also plays .mp3 files.pyMedia's sound example does . This should be all you need.wxPython has support for playing wav files on Windows and Unix - I am not sure if this includes Macs.  However it only support wav files as far as I can tell - it does not support other common formats such as mp3 or ogg.I like pygame, and the command below should work:but it doesn't on either of my computers, and there is limited help on the subject out there. edit: I figured out why the pygame sound isn't working for me, it's not loading most sounds correctly, the 'length' attribute is ~0.0002 when I load them. maybe loading them using something other than mygame will get it morking more generally.with pyglet I'm getting a resource not found error Using the above example, wigh both relative and full paths to the files.using  instead of  lets me load the files.but  only plays the first fraction of a second of the file, unless I run  which blocks everything else...I just released a simple python wrapper around sox that will play a sound with Python.  It's very easy to install as you need Python 2.6 or greater, sox (easy to get binaries for most architectures) and the wrapper (  ).  If you don't have sox, go here: You would play audio with it by:Keep in mind, the only parts actually involved in playing audio are just these:For Linux user, if low level pcm data manipulation is needed, try  module. There is a playwav.py example inside the package too. 
Python

I am attempting to filter users by a custom field in each users profile called profile. This field is called level and is an integer between 0-3.If I filter using equals, I get a list of users with the chosen level as expected:When I try to filter using less than:I get the error:Is there away to filter by < or >, or am I barking up the wrong tree.Less than or equal:Greater than or equal:Likewise,  for less than and  for greater than. You can find them all .
Python

I'm using the  library and I got this weird error and I don't know what is mean.Anybody has an idea?You need to include the protocol scheme:Without the  part,  has no idea how to connect to the remote server.One more reason, maybe your url include some hiden characters, such as '\\n'.If you define your url like below, this exception will raise:because there are '\\n' hide in the string. The url in fact become:
Python

I've been trying to find a more pythonic way of generating random string in python that can scale as well. Typically, I see something similar toIt sucks if you want to generate long string.I've been thinking about random.getrandombits for a while, and figuring out how to convert that to an array of bits, then hex encode that. Using python 2.6 I came across the bitarray object, which isn't documented.  Somehow I got it to work, and it seems really fast.It generates a 50mil random string on my notebook in just about 3 seconds.heikogerlach pointed out that it was an odd number of characters causing the issue. New code added to make sure it always sent fromhex an even number of hex digits.Still curious if there's a better way of doing this that's just as fast.and if you need url safe string :(note random_string length is greatest than string_length in that case)Sometimes a uuid is short enough and if you don't like the dashes you can always.replace('-', '') themIf you want it a specific length without dashesTaken from the  bug report at Python.org:Also, see the issues  and It seems the  method expects an even number of hex digits. Your string is 75 characters long.\nBe aware that   the last element! Just use .Regarding the last example, the following fix to make sure the line is even length, whatever the junk_len value:
Python

I am in the process of migrating an application from django 1.2 To 1.4.I have a daily task object which contains a time of day that task should be completed:In order to check if a task is still required to be completed today, I have the following code:This worked fine under 1.2, But under 1.4 I get the error:due to the lineand both comparison clauses throw this error.I have tried making timeDue timezone aware by adding pytz.UTC as an argument, but this still raises the same error.I've read some of the docs on timezones but am confused as to whether I just need to make timeDue timezone aware, or whether I need to make a fundamental change to my db and existing data.Check  for detail info.Normally, use  to make an offset-aware current datetimeAnd  to make an offset-aware datetimeYou could then compare both offset-aware datetimes w/o trouble. Furthermore, you could convert offset-awared datetime to offset-naive datetime by stripping off timezone info, then it could be compared w/ normal , under utc. is  'by default' (actually it's  by default, but the  file generated by  set it to ), then if your DB supports timezone-aware times, values of time-related model fields would be timezone-aware. you could disable it by setting (or simply remove ) in settings. 
Python

I am new to Python. I need to write some data from my program to a spreadsheet. I've searched online and there seems to be many packages available (xlwt, XlsXcessive, openpyxl). Others suggest to write to a csv file (never used csv & don't really understand what it is).The program is very simple. I have two lists (float) and three variables (strings). I don't know the lengths of the two lists and they probably won't be the same length.I want the layout to be as in the picture below:The pink column will have the values of the first list and the green column will have the values of the second list.So what's the best way to do this? Thanks.P.S. I am running Windows 7 but I won't necessarily have Office installed on the computers running this program.I wrote this using all your suggestions. It gets the job done but it can be slightly improved. How do I format the cells created in the for loop (list1 values) as scientific or number? I do not want to truncate the values. The actual values used in the program would have around 10 digits after the decimal.for more explanation:\n    Use  from . Pandas allows you to represent your data in functionally rich datastructures and will let you  excel files as well.You will first have to convert your data into a DataFrame and then save it into an excel file like so:and the excel file that comes out looks like this:Note that both lists need to be of equal length else pandas will complain. To solve this, replace all missing values with .CSV stands for comma separated values. CSV is like a text file and can be created simply by adding the for example write this code:you can open this file with excel.Try taking a look at the following libraries too: - for getting data into and out of a spreadsheet from Python, as well as manipulating workbooks and charts - an Excel add-in for writing user-defined functions (UDFs) and macros in Python instead of VBAI surveyed a few Excel modules for Python, and found  to be the best.The free book Automate the Boring Stuff with Python  with more details or you can check the  site. You won't need Office or Excel installed in order to use openpyxl.Your program would look something like this:The easiest way to import the exact numbers is to add a decimal after the numbers in your l1 and l2. Python interprets this decimal point as instructions from you to include the exact number. If you need to restrict it to some decimal place, you should be able to create a print command that limits the output, something simple like:print variable_example[:13]Would restrict it to the tenth decimal place, assuming your data has two integers left of the decimal. 
Python

Half of my Flask routes requires a variable say,  or . How do I create links to those locations? takes one argument for the function to route to but I can't add arguments?It takes keyword arguments for the variables:Refer to Other sample snippets of usage for linking js or css to your template are below. in Flask is used for creating a URL to prevent the overhead of having to change URLs throughout an application (including in templates). Without , if there is a change in the root URL of your app then you have to change it in every page where the link is present.Syntax: It can be used as:Now if you have a link the index page:you can use this:You can do a lot o stuff with it, for example:For the above we can use:Like this you can simply pass the parameters!
Python

When you have a model field with a choices option you tend to have some magic values associated with human readable names. Is there in Django a convenient way to set these fields by the human readable name instead of the value?Consider this model:At some point we have a Thing instance and we want to set its priority. Obviously you could do,But that forces you to memorize the Value-Name mapping of PRIORITIES. This doesn't work:Currently I have this silly workaround:but that's clunky. Given how common this scenario could be I was wondering if anyone had a better solution. Is there some field method for setting fields by choice name which I totally overlooked?Do as . Then you can use a word that represents the proper integer.Like so:Then they are still integers in the DB.Usage would be I'd probably set up the reverse-lookup dict once and for all, but if I hadn't I'd just use:which seems simpler than building the dict on the fly just to toss it away again;-).Here's a field type I wrote a few minutes ago that I think does what you want. Its constructor requires an argument 'choices', which may be either a tuple of 2-tuples in the same format as the choices option to IntegerField, or instead a simple list of names (ie ChoiceField(('Low', 'Normal', 'High'), default='Low') ). The class takes care of the mapping from string to int for you, you never see the int.Use it like this:I appreciate the constant defining way but I believe  type is far best for this task. They can represent integer and a string for an item in the same time, while keeping your code more readable.Enums were introduced to Python in version 3.4. If you are using any lower (such as v2.x) you can still have it by installing the : .This is pretty much all. You can inherit the  to create your own definitions and use them in a model definition like:Querying is icing on the cake as you may guess:Representing them in string is also made easy:Simply replace your numbers with the human readable values you would like. As such:This makes it human readable, however, you'd have to define your own ordering.
Python

Given an arbitrary python object, what's the best way to determine whether it is a number? Here  is defined as .For example, say you are writing a vector class. If given another vector, you want to find the dot product. If given a scalar, you want to scale the whole vector.Checking if something is , , ,  is annoying and doesn't cover user-defined objects that might act like numbers. But, checking for , for example, isn't good enough because the vector class I just described would define , but it wouldn't be the kind of number I want.Use  from the  module to test  (available since 2.6).This is, of course, contrary to duck typing.  If you are more concerned about how an object  rather than what it , perform your operations as if you have a number and use exceptions to tell you otherwise.You want to check if some objectIf you're using Python 2.5 or older, the only real way is to check some of those \"certain circumstances\" and see.In 2.6 or better, you can use  with  -- an abstract base class (ABC) that exists exactly for this purpose (lots more ABCs exist in the  module for various forms of collections/containers, again starting with 2.6; and, also only in those releases, you can easily add your own abstract base classes if you need to).Bach to 2.5 and earlier,\n\"can be added to  and is not iterable\" could be a good definition in some cases.  But,\nyou really need to ask yourself, what it is that you're asking that what you want to consider \"a number\" must definitely be able to , and what it must absolutely be  to do -- and check.This may also be needed in 2.6 or later, perhaps for the purpose of making your own registrations to add types you care about that haven't already be registered onto  -- if you want to  some types that claim they're numbers but you just can't handle, that takes even more care, as ABCs have no  method [[for example you could make your own ABC  and register there all such weird-for-you types, then first check for  thereof to bail out before you proceed to checking for  of the normal  to continue successfully.BTW, if and when you need to check if  can or cannot do something, you generally have to try something like:The presence of  per se tells you nothing useful, since e.g all sequences have it for the purpose of concatenation with other sequences.  This check is equivalent to the definition \"a number is something such that a sequence of such things is a valid single argument to the builtin function \", for example.  Totally weird types (e.g. ones that raise the \"wrong\" exception when summed to 0, such as, say, a  or  &c) will propagate exception, but that's OK, let the user know ASAP that such crazy types are just not acceptable in good company;-); but, a \"vector\" that's summable to a scalar (Python's standard library doesn't have one, but of course they're popular as third party extensions) would also give the wrong result here, so (e.g.) this check should come  the \"not allowed to be iterable\" one (e.g., check that  raises , or for the presence of special method  -- if you're in 2.5 or earlier and thus need your own checks).A brief glimpse at such complications may be sufficient to motivate you to rely instead on abstract base classes whenever feasible...;-).This is a good example where exceptions really shine. Just do what you would do with the numeric types and catch the  from everything else.But obviously, this only checks if a operation , not whether it ! The only real solution for that is to never mix types and always know exactly what typeclass your values belong to.To rephrase your question, you are trying to determine whether something is a collection or a single value. Trying to compare whether something is a vector or a number is comparing apples to oranges - I can have a vector of strings or numbers, and I can have a single string or single number. , not what type you actually have.my solution for this problem is to check whether the input is a single value or a collection by checking the presence of . For example:Or, for the duck-typing approach, you can try iterating on  first:Ultimately, it is easier to test whether something is vector-like than to test whether something is scalar-like. If you have values of different type (i.e. string, numeric, etc.) coming through, then the logic of your program may need some work - how did you end up trying to multiply a string by a numeric vector in the first place?Probably it's better to just do it the other way around: You check if it's a vector. If it is, you do a dot product and in all other cases you attempt scalar multiplication.Checking for the vector is easy, since it should of your vector class type (or inherited from it). You could also just try first to do a dot-product, and if that fails (= it wasn't really a vector), then fall back to scalar multiplication.Multiply the object by zero.  Any number times zero is zero.  Any other result means that the object is not a number (including exceptions)Using isNumber thusly will give the following output:Output:There probably are some non-number objects in the world that define  to return zero when multiplied by zero but that is an extreme exception. This solution should cover all  and  code that you generate/encouter.For the hypothetical vector class:Suppose  is a vector, and we are multiplying it by . If it makes sense to multiply each component of  by , we probably meant that, so try that first. If not, maybe we can dot? Otherwise it's a type error. -- the below code doesn't work, because  instead of raising a . I leave it because it was commented-upon.Just to add upon.\nPerhaps we can use a combination of isinstance and isdigit as follows to find whether a value is a number (int, float, etc)if isinstance(num1, int) or isinstance(num1 , float) or num1.isdigit():I had a similar issue, when implementing a sort of vector class. One way to check for a number is to just convert to one, i.e. by usingThis should reject cases where x cannot be converted to a number; but may also reject other kinds of number-like structures that could be valid, for example complex numbers.
Python

I know that fetching a url is as simple as  and I can get at the raw response body and save it to a file, but for large files, is there a way to stream directly to a file? Like if I'm downloading a movie with it or something?Oddly enough, requests doesn't have anything simple for this. You'll have to iterate over the response and write those chunks to a file:I usually just use . It works, but if you need to use a session or some sort of authentication, the above code works as well.
Python

Is there a reference for the memory size of Python data stucture on 32- and 64-bit platforms?If not, this would be nice to have it on SO. The more exhaustive the better! So how many bytes are used by the following Python structures (depending on the  and the content type when relevant)?(For containers that keep only references to other objects, we obviously do not want to count the size of the item themselves, since it might be shared.)Furthermore, is there a way to get the memory used by an object at runtime (recursively or not)?The recommendation from  on this was to use , quoting:You could take this approach:2012-09-30python 2.7 (linux, 32-bit):python 3.3 (linux, 32-bit)2016-08-01OSX, Python 2.7.10 (default, Oct 23 2015, 19:19:21) [GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwinI've been happily using  for such tasks. It's compatible with many versions of Python -- the  module in particular goes back to 2.2!For example, using hughdbrown's example but with  at the start and  at the end, I see (system Python 2.5 on MacOSX 10.5):Clearly there is some approximation here, but I've found it very useful for footprint analysis and tuning.Also you can use  module.And:Try memory profiler.\nThese answers all collect shallow size information. I suspect that visitors to this question will end up here looking to answer the question, \"How big is this complex object in memory?\"There's a great answer here: The punchline:Used like so:If you want to know Python's memory model more deeply, there's a great article here that has a similar \"total size\" snippet of code as part of a longer explanation: When you use the dir([object]) built-in function, you can the  built-in function.
Python

I have used matplotlib to plot lines on a figure. Now I would now like to set the style, specifically the marker, for individual points on the line. How do I do this?Edit:\nto clarify my question, which was answered, I want to be able to set the style for individual markers on a line, not every marker on said line.Specify the keyword args  and/or  in your call to .For example, using a dashed line and blue circle markers: A shortcut call for the same thing:Here is a list of the possible line and marker styles:   with an example of marking an arbitrary subset of points, as requested in the comments:This last example using the  kwarg is possible in since 1.4+, due to the merge of .  If you are stuck on an older version of matplotlib, you can still achieve the result by overlaying a scatterplot on the line plot.  See the  for more details.  For future reference - the  artist returned by  also has a  method which allows you to only set markers on certain points - see 
Python

I'm trying to transfer a function across a network connection (using asyncore). Is there an easy way to serialize a python function (one that, in this case at least, will have no side affects) for transfer like this?I would ideally like to have a pair of functions similar to these:You could serialise the function bytecode and then reconstruct it on the caller.  The  module can be used to serialise code objects, which can then be reassembled into a function.  ie:Then in the remote process (after transferring code_string):A few caveats:Check out , which extends Python's pickle library to support a greater variety of types, including functions:It also supports references to objects in the function's closure: is able to .The most simple way is probably  (see the ) which returns a String with the source code for a function or a method.It all depends on whether you generate the function at runtime or not:If you do -  won't work for dynamically generated functions as it gets object's source from  file, so only functions defined before execution can be retrieved as source.And if your functions are placed in files anyway, why not give receiver access to them and only pass around module and function names.The only solution for dynamically created functions that I can think of is to construct function as a string before transmission, transmit source, and then  it on the receiver side.Edit: the  solution looks also pretty smart, didn't know you can serialize something other thatn built-insThe  package (pip install cloud) can pickle arbitrary code, including dependencies.  See .The basic functions used for this module covers your query, plus you get the best compression over the wire; see the instructive source code:y_serial.py module :: warehouse Python objects with SQLite\"Serialization + persistance :: in a few lines of code, compress and annotate Python objects into SQLite; then later retrieve them chronologically by keywords without any SQL. Most useful \"standard\" module for a database to store schema-less data.\"
Python

For example I have simple DF:Can I select values from 'A' for which corresponding values for 'B' will be greater than 50, and for 'C' - not equal 900, using methods and idioms of Pandas?Sure!  Setup:We can apply column operations and get boolean Series objects:[Update, to switch to new-style ]:And then we can use these to index into the object.  For read access, you can chain indices:but you can get yourself into trouble because of the difference between a view and a copy doing this for write access.  You can use  instead:Note that I accidentally did  and not , or , but I'm too lazy to fix it. Exercise for the reader. :^)
Python

I want to copy already indented Python code / whole functions and classes into IPython. Everytime I try the indentation is screwed up and I get following error message:You can't copy to IPython directly. This are the steps:A clarification on the steps:For example:As of  you don't need any magic command, just paste itMore on this To upgrade  to the latest version  requires . If you  are in  ubuntu, you can  install it by Then  restart ipython and use  to paste  from your  clipboard.One of the useful answers was lost in the comments, so wanted to restate it along with adding a reference for another useful IPython magic function.First to restate what @EOL said, one way to solve OP's problem is to turn off auto-indentation by first running  and doing the paste (not needed if you are using , of course).Now to add more information to what is already there here, one more useful mode in IPython is  which allows you to copy paste example and test snippets from doc strings. This is also useful to execute interactive python session output that you could find in documentation and online forums, without having to first strip out the prompt strings.For ubuntu users who are on Python 3.The  is for Python 2.To make  work on Python 3, install the  package:
Python

Why does this NOT return the  tags and stuff in between? It returns nothing. And I know for a fact it exists because I'm staring right at it from  also does not work. There is no answer to this post - how do I delete it? I found that BeautifulSoup is not parsing correctly, which probably actually means the page I'm trying to parse isn't properly formatted in SGML or whatever. You should post your example document, because the code works fine:Finding s inside s works as well:To find an element by its :I think there is a problem when the 'div' tags are too much nested. I am trying to parse some contacts from a facebook html file, and the Beautifulsoup is not able to find tags \"div\" with class \"fcontent\".This happens with other classes as well. When I search for divs in general, it turns only those that are not so much nested.The html source code can be any page from facebook of the friends list of a friend of you (not the one of your friends). If someone can test it and give some advice I would really appreciate it.This is my code, where I just try to print the number of tags \"div\" with class \"fcontent\":Most probably because of the default beautifulsoup parser has problem. Change a different parser, like 'lxml' and try again.In the beautifulsoup source this line allows divs to be nested within divs; so your concern in lukas' comment wouldn't be valid.What I think you need to do is to specify the attrs you want such asHappened to me also while trying to scrape Google.\nI ended up using pyquery.\nInstall:Use:have you tried ?sounds crazy, but if you're scraping stuff from the wild, you can't rule out multiple divs...I used:As my syntax for find/findall; that said, unless there are other optional parameters between the tag and attribute list, this shouldn't be different.Here is a code fragment As you can see I find all  tags and then I find all  tags with class=\"article\" insideBeautiful Soup 4 supports most  with the , therefore you can use an  such as:If you need to specify the element's type, you can add a  before the  selector:The  method will return a collection of elements, which means that it would return the same results as the following  example:If you only want to select a single element, then you could just use the :
Python

I cannot figure out why this is giving me the error, The actual string I am trying to insert is 74 chars long, it's: \"/gifs/epic-fail-photos-there-i-fixed-it-aww-man-the-tire-pressures-low.gif\"I've tried to str(array[cnt]) before inserting it, but the same issue is happening, the database only has one column, which is a TEXT value.I've been at it for hours and I cannot figure out what is going on.You need to pass in a sequence, but you forgot the comma to make your parameters a tuple:Without the comma,  is just a grouped expression, not a tuple, and thus the  string is treated as the input sequence. If that string is 74 characters long, then Python sees that as 74 separate bind values, each one character long.If you find it easier to read, you can also use a list literal:
Python

How can I simply SSH to a remote server from a local Python (3.0) script, supply a login/password, execute a command and print the output to the Python console?I would rather not use any large external library or install anything on the remote server.I haven't tried it, but this  module might help, which in turn uses paramiko. I believe everything is client-side.The interesting command is probably  which executes an arbitrary command on the remote machine. (The module also features  and  methods which allude more to its FTP character).UPDATE:I've re-written the answer after the blog post I originally linked to is not available anymore. Some of the comments that refer to the old version of this answer will now look weird.You can code it yourself using Paramiko, as suggested above. Alternatively, you can look into Fabric, a python application for doing all the things you asked about:I think this fits your needs. It is also not a large library and requires no server installation, although it does have dependencies on paramiko and pycrypt that require installation on the client.The app used to be . It can now be found .There are several good articles on it, though you should be careful because it has changed in the last six months:Later: Fabric no longer requires paramiko to install:This is mostly cosmetic, however: ssh is a fork of paramiko, the maintainer for both libraries is the same (Jeff Forcier, also the author of Fabric), and . (This correction via .)If you want to avoid any extra modules, you can use the subprocess module to runand capture the output. Try something like:To deal with usernames and passwords, you can use subprocess to interact with the ssh process, or you could install a public key on the server to avoid the password prompt.I have written . Libssh2 is a client-side library implementing the SSH2 protocol.Your definition of \"simplest\" is important here - simple code means using a module (though \"large external library\" is an exaggeration).I believe the most up-to-date (actively developed) module is . It comes with demo scripts in the download, and has detailed online API documentation. You could also try , which is contained in . There's a short sample along with the documentation at the first link. Again with respect to simplicity, note that good error-detection is always going to make your code look more complex, but you should be able to reuse a lot of code from the sample scripts then forget about it.Like hughdbrown, I like Fabric. Please notice that while it implement its own declarative scripting (for making deploys and the such) it can also be imported as a Python module and used on your programs without having to write a Fabric script.Fabric has a new maintainer and is in the process of being rewriten; that means that most tutorials you'll (currently) find on the web will not work with the current version. Also, Google still shows the old Fabric page as the first result. For up to date documentation you can check: I found paramiko to be a bit too low-level, and Fabric not especially well-suited to being used as a library, so I put together my own library called  that uses paramiko to implement a slightly nicer interface:You can also choose to print the output of the program as it's running, which is useful if you want to see the output of long-running commands before it exits:This worked for me
Python

I want to use R in Python, as provided by the module Rpy2. I notice that R has very convenient  operations by which you can extract the specific columns or lines. How could I achieve such a function by Python scripts?My idea is to create an R vector and add those wanted elements into this vector so that the final vector is the same as that in R. I created a , but it seems that it has an initial digit 1, so the final result would always start with the digit 1, which is not what I want. So, is there a better way to do this?See also vector helpI pre-allocate a vector withYou can then use [] to insert values into it.You can create an empty vector like soAnd then add elements using c()However as romunov says, it's much better to pre-allocate a vector and then populate it (as this avoids reallocating a new copy of your vector every time you add elements)I've also seenNow  you can concatenate or bind  a vector of any dimension to To create an empty vector use:Please note, I am not making any assumptions about the type of vector you require, e.g. numeric.Once the vector has been created you can add elements to it as follows:For example, to add the numeric value 1:or, to add a string value \"a\"As pointed out by Brani, vector() is a solution, e.g.will return a vector named \"newVector\" with 50 \"0\"'s as initial values. It is also fairly common to just add the new scalar to an existing vector to arrive at an expanded vector, e.g.In rpy2, the way to get the very same operator as \"[\" with R is to use \".rx\".\nSee the documentation about For creating vectors, if you know your way around with Python there should not be any issue.\nSee the documentation about 
Python

I've got list of objects. I want to find one (first or whatever) object in this list that has attribute (or method result - whatever) equal to . What's is the best way to find it?Here's test case:I think using generators and  won't make any difference because it still would be iterating through list.ps.: Equation to  is just an example. Of course we want to get element which meets any condition.This gets the first item from the list that matches the condition, and returns  if no item matches. It's my preferred single-expression form.However,The naive loop-break version, is perfectly Pythonic -- it's concise, clear, and efficient. To make it match the behavior of the one-liner:This will assign  to  if you don't  out of the loop.I just ran into a similar problem and devised a small optimization for the case where no object in the list meets the requirement.(for my use-case this resulted in major performance improvement):Along with the list test_list, I keep an additional set test_value_set which consists of values of the list that I need to filter on. So here the else part of agf's solution becomes very-fast.
Python

I'm trying to understand how the  and  Python built-in functions work. I'm trying to compare the tuples so that if any value is different then it will return  and if they are all the same it will return . How are they working in this case to return [False, False, False]? is a .To my knowledge, this should output since (1,1) are the same, (5,6) are different, and (0,0) are the same.  You can roughly think of  and  as series of logical  and  operators, respectively. will return  when  is Truthy. Read about  will return  only when  are Truthy.  The empty iterable case is explained in the official documentation, like thisSince none of the elements is true, it returns  in this case. Since none of the elements is false, it returns  in this case. Another important thing to know about  and  is, it will short-circuit the execution, the moment they know the result. The advantage is, entire iterable need not be consumed. For example,Here,  is a generator expression which returns  if the current number within 1 and 9 is a multiple of 6.  iterates the  and when it meets , it finds a Truthy value, so it immediately returns , and rest of the  is not iterated. That is what we see when we print , the result of ,  and .This excellent thing is used very cleverly in .With this basic understanding, if we look at your code, you do which makes sure that, atleast one of the values is Truthy but not all of them. That is why it is returning . If you really wanted to check if both the numbers are not the same, and  take iterables and return  if any and all (respectively) of the elements are . If the iterables are empty,  returns , and  returns .I was demonstrating  and  for students in class today. They were mostly confused about the return values for empty iterables. Explaining it this way caused a lot of lightbulbs to turn on.They both look for a condition that allows them to stop evaluating. The first examples I gave required them to evaluate the entire list. checks for elements to be  (so it can return ), then it returns  if none of them were .The way  works is that it checks for elements to be  (so it can return FalseTrue`.I think if you keep in mind the short-cutting behavior, you will intuitively understand how they work without having to reference a Truth Table.The code in question you're asking about comes from my answer given .  It was intended to solve the problem of comparing multiple bit arrays - i.e. collections of  and .   and  are useful when you can rely on the \"truthiness\" of values - i.e. their value in a boolean context.  1 is  and 0 is , a convenience which that answer leveraged.  5 happens to also be , so when you mix that into your possible inputs... well.  Doesn't work.You could instead do something like this:It lacks the aesthetics of the previous answer (I  liked the look of ), but it gets the job done.
Python

I need to download it for Python 2.7, but can't seem to find it... 'pywin32' is its canonical name.There is a a new option as well: get it via pip!  There is a package  with wheels available, so you can just install with: !I've found that UC Irvine has a great collection of python modules, pywin32 (win32api) being one of many listed there.  I'm not sure how they do with keeping up with the latest versions of these modules but it hasn't let me down yet.UC Irvine Python Extension Repository - pywin32 module -  - 3rd .exe down
Python

Can you simply delete the directory from your python installation, or are there any lingering files that you must delete?It varies based on the options that you pass to  and the contents of the  on the system/in the package. I don't believe that any files are modified outside of directories specified in these ways.Notably,  at this time. It's also noteworthy that deleting a package/egg can cause dependency issues -- utilities like  attempt to alleviate such problems.The three things that get installed that you will need to delete are:Now on my linux system these live in:But on a windows system they are more likely to be entirely within the Python distribution directory. I have no idea about OSX except it is more likey to follow the linux pattern.Another time stamp based hack:Yes, it is safe to simply delete anything that distutils installed. That goes for installed folders or .egg files. Naturally anything that depends on that code will no longer work. If you want to make it work again, simply re-install. By the way, if you are using distutils also consider using the multi-version feature. It allows you to have multiple versions of any single package installed. That means you do not need to delete an old version of a package if you simply want to install a newer version.If this is for testing and/or development purposes,  has a  command that updates every time you make a change (so you don't have to uninstall and reinstall every time you make a change).  And you can uninstall the package using this command as well.If you do use this, anything that you declare as a  will be left behind as a lingering file.In ubuntu 12.04, I have found that the only place you need to look by default is underAnd simply remove the associated folder and file, if there is one!I just uninstalled a python package, and even though I'm not  I did so perfectly, I'm reasonably confident.  I started by getting a list of  python-related files, ordered by date, on the assumption that all of the files in my package will have more or less the same timestamp, and no other files will.Luckily, I've got python installed under ; if I had been using the Python that comes with my Linux distro, I'd have had to scour all of , which would have taken a long time.Then I just examined that list, and noted with relief that all the stuff that I wanted to nuke consisted of one directory, , and one file, .So I just deleted those.Here's how I got the date-sorted list of files:(I think that's got to be GNU \"find\", by the way; the flavor you get on OS X doesn't know about \"-printf '%T@'\")I use that  the time.For Windows 7,, then choose the python package to remove.removes all files and but leaves empty directories behind.That is not ideal, it should be enough to avoid package conflicts.And then you can finish the job manually if you want by reading , or be braver and automate empty directory removal as well.A safe helper would be:Tested in Python 2.7.6, Ubuntu 14.04.for Python in Windows:
Python

I would like to create a copy of an object. I want the new object to possess all properties of the old object (values of the fields). But I want to have independent objects. So, if I change values of the fields of the new object, the old object should not be affected by that.Have a look at the  function.  It should do exactly what you need.  Also have a look at  to a related question for a nice explanation.
Python

Module  includes  at its top. However under test conditions I'd like to   in  (mock ) and completely refrain from importing . In fact,  isn't installed in the test environment on purpose.A is the unit under test. I have to import A with all its functionality. B is the module I need to mock. But how can I mock B within A and stop A from importing the real B, if the first thing A does is import B?(The reason B isn't installed is that I use pypy for quick testing and unfortunately B isn't compatible with pypy yet.)How could this be done?You can assign to  before importing  to get what you want:::Note B.py does not exist, but when running  no error is returned and  prints . You still have to create a  where you mock B's actual functions/variables/etc. Or you can just assign a Mock() directly::The builtin  can be mocked with the 'mock' library for more control:Say  looks like: returns  which can be mocked also.I realize I'm a bit late to the party here, but here's a somewhat insane way to automate this with the  library:(here's an example usage)The reason this is so ridiculously complicated is when an import occurs python basically does this (take for example )There are some downsides to this hacked together solution: If something else relies on other stuff in the module path this kind of screws it over.  Also this  works for stuff that is being imported inline such asorIf you do an  you are really calling the builtin method  as:You could overwrite this method by importing the  module and make a wrapper around the method. Or you could play with the  hook from the  module. Catching the exception and Mock your module/class in the -block.Pointer to the relevant docs:I hope this helps. Be  adviced that you step into the more arcane perimeters of python programming and that a) solid understanding what you really want to achieve and b)thorough understanding of the implications is important.Easy, just mock the library in sys.modules before it gets imported:and then, so long as  doesn't rely on specific types of data being returned from B's objects:should just work.This works even if you have submodules, but you'll want to mock each module. Say you have this:To mock, simply do the below before the module that contains the above is imported: (My experience: I had a dependency that works on one platform, Windows, but didn't work on Linux, where we run our daily tests. \nSo I needed to mock the dependency for our tests. Luckily it was a black box, so I didn't need to set up a lot of interaction.)Addendum: Actually, I needed to simulate a side-effect that took some time. So I needed an object's method to sleep for a second. That would work like this:And then the code takes some time to run, just like the real method.You can use patch and MagicMock
Python

Title says it all.I notice that However, there should be some differences, since after all they are two different functions.np.average takes an optional weight parameter.  If it is not supplied they are equivalent.  Take a look at the source code.np.mean:np.average: always computes an arithmetic mean, and has some additional options for input and output (e.g. what datatypes to use, where to place the result). can compute a weighted average if the  parameter is supplied.There is another imporant difference that you must be aware: do not take in account masks, so compute the average over the whole set of data. takes in account masks, so compute the mean only over unmasked values.In your invocation, the two functions are the same. can compute a weighted average though.Doc links:  and 
Python

I have questions about egg files in Python.I have much Python code organized by package and I'm trying to create egg files.\nI'm following , but they are very common.According to that, it seems I need to have a setup.py file.You are reading the wrong documentation. You want this: For #4, the closest thing to starting java with a jar file for your app is a new feature in Python 2.6, .Where myapp.zip is a zip containing a  file which is executed as the script file to be executed. Your package dependencies can also be included in the file:You can also execute an egg, but the incantation is not as nice: This puts the myapp.egg on the Python path and uses the -m argument to run a module. Your myapp.egg will likely look something like:And python will run  (you should check that  in your app for command line use).Egg files are just zip files so you might be able to add  to your egg with a zip tool and make it executable in python 2.6 and run it like  instead of the above incantation where the PYTHONPATH environment variable is set.More information on executable zip files including how to make them directly executable with a  can be found on .I think you should use  for distribution instead of egg now.
Python

I've been trying to wrap my head around how threads work in Python, and it's hard to find good information on how they operate. I may just be missing a link or something, but it seems like the official documentation isn't very thorough on the subject, and I haven't been able to find a good write-up.From what I can tell, only one thread can be running at once, and the active thread switches every 10 instructions or so?Where is there a good explanation, or can you provide one? It would also be very nice to be aware of common problems that you run into while using threads with Python.Yes, because of the Global Interpreter Lock (GIL) there can only run one thread at a time. Here are some links with some insights about this:From the last link an interesting quote:If you want to use multi core,  defines an process based API to do real parallelization. The  also includes some interesting benchmarks.Python's a fairly easy language to thread in, but there are caveats.  The biggest thing you need to know about is the Global Interpreter Lock.  This allows only one thread to access the interpreter.  This means two things:  1)  you rarely ever find yourself using a lock statement in python and 2) if you want to take advantage of multi-processor systems, you have to use separate processes.  EDIT:  I should also point out that you can put some of the code in C/C++ if you want to get around the GIL as well.Thus, you need to re-consider why you want to use threads.  If you want to parallelize your app to take advantage of dual-core architecture, you need to consider breaking your app up into multiple processes.If you want to improve responsiveness, you should CONSIDER using threads.  There are other alternatives though, namely .  There are also some frameworks that you should look into:Below is a basic threading sample. It will spawn 20 threads; each thread will output its thread number. Run it and observe the order in which they print.As you have hinted at Python threads are implemented through time-slicing. This is how they get the \"parallel\" effect. In my example my Foo class extends thread, I then implement the  method, which is where the code that you would like to run in a thread goes. To start the thread you call  on the thread object, which will automatically invoke the  method...Of course, this is just the very basics. You will eventually want to learn about semaphores, mutexes, and locks for thread synchronization and message passing.Use threads in python if the individual workers are doing I/O bound operations. If you are trying to scale across multiple cores on a machine either find a good  framework for python or pick a different language.One easy solution to the GIL is the  module. It can be used as a drop in replacement to the threading module but uses multiple Interpreter processes instead of threads. Because of this there is a little more overhead than plain threading for simple things but it gives you the advantage of real parallelization if you need it.\nIt also easily scales to multiple physical machines.If you need truly large scale parallelization than I would look further but if you just want to scale to all the cores of one computer or a few different ones without all the work that would go into implementing a more comprehensive framework, than this is for you.Try to remember that the GIL is set to poll around every so often in order to do show the appearance of multiple tasks. This setting can be fine tuned, but I offer the suggestion that there should be work that the threads are doing or lots of context switches are going to cause problems.I would go so far as to suggest multiple parents on processors and try to keep like jobs on the same core(s).
Python

Besides the fact that node.js is written in JS and Tornado in Python, what are some of the differences between the two?  They're both non-blocking asynchronous web servers, right?  Why choose one over the other besides the language?The main advantage of node.js is that  so you don't have to worry much about blocking. There are async libraries for mysql, postgres, redis, etc. All is async by default.Python have a library for anything - but most of these libraries are not asynchronous. In order to take advantage of tornado (and not to block the process) special libraries for are necessary (e.g. you can't just 'pip install redis' and use it, you'll need something like ), and there are much less tornado libraries than node.js libraries. There is no async mysql tornado driver available at the moment, for example (or at least I'm not aware of it).But you can still use many python libraries with tornado (ones that doesn't do i/o), and tornado community is raising and filling the gaps. It is easier to write an app using node.js than using tornado in my experience. I personally switched to tornado from node.js because it fits into existing infrastructure of my python project better (integration between django site serving html pages and tornado server providing realtime features was quite painless). As Rich Bradshaw points out  is written in JS, which means you can keep the front end and the back end in the same language and possibly share some codebase. To me that is a huge potential benefit of .\nNode also comes with more asynchronous libraries out of the box it seems.V8 should make JS faster than Python , but it may not matter much, because both  and  (and most other web frameworks for that matter) use wrappers for native libraries. A lot of the Python standard library is written in C or can be replaced by a faster alternative, which mitigates potential differences even more.Web services are usually I/O bound, so that means we're spending the time waiting for the data store and not processing the data. That makes the synthetic speed difference between JS and Python irrelevant in many applications.node.js uses V8 which compiles into assembly code, tornado doesn't do that yet.Other than that (which doesn't actually seem to make much difference to the speed), it's the ecosystem. Do you prefer the event model of JS, or the way Python works? Are you happier using Python or JS libraries?Nodejs also has a seamless integration / implementation of websockets called Socket.io. It handles browsers supporting sockets - events and also has backward polling compatibility for older browsers. It is quite quick on development requiring a notification framework or some similar event based programming.I would suggested you go with NodeJS, if there is no personal pref to python. I like Python a lot, but for async I choose Tornado over node, and later had to struggle finding way to do a thing, or libraries with async support (like Cassandra has async in tests, but nowhere could I find way to use cqlengine with async. Had to choose Mongo since I already surpassed the deadline).\nIn terms of performance and async, Node far better than tornado.
Python

I just switched to Pycharm and I am very happy about all the warnings and hints it provides me to improve my code. Except for this one which I don't understand:I know it is bad practice to access variable from the outer scope but what is the problem with shadowing the outer scope?Here is one example, where Pycharm gives me the warning message:No big deal in your above snippet, but imagine a function with a few more arguments and quite a few more lines of code. Then you decide to rename your  argument as  but miss one of the places it is used in the function's body... Now  refers to the global, and you start having weird behaviour - where you would have a much more obvious  if you didn't have a global name . Also remember that in Python everything is an object (including modules, classes and functions) so there's no distinct namespaces for functions, modules or classes. Another scenario is that you import function  at the top of your module, and use it somewhere in your function body. Then you add a new argument to your function and named it - bad luck - . Finally, built-in functions and types also live in the same namespace and can be shadowed the same way.None of this is much of a problem if you have short functions, good naming and a decent unittest coverage, but well, sometimes you have to maintain less than perfect code and being warned about such possible issues might help. and most answers here miss the point.It doesn't matter how long your function is, or how you name your variable descriptively (to hopefully minimize the chance of potential name collision).The fact that your function's local variable or its parameter happens to share a name in the global scope is completely irrelevant. And in fact, no matter how carefully you choose you local variable name, your function can never foresee \"whether my cool name  will also be used as a global variable in future?\". The solution? Simply don't worry about that! The correct mindset is to design your function to consume input from and only from its parameters in signature, that way you don't need to care what is (or will be) in global scope, and then shadowing becomes not an issue at all.In other words, shadowing problem only matters when your function need to use the same name local variable AND the global variable. But you should avoid such design in the first place. The OP's code does NOT really have such design problem. It is just that PyCharm is not smart enough and it gives out a warning just in case. So, just to make PyCharm happy, and also make our code clean, see this solution quoting from  to remove the global variable completely.This is the proper way to \"solve\" this problem, by fixing/removing your global thing, not adjusting your current local function.It depends how long the function is. The longer the function, the more chance that someone modifying it in future will write  thinking that it means the global. In fact it means the local but because the function is so long it's not obvious to them that there exists a local with that name.For your example function, I think that shadowing the global is not bad at all.A good workaround in some cases may be to move the vars + code to another function:
Python

I want to add \u2014the Python Debugger\u2014to my toolbox. What's the best way to get started?Here's a list of resources to get started with the Python debugger:Synopsis:Now run your script:
Python

I need to verify if a list is a subset of another - a boolean return is all I seek.\nIs testing equality on the smaller list after an intersection the fastest way to do this?\nPerformance is of utmost importance given the amount of datasets that need to be compared.\nAdding further facts based on discussions:  What would be the optimum solution given the scenario?The performant function Python provides for this is . It does have a few restrictions that make it unclear if it's the answer to your question, however.A list may contain items multiple times and has a specific order. A set does not. To achieve high performance sets work on  objects only. Are you asking about subset or subsequence (which means you'll want a string search algorithm)? Will either of the lists be the same for many tests? What are the datatypes contained in the list? And for that matter, does it need to be a list? Your other post  made the types clearer and did get a recommendation to use dictionary key views for their set-like funcitonality. In that case it was known to work because dictionary keys behave like a set (so much so that before we had sets in Python we used dictionaries). One wonders how the issue got less specific in three hours. Explanation: Generator creating booleans by looping through list  checking if that item is in list .   returns  if every item is truthy, else . There is also an advantage that  return False on the first instance of a missing element rather than having to process every item. Assuming the items are hashableIf you don't care about duplicate items eg.  and  then just use: will be the fastest way to do it. Checking the length before testing  will not improve speed because you still have O(N + M) items to iterate through and check. Try bitwise ANDHaven't profiled it yet.If list1 is in list 2:If you are asking if one list is \"contained\" in another list then:If you are asking if each element in listA has an equal number of matching elements in listB try:To check if one  is subset of ,  has  and . It works on  only and works great  the complexity of internal implementation is unknown. Reference: I came up with an algorithm to check if  is a subset of  with following remarks.
Python

Suppose you have the following situationAs you can see, makeSpeak is a routine that accepts a generic Animal object. In this case, Animal is quite similar to a Java interface, as it contains only a pure virtual method. makeSpeak does not know the nature of the Animal it gets passed. It just sends it the signal \u201cspeak\u201d and leaves the late binding to take care of which method to call: either Cat::speak() or Dog::speak(). This means that, as far as makeSpeak is concerned, the knowledge of which subclass is actually passed is irrelevant.But what about Python? Let\u2019s see the code for the same case in Python. Please note that I try to be as similar as possible to the C++ case for a moment:Now, in this example you see the same strategy. You use inheritance to leverage the hierarchical concept of both Dogs and Cats being Animals. \nBut in Python, there\u2019s no need for this hierarchy. This works equally wellIn Python you can send the signal \u201cspeak\u201d to any object you want. If the object is able to deal with it, it will be executed, otherwise it will raise an exception. Suppose you add a class Airplane to both codes, and submit an Airplane object to makeSpeak. In the C++ case, it won\u2019t compile, as Airplane is not a derived class of Animal. In the Python case, it will raise an exception at runtime, which could even be an expected behavior.On the other side, suppose you add a MouthOfTruth class with a method speak(). In the C++ case, either you will have to refactor your hierarchy, or you will have to define a different makeSpeak method to accept MouthOfTruth objects, or in java you could extract the behavior into a CanSpeakIface and implement the interface for each. There are many solutions...What I\u2019d like to point out is that I haven\u2019t found a single reason yet to use inheritance in Python (apart of frameworks and trees of exceptions, but I guess that alternative strategies exist). you don\u2019t need to implement a base-derived hierarchy to perform polymorphically. If you want to use inheritance to reuse implementation, you can accomplish the same through containment and delegation, with the added benefit that you can alter it at runtime, and you clearly define the interface of the contained, without risking unintended side effects.So, in the end, the question stands: what's the point of inheritance in Python?: thanks for the very interesting answers. Indeed you can use it for code reuse, but I am always careful when reusing implementation. In general, I tend to do very shallow inheritance trees or no tree at all, and if a functionality is common I refactor it out as a common module routine and then call it from each object. I do see the advantage of having one single point of change (eg. instead of adding to Dog, Cat, Moose and so on, I just add to Animal, which is the basic advantage of inheritance), but you can achieve the same with a delegation chain (eg. a la JavaScript). I'm not claiming it's better though, just another way.I also found  on this regard.You are referring to the run-time duck-typing as \"overriding\" inheritance, however I believe inheritance has its own merits as a design and implementation approach, being an integral part of object oriented design. In my humble opinion, the question of whether you can achieve something otherwise is not very relevant, because actually you could code Python without classes, functions and more, but the question is how well-designed, robust and readable your code will be.I can give two examples for where inheritance is the right approach in my opinion, I'm sure there are more. First, if you code wisely, your makeSpeak function may want to validate that its input is indeed an Animal, and not only that \"it can speak\", in which case the most elegant method would be to use inheritance. Again, you can do it in other ways, but that's the beauty of object oriented design with inheritance - your code will \"really\" check whether the input is an \"animal\".Second, and clearly more straightforward, is Encapsulation - another integral part of object oriented design. This becomes relevant when the ancestor has data members and/or non-abstract methods. Take the following silly example, in which the ancestor has a function (speak_twice) that invokes a then-abstract function:Assuming  is an important feature, you don't want to code it in both Dog and Cat, and I'm sure you can extrapolate this example. Sure, you could implement a Python stand-alone function that will accept some duck-typed object, check whether it has a speak function and invoke it twice, but that's both non-elegant and misses point number 1 (validate it's an Animal). Even worse, and to strengthen the Encapsulation example, what if a member function in the descendant class wanted to use ?It gets even clearer if the ancestor class has a data member, for example  that is used by non-abstract methods in the ancestor like , but is initiated in the descendant class' constructor (e.g. Dog would initialize it with 4 whereas Snake would initialize it with 0). Again, I'm sure there are endless more examples, but basically every (large enough) software that is based on solid object oriented design will require inheritance.Inheritance in Python is all about code reuse.  Factorize common functionality into a base class, and implement different functionality in the derived classes.Inheritance in Python is more of a convenience than anything else.  I find that it's best used to provide a class with \"default behavior.\"Indeed, there is a significant community of Python devs who argue against using inheritance at all.  Whatever you do, don't just don't overdo it.  Having an overly complicated class hierarchy is a sure way to get labeled a \"Java programmer\", and you just can't have that.  :-)I think the point of inheritance in Python is not to make the code compile, it is for the real reason of inheritance which is extending the class into another child class, and to override the logic in the base class. However the duck typing in Python makes the \"interface\" concept useless, because you can just check if the method exist before invokation with no need to use an interface to limit the class structure.I think that it is very difficult to give a meaningful, concrete answer with such abstract examples...To simplify, there are two types of inheritance: interface and implementation. If you need to inherit the implementation, then python is not so different than statically typed OO languages like C++. Inheritance of interface is where there is a big difference, with fundamental consequences for the design of your software in my experience. Languages like Python does not force you to use inheritance in that case, and avoiding inheritance is a good point in most cases, because it is very hard to fix a wrong design choice there later. That's a well known point raised in any good OOP book.There are cases where using inheritance for interfaces is advisable in Python, for example for plug-ins, etc... For those cases, Python 2.5 and below lacks a \"built-in\" elegant approach, and several big frameworks designed their own solutions (zope, trac, twister). Python 2.6 and above has .In C++/Java/etc, polymorphism is caused by inheritance. Abandon that misbegotten belief, and dynamic languages open up to you.Essentially, in Python there is no interface so much as \"the understanding that certain methods are callable\".  Pretty hand-wavy and academic-sounding, no? It means that because you call \"speak\" you clearly expect that the object should have a \"speak\" method.  Simple, huh?  This is very Liskov-ian in that the users of a class define its interface, a good design concept that leads you into healthier TDD.So what is left is, as another poster politely managed to avoid saying, a code sharing trick.  You could write the same behavior into each \"child\" class, but that would be redundant.  Easier to inherit or mix-in functionality that is invariant across the inheritance hierarchy.  Smaller, DRY-er code is better in general.  It's not inheritance that duck-typing makes pointless, it's interfaces \u2014 like the one you chose in creating an all abstract animal class.If you had used an animal class that introduce some real behavior for its descendants to make use of, then dog and cat classes that introduced some additional behavior there would be a reason for both classes.  It's only in the case of the ancestor class contributing no actual code to the descendant classes that your argument is correct.Because Python can directly know the capabilities of any object, and because those capabilities are mutable beyond the class definition, the idea of using a pure abstract interface to \"tell\" the program what methods can be called is somewhat pointless.  But that's not the sole, or even the main, point of inheritance.You can get around inheritance in Python and pretty much any other language.  It's all about code reuse and code simplification though.  Just a semantic trick, but after building your classes and base classes, you don't even have to know what's possible with your object to see if you can do it.  Say you have d which is a Dog that subclassed Animal.If whatever the user typed in is available, the code will run the proper method.  Using this you can create whatever combination of Mammal/Reptile/Bird hybrid monstrosity you want, and now you can make it say 'Bark!' while flying and sticking out its forked tongue and it will handle it properly!  Have fun with it!I don't see much point in inheritance.Every time I have ever used inheritance in real systems, I got burned because it led to a tangled web of dependencies, or I simply realised in time that I would be a lot better off without it. Now, I avoid it as much as possible. I simply never have a use for it.James Gosling was once asked at a press conference a question along the lines: \"If you could go back and do Java differently, what would you leave out?\". His response was \"Classes\", to which there was laughter. However, he was serious and explained that really, it was not classes that were the problem but inheritance.I kind of view it like a drug dependency - it gives you a quick fix that feels good, but in the end, it messes you up. By that I mean that it is a convenient way to reuse code, but it forces an unhealthy coupling between child and parent class. Changes to the parent may break the child. The child is dependant on the parent for certain functionality and cannot alter that functionality. Therefore the functionality provided by the child is also tied to the parent - you can only have both.Better is to provide one single client facing class for an interface which implements the interface, using the functionality of other objects which are composed at construction time. Doing this via properly designed interfaces, all coupling can be eliminated and we provide a highly composable API (This is nothing new - most programmers already do this, just not enough). Note that the implementing class must not simply expose functionality, otherwise the client should just use the composed classes directly - it  do something new by combining that functionality.There is the argument from the inheritance camp that pure delegation implementations suffer because they require lots of 'glue' methods which simply pass along values through a delegation 'chain'. However, this is simply reinventing an inheritance-like design using delegation. Programmers with too many years of exposure to inheritance-based designs are particularly vulnerable to falling into this trap, as, without realising it, they will think of how they would implement something using inheritance and then convert that to delegation.Proper separation of concerns like the above code doesn't require glue methods, as each step is actually , so they are not really 'glue' methods at all (if they don't add value, the design is flawed).It boils down to this:Another small point is that op's 3'rd example, you can't call isinstance(). For example passing your 3'rd example to another object that takes and \"Animal\" type an calls speak on it. If you do it don't you would have to check for dog type, cat type, and so on. Not sure if instance checking is really \"Pythonic\", because of late binding. But then you would have to implement some way that the AnimalControl doesn't try to throw Cheeseburger types in the truck, becuase Cheeseburgers don't speak.Classes in Python are basically just ways of grouping a bunch of functions and data.. They are different to classes in C++ and such..I've mostly seen inheritance used for overriding methods of the super-class. For example, perhaps a more Python'ish use of inheritance would be..Of course cats aren't a type of dog, but I have this (third party)  class which works perfectly,  the  method which I want to override - this saves re-implementing  the entire class, just so it meows. Again, while  isn't a type of , but a cat does inherit a lot of attributes..A much better (practical) example of overriding a method or attribute is how you change the user-agent for urllib. You basically subclass  and change the version attribute ():Another manner exceptions are used is for Exceptions, when inheritance is used in a more \"proper\" way:..you can then catch  to catch all exceptions which inherit from it, or a specific one like  
Python

Assume I have a  object and I want to write it out as a CSV file. How can I do this?I know that I can write the  like this:But how can I include the fieldnames?Edit:\nIn 2.7 / 3.2 there is . Also, John Machin's answer provides a simpler method of writing the header row.\nSimple example of using the  method now available in 2.7 / 3.2:Instantiating DictWriter requires a fieldnames argument.\nFrom :  Put another way:  The Fieldnames argument is required because Python dicts are inherently unordered.\nBelow is an example of how you'd write the header and data to a file.\nNote:  statement was added in 2.6. If using 2.5: As @FM mentions in a comment, you can condense header-writing to a one-liner, e.g.:A few options:(1) Laboriously make an identity-mapping (i.e. do-nothing) dict out of your fieldnames so that csv.DictWriter can convert it back to a list and pass it to a csv.writer instance. (2) The documentation mentions \"the underlying  instance\" ... so just use it (example at the end).(3) Avoid the csv.Dictwriter overhead and do it yourself with csv.writerWriting data:orInstead of the  \"functionality\", I'd prefer to code it myself; that way you can report ALL \"extras\" with the keys and values, not just the first extra key. What is a real nuisance with DictWriter is that if you've verified the keys yourself as each dict was being built, you need to remember to use extrasaction='ignore' otherwise it's going to SLOWLY (fieldnames is a list) repeat the check:============Another way to do this would be to add before adding lines in your output, the following line :The zip would return a list of doublet containing the same value. This list could be used to initiate a dictionary.
Python

In a text file, there is a string \"I don't like this\".However, when I read it into a string, it becomes \"I don\\xe2\\x80\\x98t like this\". I understand that \\u2018 is the unicode representation of \"'\". I use command to do the reading.Now, is it possible to read the string in such a way that when it is read into the string, it is \"I don't like this\", instead of \"I don\\xe2\\x80\\x98t like this like this\"?Second edit: I have seen some people use mapping to solve this problem, but really, is there no built-in conversion that does this kind of ANSI to unicode ( and vice versa) conversion?Ref: : I'm assuming that your intended goal is just to be able to read the file properly into a string in Python. If you're trying to convert to an ASCII string from Unicode, then there's really no direct way to do so, since the Unicode characters won't necessarily exist in ASCII.If you're trying to convert to an ASCII string, try one of the following: There are a few points to consider.A \\u2018 character may appear only as a fragment of representation of a unicode string in Python, e.g. if you write:Now if you simply want to print the unicode string prettily, just use unicode's  method:To make sure that every line from any file would be read as unicode, you'd better use the  function instead of just , which allows you to specify file's encoding:But it really is \"I don\\u2018t like this\" and not \"I don't like this\". The character u'\\u2018' is a completely different character than \"'\" (and, visually, should correspond more to '`').If you're trying to convert encoded unicode into plain ASCII, you could perhaps keep a mapping of unicode punctuation that you would like to translate into ASCII.There are an awful lot of , however, but I suppose you can count on only a few of them actually being used by whatever application is creating the documents you're reading.Leaving aside the fact that your text file is broken (U+2018 is a left quotation mark, not an apostrophe): iconv can be used to transliterate unicode characters to ascii.You'll have to google for \"iconvcodec\", since the module seems not to be supported anymore and I can't find a canonical home page for it.Alternatively you can use the  command line utility to clean up your file:There is a possibility that somehow you have a non-unicode string with unicode escape characters, e.g.:This actually happened to me once before. You can use a  codec to decode the string to unicode and then encode it to any format you want:Actually, U+2018 is the Unicode representation of the special character \u2018 . If you want, you can convert instances of that character to U+0027 with this code:In addition, what are you using to write the file?  should return a string that looks like this:If it's returning  string, the file is being written incorrectly:This is Pythons way do show you unicode encoded strings. But i think you should be able to print the string on the screen or write it into a new file without any problems.
Python

I am new to Python and am working on a Linux machine (Ubuntu 10.10). It is running python 2.6, but I'd like to run 2.7 as it has features I want to use. I have been urged to not install 2.7 and set that as my default python. My question is, how can I install 2.7 and run it side by side with 2.6?I did it with  on my Ubuntu 10.10 machine..I recently backported Python 2.7 to Debian squeeze. Since Ubuntu 10.10 is newer than Debian squeeze, if you can do it on squeeze, you can certainly do it on Ubuntu. I don't have access to a Ubuntu 10.10 system. If I set one up, I'll test on it, and update this answer. So, here instead is a brief sketch of what I did on Debian.First, a general and obvious comment, but something that is easily overlooked. One should not take the listed build dependencies of a Debian package too seriously. They may be far more specific than needed. For example, software like Python, which is designed to be portable and run over a wide array of systems, is unlikely to build depend on very specific versions of software. The runtime dependencies can be adjusted as well, but this should be done with more caution. However, runtime dependencies are mostly generated dynamically based on software that is already on this system, so usually that is not a big issue.Selecting the testing version we getLooking at , we see the following build dependency lines.Build-Depends: debhelper (>= 5), quilt, autoconf, libreadline-dev, libtinfo-dev, libncursesw5-dev (>= 5.3), tk8.5-dev, zlib1g-dev, blt-dev (>= 2.4z), libssl-dev, libexpat1-dev, sharutils, libbz2-dev, libbluetooth-dev [linux-any], locales [!armel !avr32 !hppa !ia64 !mipsel], libsqlite3-dev, libffi-dev (>= 3.0.5), mime-support, libgpm2 [linux-any], netbase, lsb-release, bzip2, libdb4.8-dev, gdb, python, help2man\nBuild-Depends-Indep: python-sphinx\nBuild-Conflicts: tcl8.3-dev, tk8.3-dev, tcl8.4-dev, tk8.4-dev, python2.7-xml, python-xml, autoconf2.13, libncurses5-devMost of this is easily satisfied on squeeze. With the handy utility  we get on my machineWe see that everything except  is available in squeeze. I do have the squeeze backport versions of  and , but both of these are also available for debian squeeze in versions satisfying the build requirements.Observe also that I have libncurses5-dev installedBoth of these packages correspond to the source package . Observe that  in fact replaces .One would not expect python 2.7 to develop on such a specific version of curses, and in fact it doesn't. However, if you try to build the packages without satisfying the dependency you getSo, it is necessary to edit . Note that you also need to similarly edit the file , otherwise the \nfile will be incorrectly regenerated from . The simplest thing to do is just remove \nfrom the  line and  from the  line, and then run \nagain. If you are going to have this package installed alongside the standard default Python 2.6 packages on Debian squeeze, you\nalso need to remove the two linesThose lines are there because 2.7 includes the  functionality.\nIf 2.7 is the default python, then  is no longer necessary. \nHowever, if one is installing 2.7 as a non-default Python, that reasoning does not\napply, and  is still needed by 2.6.This should build successfully, and result in the following list of binary packages.Finally, one can install the binary packages withSometimes  can be a little difficult about satisfying dependencies when they are all installed at once, so you might have to run  afterwards if you get dependency errors, or alternatively install the packages in smaller groups.Well if the only thing you need is argparse (saw that in one of your comments!) you could just do :This is not exactly an answer to the exact question :-) , but indeed if you are only missing a few feature, many 2.7 features actually come from independent projects and/or some compatibility packages can be found, eg:The list of  is admittedly longer, but most of the other new features are probably not a big miss, and in exchange you do not mess around with multiple python installations on your box. Otherwise go with pythonbrew :-)ubuntu 12.04Install dependencies:Add the repo:Update the repo index:Install Python 3.3:ubuntu 12.04 > moreInstalling the dependencies:Download and compile python:Some nice touches to install a py command by creating a symlink:Just download Python 2.7 from  and build it.You can use  to create distinct Python environments. Just being newsy, but what does Python 2.7 have that you need?Another option is to install  if you do not want to compile things yourself. It includes a  as well.
Python

The title pretty much summarizes what I'd like to have happen.Here is what I have, and while the program doesn't blow up on a nonpositive integer, I want the user to be informed that a nonpositive integer is basically nonsense.And the output:Output with a negative:Now, obviously I could just add an if to determine  is negative, but I was curious if there was a way to trap it at the  level, so as to take advantage of the automatic usage printing.Ideally, it would print something similar to this:Like so:For now I'm doing this, and I guess I'm happy:This should be possible utilizing . You'll still need to define an actual method that decides this for you:This is basically just an adapted example from the  function in the  on . would be the recommended option to handle conditions/checks, as in Yuushi's answer.In your specific case, you can also use the  parameter if your upper limit is also known:The quick and dirty way, if you have a predictable max as well as min for your arg, is use  with a rangeA simpler alternative, especially if subclassing , is to initiate the validation from inside the  method.Inside such a subclass:This technique may not be as cool as a custom callable, but it does the job.About :Credit: 
Python

In Python, is there any difference between creating a generator object through a  versus using the  statement?Using :Using :Both functions return generator objects, which produce tuples, e.g. (0,0), (0,1) etc.Any advantages of one or the other? Thoughts?Thanks everybody! There is a lot of great information and further references in these answers!There are only slight differences in the two.  You can use the  module to examine this sort of thing for yourself.   My first version decompiled the generator expression created at module-scope in the interactive prompt.  That's slightly different from the OP's version with it used inside a function.  I've modified this to match the actual case in the question.As you can see below, the \"yield\" generator (first case) has three extra instructions in the setup, but from the first  they differ in only one respect:  the \"yield\" approach uses a  in place of a  inside the loop.  The  is  than , so it makes the \"yield\" version slightly faster than the generator expression for large enough values of  (the outer loop) because the value of  is loaded slightly faster on each pass.  For smaller values of  it would be slightly slower because of the extra overhead of the setup code.It might also be worth pointing out that the generator expression would usually be used inline in the code, rather than wrapping it with the function like that.  That would remove a bit of the setup overhead and keep the generator expression slightly faster for smaller loop values even if  gave the \"yield\" version an advantage otherwise.In neither case would the performance difference be enough to justify deciding between one or the other.  Readability counts far more, so use whichever feels most readable for the situation at hand.  In this example, not really. But  can be used for more complex constructs -  it can accept values from the caller as well and modify the flow as a result. Read  for more details (it's an interesting technique worth knowing).Anyway, the best advice is .P.S. Here's a simple coroutine example from :There is no difference for the kind of simple loops that you can fit into a generator expression.  However yield can be used to create generators that do much more complex processing.  Here is a simple example for generating the fibonacci sequence:Using  is nice if the expression is more complicated than just nested loops. Among other things you can return a special first or special last value. Consider:In usage, note a distinction between a generator object vs a generator function.A generator object is use-once-only, in contrast to a generator function, which can be reused each time you call it again, because it returns a fresh generator object.Generator expressions are in practice usually used \"raw\", without wrapping them in a function, and they return a generator object.E.g.:which outputs:Compare with a slightly different usage:which outputs:And compare with a generator expression:which also outputs:When thinking about iterators, the  module:For performance, consider Yes there is a difference.For the generator expression ,  is called when the expression is .When using  and  to create a generator, as in: is not yet called.  It will be called only when iterating on  (and might not be called at all).Taking this iterator as an example:This code:while:Since most iterators do not do a lot of stuff in , it is easy to miss this behavior.  A real world example would be Django's , which  and  might take a lot of time, while  followed by  would return immediately.For more info and the formal definition refer to .There is a difference that could be important in some contexts that hasn't been pointed out yet. Using  prevents you from using  for something else than .This means this code is ill-formed (and feeding it to an interpreter will give you an ):On the other hand, this code works like a charm:
Python

It's more about python list comprehension syntax. I've got a list comprehension that produces list of odd numbers of a given range:This makes a filter - I've got a source list, where I remove even numbers (). I'd like to use something like if-then-else here. Following code fails:There is a python expression like if-else:How to use it inside a list comprehension? is the syntax for the expression you're returning for each element. Thus you need:The confusion arises from the fact you're using a  in the first example, but not in the second. In the second example you're only  each value to another, using a ternary-operator expression.With a filter, you need:Without a filter you need:and in your second example, the expression is a \"complex\" one, which happens to involve an .Just another solution, hope some one may like it :Using: [False, True][Expression]You can do that with list comprehension too:I was able to do this
Python

Is there an easy way to sort the letters in a string alphabetically in Python?So for:I would like to return:You can do: returns a list, so you can make it a string again using :which joins the items of  together with an empty string  in between each item.Sorted() solution can give you some unexpected results with other strings. List of other solutions:If you want to get rid of the space in the result, add strip() function in any of those mentioned cases:
Python

When using setuptools/distribute, I can not get the installer to pull in any  files. Everything I've read says that the following is the correct way to do it. Can someone please advise?where  is the location of the data files.I realize that this is an old question...but for people finding there way here via Google:   is a low-down, .  It is only used when building  packages () but  when building source packages ().  This is, of course, ridiculous -- one would expect that building a source distribution would result in a collection of files that could be sent to someone else to built the binary distribution.In any case, using  will work  for binary and for source distributions.I just had this same issue. The solution, was simply to remove .After , I realized that  aims to include files from , as opposed to merely \"include package data\" as the name implies. From the docs:Taking that argument out fixed it, which is coincidentally why it also worked when you switched to distutils, since it doesn't take that argument.Following @Joe 's recommendation to remove the  line also worked for me. To elaborate a bit more, I have   file. I use Git and not CVS.Repository takes this kind of shape::I run  for a source distrib (haven't tried binary).And when inside of a brand new virtual environment, I have a , file, \nand I useAnd other than everything getting installed to my virtual environment's , those special data files get installed to  and . worked for me.If you use git, remember to include  in . Far less boring than having a  or including all path in  ( in my case it's a django app with all kind of statics )( pasted the comment I made, as  mentioned it's actually helpful as is )I solved this by switching to distutils. Looks like distribute is deprecated and/or broken.Moving the folder containing the package data into to module folder solved the problem for me.See this question: Ancient question and yet... package management of python really leaves a lot to be desired. So I had the use case of installing using pip locally to a specified directory and was surprised both package_data and data_files paths did not work out. I was not keen on adding yet another file to the repo so I ended up leveraging data_files and setup.py option --install-data; something like this
Python

I have a transparent png image \"foo.png\"\nand I've opened another image with now what i need is to merge foo.png with foo2.png.( foo.png contains some text and I want to print that text on foo2.png )First parameter to  is the image to paste. Second are coordinates, and the secret sauce is the third parameter. It indicates a  that will be used to paste the image. If you pass a image with transparency, then the alpha channel is used as mask.Check the . does not work as expected when the background image also contains transparency. You need to use real .Pillow 2.0 contains an  function that does this. EDIT: Both images need to be of the type RGBA. So you need to call  if they are paletted, etc.. If the background does not have an alpha channel, then you can use the regular paste method (which should be faster). As  already pointed out,  doesn't work properly, when source  destination both contain alpha.Consider the following scenario:Two test images, both contain alpha:\nCompositing image using  like so:produces the following image (the alpha part of the overlayed red pixels is completely taken from the 2nd layer. The pixels are not blended correctly):Compositing image using  like so:produces the following (correct) image:
Python

Is it possible to have a one line command in python to do a simple ftp server? I'd like to be able to do this as quick and temporary way to transfer files to a linux box without having to install a ftp server. Preferably a way using built in python libraries so there's nothing extra to install.Obligatory  example:And probably useful:Check out  from Giampaolo Rodola.  It is one of the very best ftp servers out there for python.  It's used in google's chromium (their browser) and bazaar (a version control system).  It is the most complete implementation on Python for  (aka: FTP server implementation spec).From the commandline:Alternatively 'my_server.py':There's more examples on the website if you want something more complicated.To get a list of command line options:Note, if you want to override or use a standard ftp port, you'll need admin privileges (e.g. sudo).Why don't you instead use a one-line  server?will serve the contents of the current working directory over HTTP on port 8000.If you use Python 3, you should instead writeSee the  module docs for 2.x and the  docs for 3.x.By the way, in both cases the port parameter is optional.The answers above were all assuming your Python distribution would have some third-party libraries in order to achieve the \"one liner python ftpd\" goal, but that is not the case of what @zio was asking, also, SimpleHTTPServer involves web broswer for downloading files, it's not quick enough.  Python can't do ftpd by itself, but you can use :   (netcat) is basically a built-in tool from any UNIX-like systems (even embedded systems), so it's prefect for \"\".step-1, on the receiver side, run:\n\nwill listen on port 12345, waiting for data.  step-2, on the sender side:\n  You can also put  in the middle to monitor the progress of transferring:\n  After the transferring finished, both sides of  will quit automatically,  and job done.For pyftpdlib users. I found this on the pyftpdlib website. This creates anonymous ftp with write access to your filesystem so please use with due care. More features are available under the hood for better security so just go look:Might be helpful for those that tried using the deprecated method above. Install:Then the code:Get deeper:Good list of tools atI've used woof myself on a number of occasions. Very nice.I dont know about a one-line FTP server, but if you doIt'll run an HTTP server on 0.0.0.0:8000, serving files out of the current directory. If you're looking for a way to quickly get files off a linux box with a web browser, you cant beat it.
Python

Given a list of strings, I want to sort it alphabetically and remove duplicates. I know I can do this:but I don't know how to retrieve the list members from the hash in alphabetical order.I'm not married to the hash, so any way to accomplish this will work. Also, performance is not an issue, so I'd prefer a solution that is expressed in code clearly to a fast but more opaque one.A list can be sorted and deduplicated using built-in functions:If your input is already sorted, then there may be a simpler way to do it:If you want to keep order of the original list, just use OrderedDict with  as values.In Python2:In Python3 it's even simpler:If you don't like iterators (zip and repeat) you can use a generator (works both in 2 & 3):If it's clarity you're after, rather than speed, I think this is very clear:It's O(n^2) though, with the repeated use of not in for each element of the input list.> but I don't know how to retrieve the list members from the hash in alphabetical order.Not really your main question, but for future reference Rod's answer using  can be used for traversing a 's keys in sorted order:and also because 's are ordered by the first member of the tuple, you can do the same with :For the string data
Python

I'm trying to remove the last 3 characters from a string in python, I don't know what these characters are so I can't use , I also need to remove any white space and convert to upper-casean example would be:This works and gives me BS12 which is what I want, however if the last 4th & 3rd characters are the same I loose both eg if  I just get examples of  could be:The string could be 6 or 7 characters and I need to drop the last 3 (assuming no white space)Any tips?It doesn't work as you expect because strip is character based. You need to do this instead:Removing any and all whitespace:Removing last three characters:Converting to capital letters:All of that code in one line:You might have misunderstood rstrip slightly, it strips not a string but any character in the string you specify.Like this:So instead, just use (after replacing whitespace with nothing)I try to avoid regular expressions, but this appears to work:What's wrong with this?Aren't you performing the operations in the wrong order? You requirement seems to be It some what depends on your definition of whitespace. I would generally call whitespace to be spaces, tabs, line breaks and carriage returns. If this is your definition you want to use a regex with \\s to replace all whitespace charactors:
Python

 is an extremely useful library, and from using it I've found that it's capable of handling matrices which are quite large (10000 x 10000) easily, but begins to struggle with anything much larger (trying to create a matrix of 50000 x 50000 fails). Obviously, this is because of the massive memory requirements.Is there is a way to create huge matrices natively in NumPy (say 1 million by 1 million) in some way (without having several terrabytes of RAM)?PyTables and NumPy are the way to go.PyTables will store the data on disk in HDF format, with optional compression. My datasets often get 10x compression, which is handy when dealing with tens or hundreds of millions of rows. It's also very fast; my 5 year old laptop can crunch through data doing SQL-like GROUP BY aggregation at 1,000,000 rows/second. Not bad for a Python-based solution!Accessing the data as a NumPy recarray again is as simple as:The HDF library takes care of reading in the relevant chunks of data and converting to NumPy.s are meant to live in memory.  If you want to work with matrices larger than your RAM, you have to work around that.  There are at least two approaches you can follow:You should be able to use numpy.memmap to memory map a file on disk.  With newer python and 64-bit machine, you should have the necessary address space, without loading everything into memory.  The OS should handle only keep part of the file in memory.To handle sparse matrices, you need the  package that sits on top of  -- see  for more details about the sparse-matrix options that  gives you.Stefano Borini's  got me to look into how far along this sort of thing already is.    It appears to do basically what you want.  HDF5 will let you store very large datasets, and then access and use them in the same ways NumPy does.  Make sure you're using a 64-bit operating system and a 64-bit version of Python/NumPy. Note that on 32-bit architectures you can address typically 3GB of memory (with about 1GB lost to memory mapped I/O and such). With 64-bit and things arrays larger than the available RAM you can get away with virtual memory, though things will get slower if you have to swap. Also, memory maps (see numpy.memmap) are a way to work with huge files on disk without loading them into memory, but again, you need to have a 64-bit address space to work with for this to be of much use. PyTables will do most of this for you as well.It's a bit alpha, but  seems to be working on solving this. Are you asking how to handle a 2,500,000,000 element matrix without terabytes of RAM?  The way to handle 2 billion items without 8 billion bytes of RAM is by not keeping the matrix in memory.That means much more sophisticated algorithms to fetch it from the file system in pieces.Usually when we deal with large matrices we implement them as .I don't know if numpy supports sparse matrices but I found  instead.As far as I know about numpy, no, but I could be wrong. I can propose you this alternative solution: write the matrix on the disk and access it in chunks. I suggest you the HDF5 file format. If you need it transparently, you can reimplement the ndarray interface to paginate your disk-stored matrix into memory. Be careful if you modify the data to sync them back on the disk. Sometimes one simple solution is using a custom type for your matrix items. Based on the range of numbers you need, you can use a manual  and specially smaller for your items. Because Numpy considers the largest type for object by default this might be a helpful idea in many cases. Here is an example:And with custom type:
Python

I've tried lots of solution that posted on the net, they don't work.So the system can find the _imaging but still can't use truetype fontRaises this error:Your installed PIL was compiled without libfreetype.You can get precompiled installer of PIL (compiled with libfreetype) here (and many other precompiled Python C Modules):On Ubuntu, you need to have libfreetype-dev installed before compiling PIL.i.e.PS! Running pip install as sudo will usually install packages to /usr/local/lib on most Ubuntu versions. You may consider to install Pil in a virtual environment (virtualenv or venv) in a path owned by the user instead.You may also consider installing pillow instead of pil, which I believe is API compatible: .The following worked for me on Ubuntu 14.04.1 64 bit:Then, in the virtualenv:solution for CentOS 6 (and probably other rpm based):In OS X, I did this to solve the problem:Basically, you need to install freetype before installing PIL.If you're using  on OS X it's just a matter of:Worked for Ubuntu 12.10:For OS X (I'm running 10.6 but should work for others) I was able to get around this error using the advice from . Basically you need to install a couple of the dependencies then reinstall PIL.For me none of the solutions posted here so far has worked. I found another solution here: First install the dev packages:Then create some symlinks:Afterwards PIL should compile just fine:The followed works on ubuntu 12.04:when your see \"-- JPEG support avaliable\" that means it works.But, if it still doesn't work when your edit your jpeg image, check the python path!!\nMy python path missed , so I edit the  add the following code to this file:then, finally, it works!!I used homebrew to install freetype and I have the following in /usr/local/lib:libfreetype.6.dylib\nlibfreetype.a\nlibfreetype.dylibBut the usual:Does not work for me, so I used:Ubuntu 11.10 installs zlib and freetype2 libraries following the multi-arch spec (e.g. ). You may use PIL setup environment variables so it can find them. However it only works on PIL versions beyond the pil-117 tag.Since your multi-arch path may be different (x86-64), it's preferable to install the  packages and use  to retrieve the correct path.Another way given by Barry on Pillow's setup.py is to use  to obtain the proper library directory suffix.See In my Mac, the following steps in terminal works:hopes it works for you. Good luck!\u3010solved\u3011\nIn my ubuntu12.04, after I installed python-imaging using apt-get, it works.
Python

I have a long Hex string that represents a series of values of different types. I wish to convert this Hex String into a byte array so that I can shift each value out and convert it into its proper data type. Suppose your hex string is something likeor since Python 2.6:However, it's possible that by \u201chex string\u201d you just mean a string with unprintable characters, such as In that case, use the options above without the  part.There is a built-in function in bytearray that does what you intend.It returns a bytearray and it reads hex strings with or without space separator.provided I understood correctly, you should look for binascii.unhexlifyYou should be able to build a string holding the binary data using something like:This is probably not the fastest way (many string appends), but quite simple using only core Python.Assuming you have a byte string like soand you know the amount of bytes and their type you can also use this approachAs I specified little endian (using the '<' char) at the start of the format string the function returned the decimal equivalent.0x12 = 180x45 = 690xAB00 = 43776B is equal to one byte (8 bit) unsignedH is equal to two bytes (16 bit) unsignedYou can specify more than one byte and the endian of the valuesYou really need to know the type and length of data your dealing withA good one liner is:This will iterate over each char in the string and run it through the ord() function.  Only tested on python 2.6, not too sure about 3.0+.-JoshFor back conversion use \nbinascii.b2a_hex(obj)
Python

Sometimes it is useful to \"clone\" a row or column vector to a matrix. By cloning I mean converting a row vector such asInto a matrixor a column vector such asintoIn matlab or octave this is done pretty easily:I want to repeat this in numpy, but unsuccessfullyWhy wasn't the first method (In[16]) working? Is there a way to achieve this task in python in a more elegant way?Here's an elegant, Pythonic way to do it:the problem with  seems to be that the transpose has no effect for an array. you're probably wanting a matrix instead:Use :or for repeating columns:First note that with numpy's  operations it's usually not necessary to duplicate rows and columns.  See  and  for descriptions.But to do this,  and  are probably the best wayThis example is for a row vector, but applying this to a column vector is hopefully obvious.  repeat seems to spell this well, but you can also do it via multiplication as in your exampleI think using the broadcast in numpy is the best, and fasterI did a compare as followingabout 15 times faster using broadcastYou can use tile will generate the reps of the vector and reshape will give it the shape you want
Python

At some point in the last few days, Matplotlib stopped working for me on OS X. Here's the error I get when trying to :The only system change I can think of was the Apple-forced NTP update and maybe some permission changes I did in /usr/local to get Brew working again.I tried reinstalling both Matplotlib and Python-dateutil via Pip, but this did not help.  Also tried a reboot.  I'm running Python 2.7.6, which is located in /usr/bin/python.  I'm running Yosemite (OS X 10.10.1).I had the same error message this afternoon as well, although I did recently upgrade to Yosemite. I'm not totally sure I understand why reverting dateutil to a previous version works for me, but since running the above I'm having no trouble (I generally use pyplot inline in an ipython notebook).This problem is fixed in the latest  and  versions. However, in OS X, even if you update your  to the latest version, you might not actually update it correctly. This is what happened to me:After doing a , the new  module was installed in . However, when I loaded  in a python 2.7 terminal, and checked its path, this is what I got:So, python was using an old version of , which I removed by typing:This fixed this issue for me.It is possible that you have a perfectly installed version of any packages you have installed, but the version used by default is not the one you want. You can see the list of paths that python search from in order to find its packages as follows:In order to let python search first the most updated version of certain package, instead of removing the system version, what can be done is to set the system variable  in the ~/.bash_profile (or ~/.bashrc if linux) config file to the path where the new packages are installed: An alternative is to modify the python path inside your python script by adding the path at the beginning of the path list:This needs to be done for every script you need a certain package version. You might want for some reason use an older version that you have installed.\nBTW all my installations with easy_install, or pip, or from sources go to /Library/Python/2.7/site-packages\nThis worked en EL Capitan, and now also in macOS Sierra (10.12.2)Installing the  did not work for me.But a quick-and-dirty workaround did work! I replace  in python 2.7 with the  from python 3.4 (virtualenv). Since, I have the problem in 2.7 but not 3.4.I had the same problem again after reinstalling python (and after upgrading to El Capitan). Un-obvious thing is that this error occurs only in the  shell and notebook (when I do ) but works fine from a Python shell. So a better solution (that did work in my case) without a dirty work-around is to force install both  and . Here is what I did to have this fixed :
Python

I have a program that reads an xml document from a socket. I have the xml document stored in a string which I would like to convert directly to a Python dictionary, the same way it is done in Django's  library.Take as an example:Then  would look like Thanks in advance,\nZe MariaThis is a great module that someone created. I've used it several times. \nHere is the code from the website just in case the link goes bad. Example usage://Or, if you want to use an XML string: (full disclosure: I wrote it) does exactly that:The following XML-to-Python-dict snippet parses entities as well as attributes following . It is the most general solution handling all cases of XML.It is used:The output of this example (as per above-linked \"specification\") should be:Not necessarily pretty, but it is unambiguous, and simpler XML inputs result in simpler JSON. :)If you want to do the , emit an , you can use:This lightweight version, while not configurable, is pretty easy to tailor as needed, and works in old pythons.  Also it is rigid - meaning the results are the same regardless of the existence of attributes.So:Results in:The most recent versions of the PicklingTools libraries (1.3.0 and 1.3.1) support tools for converting from XML to a Python dict.The download is available here:  There is quite a bit of documentation for the converters : the documentation describes in detail all of the decisions and issues that will arise when converting between XML and Python dictionaries (there are a number of edge cases: attributes, lists, anonymous lists, anonymous dicts, eval, etc. that most converters don't handle).  In general, though,\nthe converters are easy to use.  If an 'example.xml' contains:Then to convert it to a dictionary:There are tools for converting in both C++ and Python: the C++ and Python do indentical conversion, but the C++ is about 60x fasterDisclaimer:\nThis modified XML parser was inspired by  \nThe original XML parser works for most of simple cases. However, it didn't work for some complicated XML files. I debugged the code line by line and finally fixed some issues. If you find some bugs, please let me know. I am glad to fix it.The easiest to use XML parser for Python is ElementTree (as of 2.5x and above it is in the standard library xml.etree.ElementTree). I don't think there is anything that does exactly what you want out of the box. It would be pretty trivial to write something to do what you want using ElementTree, but why convert to a dictionary, and why not just use ElementTree directly.Here's a link to an  - and the code in case it disappears again.The code from  works well, but if there are multiple elements that are the same at a given place in the hierarchy it just overrides them.I added a shim between that looks to see if the element already exists before self.update().  If so, pops the existing entry and creates a lists out of the existing and the new.  Any subsequent duplicates are added to the list.Not sure if this can be handled more gracefully, but it works:From @K3---rnc  (the best for me) I've added a small modifications to get an OrderedDict from an XML text (some times order matters):Following @K3---rnc example, you can use it:Hope it helps ;)At one point I had to parse and write XML that only consisted of elements without attributes so a 1:1 mapping from XML to dict was possible easily. This is what I came up with in case someone else also doesnt need attributes:@dibrovsd: Solution will not work if the xml have more than one tag with same nameOn your line of thought, I have modified the code a bit and written it for general node instead of root:You can do this quite easily with lxml. First install it:Here is a recursive function I wrote that does the heavy lifting for you:The below variant preserves the parent key / element:If you want to only return a subtree and convert it to dict, you can use  to get the subtree and then convert it: See the lxml docs . I hope this helps!I have a recursive method to get a dictionary from a lxml element
Python

Let's take an exampleI wanted to append value in list 'b' but the value of list 'a' have also changed.\n\nI think I have little idea why its like this (python passes lists by reference).\n\nMy question is \"how can I pass it by value so that appending 'b' does't change values in 'a' ?\"As answered in the :To copy a list you can use  or . In both cases a new object is created.\nThese two methods, however, have limitations with collections of mutable objects as inner objects keep their references intact:If you want a full copy of your objects you need Also, you can do:This will work for any sequence, even those that don't support indexers and slices...In terms of performance my favorite answer would be:Check how the related alternatives compare with each other in terms of performance:To create a copy of a list do this:When you do  you simply create another pointer to the same memory of ,\nthat's why when you append to  ,  changes too.You need to create  of  and that's done like this:If you want to copy a one-dimensional list, useHowever, if a is a 2 dimensional list, this is not going to work for you. That is, any changes in a will also be reflected in b. In that case, useI found that we can use extend() to implement the function of copy()As mentioned by phihag in his answer,will work for your case since slicing a list creates a new memory id of the list (meaning you are no longer referencing the same object in your memory and the changes you make to one will not be reflected in the other.)However, there is a slight problem.  If your list is multidimensional, as in lists within lists, simply slicing will not solve this problem.  Changes made in the higher dimensions, i.e. the lists within the original list, will be shared between the two.Do not fret, there is a solution.  The module copy has a nifty copying technique that takes care of this issue.will copy a list with a new memory id no matter how many levels of lists it contains!See .
Python

Today I was bitten again by mutable default arguments after many years. I usually don't use mutable default arguments unless needed, but I think with time I forgot about that.  Today in the application I added tocElements=[] in a PDF generation function's argument list and now \"Table of Contents\" gets longer and longer after each invocation of \"generate pdf\". :)What else should I add to my list of things to MUST avoid?Don't :Do : will automate most iteration operations for you.Use  if you really need both the index and the element. Pythonistas usually say \"It's easier to ask for forgiveness than permission\".Don't :Do :Or even better with python 2.6 / 3:It is much better because it's much more generical. You can apply \"try / except\" to almost anything. You don't need to care about what to do to prevent it, just about the error you are risking. Python is dynamically typed, therefore checking for type makes you lose flexibility. Instead, use duck typing by checking behavior. E.G, you expect a string in a function, then use str() to convert any object in a string. You expect a list, use list() to convert any iterable in a list.Don't :Do :Using the last way, foo will accept any object. Bar will accept strings, tuples, sets, lists and much more. Cheap DRY :-)Just don't. You would cry.This is tricky, but it will bite you as your program grows. There are old and new classes in Python 2.x. The old ones are, well, old. They lack some features, and can have awkward behavior with inheritance. To be usable, any of your class must be of the \"new style\". To do so, make it inherit from \"object\" :Don't :Do :In Python 3.x all classes are new style so you don't need to do that.People coming from other languages find it tempting because that what you do the job in Java or PHP. You write the class name, then list your attributs and give them a default value. It seems to work in Python, however, this doesn't work the way you think.Doing that will setup class attributes (static attributes), then when you will try to get the object attribute, it will gives you its value unless it's empty. In that case it will return the class attributes. It implies two big hazards :Don't (unless you want static) :Do : When you need a population of arrays you might be tempted to type something like this:And sure enough it will give you what you expect when you look at itBut don't expect the elements of your population to be seperate objects:Unless this is what you need...It is worth mentioning a workaround:Python Language Gotchas -- things that fail in very obscure waysPython Design GotchasMutating a default argument:The default value is evaluated only once, and not every time the function is called. Repeated calls to  would return , , , ...If you want to mutate bar do something like this:Or, if you like arguments to be final:I don\u00b4t know whether this is a common mistake, but while python doesn\u00b4t has increment and decrement operators, double signs are allowed, soandis syntactically correct code, but doesn\u00b4t do anything.Rolling your own code before looking in the standard library. For example, writing this:When you could just use this:Examples of frequently overlooked modules (besides ) include:The another one could be to avoid using keywords as your own identifiers. Also it's always good to not use BTW, wouldn't it be better to post it to community wiki?Surprised that nobody said thisMix tab and spaces when indenting.really, it's a killer. believe me.  if it runs.If you're coming from C++, realize that variables declared in a class definition are static.  You can initialize nonstatic members in the  method.Example:Not using functional tools.  This isn't just a mistake from a style standpoint, it's a mistake from a speed standpoint because a lot of the functional tools are optimized in C.This is the most common example:The correct way to do it:The just as correct way to do it:And if you only need the processed items available one at a time, rather than all at once, you can save memory and improve speed by using the iterable equivalentsImporting  and using the full regular expression approach to string matching/transformation, when perfectly good  exist for every common operation (e.g. capitalisation, simple matching/searching).Last link is the original one, this SO question is an duplicate.Normal copying (assigning) is done by reference, so filling a container by adapting the same object and inserting, ends up with a container with references to the last added object.\nUse copy.deepcopy instead.Using the  formatter in error messages. In almost every circumstance,  should be used.For example, imagine code like this:Printed this error:It's impossible to tell if the  variable is the string , the unicode string  or an instance of the  class (which has  defined as ). Whereas, if  was used, there would be three different error messages:Would produce the much more helpful errors:Another good reason for this is that paths are a whole lot easier to copy/paste. Imagine:If  is , the error message will be:Which is hard to visually parse and hard to copy/paste into a shell.Whereas, if  is used, the error would be:Easy to visually parse, easy to copy-paste, all around better.I would stop using deprecated methods in 2.6 so your app/script will be ready and easier to convert to python 3.A bad habit I had to train myself out of was using  for inline logic.Unless you can 100% always guarantee that  will be a true value, even when your code changes in 18 months time, you set yourself up for some unexpected behaviour.Thankfully, in later versions you can use .some personal opinions, but I find it best NOT to: (edited : best to --> NOT to of course, duh.)Beautiful is better than ugly.\nExplicit is better than implicit.\nSimple is better than complex.\nComplex is better than complicated.\nFlat is better than nested.\nSparse is better than dense.\nReadability counts.\nSpecial cases aren't special enough to break the rules.\nAlthough practicality beats purity.\nErrors should never pass silently.\nUnless explicitly silenced.\nIn the face of ambiguity, refuse the temptation to guess.\nThere should be one-- and preferably only one --obvious way to do it.\nAlthough that way may not be obvious at first unless you're Dutch.\nNow is better than never.\nAlthough never is often better than  now.\nIf the implementation is hard to explain, it's a bad idea.\nIf the implementation is easy to explain, it may be a good idea.\nNamespaces are one honking great idea -- let's do more of those!  Write ugly code.\nWrite implicit code.\nWrite complex code.\nWrite nested code.\nWrite dense code.\nWrite unreadable code.\nWrite special cases.\nStrive for purity.\nIgnore errors and exceptions.\nWrite optimal code before releasing.\nEvery implementation needs a flowchart.\nDon't use namespaces.  I've started learning Python as well and one of the bigest mistakes I made is constantly using C++/C# indexed \"for\" loop. Python have for(i ; i < length ; i++) type loop and for a good reason - most of the time there are better ways to do there same thing.Example:\nI had a method that iterated over a list and returned the indexes of selected items:Instead Python has list comprehension that solves the same problem in a more elegant and easy to read way:Never assume that having a multi-threaded Python application and a SMP capable machine (for instance one equipped with a multi-core CPU) will give you the benefit of introducing true parallelism into your application. Most likely it will not because of GIL (Global Interpreter Lock) which synchronizes your application on the byte-code interpreter level. There are some workarounds like taking advantage of SMP by putting the concurrent code in  C API calls or using multiple processes (instead of threads) via wrappers (for instance like the one available at ) but if one needs true multi-threading in Python one should look at things like Jython, IronPython etc. (GIL is a feature of the CPython interpreter so other implementations are not affected).According to Python 3000 FAQ (available at Artima) the above still stands even for the latest Python versions.++n and --n may not work as expected by people coming from C/Java background++n is positive of a positive number which is positive =  n--n is negative of a negative number which is positive =  nSomewhat related to the default mutable argument, how one checks for the \"missing\" case results in differences when an empty list is passed:Here's the output:The very first mistake before you even start: Don't be afraid of whitespace.When you show someone a piece of Python code, they are impressed until you tell them that they  to indent correctly. For some reason, most people feel that a language shouldn't force a certain style on them while all of them will indent the code nonetheless.Similar to mutable default arguments is the mutable class attribute.Python won't warn you in any way that on the second assignment you misspelled the variable name and created a new one.You've mentioned default arguments... One that's almost as bad as mutable default arguments: default values which aren't .Consider a function which will cook some food:Because it specifies a default value for , it is impossible for some other function to say \"cook your default breakfast\" without a special-case:However, this could be avoided if  used  as a default value:A good example of this is Django bug . Django's caching module had a \"save to cache\" function which looked like this:But, for the memcached backend, a timeout of  means \"never timeout\"\u2026 Which, as you can see, would be impossible to specify.Don't modify a list while iterating over it.One common suggestion to work around this problem is to iterate over the list in reverse:But even better is to use a list comprehension to build a new list to replace the old:Common pitfall: Default arguments are evaluated once:prints:i.e. you always get the same list.Similar to mutable default arguments is the mutable class attribute.Not what you expect.
Python

I am learning how to use the  and the  modules in Python to run certain operations in parallel and speed up my code.I am finding this hard (maybe because I don't have any theoretical background about it) to understand what the difference is between a  object and a  one.Also, it is not entirely clear to me how to instantiate a queue of jobs and having only 4 (for example) of them running in parallel, while the other wait for resources to free before being executed.I find the examples in the documentation clear, but not very exhaustive; as soon as I try to complicate things a bit, I receive a lot of weird errors (like a method that can't be pickled, and so on).So, when should I use the  and  modules?Can you link me to some resources that explain the concepts behind these two modules and how to use them properly for complex tasks? is true for multithreading vs. multiprocessing .However, Python has an added issue: There's a Global Interpreter Lock that prevents two threads in the same process from running Python code at the same time. This means that if you have 8 cores, and change your code to use 8 threads, it won't be able to use 800% CPU and run 8x faster; it'll use the same 100% CPU and run at the same speed. (In reality, it'll run a little slower, because there's extra overhead from threading, even if you don't have any shared data, but ignore that for now.)There are exceptions to this. If your code's heavy computation doesn't actually happen in Python, but in some library with custom C code that does proper GIL handling, like a numpy app, you will get the expected performance benefit from threading. The same is true if the heavy computation is done by some subprocess that you run and wait on.More importantly, there are cases where this doesn't matter. For example, a network server spends most of its time reading packets off the network, and a GUI app spends most of its time waiting for user events. One reason to use threads in a network server or GUI app is to allow you to do long-running \"background tasks\" without stopping the main thread from continuing to service network packets or GUI events. And that works just fine with Python threads. (In technical terms, this means Python threads give you concurrency, even though they don't give you core-parallelism.)But if you're writing a CPU-bound program in pure Python, using more threads is generally not helpful.Using separate processes has no such problems with the GIL, because each process has its own separate GIL. Of course you still have all the same tradeoffs between threads and processes as in any other languages\u2014it's more difficult and more expensive to share data between processes than between threads, it can be costly to run a huge number of processes or to create and destroy them frequently, etc. But the GIL weighs heavily on the balance toward processes, in a way that isn't true for, say, C or Java. So, you will find yourself using multiprocessing a lot more often in Python than you would in C or Java.Meanwhile, Python's \"batteries included\" philosophy brings some good news: It's very easy to write code that can be switched back and forth between threads and processes with a one-liner change.If you design your code in terms of self-contained \"jobs\" that don't share anything with other jobs (or the main program) except input and output, you can use the  library to write your code around a thread pool like this:You can even get the results of those jobs and pass them on to further jobs, wait for things in order of execution or in order of completion, etc.; read the section on  objects for details.Now, if it turns out that your program is constantly using 100% CPU, and adding more threads just makes it slower, then you're running into the GIL problem, so you need to switch to processes. All you have to do is change that first line:The only real caveat is that your jobs' arguments and return values have to be pickleable (and not take too much time or memory to pickle) to be usable cross-process. Usually this isn't a problem, but sometimes it is.But what if your jobs can't be self-contained? If you can design your code in terms of jobs that  from one to another, it's still pretty easy. You may have to use  or  instead of relying on pools. And you will have to create  or  objects explicitly. (There are plenty of other options\u2014pipes, sockets, files with flocks, \u2026 but the point is, you have to do  manually if the automatic magic of an Executor is insufficient.)But what if you can't even rely on message passing? What if you need two jobs to both mutate the same structure, and see each others' changes? In that case, you will need to do manual synchronization (locks, semaphores, conditions, etc.) and, if you want to use processes, explicit shared-memory objects to boot. This is when multithreading (or multiprocessing) gets difficult. If you can avoid it, great; if you can't, you will need to read more than someone can put into an SO answer.From a comment, you wanted to know what's different between threads and processes in Python. Really, if you read Giulio Franco's answer and mine and all of our links, that should cover everything\u2026\u00a0but a summary would definitely be useful, so here goes:Multiple threads can exist in a single process.\nThe threads that belong to the same process share the same memory area (can read from and write to the very same variables, and can interfere with one another).\nOn the contrary, different processes live in different memory areas, and each of them has its own variables. In order to communicate, processes have to use other channels (files, pipes or sockets).If you want to parallelize a computation, you're probably going to need multithreading, because you probably want the threads to cooperate on the same memory.Speaking about performance, threads are faster to create and manage than processes (because the OS doesn't need to allocate a whole new virtual memory area), and inter-thread communication is usually faster than inter-process communication. But threads are harder to program. Threads can interfere with one another, and can write to each other's memory, but the way this happens is not always obvious (due to several factors, mainly instruction reordering and memory caching), and so you are going to need synchronization primitives to control access to your variables.I believe  answers your question in an elegant way.To be short, if one of your sub-problems has to wait while another finishes, multithreading is good (in I/O heavy operations, for example); by contrast, if your sub-problems could really happen at the same time, multiprocessing is suggested. However, you won't create more processes than your number of cores.Here's some performance data for python 2.6.x that calls to question the  notion that threading is more performant that multiprocessing in IO-bound scenarios. These results are from a 40-processor IBM System x3650 M4 BD.IO-Bound Processing : Process Pool performed better than Thread PoolCPU-Bound Processing : Process Pool performed better than Thread PoolThese aren't rigorous tests, but they tell me that multiprocessing isn't entirely unperformant in comparison to threading.Code used in the interactive python console for the above testsWell, most of the question is answered by Giulio Franco. I will further elaborate on the consumer-producer problem, which I suppose will put you on the right track for your solution to using a multithreaded app.You could read more on the synchronization primitives from:The pseudocode is above. I suppose you should search the producer-consumer-problem to get more references.
Python

I'm following the tutorial on  in a Windows 7 environment. My settings file is:I got the  from  the template  from within the default Django admin template directory in the source code of Django itself (django/contrib/admin/templates) into an admin subdirectory of myapp directory as the tutorial instructed. It doesn't seem to take affect for some reason. Any clue of what might be the problem? Do I have to do a sync db?I know this isn't in the Django tutorial, and shame on them, but it's better to set up relative paths for your path variables. You can set it up like so:This way you can move your Django project and your path roots will update automatically. This is useful when you're setting up your production server.Second, there's something suspect to your TEMPLATE_DIRS path. It should point to the root of your template directory. Also, it should also end in a trailing .I'm just going to guess here that the  directory is not your template root. If you still want to write absolute paths you should take out the reference to the admin template directory.With that being said, the template loaders by default should be set up to recursively traverse into your app directories to locate template files.You shouldn't need to copy over the admin templates unless if you specifically want to overwrite something.You will have to run a syncdb if you haven't run it yet. You'll also need to statically server your media files if you're hosting django through runserver.If using Django settings as installed, then why not just use its baked-in, predefined BASE_DIR and TEMPLATES? In the pip installed Django(v1.8), I get: I also had issues with this part of the tutorial (used tutorial for version 1.7).My mistake was that I only edited the 'Django administration' string, and did not pay enough attention to the manual.This is the line from :But after some time and frustration it became clear that there was the 'site_header or default:_' statement, which should be removed. So after removing the statement (like the example in the manual everything worked like expected).Example manual:For Django 1.6.6:Also static and media for debug and production mode:Into urls.py you must add:In Django 1.8 you can set template paths, backend and other parameters for templates in one dictionary ():
Python

I can do such thing in python:This will check if 'some word' exists in the list. But can I do reverse thing?I have to check whether some words from array are in the string. I can do this using cycle but this way has more lines of code.If your list of words is of substantial length, and you need to do this test many times, it may be worth converting the list to a set and using set intersection to test (with the added benefit that you wil get the actual words that are in both lists):Here are a couple of alternative ways of doing it, that may be faster or more suitable than KennyTM's answer, depending on the context.1) use a regular expression:2) You could use sets if you want to match whole words, e.g. you do not want to find the word \"the\" in the phrase \"them theorems are theoretical\":Of course you can also do whole word matches with regex using the \"\\b\" token.The performance of these and Kenny's solution are going to depend on several factors, such as how long the word list and phrase string are, and how often they change.  If performance is not an issue then go for the simplest, which is probably Kenny's.
Python

I have two times, a start and a stop time, in the format of 10:33:26 (HH:MM:SS).  I need the difference between the two times.  I've been looking through documentation for Python and searching online and I would imagine it would have something to do with the datetime and/or time modules.  I can't get it to work properly and keep finding only how to do this when a date is involved.Ultimately, I need to calculate the averages of multiple time durations. I got the time differences to work and I'm storing them in a list. I now need to calculate the average. I'm using regular expressions to parse out the original times and then doing the differences.  For the averaging, should I convert to seconds and then average?Yes, definitely  is what you need here. Specifically, the  function, which parses a string into a time object.That gets you a  object that contains the difference between the two times. You can do whatever you want with that, e.g. converting it to seconds or adding it to another .This will return a negative result if the end time is earlier than the start time, for example  and . If you want the code to assume the interval crosses midnight in this case (i.e. it should assume the end time is never earlier than the start time), you can add the following lines to the above code:(of course you need to include  somewhere). Thanks to J.F. Sebastian for pointing out this use case.Try this -- it's efficient for timing short-term events.  If something takes more than an hour, then the final display probably will want some friendly formatting.Structure that represent time difference in Python is called . If you have  and  as  types you can calculate the difference using  operator like:you should do this before converting to particualr string format (eg. before start_time.strftime(...)). In case you have already string representation you need to convert it back to time/datetime by using  method.Here's a solution that supports finding the difference even if the end time is less than the start time (over midnight interval) such as  (a half an hour duration): returns a timedelta object that you can pass (as a part of the sequence) to a  function directly e.g.:The  result is also  object that you can convert to seconds ( method (since Python 2.7)), hours ( (Python 3)), etc. site says to try: uses time.mktime()Both  and  have a date component.Normally if you are just dealing with the time part you'd supply a default date. If you are just interested in the difference and know that both times are on the same day then construct a  for each with the day set to today and subtract the start from the stop time to get the interval ().Take a look at the datetime module and the timedelta objects.  You should end up constructing a datetime object for the start and stop times, and when you subtract them, you get a timedelta.I like how this guy does it \u2014 .\nNot sure if it has some cons.But looks neat for me :)Regarding to the question you still need to use  as others said earlier.Try thisOUTPUT :
Python

I'm starting a new application and looking at using an ORM -- in particular, SQLAlchemy.Say I've got a column 'foo' in my database and I want to increment it.  In straight sqlite, this is easy:I figured out the SQLAlchemy SQL-builder equivalent:This is slightly slower, but there's not much in it.Here's my best guess for a SQLAlchemy ORM approach:This does the right thing, but it takes just under fifty times as long as the other two approaches.  I presume that's because it has to bring all the data into memory before it can work with it.Is there any way to generate the efficient SQL using SQLAlchemy's ORM?  Or using any other python ORM?  Or should I just go back to writing the SQL by hand?SQLAlchemy's ORM is meant to be used together with the SQL layer, not hide it. But you do have to keep one or two things in mind when using the ORM and plain SQL in the same transaction. Basically, from one side, ORM data modifications will only hit the database when you flush the changes from your session. From the other side, SQL data manipulation statements don't affect the objects that are in your session.So if you sayit will do what it says, go fetch all the objects from the database, modify all the objects and then when it's time to flush the changes to the database, update the rows one by one.Instead you should do this:This will execute as one query as you would expect, and because atleast the default session configuration expires all data in the session on commit you don't have any stale data issues.In the almost-released 0.5 series you could also use this method for updating:That will basically run the same SQL statement as the previous snippet, but also select the changed rows and expire any stale data in the session. If you know you aren't using any session data after the update you could also add synchronize_session=False to the update statement and get rid of that select.Try this =)There are several ways to UPDATE using sqlalchemyWithough testing, I'd try:(IIRC, commit() works without flush()).I've found that at times doing a large query and then iterating in python can be up to 2 orders of magnitude faster than lots of queries.  I assume that iterating over the query object is less efficient than iterating over a list generated by the all() method of the query object.[Please note comment below - this did not speed things up at all].If it is because of the overhead in terms of creating objects, then it probably can't be sped up at all with SA.If it is because it is loading up related objects, then you might be able to do something with lazy loading.  Are there lots of objects being created due to references?  (IE, getting a Company object also gets all of the related People objects).Here's an example of how to solve the same problem without having to map the fields manually:So to update a Media instance, you can do something like this:
Python

I have generated an image using . How can I save it to a string in memory?\nThe  method requires a file.I'd like to have several such images stored in dictionary.You can probably use the  class to get a wrapper around strings that behaves like a file. The StringIO object provides the same interface as a file, but saves the contents just in memory:This might lead to a  if PIL tries to automatically detect the output format.  To avoid this problem you can specify the format manually:sth's solution didn't work for me\nbecause in ...It was trying to detect the format from the extension in the filename , which doesn't exist in StringIO case  You can bypass the format detection by setting the format yourself in a parameter  save() can take a file-like object as well as a path, so you can use an in-memory buffer like a StringIO:For Python3 it is required to use BytesIO: When you say \"I'd like to have number of such images stored in dictionary\", it's not clear if this is an in-memory structure or not.You don't need to do any of this to meek an image in memory.  Just keep the  object in your dictionary.If you're going to write your dictionary to a file, you might want to look at   method and the  functionThe \"format\" (.jpeg, .png, etc.) only matters on disk when you are exchanging the files.  If you're not exchanging files, format doesn't matter.
Python

When I install PIL using easy_install or buildout it installs in such way, that I must do 'import Image', not 'from PIL import Image'.However, if I do \"apt-get install python-imaging\" or use \"pip -E test_pil install PIL\", all work fine.Here are examples of how I trying to install PIL using virtualenv:I see, that easy_install pack PIL into the Egg, and PIP does not. Same thing with buildbot, it uses eggs.How could I install PIL properly, using easy_install or buildout?The PIL version packaged on pypi (by the author) is incompatible with setuptools and thus not easy_installable. People have created easy_installable versions elsewhere. Currently, you need to specify a find-links URL and use  get a good package:By using  with the  you avoid running the risk of finding the PyPI (non-fixed) original of PIL. If you were to use , you must use a direct link to the source tarball of a corrected version; easy_install stubbornly still uses the PyPI link over the find-links URL:To include PIL in a buildout, either specify the egg with the same version pin or use a versions section:Edit March 2011: Fixes to address the packaging issues have been merged into  now, so this workaround may soon be obsolete.Edit February 2013: Just use  and be done with it. :-) Clearly waiting for the original package to be fixed has not paid off.Use  :-) It offers:If PIL ever does exactly what Pillow does, then the fork will die. Until that happens, we have Pillow.: I am the fork author, and Pillow was created mainly to make my job easier (although it's great to see other folks using it too).: Pillow 2.0.0 was released on March 15, 2013. It offers Python 3 support and many bug fixes/enhancements. While we still attempt to track changes with upstream PIL, (unfortunately or fortunately depending on how you look at it) Pillow has begun to drift away from PIL.For Ubuntu  I found I needed to to install the C headers package for my python version (2.7)Afterwards,  worked. On Windows, I installed PIL in a virtualenv as follows:Install PIL in your global python site-packages by executing the .exe from:\nThen, as a \"do it yourself-er\", copy the PIL.pth file and PIL directory in C:\\Python25\\Lib\\site-packages to your virtualenv site-packages directory.   Yeah, python is still a \"get your hands dirty\" environment...
Python

I have a situation with some code where  came up as a possible solution.  Now I have never had\nto use  before but, I have come across plenty of information about the potential\ndanger it can cause.  That said, I'm very wary about using it.My situation is that I have input being given by a user:Where  needs to be a dictionary.  I searched around and found that  could work this out.\nI thought that I might be able to check the type of the input before trying to use the data and that\nwould be a viable security precaution.I read through the docs and I am still unclear if this would be safe or not.  Does eval evaluate the data as soon as its entered or after the  variable is called?Is the  module's  the only safe option? means that you actually evaluate the code  you deem it to be unsafe or not. It evaluates the code as soon as the function is called. See also . raises an exception if the input isn't a valid Python datatype, so the code won't be executed if it's not.Use  whenever you need . You shouldn't usually evaluate literal Python statements. only considers a small subset of Python's syntax to be valid:Passing  into  will raise an error, but  will happily wipe your drive.Since it looks like you're only letting the user input a plain dictionary, use . It safely does what you want and nothing more.Python's  in its evaluation, so  will evaluate the user's input as soon as it hits the , regardless of what you do with the data afterwards. Therefore, , especially when you  user input.Use .As an example, entering this at the prompt will be very, very bad for you:\nThis is very powerful, but is also very dangerous if you accept strings to evaluate from untrusted input. Suppose the string being evaluated is \"os.system('rm -rf /')\" ? It will really start deleting all the files on your computer.\n\nSafely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, None, bytes and sets.\n
Python

Suppose you have a dictionary like:How would you go about flattening that into something like:Basically the same way you would flatten a nested list, you just have to do the extra work for iterating the dict by key/value, creating new keys for your new dictionary and creating the dictionary at final step.There are two big considerations that the original poster needs to consider:(Performance is not likely an issue, but I'll elaborate on the second point in case anyone else cares: In implementing this, there are numerous dangerous choices. If you do this recursively and yield and re-yield, or  equivalent which touches nodes more than once (which is quite easy to accidentally do), you are doing potentially O(N^2) work rather than O(N). This is because maybe you are calculating a key  then  then ..., and then calculating  then  then ..., but really you shouldn't have to calculate  again. Even if you aren't recalculating it, re-yielding it (a 'level-by-level' approach) is just as bad. A good example is to think about the performance on )Below is a function I wrote  which can be adapted to many purposes and can do what you want. Sadly it is fairly hard to make a lazy version of this function without incurring the above performance penalties (many python builtins like chain.from_iterable aren't actually efficient, which I only realized after extensive testing of three different versions of this code before settling on this one).To better understand what's going on, below is a diagram for those unfamiliar with (left), otherwise known as \"fold left\". Sometimes it is drawn with an initial value in place of k0 (not part of the list, passed into the function). Here,  is our  function. We preprocess each k with .This is in fact the same as , but where our function does this to all key-paths of the tree.Demonstration (which I'd otherwise put in docstring):Performance:... sigh, don't think that one is my fault...[unimportant historical note due to moderation issues]That question's solution can be implemented in terms of this one by doing . The reverse is not possible: while it is true that the  of  can be recovered from the alleged duplicate by mapping a higher-order accumulator, one cannot recover the keys. (edit: Also it turns out that the alleged duplicate owner's question is completely different, in that it only deals with dictionaries exactly 2-level deep, though one of the answers on that page gives a general solution.)Here is a kind of a \"functional\", \"one-liner\" implementation. It is recursive, and based on a conditional expression and a dict comprehension.Test:Code:Results:I am using python3.2, update for your version of python.This is not restricted to dictionaries, but every mapping type. Further ist faster as it avoides an if condition. Nevertheless credits go to Imran:This is similar to both imran's and ralu's answer. It does not use a generator, but instead employs recursion with a closure:Davoud's solution is very nice but doesn't give satisfactory results when the nested dict also contains lists of dicts, but his code be adapted for that case:Here's an algorithm for elegant, in-place replacement. Tested with Python 2.7 and Python 3.5. Using the dot character as a separator.Example:Output:I published this code  along with the matching  function.My Python 3.3 Solution using generators:Using generators:The answers above work really well. Just thought I'd add the unflatten function that I wrote:Note: This doesn't account for '_' already present in keys, much like the flatten counterparts.Or if you are already using pandas, You can do it with  like so:Output:If you don't want  separator, you can hack it like so:Output:How about a  and performant solution in Python3?In use:I tried to flatten following json:The best option to flatten that file, with . as seperation mark was this one: \nIt only left out the \"pids_stats\": {}, option:In terms of unflattening the file, with . as option, I choose  - because it worked recursively and perfectly. Note that \"pids_stats\": {} is missing as it was lost in the previous step.Simple function to flatten nested dictionaries:The idea/requirement was:\nGet flat dictionaries with no keeping parent keys.Example of usage:Keeping parent keys is simple as well.
Python

I receive as input a list of strings and need to return a list with these same strings but in randomized order. I must allow for duplicates - same string may appear once or more in the input and must appear the same number of times in the output.I see several \"brute force\" ways of doing that (using loops, god forbid), one of which I'm currently using. However, knowing Python there's probably a cool one-liner do get the job done, right?Looks like this is the simplest way, if not the most truly random ( more fully explains the limitations): Given a string , here is a one-liner:  You'll have to read the strings into an array and then use a shuffling algorithm. I recommend 
Python

I'm building an admin for Flask and SQLAlchemy, and I want to pass the HTML for the different inputs to my view using . The templating framework seems to escape the html automatically, so all <\"'> are converted to html entities. How can I disable that so that the HTML renders correctly?the ideal way is tothan completely turning off auto escaping. You can also declare it HTML safe from the code:Then pass that value to the templates and they don't have to  it.Example Check this In the secction HTML Escaping
Python

I have a simple line plot and need to move the y-axis ticks from the (default) left side of the plot to the right side. Any thoughts on how to do this?Use for example:For right labels use , i.e.:joaquin's answer works, but has the side effect of removing ticks from the left side of the axes. To fix this, follow up  with a call to . A revised example:The result is a plot with ticks on both sides, but tick labels on the right.Just is case somebody asks (like I did), this is also possible when one uses subplot2grid. For example:It will show this:
Python

In my django app, I need to get the domain name from the referer in  along with its protocol so that from URLs like:I should get:I looked over other related questions and found about urlparse, but that didn't do the trick sinceBesides I didn't find a way to get the protocol and maybe do a simple concatenation :\\Thanks in advance for any helpYou should be able to do it with:UPDATE:Python docs on urlparse (, ) are also quite good, so you may want to check them out :)EDIT:Incorporated a cleaner way of formatting the  string as suggested by @J.F.Sebastian (thanks!)This is a more verbose version of urlparse.  It detects domains and subdomains for you.From their documentation: is a namedtuple, so it's simple to access the parts you want.Pure string operations :):That's all, folks.Is there anything wrong with pure string operations:If you prefer having a trailing slash appended, extend this script a bit like so:That can probably be optimized a bit ...This is a bit obtuse, but uses  in both directions:that odd  bit is because urlparse expects a sequence of   = 6
Python

I need to insert multiple rows with one query (number of rows is not constant), so I need to execute query like this one:The only way I know isbut I want some simpler way.I built a program that inserts multiple lines to a server that was located in another city.  I found out that using this method was about 10 times faster than . In my case  is a tuple containing about 2000 rows. It took about 10 seconds when using this method:and 2 minutes when using this method:New  in Psycopg 2.7:The pythonic way of doing it in Psycopg 2.6:Explanation: If the data to be inserted is given as a list of tuples like inthen it is already in the exact required format as The only necessary work is to provide a records list template to be filled by psycopgand place it in the  queryPrinting the  outputsNow to the usual  arguments substitutionOr just testing what will be sent to the serverOutput:A snippet from Psycopg2's tutorial page at :It doesn't save much code, but it definitively looks better. is the fastest solution I've found for bulk inserts by far.  I made containing a class named IteratorFile which allows an iterator yielding strings to be read like a file. We can convert each input record to a string using a generator expression. So the solution would beFor this trivial size of args it won't make much of a speed difference, but I see big speedups when dealing with thousands+ of rows. It will also be more memory efficient than building a giant query string. An iterator would only ever hold one input record in memory at a time, where at some point you'll run out of memory in your Python process or in Postgres by building the query string.All of these techniques are called 'Extended Inserts\" in Postgres terminology, and as of the 24th of November 2016, it's still a ton faster than psychopg2's executemany() and all the other methods listed in this thread (which i tried before coming to this answer).Here's some code which doesnt use cur.mogrify and is nice and simply to get your head around:But it should be noted that if you can use copy_from(), you should use copy_from ;)[Update with psycopg2 2.7]The classic  is about 60 times slower than @ant32 's implementation (called \"folded\") as explained in this thread: This implementation was added to psycopg2 in version 2.7 and is called :[Previous Answer]To insert multiple rows, using the multirow  syntax with  is about 10x faster than using psycopg2 . Indeed,  just runs many individual  statements.@ant32 's code works perfectly in Python 2. But in Python 3,  returns bytes,  takes either bytes or strings, and  expects  instance.So in Python 3 you may need to modify @ant32 's code, by adding :Or by using bytes (with  or ) only:   - The snippet below works perfectly fineAnother nice and efficient approach - is to pass rows for insertion as 1 argument, \nwhich is array of json objects.E.g. you passing argument:It is array, which may contain any amount of objects inside.\nThen your SQL looks like:Notice: Your postgress must be new enough, to support jsonIf you're using SQLAlchemy, you don't need to mess with hand-crafting the string because SQLAlchemy :If you want to insert multiple rows within one insert statemens (assuming you are not using ORM) the easiest way so far for me would be to use list of dictionaries. Here is an example:As you can see only one query will be executed:
Python

Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2.5. shows you can do it with  and  modules without too much extra effort.  I added a little to the article as follows:This outputs:If you just want a single function that takes strings it would look like this:I like to use  for that:As arno_v pointed out in the comments, new version of netaddr does it like this:Using  (, ):If you want to evaluate a  of IP addresses this way, you'll probably want to calculate the netmask upfront, likeThen, for each address, calculate the binary representation with one ofFinally, you can simply check:This code is working for me on Linux x86.  I haven't really given any thought to endianess issues, but I have tested it against the \"ipaddr\" module using over 200K IP addresses tested against 8 different network strings, and the results of ipaddr are the same as this code.Example:I tried Dave Webb's solution but hit some problems:Most fundamentally - a match should be checked by ANDing the IP address with the mask, then checking the result matched the Network address exactly. Not ANDing the IP address with the Network address as was done.I also noticed that just ignoring the Endian behaviour assuming that consistency will save you will only work for masks on octet boundaries (/24, /16). In order to get other masks (/23, /21) working correctly I added a \"greater than\" to the struct commands and changed the code for creating the binary mask to start with all \"1\" and shift left by (32-mask). Finally, I added a simple check that the network address is valid for the mask and just print a warning if it is not.Here's the result:I'm not a fan of using modules when they are not needed.  This job only requires simple math, so here is my simple function to do the job:Then to use it:That's it, this is much faster than the solutions above with the included modules.The accepted answer doesn't work ... which is making me angry. Mask is backwards and doesn't work with any bits that are not a simple 8 bit block (eg /24). I adapted the answer, and it works nicely.here is a function that returns a dotted binary string to help visualize the masking.. kind of like  output.eg:Marc's code is nearly correct. A complete version of the code is -Obviously from the same sources as above...A very Important note is that the first code has a small glitch - The IP address 255.255.255.255 also shows up as a Valid IP for any subnet. I had a heck of time getting this code to work and thanks to Marc for the correct answer.Not in the Standard library for 2.5, but ipaddr makes this very easy. I believe it is in 3.3 under the name ipaddress. Here is the usage for this method:Basically you provide an ip address as the first argument and a list of cidrs as the second argument.  A list of hits are returned.Here is a class I wrote for longest prefix matching:And here is a test program:I don't know of anything in the standard library, but  is a Python library that will do subnet matching.Thank you for your script!\nI have work quite a long on it to make everything working... So I'm sharing it hereSo my new addressInNetwork function looks-like:And now, answer is right!!I hope that it will help other people, saving time for them!Relating to all of the above, I think socket.inet_aton() returns bytes in network order, so the correct way to unpack them is probablybugfixed code:The choosen answer has a bug.Following is the correct code:Note:  instead of . I also replace  with , as the latter seems more understandable.There is an API that's called SubnetTree available in python that do this job very well. \nThis is a simple example : $ python check-subnet.py\nFalse\nTrue\nFalseFrom various sources above, and from my own research, this is how I got subnet and address calculation working.  These pieces are enough to solve the question and other related questions.Here is my code
Python

Is there any rule about which built-in and standard library classes are not subclassable (\"final\")?As of Python 3.3, here are a few examples:I found a  which deals with the implementation of \"final\" classes, both in C and pure Python.I would like to understand what reasons may explain why a class is chosen to be \"final\" in the first place. There seems to be two reasons for a class to be \"final\" in Python.Classes that follow Singleton pattern have an invariant that there's a limited (pre-determined) number of instances. Any violation of this invariant in a subclass will be inconsistent with the class' intent, and would not work correctly. Examples:There may be cases other than the Singleton pattern in this category but I'm not aware of any.A class implemented in C requires additional work to allow subclassing (at least in CPython). Doing such work without a convincing use case is not very attractive, so volunteers are less likely to come forward. Examples:Note 1: I originally thought there were valid use cases, but simply insufficient interest, in subclassing of  and . Thanks to @agf for pointing out that the use cases offered  and  are not convincing (see @agf comments to the question).Note 2:My concern is that another Python implementation might accidentally allow subclassing a class that's final in CPython. This may result in non-portable code (a use case may be weak, but someone might still write code that subclasses  if their Python supports it). This can be resolved by marking in Python documentation all built-in and standard library classes that cannot be subclassed, and requiring that all implementations follow CPython behavior in that respect.Note 3:The message produced by CPython in all the above cases is:It is quite cryptic, as numerous questions on this subject show. I'll submit a suggestion to add a paragraph to the documentation that explains final classes, and maybe even change the error message to:
Python

I'm used to bringing data in and out of Python using .csv files, but there are obvious challenges to this.  Any advice on simple ways to store a dictionary (or sets of dictionaries) in a json or pck file?  For example:I would like to know both how to save this, and then how to load it back in.Supply extra arguments like  or  to get a pretty result. The argument  will sort the keys alphabetically and  will indent your data structure with  spaces.Minimal example, writing directly to a file:or safely opening / closing:If you want to save it in a string instead of a file:If you're after serialization but won't need the data in other programs I strongly recommend the  module.  Think of it as a persistent dictionary.Also see the speeded-up package ujson.\nIf you want an alternative to  or , you can use .With , if you had used , the dictionary would have been written to  as a pickled dictionary instead of with clear text.You can get  here:  is probably a better choice for pickling then  itself, as  can serialize almost anything in python.   also can use .You can get  here: The additional mumbo-jumbo on the first few lines are because  can be configured to store dictionaries to a file, to a directory context, or to a SQL database.  The API is the same for whatever you choose as the backend archive.  It gives you an \"archivable\" dictionary with which you can use  and  to interact with the archive.To write to a file:To read from a file: is the file object for the file that you stored the dict in.
Python

I am using the following command to run a python script in the background:But it appears that nohup is not writing anything to the log file. cmd.log is created but is always empty. In the python script, I am using  instead of  to print to standard output. Am I doing anything wrong?It looks like you need to flush stdout periodically (e.g. ). In my testing Python doesn't automatically do this even with  until the program exits.You can run Python with the  flag to avoid output buffering:or
Python

How do you find the median of a list in Python? The list can be of any size and the numbers are not guaranteed to be in any particular order.If the list contains an even number of elements, the function should return the average of the middle two.Here are some examples (sorted for display purposes):Python 3.4 has :Usage:It's pretty careful with types, too:Use  to make a one-line function:This runs as:Or, to :Which runs as:The sorted() function is very helpful for this. Use the sorted function\nto order the list, then simply return the middle value (or average the two middle\nvalues if the list contains an even amount of elements).Here's a cleaner solution:Note: Answer changed to incorporate suggestion in comments.You can try the  algorithm if faster average-case running times are needed. Quickselect has average (and best) case performance , although it can end up  on a bad day.Here's an implementation with a randomly chosen pivot:You can trivially turn this into a method to find medians:This is very unoptimised, but it's not likely that even an optimised version will outperform Tim Sort (CPython's built-in ) because that's . I've tried before and I lost.You can use the  to avoid creating new lists with  and sort the lists in place.Also you should not use  as a variable name as it shadows  python's own .Here what I came up with during this exercise in Codecademy:I defined a median function for a list of numbers asI posted my solution at  , which is a little bit faster than using sort().  My solution uses 15 numbers per column, for a speed ~5N which is faster than the speed ~10N of using 5 numbers per column.  The optimal speed is ~4N, but I could be wrong about it.Per Tom's request in his comment, I added my code here, for reference.  I believe the critical part for speed is using 15 numbers per column, instead of 5.I had some problems with lists of float values. I ended up using a code snippet from the python3  and is working perfect with float values without imports. Here's the tedious way to find median without using the  function: 
Python

I have a small Django project I received from a friend. The code works perfectly on his system. However, on my system I get the following error message when running the server:The problem is with a line in an html file:This exact same code works on his system with no errors. What could that be?I would suggest the following:If everything else fails, check this link:\nI had this problem and fixed it by adding a blank  file in my appname/templatetags/ directory.Possibilities are many: has solved the issue for me. They must have mentioned it in the documentation.suppose you have the following structure:-- Application_Name-------templatetags--------------.py--------------templates_extras.py-------.py-------settings.py-- manage.pyYou have to make sure of the following:\"custom tags\" is not a valid tag library error, more often is occurred because the custom tags are not loaded into the app.place an empty .py inside the same folder where your \"custom template tag\" is placed and run the below code on the terminal to load the custom template tagsI was getting the same error but for a different reason so I'll tell you (in case someone else comes the same problem).I had everything right but I had my custom tag inside a folder named  and after a long search I found out that it had to be , and now it works. So .Please ensure your templatetags folder is initialized with python, if you are in doubt, just take bakup of all files,Remove all files,\nInside templatetags folder create .py file only,\nthen restart your server,Now your folder is under Python, then do your stuff.This works for me...Make sure the  statement is correct. It should be the name of the file, not the name of the app. For instance, if you have this app:Then you should put this in your template:Of course, you should check the other answers too.After you have created the template tag and it should be within the 'templatetags' package within an app installed in the settings.INSTALLED_APPS, make sure you restart your dev-server.For me, it was the mistake of putting quotes around the library name in  tag.WRONG: CORRECT: Refer to other answers too. I solved a couple of those problems too before landing here.All of the advice listed here didn't help me. So in my specific case the problem was that the templatetag had to be loaded from a third-party app, and I manually copied source folder with that app into  folder in my virtualenv. Then I ran  inside that folder. After that django could not load this module. Then I removed the source and installed folder of this app and installed it using  after adding a relevant line into  file. It was downloaded into the  folder, installed and everything began working properly. Hope this helps someone.Maybe someone will find this useful: somehow I had named the directory  instead of , that is -- with a space at the end. Took hours to finally realize.
Python

Ok, Tornado is non-blocking and quite fast and it can handle a lot of standing requests easily.But I guess it's not a silver bullet and if we just blindly run Django-based or any other site with Tornado it won't give any performance boost.I couldn't find comprehensive explanation of this, so I'm asking it here:This distinction is a bit blurry. Only if you are serving static pages, you would use one of the fast server like lighthttpd. Other wise, most servers provides a varying complexity of framework to develop web applications. Tornado is a good web framework. Twisted is even more capable and is considered a good networking framework. It has support for lot of protocols. Tornado and Twisted are frameworks that provide support non-blocking, asynchronous web / networking application development. By it's very nature, Async / Non-Blocking I/O works great when it is I/O intensive and not computation intensive. Most web / networking applications suits well for this model. If your application demands certain computational intensive task to be done then it has to be delegated to some other service that can handle it better. While Tornado / Twisted can do the job of web server, responding to web requests.Performance is usually a characteristic of complete web application architecture. You can bring down the performance with most web frameworks, if the application is not designed properly. Think about caching, load balancing etc. Tornado and Twisted provides reasonable performance and is good for building a very performant web application. You can check out the testimonials for both twisted and tornado to see what they are capable of. I'm sorry for answering an old question, but I came across this one and wondered why it didn't have more answers. To answer Bart J's question:Well that depends on what kind of parsing you're doing and on what hardware :) Long time is long time, so if your app takes more than say half a second to respond, it'll seem sluggish -  profile your app.The key to fast systems is great architecture, not so much the specifics as for instance which framework you're using (Twisted, Tornado, Apache+PHP). Tornado has an asynchronous processing style and that's really what a lot of it comes down to in my opinion. Node.js, Twisted and Yaws are examples of other asynchronous web servers that scale very well because of a lightweight approach and asynchronous processing style.So:Tornado is good for handling a lot of connections, since it can respond to an incoming client, dispatch a request handler and don't think about that client until the result-callback is pushed on the event queue. So for that specific quality Tornado should be used when you want to scale well when handling a lot of requests. \nThe async processing facilitates functional decoupling and shared-nothing data access. That swings really well with stateless design like  or other s. You also don't have to deal with spawning threads or processes with the inherent overhead so much and you can save some of the locking/IPC trouble.Tornado won't make much of a difference, on the other hand, if your backend and/or data store takes a long time to process the requests. It helps doing concurrent designs and Web services in particular. The concurrent architecture makes it easier to scale your design and keep the coupling low. That's my experience with Tornado at least. 
Python

OK I love Python's  function. Use it all the time, it's brilliant. Every now and again I want to do the opposite of , think \"I used to know how to do that\", then google python unzip, then remember that one uses this magical  to unzip a zipped list of tuples. Like this:What on earth is going on? What is that magical asterisk doing? Where else can it be applied and what other amazing awesome things in Python are so mysterious and hard to google?The asterisk in Python is documented in the Python tutorial, under .The asterisk performs  (as it's known in Lisp and Scheme). Basically, it takes your list, and calls the function with that list's contents as arguments.It's also useful for multiple args:And, you can use double asterisk for keyword arguments and dictionaries:And of course, you can combine these:Pretty neat and useful stuff.It doesn't always work:Oops! I think it needs a skull to scare it into working:In python3 I think you needsince zip now returns a generator function which is not False-y.I'm extremely new to Python so this just recently tripped me up, but it had to do more with how the example was presented and what was emphasized.What gave me problems with understanding the zip example was the asymmetry in the handling of the zip call return value(s). That is, when zip is called the first time, the return value is assigned to a single variable, thereby creating a list reference (containing the created tuple list). In the second call, it's leveraging Python's ability to automatically unpack a list (or collection?) return value into multiple variable references, each reference being the individual tuple. If someone isn't familiar with how that works in Python, it makes it easier to get lost as to what's actually happening.Addendum to @bcherry's answer:So it works not just with keyword arguments (in ), but with named arguments too (aka  arguments).
Python

I'm using Vim and editing Python scripts.Autoindent works pretty well in general, but when I start a new line and type '#' to type a comment, Vim unindents that line for me. For example, if haveand I press enter, Vim will indent properlybut, if instead of typing , I type , it unindents automaticallymy .vimrc file follows.  anyone know why this is happening?Setting  on makes Vim behave like you describe for me, whereas with  (which is what I tend to use) it behaves like you'd prefer it to.Update: From the docs on :That seems to be it.Update: Probably no need to bother with the following... I'll leave it here for the added informational value. ;-)If setting  doesn't help, perhaps you could use the  command -- with no parameters -- to obtain the list of all settings in effect in your Vim session, then paste it somewhere (on  perhaps). There's a few other options which affect automatic indentation, as far as I remember.While Micha\u0142's post explains what smartindent does, you can do a lot better than just turning it off. You could configure it more to your liking, or better yet, let Vim pick better indentation for you. With the following in your vimrc instead of other indent settings:Vim will automatically use the proper indent plugin for python. This is way better than just not de-indenting a # line - pretty much everything should be properly indented.You can try an option only for python files:For some unkown reason the above behavior was caused when i had  on. Turning it off fixed it for me. None of the other fixes above helped.If you install this script, you will get  python (pep8) indenting:
Python

I've installed Anaconda and created two extra environments: py3k (which holds Python 3.3) and py34 (which holds Python 3.4). Besides those, I have a default environment named 'root' which the Anaconda installer created by default and which holds Python 2.7. This last one is the default, whenever I launch 'ipython' from the terminal it gives me version 2.7. In order to work with Python 3.4, I need to issue the commands (in the shell)which change the default environment to Python 3.4. This works fine, but it's annoying since most of the time I work on Python 3.4, instead of Python 2.7 (which I hold for teaching purposes, it's a rather long story). Anyway, I'll like to know how to change the default environment to Python 3.4, bearing in mind that I don't want to reinstall everything from scratch.  First, make sure you have the latest version of conda by runningThen runThis will attempt to update all your packages in your root environment to Python 3 versions. If it is not possible (e.g., because some package is not built for Python 3), it will give you an error message indicating which package(s) caused the issue.If you installed packages with pip, you'll have to reinstall them. Under Linux there is an easier way to set the default environment by modifying  or \nAt the end you'll find something likeReplace it with and thats all there is to it.\nSome people have multiple Anaconda environments with different versions of python for compatibility reasons.  In this case, you should have a script that sets your default environment.  With this method you can preserve the versions of python you use in your environments.The following assumes  is the name of your environment  \nEdit your bash profile so that the last line is \"source activate \".  In Mac OSX this is ~/.bash_profile, in other environments this may be ~/.bashrc \nHere's how i did it on Mac OSXThe result shows that i'm using my p3.5 environment by default.\nCreate a command file (.cmd) with \"activate \" and follow these instructions to have it execute whenever you open a command promptfrom this answer: I wasn't satisfied with any of the answers presented here, since activating an environment takes a few seconds on my platform (for whatever reason)I modified my path variable so that the environment I want as default has priority over the actual default. In my case I used the following commands to accomplish that for the environment \"py35\":to find out where your environment is stored, activate it and enter .\nI'm not sure yet if this approach has any downsides. Since it also changes the default path of the conda executable. If that should be the case, please comment.
Python

In numpy one can use the 'newaxis' object in the slicing syntax to create an axis of length one, e.g.:The  that one can also use  instead of , the effect is exactly the same.Is there any reason to choose one over the other? Is there any general preference or style guide? My impression is that  is more popular, probably because it is more explicit. So is there any reason why  is allowed? is allowed because  is merely an alias for .The authors probably chose it because they needed a convenient constant, and  was available.As for why you should prefer  over : mainly it's because it's more explicit, and partly because someday the  authors might change it to something other than .  (They're not planning to, and probably won't, but there's no good reason to prefer .)
Python

Consider the following code:From , how do I call ? I would normally use  or even the base class name directly if this is a normal object method, but apparently I can't find a way to call the classmethod in the base class. In the above example,  prints  class instead of  class.: Oh, wait a minute... it's not clear exactly what you're asking. This is how you would invoke the code in the base class's version of the method, from the derived class.this has been a while, but I think I may have found an answer. When you decorate a method to become a classmethod the original unbound method is stored in a property named 'im_func':This works for me:
Python

Sorry for the simple question, but I'm having a hard time finding the answer.When I compare 2 lists, I want to know if they are \"equal\" in that they have the same contents, but in different order.Ex:I want  to evaluate to .You can simply check whether the multisets with the elements of x and y are equal:This requires the elements to be hashable; runtime will be in , where  is the size of the lists.If the elements are also unique, you can also convert to sets (same asymptotic runtime, may be a little bit faster in practice):If the elements are not hashable, but sortable, another alternative (runtime in ) isIf the elements are neither hashable nor sortable you can use the following helper function. Note that it will be quite slow () and should generally  be used outside of the esoteric case of unhashable and unsortable elements.Inferring from your example:that the elements of the lists won't be repeated (they are unique) as well as hashable (which strings and other certain immutable python objects are),  uses Python's builtin sets, (which are semantically like mathematical sets you may have learned about in school). In the case that the elements are hashable, but non-unique, the  also works semantically as a multiset, but :Prefer to use :if the elements are orderable. This would account for non-unique or non-hashable circumstances, but this could be much slower than using sets.An empirical experiment concludes that one should prefer , then . Only opt for  if you need other things like counts or further usage as a multiset.First setup:And testing:So we see that comparing sets is the fastest solution, and comparing sorted lists is second fastest.This seems to work, though possibly cumbersome for large lists.However, if each list  contain all the elements of other then the above code is problematic. The problem arises when  and, in this example, . To avoid this, you can add one more statement.One more thing, I benchmarked my solution with timeit.repeat, under the same conditions used by Aaron Hall in his post. As suspected, the results are disappointing. My method is the last one.  it is.As mentioned in comments above, the general case is a pain. It is fairly easy if all items are hashable or all items are sortable. However I have recently had to try solve the general case. Here is my solution. I realised after posting that this is a duplicate to a solution above that I missed on the first pass. Anyway, if you use slices rather than list.remove() you can compare immutable sequences.
Python

I just discovered a logical bug in my code which was causing all sorts of problems. I was inadvertently doing a  instead of a .I changed the code from:TO:To my surprise, I got the rather cryptic error message:Why was a similar error not emitted when I use a bitwise operation - and how do I fix this? is a numpy (rec)array. So  is also a (boolean)\narray. For numpy arrays the  operation returns the bitwise-and of the two\nboolean arrays.The NumPy developers felt there was no one commonly understood way to evaluate\nan array in boolean context: it could mean  if  element is\n, or it could mean  if  elements are , or  if the array has non-zero length, just to name three possibilities.Since different users might have different needs and different assumptions, the\nNumPy developers refused to guess and instead decided to raise a ValueError\nwhenever one tries to evaluate an array in boolean context. Applying  to\ntwo numpy arrays causes the two arrays to be evaluated in boolean context (by\ncalling  in Python3 or  in Python2).Your original code looks correct. However, if you do want , then instead of  use  or .I had the same problem (i.e. indexing with multi-conditions, here it's finding data in a certain date range). The  or  seem not working, at least for me. Alternatively I found another solution which works perfectly for my desired functionality ).Instead of using suggested code above, simply using a  would work. Here you may want to rewrite the code as The reason for the exception is that  implicitly calls . First on the left operand and (if the left operand is ) then on the right operand. So  is equivalent to . However the  on a  (if it contains more than one element) will throw the exception you have seen:The  call is implicit in , but also in , , , so any of the following examples will also fail:There are more functions and statements in Python that hide  calls, for example  is just another way of writing . And the  will call : .The  equivalent for  would be the  function, similarly you could use  as equivalent for . For boolean arrays - and comparisons like , , , ,  and  on NumPy arrays return boolean NumPy arrays - you can also use the  functions (and operators):  ( operator)and  ( operator):A complete list of logical and binary functions can be found in the NumPy documentation:
Python

I'm having trouble understanding the purpose of 'distributed task queues'. For example, python's . I know that in celery, the python framework, you can set timed windows for functions to get executed. However, that can also be easily done in a linux crontab directed at a python script. And as far as I know, and shown from my own django-celery webapps, celery consumes much more RAM memory than just setting up a raw crontab. Few hundred MB difference for a relatively small app.Can someone please help me with this distinction? Perhaps a high level explanation of how task queues / crontabs work in general would be nice also.Thank you.It depends what you want your tasks to be doing, if you need to distribute them, and how you want to manage them.A crontab is capable of executing a script every N intervals. It runs, and then returns. Essentially you get a single execution each interval. You could just direct a crontab to execute a django management command and get access to the entire django environment, so celery doesn't really help you there.What celery brings to the table, with the help of a message queue, is distributed tasks. Many servers can join the pool of workers and each receive a work item without fear of double handling. It's also possible to execute a task as soon as it is ready. With cron, you're limited to a minimum of one minute.As an example, imagine you've just launched a new web application and you're receiving hundreds of sign ups that require an email to be sent to each user. Sending an email may take a long time (comparatively) so you decide that you'll handle activation emails via tasks.If you were using cron, you'd need to ensure that every minute cron is able to process all of the emails that need to be sent. If you have several servers you now need to make sure that you aren't sending multiple activation emails to the same user - you need some kind of synchronization.With celery, you add a task to the queue. You may have several workers per server so you've already scaled ahead of a cronjob. You may also have several servers allowing you to scale even more. Synchronization is handled as part of the 'queue'.You  use celery as a cron replacement but that's not really its primary use. It is used for farming out asynchronous tasks across a distributed cluster.And of course, celery has a  that cron does not.
Python

Recently began branching out from my safe place (R) into Python and and am a bit confused by the cell localization/selection in . I've read the documentation but I'm struggling to understand the practical implications of the various localization/selection options. Is there a reason why I should ever use  or  over the most general option ? I understand that , , , and  may provide some guaranteed correctness that  can't offer, but I've also read where  tends to be the fastest solution across the board. Can someone please explain the real world, best practices reasoning behind utilizing anything other than ? only work on index\n work on position\n You can get data from dataframe without it being in the index\n get scalar values. It's a very fast loc\n Get scalar values. It's a very fast ilocUpdated for   given that  is deprecated.  This demonstrates not only how to use , , , , , but how to accomplish, mixed positional/label based indexing. - \nAllows you to pass 1-D arrays as indexers.  Arrays can be either slices (subsets) of the index or column, or they can be boolean arrays which are equal in length to the index or columns.   when a scalar indexer is passed,  can assign a new index or column value that didn't exist before. - \nSimilar to  except with positions rather that index values.  However, you  assign new columns or indices. - \nWorks very similar to  for scalar indexers.   operate on array indexers.   assign new indices and columns.   over  is that this is faster.\n is that you can't use arrays for indexers. - \nWorks similarly to .   work in array indexers.   assign new indices and columns. over  is that this is faster.\n is that you can't use arrays for indexers. - \nWorks very similar to  for scalar indexers.   operate on array indexers.   assign new indices and columns Super fast, because there is very little overhead!\n There is very little overhead because  is not doing a bunch of safety checks.  .  Also, this is not intended for public use. - \nWorks similarly to .   work in array indexers.   assign new indices and columns. Super fast, because there is very little overhead!\n There is very little overhead because  is not doing a bunch of safety checks.  .  Also, this is not intended for public use.
Python

I have encountered this weird behavior and failed to explain it. These are the benchmarks:How come comparison with variable assignment is faster than using a one liner with temporary variables by more than 27%?By the Python docs, garbage collection is disabled during timeit so it can't be that. Is it some sort of an optimization?The results may also be reproduced in Python 2.x though to lesser extent.Running Windows 7, CPython 3.5.1, Intel i7 3.40 GHz, 64 bit both OS and Python. Seems like a different machine I've tried running at Intel i7 3.60 GHz with Python 3.5.0 does not reproduce the results.Running using the same Python process with  @ 10000 loops produced 0.703 and 0.804 respectively. Still shows although to lesser extent. (~12.5%)My results were similar to yours: the code using variables was pretty consistently 10-20 % faster. However when I used IPython on the very same Python 3.4, I got these results:Notably, I never managed to get even close to the 74.2 \u00b5s for the former when I used  from the command line.So I decided to run the command with  and indeed there is something fishy going on:Now that is a good reason for the difference. The code that does not use variables causes the  system call be called almost 1000x more than the one that uses intermediate variables.The  is full of / for a 256k region; these same lines are repeated over and over again:The  call seems to be coming from the function  from ; the  also contains the macro , which is d to be  (that is ); similarly the  matches the  from . says thatThus these heuristics and the fact that Python object allocator releases these free arenas as soon as they're emptied lead to  triggering pathological behaviour where one 256 kiB memory area is re-allocated and released repeatedly; and this allocation happens with /, which is comparatively costly as they're system calls - furthermore,  with  requires that the newly mapped pages must be zeroed - even though Python wouldn't care.The behaviour does not seem to be present with the code that uses an intermediate variable, possibly because it is using slightly  memory and never actually freeing all the objects from the last memory arena. Most notably it cannot be guaranteed that the code using intermediate variables is always faster - indeed in some setups it might be that using intermediate variables will result in extra  calls, whereas the code that compares return values directly might be fine.The first question here has to be, is it reproducable? For some of us at least it definitely is though other people say they aren't seeing the effect.\nThis on Fedora, with the equality test changed to  as actually doing a comparison seems irrelevant to the result, and the range pushed up to 200,000 as that seems to maximise the effect:I note that variations between the runs, and the order in which the expressions are run make very little difference to the result.Adding assignments to  and  into the slow version doesn't speed it up. In fact as we might expect assigning to local variables has negligible effect. The only thing that does speed it up is splitting the expression entirely in two. The only difference this should be making is that it reduces the maximum stack depth used by Python while evaluating the expression (from 4 to 3).That gives us the clue that the effect is related to stack depth, perhaps the extra level pushes the stack across into another memory page. If so we should see that making other changes that affect the stack will change (most likely kill the effect), and in fact that is what we see:So, I think the effect is entirely due to how much Python stack is consumed during the timing process. It is still weird though.
Python

I want to send a POST request, but one of the fields should be a list of numbers. How can I do that ? (JSON?)If your server is expecting the POST request to be json, then you would need to add a header, and also serialize the data for your request...If you don't specify the header, it will be the default  type.I recommend using the incredible  module.for python 3.4.2 I found the following will work:You have to add header,or you will get http 400 error.\nThe code works well on python2.6,centos5.4code:This works perfect for Python Version 3.5, If the URL contains Query String / Parameter value,Request URL = Parameter value = 21f6bb43-98a1-419d-8f0c-8133669e40ca
Python

I'm trying to install pycurl via:It downloaded fine, but when when it runs setup.py I get the following traceback:Any idea why this is happening and how to get around it On Debian I needed the following package to fix this.Similarly with  package managerin my case this fixed the problem:as explained I encountered the same problem whilst trying to get Shinken 2.0.3 to fire up on Ubuntu. Eventually I did a full uninstall then reinstalled Shinken with . As it cleaned up, it mentioned:Installed that with , and all the brokers fired up as expected :-)That solved my problem on Ubuntu 14.04:On OpenSUSE:
Python

I'm running a set of tests with py.test. They pass. Yippie! But I'm getting this message:How should I go about tracking down the source of that? (I'm not using threading directly, but am using gevent.)I observed a similar issue and decided to see what's going on exactly - let me describe my findings. I hope someone will find it useful.It is indeed related to monkey-patching the  module. In fact, I can easily trigger the exception by importing the threading module before monkey-patching threads. The following 2 lines are enough:When executed it spits the message about ignored :If you swap the import lines, the problem is gone. I could stop my debugging here, but I decided it's worth to understand the exact cause of the problem.First step was to find the code that prints the message about ignored exception. It was a little hard for me to find it (grepping for  yielded nothing), but grepping around CPython source code I've eventually found a function called  in , with a very interesting comment:I decided to check who's calling it, with a little help from , just to get the following C-level stack trace:Now we can clearly see that the exception is thrown while  executes - this call is responsible for shutting down the Python interpreter, freeing allocated memory, etc. It's called just before exitting.Next step was to look at  code (it's in ). The very first call it makes is  - worth looking at, as we know the problem is related to threading. This function in turn calls  callable in the  module. Good, we can go back to python code now. Looking at  I've found the following interesting parts:Clearly, the responsibility of  call is to join all non-daemon threads and delete main thread (whatever that means exactly). I decided to patch  a bit - wrap the whole  body with / and print the stack trace with  module. This gave the following trace:Now we know the exact place where the exception is thrown - inside  method. The rest of the story is obvious after reading  for a while. The  dictionary maps thread IDs (as returned by ) to  instances, for all threads created. When  module is loaded, an instance of  class is always created and added to  (even if no other threads are explicitly created). The problem is that one of the methods patched by 's monkey-patching is  - original one maps to , monkey-patching replaces it with . Obviously both calls return different IDs for main thread.Now, if  module is loaded before monkey-patching,  call returns one value when  instance is created and added to , and another value at the time  is called - hence  in .On the contrary, if monkey-patching is done before  is loaded, all is fine - at the time  instance is being added to ,  is already patched, and the same thread ID is returned at cleanup time. That's it!To make sure I import modules in the right order, I added the following snippet to my code, just before monkey-patching call:I hope you find my debugging story useful :)You could use this:I had a similar problem with a gevent prototype script.The Greenlet callback was executing fine and I was synchronizing back to the main thread via g.join(). For my problem, I had to call gevent.shutdown() to shutdown (what I assume is) the Hub. After I manually shutdown the event loop, the program terminates properly without that error. 
Python

Is there anyway to get tuple operations in Python to work like this:instead of:I know it works like that because the  and  methods are defined to work like that. So the only way would be to redefine them?Using all built-ins..This solution doesn't require an import:Sort of combined the first two answers, with a tweak to ironfroggy's code so that it returns a tuple:Note: using  instead of  to ease subclassing.gives .See All generator solution. Not sure on performance (itertools is fast, though)simple solution without class definition that returns tupleYes. But you can't redefine built-in types. You have to subclass them:Generator comprehension could be used instead of map. Built-in map function is not obsolete but it's less readable for most people than list/generator/dict comprehension, so I'd recommend not to use map function in general.even simpler and without using map, you can do that
Python

The greatest common divisor (GCD) of a and b is the largest number that divides both of them with no remainder.One way to find the GCD of two numbers is Euclid\u2019s algorithm, which is based on the observation that if  is the remainder when  is divided by , then . As a base case, we can use .Write a function called gcd that takes parameters  and  and returns their greatest common divisor.It's .Source code from the  module in Python 2.7:As of Python 3.5,  ; the one in  is deprecated. Moreover,  no longer returns explanatory source code for either method.The algorithms with m-n can runs awfully long.This one performs much better:This version of code utilizes Euclid's Algorithm for finding GCD.I think another way is to use recursion. Here is my code:A different approach based on euclid's algorithm.The value swapping didn't work well for me. So I just set up a mirror-like situation for numbers that are entered in either a < b OR a > b: in python with recursion:greatest_common_devisor(A)
Python

I'm looking for the same effect as  in JavaScript.I wrote a simple web-based interpreter this afternoon using Twisted.web. You basically submit a block of Python code through a form, and the client comes and grabs it and executes it. I want to be able to make a simple popup message, without having to re-write a whole bunch of boilerplate wxPython or TkInter code every time (since the code gets submitted through a form and then disappears).I've tried tkMessageBox:but this opens another window in the background with a tk icon. I don't want this. I was looking for some simple wxPython code but it always required setting up a class and entering an app loop etc. Is there no simple, catch-free way of making a message box in Python?You could use an import and single line code like this:Or define a function (Mbox) like so:Note the styles are as follows:Have fun!Note: edited to use  instead of Have you looked at ?Also you can position the other window before withdrawing it so that you position your messageThe code you presented is fine! You just need to explicitly create the \"other window in the background\" and hide it, with this code:Right before your messagebox.On Mac, the python standard library has a module called . There is also a (ctypes based) windows version at If it matters to you: it uses native dialogs and doesn't depend on Tkinter like the already mentioned , but it might not have as much features.In Windows, you can use :The PyMsgBox module does exactly this. It has message box functions that follow the naming conventions of JavaScript: alert(), confirm(), prompt() and password() (which is prompt() but uses * when you type). These function calls block until the user clicks an OK/Cancel button. It's a cross-platform, pure Python module with no dependencies.Install with: Sample usage:Full documentation at UseThe master window has to be created before. This is for Python 3. This is not fot wxPython, but for tkinter.Not the best, here is my basic Message box using only tkinter.check out my python module: pip install quickgui  (Requires wxPython, but requires no knowledge of wxPython)\nCan create any numbers of inputs,(ratio, checkbox, inputbox), auto arrange them on a single gui. 
Python

How would I generate a random date that has to be between two other given dates? \nThe functions signature should something like this-and would return a date such as-\n\"2/4/2008 7:20 PM\"Convert both strings to timestamps (in your chosen resolution, e.g. milliseconds, seconds, hours, days, whatever), subtract the earlier from the later, multiply your random number (assuming it is distributed in the range [0, 1]) with that difference, and add again to the earlier one.  Convert the timestamp back to date string and you have a random time in that range.Python example (output is almost in the format you specified, other than 0 padding - blame the American time format conventions):The precision is seconds. You can increase precision up to microseconds, or decrease to, say, half-hours, if you want. For that just change the last lines calculation.example run:output:A tiny version.Note that both  and  arguments should be  objects. If\nyou've got strings instead, it's fairly easy to convert. The other answers point\nto some ways to do so.It's very simple using radar$ pip install radarThis is a different approach - that sort of works..To chip in a pandas-based solution I use:I like it, because of the nice  features that allow me to throw different stuff and formats at it. Consider the following few examples...Your signature.Random position.Different format.Passing pandas/datetime objects directly.The easiest way of doing this is to convert both numbers to timestamps, then set these as the minimum and maximum bounds on a random number generator.A quick PHP example would be:This function makes use of  to convert a datetime description into a Unix timestamp, and  to make a valid date out of the random timestamp which has been generated.Here is an answer to the literal meaning of the title rather than the body of this question:This code is based loosely on the accepted answer.Since Python 3  supports multiplication with floats, so now you can do:given that  and  are of the type . For example, to generate a random datetime within the next day:You can Use ,and,Many algorithms for converting date to and from numbers are already available in many operating systems.What do you need the random number for? Usually (depending on the language) you can get the number of seconds/milliseconds from the Epoch from a date. So for a randomd date between startDate and endDate you could do:Conceptually it's quite simple.  Depending on which language you're using you will be able to convert those dates into some reference 32 or 64 bit integer, typically representing seconds since epoch (1 January 1970) otherwise known as \"Unix time\" or milliseconds since some other arbitrary date.  Simply generate a random 32 or 64 bit integer between those two values.  This should be a one liner in any language.On some platforms you can generate a time as a double (date is the integer part, time is the fractional part is one implementation).  The same principle applies except you're dealing with single or double precision floating point numbers (\"floats\" or \"doubles\" in C, Java and other languages).  Subtract the difference, multiply by random number (0 <= r <= 1), add to start time and done.In python:(need python  library \u2013 )Use ApacheCommonUtils to generate a random long within a given range,\nand then create Date out of that long. Example:import org.apache.commons.math.random.RandomData;import org.apache.commons.math.random.RandomDataImpl;public Date nextDate(Date min, Date max) {}I made this for another project using random and time. I used a general format from time you can view the documentation  for the first argument in strftime(). The second part is a random.randrange function. It returns an integer between the arguments. Change it to the ranges that match the strings you would like. You must have nice arguments in the tuple of the second arugment.Just to add another one:The day handling needs some considerations. With 28 you are on the secure site.Pandas + numpy solutiondts is the difference between timestamps in seconds (float). It is then used to create a pandas timedelta between 0 and dts, that is added to the start timestamp.Based on the answer by mouviciel, here is a vectorized solution using numpy. Convert the start and end dates to ints, generate an array of random numbers between them, and convert the whole array back to dates. 
Python

How do I limit  to only return files in the directory I provide it?Use the  function.It works just like , but you can pass it a  parameter that indicates how deep the recursion will go.Don't use os.walk.Example:I think the solution is actually very simple.use to only do first iteration of the for loop, there must be a more elegant way.The first time you call os.walk, it returns tulips for the current directory, then on next loop the contents of the next directory.  Take original script and just add a .The suggestion to use  is a good one.  The direct answer to your question is If you have more complex requirements than just the top directory (eg ignore VCS dirs etc), you can also modify the list of directories to prevent os.walk recursing through them.ie:Note - be careful to mutate the list, rather than just rebind it.  Obviously os.walk doesn't know about the external rebinding.You could use  which returns a list of names (for both files and directories) in a given directory. If you need to distinguish between files and directories, call  on each name.The same idea with , but shorter:In Python 3, I was able to do this:Felt like throwing my 2 pence in.You could also do the following:This is how I solved itThere is a catch when using listdir.  The os.path.isdir(identifier) must be an absolute path.  To pick subdirectories you do:The alternative is to change to the directory to do the testing without the os.path.join().You can use this snippet
Python

Is there an efficient way to know how many elements are in an iterator in Python, in general, without iterating through each and counting?No. It's not possible.Example:Length of  is unknown until you iterate through it.This code should work:Although it does iterate through each item and count them, it is the fastest way to do so.No, any method will require you to resolve every result. You can do but running that on an infinite iterator will of course never return. It also will consume the iterator and it will need to be reset if you want to use the contents.Telling us what real problem you're trying to solve might help us find you a better way to accomplish your actual goal.Edit: Using  will read the whole iterable into memory at once, which may be undesirable. Another way is to doas another person posted. That will avoid keeping it in memory.You cannot (except the type of a particular iterator implements some specific methods that make it possible).Generally, you may count iterator items only by consuming the iterator. One of probably the most efficient ways:(For Python 3.x replace  with ).Kinda. You  check the  method, but be warned that (at least up to Python 3.4, as gsnedders helpfully points out) it's a  (), that could very well vanish or summon nasal demons instead.Otherwise, no. Iterators are just an object that only expose the  method. You can call it as many times as required and they may or may not eventually raise . Luckily, this behaviour is most of the time transparent to the coder. :)An iterator is just an object which has a pointer to the next object to be read by some kind of buffer or stream, it's like a LinkedList where you don't know how many things you have until you iterate through them. Iterators are meant to be efficient because all they do is tell you what is next by references instead of using indexing (but as you saw you lose the ability to see how many entries are next).Regarding your original question, the answer is still that there is no way in general to know the length of an iterator in Python.Given that you question is motivated by an application of the pysam library, I can give a more specific answer: I'm a contributer to PySAM and the definitive answer is that SAM/BAM files do not provide an exact count of aligned reads.  Nor is this information easily available from a BAM index file.  The best one can do is to estimate the approximate number of alignments by using the location of the file pointer after reading a number of alignments and extrapolating based on the total size of the file.  This is enough to implement a progress bar, but not a method of counting alignments in constant time.I like the  package for this, it is very lightweight and tries to use the fastest possible implementation available depending on the iterable.Usage:The actual  implementation is as follows:There are two ways to get the length of \"something\" on a computer.The first way is to store a count - this requires anything that touches the file/data to modify it (or a class that only exposes interfaces -- but it boils down to the same thing).The other way is to iterate over it and count how big it is.It's common practice to put this type of information in the file header, and for pysam to give you access to this.  I don't know the format, but have you checked the API?As others have said, you can't know the length from the iterator.This is against the very definition of an iterator, which is a pointer to an object, plus information about how to get to the next object.An iterator does not know how many more times it will be able to iterate until terminating.  This could be infinite, so infinity might be your answer.A quick benchmark:The results:I.e. the simple count_sum is the way to go.
Python

I am writing a Python module that includes Cython extensions and uses  (and ).  I am open to using either  or , or some kind of  or  solution if necessary.  What is important is that I am able to call  and  routines from Cython in tight loops without Python call overhead.I've found one example .  However, that example depends on SAGE.  I want my module to be installable without installing SAGE, since my users are not likely to want or need SAGE for anything else.  My users are likely to have packages like numpy, scipy, pandas, and scikit learn installed, so those would be reasonable dependencies.  What is the best combination of interfaces to use, and what would the minimal setup.py file look like that could fetch the necessary information (from numpy, scipy, etc.) for compilation?\nHere is what I ended up doing.  It works on my macbook, but I have no idea how portable it is.  Surely there's a better way.This works because, on my macbook, the  header file is in the same directory as .  I can then do this in my pyx file:If I have understood the question correctly, you could make use of SciPy's Cython wrappers for BLAS and LAPACK routines. These wrappers are documented here:As the documentation states, you are responsible for checking that any arrays that you pass to these functions are aligned correctly for the Fortran routines. You can simply import and use these functions as needed in your .pyx file. For instance:Given that this is well-tested, widely-used code that runs on different platforms, I'd argue that it is a good candidate for reliably distributing Cython extensions that directly call BLAS and LAPACK routines.If you do not want your code to have a dependency on the entirety of SciPy, you can find many of the relevant files for these wrapper functions in SciPy's  directory . A useful reference is  which list the source and header files. Note that a Fortran compiler is required!In  it should be possible to isolate only the source files here that are needed to compile the BLAS and LAPACK Cython wrappers and then bundle them as an independent extension with your module. In  this is very fiddly to do. The build process for the linalg submodule requires some Python functions to aid the compilation on different platforms (e.g. from ). Building also relies upon other C and Fortran source files (), the paths of which are hard-coded into these Python functions. Clearly a lot of work has gone into making sure that SciPy compiles properly on different operating systems and architectures.I'm sure it is possible to do, but after shuffling files about and tweaking paths, I have not yet found the right way to build this part of the linalg submodule independently from the rest of SciPy. Should I find the correct way, I'll be sure to update this answer.
Python

I am trying to load the MNIST dataset linked  in Python 3.2 using this program:Unfortunately, it gives me the error:I then tried to decode the pickled file in Python 2.7, and re-encode it.  So, I ran this program in Python 2.7:It ran without error, so I reran this program in Python 3.2:However, it gave me the same error as before.  How do I get this to work?This seems like some sort of incompatibility. It's trying to load a \"binstring\" object,  which is assumed to be ASCII, while in this case it is binary data. If this is a bug in the Python 3 unpickler, or a \"misuse\" of the pickler by numpy, I don't know.Here is something of a workaround, but I don't know how meaningful the data is at this point:Unpickling it in Python 2 and then repickling it is only going to create the same problem again, so you need to save it in another format.If you are getting this error in python3, then, it could be an incompatibility issue between python 2 and python 3, for me the solution was to  with  encoding:It looks like  in pickle between 2.x and 3.x due to the move to unicode. Your file appears to be pickled with python 2.x and decoding it in 3.x could be troublesome.I'd suggest unpickling it with python 2.x and saving to a format that plays more nicely across the two versions you're using.It appears to be an incompatibility issue between Python 2 and Python 3.  I tried loading the MNIST dataset withand it worked for Python 3.5.2
Python

When implementing a class with multiple properties (like in the toy example below), what is the best way to handle hashing?I guess that the  and  should be consistent, but how to implement a proper hash function that is capable of handling all the properties?I read on  that tuples are hashable, so I was wondering if something like the example above was sensible. Is it? should return the same value for objects that are equal. It also shouldn't change over the lifetime of the object; generally you only implement it for immutable objects.A trivial implementation would be to just . This is always correct, but performs badly.Your solution, returning the hash of a tuple of properties, is good. But note that you don't need to list all properties that you compare in  in the tuple. If some property usually has the same value for inequal objects, just leave it out. Don't make the hash computation any more expensive than it needs to be.Edit: I would recommend against using xor to mix hashes in general. When two different properties have the same value, they will have the same hash, and with xor these will cancel eachother out. Tuples use a more complex calculation to mix hashes, see  in .It's dangerous to writebecause if your rhs (i.e., ) object evaluates to boolean False, it will never compare as equal to anything!In addition, you might want to double check if  belongs to the class or subclass of . If it doesn't, you'll either get exception  or a false positive (if the other class happens to have the same-named attributes with matching values). So I would recommend to rewrite  as:If by any chance you want an unusually flexible comparison, which compares across unrelated classes as long as attributes match by name, you'd still want to at least avoid  and check that  doesn't have any additional attributes. How you do it depends on the situation (since there's no standard way to find all attributes of an object).Documentation for 
Python

I'd like to point to a function that does nothing:my use case is something like thisOf course, I could use the  defined above, but a built-in would certainly run faster (and avoid bugs introduced by my own).Apparently,  and  use  for the identity, but this is specific to their implementations.Doing some more research, there is none, a feature was asked in  And from :So a better way to do it is actually (a lambda avoids naming the function):ORNo, there isn't a built-in  function, but writing one that behaves appropriately for both single and multiple inputs is not difficult:And in use:While you might argue that the second result is a , and you didn't pass a  into the  function, you should also realize that s are how Python passes groups of objects around as a single entity, and in use is what you would want:rds' versions will either:rds' first version (no name, assigned to ):rds' second version (also no name, also assigned to ):yours will work fine. When the number of parameters is fix you can use an anonymous function like this:No, there isn't.Note that your :So, you may want to use  if you want a true identity function.The thread is pretty old. But still wanted to post this.It is possible to build an identity method for both arguments and objects. In the example below, ObjOut is an identity for ObjIn. All other examples above haven't dealt with dict **kwargs.
Python

Does anybody know how Python manage internally int and long types? How should I understand the code below?Update:  and  were \"unified\" . Before that it was possible to overflow an int through math ops.3.x has further advanced this by eliminating int altogether and only having long.Python 2:  contains the maximum value a Python int can hold.Python 3:  contains the maximum value a Python int can hold. This  should help. Bottom line is that you really shouldn't have to worry about it in python versions > 2.4On my machine:Python uses ints (32 bit signed integers, I don't know if they are C ints under the hood or not) for values that fit into 32 bit, but automatically switches to longs (arbitrarily large number of bits - i.e. bignums)  for anything larger. I'm guessing this speeds things up for smaller values while avoiding any overflows with a seamless transition to bignums.Interesting.  On my 64-bit (i7 Ubuntu) box:Guess it steps up to 64 bit ints on a larger machine.Python 2.7.9 auto promotes numbers.\nFor a case where one is unsure to use int() or long().It manages them because  and  are sibling class definitions.  They have appropriate methods for +, -, *, /, etc., that will produce results of the appropriate class.For exampleIn this case, the class  has a  method (the one that implements *) which creates a  result when required.From python 3.x, the unified integer libries are even more smarter than older versions. On my (i7 Ubuntu) box I got the following,For implementation details refer  files. The last file is a dynamic module (compiled to an so file). The code is well commented to follow.
Python

How do you dynamically set local variable in Python?(where the variable name is dynamic) I'm aware this isn't good practice, and the remarks are legit, but this doesn't make it a bad question, just a more theoretical one - I don't see why this justifies downvotes.Contrary to other answers already posted you cannot modify  directly and expect it to work.Modifying  is undefined. Outside a function when  and  are the same it will work; inside a function is will  not work.Use a dictionary, or set an attribute on an object:or if you prefer, use a class::\nAccess to variables in namespaces that aren't functions (so modules, class definitions, instances) are usually done by dictionary lookups (as Sven points out in the comments there are exceptions, for example classes that define ). Function locals can be optimised for speed because the compiler (usually) knows all the names in advance, so there isn't a dictionary until you call .In the C implementation of Python  (called from inside a function) creates an ordinary dictionary initialised from the current values of the local variables. Within each function any number of calls to  will return the same dictionary, but every call to  will update it with the current values of the local variables. This can give the impression that assignment to elements of the dictionary are ignored (I originally wrote that this was the case). Modifications to existing keys within the dictionary returned from  therefore only last until the next call to  in the same scope.In IronPython things work a bit differently. Any function that calls  inside it uses a dictionary for its local variables so assignments to local variables change the dictionary and assignments to the dictionary change the variables  that's only if you explicitly call  under that name. If you bind a different name to the  function in IronPython then calling it gives you the local variables for the scope where the name was bound and there's no way to access the function locals through it:This could all change at any time. The only thing guaranteed is that you cannot depend on the results of assigning to the dictionary returned by .Others have suggested assigning to . This won't work inside a function, where locals are accessed using the  opcode,  you have an  statement somewhere in the function. To support this statement, which could create new variables that are not known at compile time, Python is then forced to access local variables by name within the function, so writing to  works. The  can be out of the code path that is executed.Note: This only works in Python 2.x. They did away with this foolishness in Python 3, and other implementations (Jython, IronPython, etc.) may not support it either.This is a bad idea, though. How will you access the variables if you don't know their name? By  probably. So why not just use your own dictionary rather than polluting  (and taking the chance of overwriting a variable your function actually needs)?I've spent the last... couple hours, I guess, trying to hack around the lack of function closures, and I came up with this, which might help:It's a pretty heavy handed / contrived example, but if there are a lot of locals or you're still in the process of prototyping this pattern becomes useful.  Mostly I was just bitter about all the data stores being replicated or moved in order to handle callback delegates, etc.You can use a local dictionary and put all the dynamic bindings as items into the dictionary. Then knowing the name of such a \"dynamic variable\" you can use the name as the key to get its value.(Just a quick note for others googlin')Ok, so modifying   ( while modifying  ). In the meantime,  , but it's painfully slow, so, as with regular expressions, we may want to  it first:Let's say We have the below dictionary:I want to create new dictionaries as below:a oneliner:would be outputted to:But to precisely declaring variables we could go with:As can be seen the first 3  variables:As mentioned by others, if you want to put it in a function you should add it to the :\nBut a better way would be to have some dict that holds all your dynamic variable names as dictionary keys:
Python

Do child processes spawned via  share objects created earlier in the program?I have the following setup:I'm loading some big object into memory, then creating a pool of workers that need to make use of that big object. The big object is accessed read-only, I don't need to pass modifications of it between processes.My question is: is the big object loaded into shared memory, as it would be if I spawned a process in unix/c, or does each process load its own copy of the big object? Update: to clarify further - big_lookup_object is a shared lookup object. I don't need to split that up and process it separately. I need to keep a single copy of it. The work that I need to split it is reading lots of other large files and looking up the items in those large files against the lookup object.Further update: database is a fine solution, memcached might be a better solution, and file on disk (shelve or dbm) might be even better. In this question I was particularly interested in an in memory solution. For the final solution I'll be using hadoop, but I wanted to see if I can have a local in-memory version as well.\"Do child processes spawned via multiprocessing share objects created earlier in the program?\"No.  Processes have independent memory space.To make best use of a large structure with lots of workers, do this.Each process reads, does work and writes.This is remarkably efficient since all processes are running concurrently.  The writes and reads pass directly through shared buffers between the processes.In some cases, you have a more complex structure -- often a \"fan-out\" structure.  In this case you have a parent with multiple children.The child parts are pleasant to write because each child simply reads .  The parent has a little bit of fancy footwork in spawning all the children and retaining the pipes properly, but it's not too bad.Fan-in is the opposite structure.  A number of independently running processes need to interleave their inputs into a common process.  The collector is not as easy to write, since it has to read from many sources.  Reading from many named pipes is often done using the  module to see which pipes have pending input.Shared lookup is the definition of a database.  Solution 3A -- load a database.  Let the workers process the data in the database.Solution 3B -- create a very simple server using  (or similar) to provide WSGI applications that respond to HTTP GET so the workers can query the server.Shared filesystem object.  Unix OS offers shared memory objects.  These are just files that are mapped to memory so that swapping I/O is done instead of more convention buffered reads.You can do this from a Python context in several waysIt depends. For global read-only variables it can be often considered so (apart from the memory consumed) else it should not. 's documentation says:On Windows (single CPU):With :Without : is correct. Python's multiprocessing shortcuts effectively give you a separate, duplicated chunk of memory.On most *nix systems, using a lower-level call to  will, in fact, give you copy-on-write memory, which might be what you're thinking. AFAIK, in theory, in the most simplistic of programs possible, you could read from that data without having it duplicated.However, things aren't quite that simple in the Python interpreter. Object data and meta-data are stored in the same memory segment, so even if the object never changes,  something like a reference counter for that object being incremented will cause a memory write, and therefore a copy. Almost any Python program that is doing more than \"print 'hello'\" will cause reference count increments, so you will likely never realize the benefit of copy-on-write.Even if someone did manage to hack a shared-memory solution in Python, trying to coordinate garbage collection across processes would probably be pretty painful.If you're running under Unix, they may share the same object, due to  (i.e., the child processes have separate memory but it's copy-on-write, so it may be shared as long as nobody modifies it).  I tried the following:and got the following output:Of course this doesn't  that a copy hasn't been made, but you should be able to verify that in your situation by looking at the output of  to see how much real memory each subprocess is using.Different processes have different address space. Like running different instances of the interpreter. That's what IPC (interprocess communication) is for.You can use either queues or pipes for this purpose. You can also use rpc over tcp if you want to distribute the processes over a network later.Not directly related to multiprocessing per se, but from your example, it would seem you could just use the  module or something like that. Does the \"big_lookup_object\" really have to be completely in memory?For Linux/Unix/MacOS platform, forkmap is a quick-and-dirty solution. 
Python

This is ugly. What's a more Pythonic way to do it?Generally, you can use the  syntax. You can even pass a part of the tuple, which seems like what you're trying to do here:This is called  a tuple, and can be used for other iterables (such as lists) too. Here's another example (from the ):Refer 
Python

Is there a Bash equivalent to the Python's  statement?You can use  for this. is a command that successfully does nothing.( would, in a way, be the opposite: it doesn't do anything, but claims that a failure occurred.)
Python

I wish to write to a file based on whether that file already exists or not, only writing if it doesn't already exist (in practice, I wish to keep trying files until I find one that doesn't exist).The following code shows a way in which a potentially attacker could insert a symlink, as suggested in  in between a test for the file and the file being written. If the code is run with high enough permissions, this could overwrite an arbitrary file.Is there any way to solve this problem?: See also : from Python 3.3, you can use the  flag to  to provide this function.Yes, but not using Python's standard  call. You'll need to use  instead, which allows you to specify flags to the underlying C code.In particular, you want to use . From the man page for  under  on my Unix system:So it's not perfect, but AFAIK it's the closest you can get to avoiding this race condition.Edit: the other rules of using  instead of  still apply. In particular, if you want use the returned file descriptor for reading or writing, you'll need one of the ,  or  flags as well.All the  flags are in Python's  module, so you'll need to  and use  etc.For reference, Python 3.3 implements a new  mode in the  function to cover this use-case (create only, fail if file exists).This code will easily create a FILE if one does not exists.
Python

Today, I saw one statement which didn't throw an exception. Can anyone explain the theory behind it?In Python, every  can be unpacked:Moreover, because iterating over a dictionary returns only its keys:unpacking a dictionary (which iterates over it) likewise unpacks only its keys.Actually, I should say that every iterable can be unpacked  the names to unpack into equals the length of the iterable:But this is only the case for Python 2.x.  In Python 3.x, you have , which allows you to unpack an iterable of any (finite) size into just the names you need:Iterating a  iterates over the keys. Since your dict literal has exactly two keys, you can unpack it into a 2-tuple.This is probably not a good practice in general, since dicts are unordered and  and  would be a prefectly legal outcome of that code.when you iterate over a dictionary, you get its keysUnpacking is nothing else than iterating over the object and put the elements in the given variables:No rocket science behind it.  is an iterable, which return the keys in each iteration.  can receive any iterable as argument (as long as they are finite), so:Seeing this, is easy to infer that unpacking will work as shown. Moreover, any  iterable can be unpacked:When in iterable context, dicts are treated as an (unordered) collection of keys, which is what you get when you do , which is the same as calling  on the dict:However, you can also do more.You can unpack both a 's both keys  values if you turn it into a list of pairs first:or if you just want the pairsor, say, just the keys:etc.But of course since dictionaries \u2014 and I mean in general, not only in Python \u2014 contain their items in an un-ordered manner,  (in Python) will also return them in a seemingly arbitrary order, and thus there is no way to know which key will be stored in which variable:As you see, the order of the pairs returned by  was reversed in comparison to their definition order.
Python

After updating to new version 2016.2, I am getting'tests' is a package inside my main app package, and I receive these warnings when I try to execute unit tests inside this folder. This issue only came up after updating to 2016.2. Besides the warnings, the remaining code works fine.Edit: This is a known issue - . They are suggesting to replace utrunner.py in PyCharm installation folder.This is a known issue introduced with the 2016.2 release. Progress can be followed on the JetBrains website . According to this page it is due to be fixed in the 2017.1 release. You can follow the utrunner.py workaround that others have mentioned in the meantime - a copy of this file is attached to the linked ticket.The latest recommendation  is to put this line at the top of your unit test script:On OS X I've fixed this by replacing with an older version that can be found at \n    On  Bobby's solution also works:Just replace your local  file at by the one from the Jetbrains website:  On Windows 10 Bobby's solution also works:Just replace your local utrunner.py file atwith the one from the Jetbrains website: 
Python

How to make a multi-thread python program response to Ctrl+C key event? The code is like this:I tried to remove join() on all threads but it still doesn't work. Is it because the lock segment inside each thread's run() procedure? The above code is supposed to work but it always interrupted when current variable was in 5,000-6,000 range and through out the errors as belowMake every thread except the main one a daemon ( in 2.6 or better,  in 2.6 or less, for every thread object  before you start it).  That way, when the main thread receives the KeyboardInterrupt, if it doesn't catch it or catches it but decided to terminate anyway, the whole process will terminate.  See .: having just seen the OP's code (not originally posted) and the claim that \"it doesn't work\", it appears I have to add...:Of course, if you want your main thread to stay responsive (e.g. to control-C), don't mire it into blocking calls, such as ing another thread -- especially not totally  blocking calls, such as ing  threads.  For example, just change the final loop in the main thread from the current (utterless and damaging):to something more sensible like:if your main has nothing better to do than either for all threads to terminate on their own, or for a control-C (or other signal) to be received.Of course, there are many other usable patterns if you'd rather have your threads not terminate abruptly (as daemonic threads may) -- unless , too, are mired forever in unconditionally-blocking calls, deadlocks, and the like;-).There're two main ways, one clean and one easy.The clean way is to catch KeyboardInterrupt in your main thread, and set a flag your background threads can check so they know to exit; here's a simple/slightly-messy version using a global:The messy but easy way is to catch KeyboardInterrupt and call os._exit(), which terminates all threads immediately.A  might be helpful for you:I would rather go with the code proposed in :What I have changed is the  from  to . The actual number of seconds does not matter, unless you specify a timeout number, the main thread will stay responsive to Ctrl+C. The except on  makes the signal handling more explicit.If you spawn a Thread like so -  - and then do . When CTRL-C is initiated, the main thread doesn't exit because it is waiting on that blocking  call. To fix this, simply put in a timeout on the .join() call. The timeout can be as long as you wish. If you want it to wait indefinitely, just put in a really long timeout, like 99999. It's also good practice to do  so all the threads exit when the main thread(non-daemon) exits.You can always set your threads to \"daemon\" threads like:And whenever the main thread dies all threads will die with it.When you want to kill the thread just use:
Python

This may sound like a stupid question, since the very purpose of  is to this exactly: Installing some specific version of a package (in this case Django) inside the virtual environment. But it's exactly what I want to do, and I can't figure it out.I'm on Windows XP, and I created the virtual environment successfully, and I'm able to run it, but how am I supposed to install the Django version I want into it? I mean, I know to use the newly-created  script, but how do I make it install Django 1.0.7? If I do , it will install the latest version. I tried putting the version number  into this command in various ways, but nothing worked.How do I do this?There was never a Django 1.0.7. The 1.0 series only went up to 1.0.4. You can see all the releases in the .However to answer your question, don't use , use . (If it's not already installed, do , then never touch easy_install again). Now you can do:+1 on the previous poster's reply: use  if you can. But, in a pinch, the easiest way is to install an older version would be to download the tarball from the  page or, if you have subversion installed, do an  of the release you want (they are all tagged ). Once you have the version of Django you want, just run the following command inside the django directory:This will install that version of Django in your virtualenv. 
Python

Is there a way to automatically create the db file if it doesn't already exist when I connect to it?thanksThe code you give  create  if it doesn't exist.If it isn't created automatically, make sure that you have the directory permissions correctPretty sure .connect will create the file if it doesn't exist.As it was already mentioned, your code should work if you have permissions to write for this path. However, it is important that . If you make call for non-existing folder:It will not work, you will have The same is for relative paths:First will always work, because you are working in already existing directory and second will not work if you do not create te folder beforehand..connect should create a new database file on the fly,  given sub-directories do exist, and you have adequate permissioning.
Python

I had a string which is stored in a variable . I want to split it with delimiter like we do using  in PHP.What is the equivalent in Python?Choose one you need: and The alternative for explode in php is .The first parameter is the delimiter, the second parameter the maximum number splits. The parts are returned without the delimiter present (except possibly the last part). When the delimiter is None, all whitespace is matched. This is the default.
Python

When is it better to use  instead of ?When you know you'll want the full list of items constructed (for instance, for passing to a function that would modify that list in-place). Or when you want to force the arguments you're passing to  to be completely evaluated at that specific point. computes all the list at once,  computes the elements only when requested.One important difference is that 'zip' returns an actual list, 'izip' returns an 'izip object', which is not a list and does not support list-specific features (such as indexing):So, if you need a list (an not a list-like object), just use 'zip'.Apart from this, 'izip' can be useful for saving memory or cycles.E.g. the following code may exit after few cycles, so there is no need to compute all items of combined list:using  would have computed   couples before entering the cycle.Moreover, if  and  are very large (e.g. millions of records),  will build a third list with double space.But if you have small lists, maybe  is faster.In 2.x, when you  a list instead of an iterator.The itertools library provides \"iterators\" for common Python functions. From the itertools docs, \"Like zip() except that it returns an iterator instead of a list.\" The I in izip() means \"iterator\".Python iterators are a \"lazy loaded\" sequence that saves memory over regular in-memory list. So, you would use itertools.izip(a, b) when the two inputs a, b are too big to keep in memory at one time.Look up the Python concepts related to efficient sequential processing:
Python

I'd really like to be able to print out valid SQL for my application, including values, rather than bind parameters, but it's not obvious how to do this in SQLAlchemy (by design, I'm fairly sure). Has anyone solved this problem in a general way?In the vast majority of cases, the \"stringification\" of a SQLAlchemy statement or query is as simple as:This applies both to an ORM  as well as any  or other statement.: the following detailed answer is being maintained on the .To get the statement as compiled to a specific dialect or engine, if the statement itself is not already bound to one you can pass this in to :or without an engine:When given an ORM  object, in order to get at the  method we only need access the  accessor first:with regards to the original stipulation that bound parameters are to be \"inlined\" into the final string, the challenge here is that SQLAlchemy normally is not tasked with this, as this is handled appropriately by the Python DBAPI, not to mention bypassing bound parameters is probably the most widely exploited security holes in modern web applications.   SQLAlchemy has limited ability to do this stringification in certain circumstances such as that of emitting DDL.  In order to access this functionality one can use the 'literal_binds' flag, passed to :the above approach has the caveats that it is only supported for basic\ntypes, such as ints and strings, and furthermore if a \nwithout a pre-set value is used directly, it won't be able to\nstringify that either.To support inline literal rendering for types not supported, implement\na  for the target type which includes a\n method:producing output like:This works in python 2 and 3 and is a bit cleaner than before, but requires SA>=1.0.Demo:Gives this output: (tested in python 2.7 and 3.4)This code is based on brilliant  from @bukzor. I just added custom render for  type into Oracle's . Feel free to update code to suit your database:So building on @zzzeek's comments on @bukzor's code I came up with this to easily get a \"pretty-printable\" query:I personally have a hard time reading code which is not indented so I've used  to reindent the SQL. It can be installed with .I would like to point out that the solutions given above do not \"just work\" with non-trivial queries. One issue I came across were more complicated types, such as pgsql ARRAYs causing issues. I did find a solution that for me, did just work even with pgsql ARRAYs:borrowed from:\nThe linked code seems to be based on an older version of SQLAlchemy. You'll get an error saying that the attribute _mapper_zero_or_none doesn't exist. Here's an updated version that will work with a newer version, you simply replace _mapper_zero_or_none with bind. Additionally, this has support for pgsql arrays:Tested to two levels of nested arrays.
Python

How do I install SciPy on my system?For the NumPy part (that SciPy depends on) there is actually an installer for 64 bit Windows:  (is direct download URL, 2310144 bytes).Running the SciPy superpack installer results in this\nmessage in a dialog box:I already have Python 2.6.2 installed (and a working Django installation\nin it), but I don't know about any Registry story.The registry entries seem to already exist:What I have done so far:Downloaded the NumPy superpack installer\nnumpy-1.3.0rc2-win32-superpack-python2.6.exe\n(, 4782592 bytes). Running this installer\nresulted in the same message, \"Cannot install. Python\nversion 2.6 required, which was not found in the registry.\".\n: there is actually an installer for NumPy that works - see beginning of the question.Tried to install NumPy in another way. Downloaded the zip\npackage numpy-1.3.0rc2.zip (, 2404011 bytes),\nextracted the zip file in a normal way to a temporary\ndirectory, D:\\temp7\\numpy-1.3.0rc2 (where setup.py and\nREADME.txt is). I then opened a command line window and:This ran for a long time and also included use of cl.exe\n(part of Visual Studio). Here is a nearly 5000 lines long\n (230 KB).This seemed to work. I can now do this in Python:with this result:Downloaded the SciPy superpack installer, scipy-0.7.1rc3-\nwin32-superpack-python2.6.exe (, 45597175\nbytes). Running this installer resulted in the message\nlisted in the beginningTried to install SciPy in another way. Downloaded the zip\npackage scipy-0.7.1rc3.zip (, 5506562\nbytes), extracted the zip file in a normal way to a\ntemporary directory, D:\\temp7\\scipy-0.7.1 (where setup.py\nand README.txt is). I then opened a command line window and:This did not achieve much - here is a  (about 95\nlines).And it fails:Platform: Python 2.6.2 installed in directory D:\\Python262,\nWindows XP 64 bit SP2, 8 GB RAM, Visual Studio 2008\nProfessional Edition installed.The startup screen of the installed Python is:Value of PATH, result from SET in a command line window:I haven't tried it, but you may want to download  of . It comes with Scipy-0.7.0b1 running on Python 2.5.4. Unofficial 64-bit installers for  and  are available at You'll want to ;  From a CMD prompt with administrator privileges for a system-wide (aka. Program Files) install: include the  flag to install to the current user's application folder (Typically  on Windows) from a  CMD prompt:Then do the same for SciPy:Short answer: windows 64 support is still work in progress at this time. The superpack will certainly not work on a 64 bits python (but it should work fine on a 32 bits python, even on windows 64).The main issue with windows 64 is that building with mingw-w64 is not stable at this point: it may be our's (numpy devs) fault, python's fault or mingw-w64. Most likely a combination of all those :). So you have to use proprietary compilers: anything other than MS compiler crashes numpy randomly; for the fortran compiler, ifort is the one to use. As of today, both numpy and scipy source code can be compiled with VS 2008 and ifort (all tests passing), but building it is still quite a pain, and not well supported by numpy build infrastructure.As the transcript for SciPy told you, SciPy isn't really supposed to work on Win64:So I would suggest to install the 32-bit version of Python, and stop attempting to build SciPy yourself. If you still want to try anyway, you first need to compile BLAS and LAPACK, as PiotrLegnica says. See the transcript for the places where it was looking for compiled versions of these libraries. is an open-source distribution that has 64-bit numpy and scipy.Another alternative: Free and includes lots of stuff meant to work together smoothly. says Though I'm not quite sure what that means.This appears to be dead. I use  now, which has 32-bit or 64-bit installers.For completeness:   has a Python distribution which includes SciPy; however, it's not free.  Caveat:  I've never used it.Update: This answer had been long forgotten until an upvote brought me back to it.  At this time, I'll second  of , which is free.Try to install Python 2.6.3 over your 2.6.2 (this should also add correct Registry entry), or to register your existing installation . Installer should work after that.Building SciPy requires a Fortran compiler and libraries -  and .It is terrible to install such Python data science packages independently on Windows. Try  (one installer, 400 more Python packages, py2 & py3 support). Anaconda really helps me a lot!I have a 32bit python3.5 on a 64bit win8.1 machine, I just tried almost every way I can find on Stackoverflow and no one works !Then on : I found it says:then I installed mklthen I install scipy:It worked~ yeah :)A tip: You can just google \"whl_file_name.whl\" to know where to download it~ :)After all these steps you will find that you still can not use scipy in python3, if you print \"import scipy\" you will find there are error messages, but don't worry, there is only one more thing to do. \n\u2014\u2014just comment out that line ,simple and useful.I promise that it is the last thing to do :)PS: \nBefore all these steps, you better install numpy first, that's very simple using command: I was getting this same error on a 32-bit machine.  I fixed it by registering my Python installation, using the script at: It's possible that the script would also make the 64-bit superpack installers work.Install Python distribution .Download and Install Anaconda Python Distribution.Make Anaconda Python distribution link to py3.3, if you want Numpy, Scipy or Matplotlib to work in py3.3 or just use it like that to have only py2.7 and older functionality.The link below provides more detail about Anaconda:\n.You can either download a scientific python distribution. One of the ones mentioned :  Or pip install from whl file  if the above is not an option for you.Okay a lot has been said but just in-case nothing above works, you can try;According to them;\nOkey, Here I am going to share what I have done to install  on my windows-pc without command. 
Python

I have a problem with Python threading and sending a string in the arguments..Where dRecieved is the string of one line read by a connection. It calls a simple function which as of right now has only one job of printing \"hello\".However I get the following error232 is the length of the string that I am trying to pass, so I guess its breaking it up into each character and trying to pass the arguments like that. It works fine if I just call the function normally but I would really like to set it up as a separate thread.You're trying to create a tuple, but you're just parenthesizing a string :)Add an extra ',': Or use brackets to make a list:If you notice, from the stack trace: The  turns your string into a list of characters, passing them to the \nfunction.  If you pass it a one element list, it will pass that element as the first argument - in your case, the string.
Python

This function doesn't work and raises an error. Do I need to change any arguments or parameters?  If the file does not exists,  will fail.You can use , which creates the file if the file does not exist, but it will truncate the existing file.Alternatively, you can use ; this will create the file if the file does not exist, but will not truncate the existing file.instead of using try-except blocks, you could use, if elsethis will not execute if the file is non-existent,\n    open(name,'r+')'w' creates a file if its non-exisfollowing script will use to create any kind of file, with user input as extensionThis works just fine, but instead of you should usealong withYou can os.system function for simplicity :This invokes system terminal to accomplish the task.this will work promise :)You can use However, when you enter filename, use inverted commas on both sides, otherwise cannot be added to filename 
Python

I am trying to take one string, and append it to every string contained in a list, and then have a new list with the completed strings. Example:I tried for loops, and an attempt at list comprehension, but it was garbage. As always, any help, much appreciated. The simplest way to do this is with a list comprehension:Notice that I avoided using builtin names like  because that shadows or hides the builtin names, which is very much not good.Also, if you do not actually need a list, but just need an iterator, a generator expression can be more efficient (although it does not likely matter on short lists):These are very powerful, flexible, and concise.  Every good python programmer should learn to wield them.This will print:I havent found a way to comment on answers till now. So here it is.\nI support Ignacio Vazquez-Abrams's answer of .Others answers with  would work for most of times, but if you accept a more general solution for the simplest case you're - IMHO - following Python Design Principles. There should be preferably one obvious way to do it.  works all the time. seems like the right tool for the job to me.See  on functional programming tools for more examples of .And don't use  as a name; it shadows the built-in type.Using names such as \"list\" for your variable names is bad since it will overwrite/override the builtins.you can use lambda inside map in python. wrote a gray codes generator.\n\n        # your code goes here\n        '''\n        the n-1 bit code, with 0 prepended to each word, followed by\n        the n-1 bit code in reverse order, with 1 prepended to each word.\n        '''Running the following experiment the pythonic way:seems to be ~35% faster than the obvious use of a for loop like this:
Python

what I'm trying to do is this:Any suggestions?What aboutIn Django 1.4 and newer you can order by providing multiple fields.\nReference: By default, results returned by a  are ordered by the ordering tuple given by the  option in the model\u2019s Meta. You can override this on a per-QuerySet basis by using the  method.The result above will be ordered by  descending, then by  ascending. The negative sign in front of  indicates descending order. Ascending order is implied.I just wanted to illustrate that the built-in solutions (SQL-only) are not always the best ones.  At first I thought that because Django's  method accepts multiple arguments, you could easily chain them:But, it does not work as you would expect.  Case in point, first is a list of presidents sorted by score (selecting top 5 for easier reading):Using Alex Martelli's solution which accurately provides the top 5 people sorted by :And now the combined  call:As you can see it is the same result as the first one, meaning it doesn't work as you would expect.  Here's a way that allows for ties for the cut-off score.You may get more than 30 authors in top_authors this way and the  is there incase you have fewer than 30 authors.
Python

I am learning the concept of filters in Python. I am running a simple code like this.But instead of getting a list, I am getting some message like this.What does this mean? Does it means that my filtered object i.e list to come out is stored at that memory location? How do I get the list which I need?It looks like you're using python 3.x.  In python3, , , , etc return an object which is iterable, but not a list.  In other words,is equivalent to:I think it was changed because you (often) want to do the filtering in a lazy sense -- You don't need to consume all of the memory to create a list up front, as long as the iterator returns the same thing a list would during iteration.  If you're familiar with list comprehensions and generator expressions, the above filter is now (almost) equivalent to the following in python3.x:As opposed to:in python 2.xIt's an  returned by the  function.If you want a list, just doNonetheless, you can just iterate over this object with a  loop.
Python

Suppose I have a model:Currently I am using the default admin to create/edit objects of this type.\nHow do I remove the field  from the admin so that each object  be created with a value, and rather will receive a default value of ?Set  to  and  to your default value.Also, your  field is unnecessary.  Django will add it automatically.You can set the default like this:and then you can hide the field with your model's Admin class like this:You can also use a callable in the default field, such as:And then define the callable:
Python

Assume that I have a such set of pair datas where index 0 is the value and the index 1 is the type:I want to group them by their type(by the 1st indexed string) as such:How can I achieve this in an efficient way?ThanksDo it in 2 steps. First, create a dictionary.Then, convert that dictionary into the expected format.It is also possible with itertools.groupby but it requires the input to be sorted first.Note both of these do not respect the original order of the keys. You need an OrderedDict if you need to keep the order.Python's built-in  module actually has a  function that you could use, but the elements to be grouped must first be sorted such that the elements to be grouped are contiguous in the list:Now input looks like: returns a sequence of 2-tuples, of the form .  What we want is to turn this into a list of dicts where the 'type' is the key, and 'items' is a list of the 0'th elements of the tuples returned by the values_iterator.  Like this:Now  contains your desired dict, as stated in your question.You might consider, though, just making a single dict out of this, keyed by type, and each value containing the list of values.  In your current form, to find the values for a particular type, you'll have to iterate over the list to find the dict containing the matching 'type' key, and then get the 'items' element from it.  If you use a single dict instead of a list of 1-item dicts, you can find the items for a particular type with a single keyed lookup into the master dict.  Using , this would look like: now contains this dict (this is similar to the intermediate  defaultdict in @KennyTM's answer):(If you want to reduce this to a one-liner, you can:or using the newfangled dict-comprehension form:The following function will quickly ( required) group tuples of any length by a key having any index:In the case of your question, the index of key you want to group by is 1, therefore:giveswhich is not exactly the output you asked for, but might as well suit your needs.I also liked pandas simple . it's powerful, simple and most adequate for large data set
Python

I have the following recursion code, at each node I call sql query to get the nodes belong to the parent node. here is the error: Method that I call to get sql results:I actually don't have any issue with the above method but I put it anyways to give proper overview of the question.Recursion Code:Calling the recursive function Code to print the dictionary, If the recursion is too deep I should be getting the error when I call my recursion function, but when I get this error when I print the dictionary.You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.
Python

I want to plot data, then create a new figure and plot data2, and finally come back to the original plot and plot data3, kinda like this:FYI  does something similar, but not quite! It doesn't let me get access to that original plot.If you find yourself doing things like this regularly it may be worth investigating the object-oriented interface to matplotlib. In your case:It is a little more verbose but it's much clearer and easier to keep track of, especially with several figures each with multiple subplots.When you call , simply number the plot.Edit: Note that you can number the plots however you want (here, starting from ) but if you don't provide figure with a number at all when you create a new one, the automatic numbering will start at  (\"Matlab Style\" according to the docs).However, numbering starts at , so:Also, if you have multiple axes on a figure, such as subplots, use the  command where  is the handle of the desired axes object to focus on that axes.(don't have comment privileges yet, sorry for new answer!)
Python

Is there an equivalent to 'intellisense' for Python?Perhaps i shouldn't admit it but I find having intellisense really speeds up the 'discovery phase' of learning a new language.  For instance switching from VB.net to C# was a breeze due to snippets and intellisense helping me along. blog entry explains setting Vim up as a Python IDE, he covers Intellisense-like functionality:This is standard in Vim 7. There are a number of other very useful plugins for python development in Vim, such as  which checks code on the fly and  which provides functionality for manipulating python indentation & code blocks.The  environment for Eclipse has intellisense-like functionality for Python. Keeping an interactive console open, along with the  function is very helpful.Have a look at , they provide code completion (a.k.a  intellisense), debugging etc ...Below is a screenshot of the interactive shell for python showing code completion.The dynamic nature of the language tends to make autocomplete type analysis difficult, so the quality of the various completion facilities menitoned above varies wildly.While it's not exactly what you asked for, the ipython shell is very good for exploratory work. When I'm working with a new module, I tend to pull it into ipython and poke at it. Having tried most of the solutions mentioned above (though it's been years since Wing), ipython's completion facilities are consistently more reliable. The two main tools for exploration are tab complete and appending a question mark to the module/function name to get the help text, e.g.:I strongly recommend . In Pydev you can put the module you are using in the , mostly the code-completion will work better than in other IDEs like KOMODO EDIT.Also I think  is very helpful. Since it is 'run-time' in IPython, the code-completion in IPython won't miss anything.The  that comes with Python has an intellisense feature that auto-discovers imported modules, functions, classes and attributes.Wingware for example implements auto-completion, see  .I'd recommend .  However, I should point something out:  you're not going to get anything quite as good as what you're used to with Visual Studio's C# intellisense.  Python's dynamic nature can make it difficult to do these kinds of features. is the best Python IDE with IntelliSense support.ctags + vim works ok, too, although it is not as powerful as intellisense. Using this with ipython, you can get online help, automatic name completion, etc... But that's obviously command-line oriented.Eclipse + pydev can do it as well, but I have no experience with it: Well, I think the most dynamic way to learn Python is to use .You got autocompletion when using tab, dynamic behaviour because it's a shell and you can get the full documentation of any object / method typing :When developping, I agree that PyDev is cool. But it's heavy, so while learning, a text editor + iPython is really nice. has the best intellisense i have meet :)For emacs and VI there's also .I would recommend , it's perfect to me, try it and you won't regret.IronPython is the way to go. Visual Studio has the best intellisense support and you can utilize that using IronPythonTry visual Studio Code. It has very powerful Python and Django support and thousands of plugins for other languages used in a Python project such as CSS, HTML and Django templates. Best of all, it is free:\n
Python

Basically, I'm asking the user to input a string of text into the console, but the string is very long and includes many line breaks.  How would I take the user's string and delete all line breaks to make it a single line of text.  My method for acquiring the string is very simple.Is there a different way I should be grabbing the string from the user?  I'm running Python 2.7.4 on a Mac.P.S. Clearly I'm a noob, so even if a solution isn't the most efficient, the one that uses the most simple syntax would be appreciated.How do you enter line breaks with ? But, once you have a string with some characters in it you want to get rid of, just  them.In the example above, I replaced all spaces. The string  represents newlines. And  represents carriage returns (if you're on windows, you might be getting these and a second  will handle them for you!).basically:Note also, that it is a bad idea to call your variable , as this shadows the module . Another name I'd avoid but would love to use sometimes: . For the same reason.You can try using string replace:updated based on  comment:read more You can split the string with no separator arg, which will treat consecutive whitespace as a single separator (including newlines and tabs). Then join using a space:A method taking into considerationit takes such a multi-line string which may be messy e.g.and produces nice one-line string
Python

I understand what  does, but of what \"type\" is that language element? I think it's a function, but why does this fail?Isn't  a function? Shouldn't it print something like this?In 2.7 and down,  is a statement. In python 3,  is a function. To use the print function in Python 2.6 or 2.7, you can do See  from the Python Language Reference, as well as  for why it changed.In Python 3,  is a built-in function (object)Before this,  was a . Demonstration... is a mistake that has been rectified in Python 3. In Python 3 it is a function. In Python 1.x and 2.x it is not a function, it is a special form like  or , but unlike those two it is not a control structure.So, I guess the most accurate thing to call it is a statement.In Python all statements (except assignment) are expressed with reserved words, not addressible objects.  That is why you cannot simply  and you get a  for trying.  It's a reserved word, not an object.Confusingly, you  have a variable named .  You can't address it in the normal way, but you can  and then .Other reserved words that might be desirable as variable names but are nonetheless verboten:In Python 2,  is a statement, which is a whole different kind of thing from a variable or function. Statements are not Python objects that can be passed to ; they're just part of the language itself, even more so than built-in functions. For example, you could do  (even though you shouldn't), but you can't do  or  because  and  are statements.In Python 3, the  statement was replaced with the  function. So if you do , it'll return .In Python 2.6+, you can put  at the top of your script (as the first line of code), and the  statement will be replaced with the  function.
Python

What's the best strategy for managing third-party Python libraries with Google App Engine?Say I want to use Flask, a webapp framework.  says to do this, which doesn't seem right:There must be a better way to manage third-party code, especially if I want to track versions, test upgrades or if two libraries share a subdirectory. I know that Python can import modules from zipfiles and that  can work with a wonderful REQUIREMENTS file, and I've seen that  has a  command for use with GAE.(Note: There's a handful of similar questions \u2014 , , , ,  \u2014 but they're case-specific and don't really answer my question.)What about simply:Create/edit :Google updated their sample to , like:Note: Even though their example has  ignoring  directory you still need to keep that directory under source control if you use  deployment method.Here's how I do it:The  directory is the top level directory where the virtualenv sits. I get the virtualenv using the following commands:The  directory is where all your code goes. When you deploy your code to GAE,  deploy those in the src directory and nothing else. The  will resolve the symlinks and copy the library files to GAE for you.I don't install my libraries as zip files mainly for convenience in case I need to read the source code, which I happen to do a lot just out of curiosity. However, if you really want to zip the libraries, put the following code snippet into your main.pyAfter this you can import your zipped up packages as usual.One thing to watch out for is setuptools' . I copied that directly into my  directory so my other symlinked packages can use it. Watch out for anything that uses s. In my case I'm using Toscawidgets2 and I had to dig into the source code to manually wire up the pieces. It can become annoying if you had a lot of libraries that rely on .I prefer .You set up dependencies in setup.py in your project or buildout.cfg, pin the versions in buildout.cfg, and specify which packages are not available on GAE and should be included in packages.zip. rod.recipe.appengine will copy required packages into packages.zip, and as long as you insert packages.zip into the sys.path, they can be imported anywhere.You can also use forks from github if the package you need is not on pypiand all of these settings and dependencies are versioned in git.Instead of wondering which copy of Flask is currently included in your source tree and perhaps copied into your version control (or requiring new developers to manually unpack and upgrade), you simply check the version in buildout.cfg. If you want a new version, change buildout.cfg and rerun buildout.You can also use it to insert variables into config file templates, like setting the appspot id and version in app.yaml if you have staging server with staging.cfg and so on.I recently created a tool for this called gaenv. It follows a requirements.txt format, but doesn't install it, you can install with pip install -r requirements.txt then run the command line tool gaenv.This creates symlinks automatically, you could install gaenv in your virtualenv too and run the binary from there.\nHere is a blog post about it: also on github is the closest to current practice in the , which I've already improved by changing the  call to  in order to allow for  by processing their attendant  files (which are important for frameworks like Pyramid).So far so good, but that  the directory to the path, and so loses the opportunity to override the included libraries (like WebOb and requests) with newer versions.What is needed then in  (and I am trying to get this change accepted into the official repos as well) is the following:The final version of this code may end up hidden away in a  module and called like  or some other variation, as you can see , but the logic is more or less how it will work regardless, to allow a simple  to work for all packages including namespace ones, and to still allow overriding the included libraries with new versions, as I have so far been .Note: this answer is specific for Flask on Google App Engine.See the flask-appengine-template project for an example of how to get Flask extensions to work on App Engine.\nDrop the extension into the namespace package folder at src/packages/flaskext and you're all set.\nNon-Flask packages can be dropped into the src/packages folder as zip files, eggs, or unzipped packages, as the project template includes the sys.path.insert() snippet posted above.
Python

I am usingbut I get a request.exceptions.SSLError.\nThe website has an expired certficate, but I am not sending sensitive data, so it doesn't matter to me.\nI would imagine there is an argument like 'verifiy=False' that I could use, but I can't seem to find it.From :If you're using a third-party module and want to disable the checks, here's a context manager that monkey patches  and changes it so that  is the default.And an example of how to use it:Use requests.packages.urllib3.disable_warnings().If you want to send exactly post request with verify=False option, fastest way is to use this code:
Python

I have this python script where I need to run but I get an exception on this line:The  is invalid syntax. I am curious as to why, and what the author probably meant to do. I'm new to python if you haven't already guessed.I think the root cause of the problem is that these imports are failing\nand therefore one must contain this import Are you sure you are using Python 3.x? The syntax isn't available in Python 2.x because  is still a statement.in Python 2.x is identical toori.e. as a call to print with a tuple as argument.That's obviously bad syntax (literals don't take keyword arguments). In Python 3.x  is an actual function, so it takes keyword arguments, too.The correct idiom in Python 2.x for  is:(note the final comma, this makes it end the line with a space rather than a linebreak)If you want more control over the output, consider using  directly. This won't do any special magic with the output.Of course in somewhat recent versions of Python 2.x (2.5 should have it, not sure about 2.4), you can use the  module to enable it in your script file:The same goes with  and some other nice things (, for example). This won't work in really old versions (i.e. created before the feature was introduced) of Python 2.x, though.How about this:This allows you to use the Python 3.0 style  function without having to hand-edit all occurrences of  :)First of all, you're missing a quote at the beginning but this is probably a copy/paste error.In Python 3.x, the  part will place a space after the displayed string instead of a newline. To do the same thing in Python 2.x, you'd put a comma at the end: I think he's using Python 3.0 and you're using Python 2.6.It looks like you're just missing an opening double-quote.  Try:I think the author probably meant:He's missing an initial quote after .Note that as of ,  is a function as opposed to a statement, if you're using older versions of Python the equivalent would be:The  parameter means that the line gets  at the end rather than a newline character. The equivalent in earlier versions of Python is:(thanks Ignacio).USE ::  I had such error , this occured because i have two versions of python installed on my drive namely python2.7 and python3 .\nFollowing was my code :when i run it by the  command  I got the following errorwhen I run it by the command  I executed successfullyThis is just a version thing. Since Python 3.x the print is actually a function, so it now takes arguments like any normal function.The  is just to say that you want a space after the end of the statement instead of a new line character. In Python 2.x you would have to do this by placing a comma at the end of the print statement.For example, when in a Python 3.x environment:Will give the following output:Where as:Will give as output:For python 2.7 I had the same issue \nJust use \"\" without quotes to resolve this issue.This Ensures Python 2.6 and later Python 2.x can use Python 3.x print function.we need to import a header before using , as it is not included in the python's normal runtime.it shall work perfectly now
Python

I have a Python script I recently wrote that I call using the command line with some options. I now want a very thin web interface to call this script locally on my Mac.I don't want to go through the minor trouble of installing mod_python or mod_wsgi on my Mac, so I was just going to do a system() or popen() from PHP to call the Python script.Any better ideas? Thanks in advance!Depending on what you are doing,  or  may be perfect.  Use system() if the Python script has no output, or if you want the Python script's output to go directly to the browser.  Use popen() if you want to write data to the Python script's standard input, or read data from the Python script's standard output in php.  popen() will only let you read or write, but not both.  If you want both, check out , but with two way communication between programs you need to be careful to avoid deadlocks, where each program is waiting for the other to do something.If you want to pass user supplied data to the Python script, then the big thing to be careful about is command injection.  If you aren't careful, your user could send you data like \"; evilcommand ;\" and make your program execute arbitrary commands against your will. and  can help with this, but personally I like to remove everything that isn't a known good character, using something likeThe backquote operator will also allow you to run python scripts using similar syntax to aboveIn a python file called python.py:In a php file called python.php:There's also a PHP extension: , which I've never tried but had it bookmarked for just such an occasionYou can run a python script via php, and outputs on browser.Basically you have to call the python script this way:Note: if you run any time.sleep() in you python code, it will not outputs the results on browser.For full codes working, visit I do this kind of thing all the time for quick-and-dirty scripts.  It's quite common to have a CGI or PHP script that just uses system/popen to call some external program.Just be extra careful if your web server is open to the internet at large.  Be sure to sanitize your GET/POST input in this case so as to not allow attackers to run arbitrary commands on your machine.Your call_python_file.php should look like this:This executes the python script and outputs the result to the browser.\nWhile in your python script the (sys.argv[1:]) variable will bring in all your arguments. To display the argv as a string for wherever your php is pulling from so if you want to do a text area:If you want to execute your Python script in PHP, it's necessary to do this command in your php script:
Python

I want to check the operating system (on the computer where the script runs).I know I can use  in Linux, but it gives me a message in the console, and I want to write to a variable.It will be okay if the script can tell if it is Mac, Windows or Linux. How can I check it? You can use :For the valid values, consult .You can get a pretty coarse idea of the OS you're using by checking .Once you have that information you can use it to determine if calling something like  is appropriate to gather more specific information.  You could also use something like  on unix-like OSes, or  for Windows.There's also  if you want to do more in-depth inspection without wanting to care about the OS.More detailed information are available in the .You can use .There seems to be some conflicting information about how Windows identifies. Some sources are saying \"Windows\", and other sources are saying \"win32\".With that in mind...That might be true in Cygwin though. But you can always add a check to make sure \"cy\" isn't in there.
Python

I have a 2D NumPy array and would like to replace all values in it greater than or equal to a threshold T with 255.0. To my knowledge, the most fundamental way would be:This will be part of a window/level adjustment subroutine for MRI scans of the human head. The 2D numpy array is the image pixel data.I think both the fastest and most concise way to do this is to use Numpy's builtin indexing. If you have a  named  you can replace all elements  with a value  as follows:I ran this on my machine with a 500 x 500 random matrix, replacing all values >0.5 with 5, and it took an average of 7.59ms.Since you actually want a different array which is  where , and  otherwise, this can be done simply:More generally, for a lower and/or upper bound:If you just want to access the values over 255, or something more complicated, @mtitan8's answer is more general, but  and  (or ) are nicer and much faster for your case:If you want to do it in-place (i.e., modify  instead of creating ) you can use the  parameter of :or(the  name is optional since the arguments in the same order as the function's definition.)For in-place modification, the boolean indexing speeds up a lot (without having to make and then modify the copy separately), but is still not as fast as :For comparison, if you wanted to restrict your values with a minimum as well as a maximum, without  you would have to do this twice, with something likeor, You can consider using :Here is a performance comparison with the Numpy's builtin indexing:I think you can achieve this the quickest by using the  function:For example looking for items greater than 0.2 in a numpy array and replacing those with 0:
Python

I am using the standard  in python 2.6 to serialize a list of floats. However, I'm getting results like this:I want the floats to be formated with only two decimal digits. The output should look like this:I have tried defining my own JSON Encoder class:This works for a sole float object:But fails for nested objects:I don't want to have external dependencies, so I prefer to stick with the standard json module.How can I achieve this?Unfortunately, I believe you have to do this by monkey-patching (which, to my opinion, indicates a design defect in the standard library  package). E.g., this code:emits:as you desire. Obviously, there should be an architected way to override  so that EVERY representation of a float is under your control if you wish it to be; but unfortunately that's not how the  package was designed:-(.emitsNo monkeypatching necessary.If you're using Python 2.7, a simple solution is to simply round your floats explicitly to the desired precision.This works because Python 2.7 made . Unfortunately this does not work in Python 2.6: The solutions mentioned above are workarounds for 2.6, but none are entirely adequate. Monkey patching json.encoder.FLOAT_REPR does not work if your Python runtime uses a C version of the JSON module. The PrettyFloat class in Tom Wuttke's answer works, but only if %g encoding works globally for your application. The %.15g is a bit magic, it works because float precision is 17 significant digits and %g does not print trailing zeroes.I spent some time trying to make a PrettyFloat that allowed customization of precision for each number. Ie, a syntax likeIt's not easy to get this right. Inheriting from float is awkward. Inheriting from Object and using a JSONEncoder subclass with its own default() method should work, except the json module seems to assume all custom types should be serialized as strings. Ie: you end up with the Javascript string \"0.33\" in the output, not the number 0.33. There may be a way yet to make this work, but it's harder than it looks.You can do what you need to do, but it isn't documented:If you're stuck with Python 2.5 or earlier versions: The monkey-patch trick does not seem to work with the original simplejson module if the C speedups are installed:Alex Martelli's solution will work for single threaded apps, but may not work for multi-threaded apps that need to control the number of decimal places per thread. Here is a solution that should work in multi threaded apps:You can merely set encoder.thread_local.decimal_places to the number of decimal places you want, and the next call to json.dumps() in that thread will use that number of decimal placesWhen importing the standard json module, it is enough to change the default encoder FLOAT_REPR. There isn't really the need to import or create Encoder instances.Sometimes is also very useful to output as json the best representation python can guess with str. This will make sure signifficant digits are not ignored.Really unfortunate that  doesn't allow you to do anything to floats. However  does. So if you don't mind the extra CPU load, you could throw it through the encoder/decoder/encoder and get the right result:Pros:Cons:If you need to do this in python 2.7 without overriding the global json.encoder.FLOAT_REPR, here's one way.Then, in python 2.7:In python 2.6, it doesn't quite work as Matthew Schinckel points out below:I agree with @Nelson that inheriting from float is awkward, but perhaps a solution that only touches the  function might be forgiveable. I ended up using the  package for this to reformat floats when needed. The upside is that this works in all contexts where  is being called, so also when simply printing lists to stdout for example. Also, the precision is runtime configurable, after the data has been created. Downside is of course that your data needs to be converted to this special float class (as unfortunately you cannot seem to monkey patch ). For that I provide a brief conversion function.The code:Usage example:
Python

Or is there a better way to quickly output the contents of an array (multidimensional or what not).  Thanks.The python  statement does a good job of formatting multidimesion arrays without requiring the  available in php.As the definition for print states that each object is converted to a string, and as simple arrays print a '[' followed by a comma separated list of object values followed by a ']', this will work for any depth and shape of arrays.For exampleIf you need more advanced formatting than this, s answer suggesting  is probably the way to go.Check out . and  are great for built-in data types or classes which define a sane object representation. If you want a full dump of arbitrary objects, you'll have to roll your own. That is not that hard: simply create a recursive function with the base case being any non-container built-in data type, and the recursive case applying the function to each item of a container or each attribute of the object, which can be gotten using  or the  module.there is print_r for python \nbut it is better to use standard modulesYou were looking for the  bult-in function.\nhere's one you can try:you can install it simply using disclaimer: I wrote it :)if you want to format  as a string you can do:it works regardless the type, and doesn't requiere any imports.If you want to include the contents of an object in a single string together with its type:For simple test views I use HttpResponse. Testing request from form, variable, string, id, not Object
Python

I'd like to add comments for a few packages in a pip requirements file. (Just to explain why that package is on the list.) Can I do this?I'm imagining something likeSure, you can, based on :Go ahead!
Python

Say I have an image of size 3841 x 7195 pixels. I would like to save the contents of the figure to disk, resulting in an image of the  I specify in pixels.No axis, no titles. Just the image. I don't personally care about DPIs, as I only want to specify the size the image takes in the screen in disk .I have read  , and they all seem to do conversions to inches and then specify the dimensions of the figure in inches and adjust dpi's in some way. I would like to avoid dealing with the potential loss of accuracy that could result from pixel-to-inches conversions.I have tried with:with no luck (Python complains that width and height must each be below 32768 (?))From everything I have seen,  requires the figure size to be specified in  and , but I am only interested in  the figure takes in disk. How can I do this?To clarify: I am looking for a way to do this with , and not with other image-saving libraries.Matplotlib doesn't work with pixels directly, but rather physical sizes and DPI. If you want to display a figure with a certain pixel size, you need to know the DPI of your monitor. For example  will detect that for you.If you have an image of 3841x7195 pixels it is unlikely that you monitor will be that large, so you won't be able to show a figure of that size (matplotlib requires the figure to fit in the screen, if you ask for a size too large it will shrink to the screen size). Let's imagine you want an 800x800 pixel image just for an example. Here's how to show an 800x800 pixel image in my monitor ():So you basically just divide the dimensions in inches by your DPI. If you want to save a figure of a specific size, then it is a different matter. Screen DPIs are not so important anymore (unless you ask for a figure that won't fit in the screen). Using the same example of the 800x800 pixel figure, we can save it in different resolutions using the  keyword of . To save it in the same resolution as the screen just use the same dpi:To to save it as an 8000x8000 pixel image, use a dpi 10 times larger:Note that the setting of the DPI is not supported by all backends. Here, the PNG backend is used, but the pdf and ps backends will implement the size differently. Also, changing the DPI and sizes will also affect things like fontsize. A larger DPI will keep the same relative sizes of fonts and elements, but if you want smaller fonts for a larger figure you need to increase the physical size instead of the DPI. Getting back to your example, if you want to save a image with 3841 x 7195 pixels, you could do the following:Note that I used the figure dpi of 100 to fit in most screens, but saved with  to achieve the required resolution. In my system this produces a png with 3840x7190 pixels -- it seems that the DPI saved is always 0.02 pixels/inch smaller than the selected value, which will have a (small) effect on large image sizes. Some more discussion of this .This worked for me, based on your code, generating a 93Mb png image with color noise and the desired dimensions:I am using the last PIP versions of the Python 2.7 libraries in Linux Mint 13.Hope that helps!for manipulating images directly I would use the opencv bindings to python, or else numpy arrays
Python

I am having a problem with my encoding in Python. I have tried different methods but I can't seem to find the best way to encode my output to UTF-8.This is what I am trying to do: returns the first Google result for .This is the error I get:Does anyone know how I can make Python encode my output in UTF-8 to avoid this error?Looks like  already returns :So what you want is:As a side note, your code expects it to return a  encoded string so what was the point in decoding it (using ) and encoding back (using ) using the same encoding?
Python

I want to start reading the Python source code.My experience,I know Python and Java very well. I know some other languages at various levels of proficiency, but neither C/C+/ particularly well. I studied C in college, but have never professionally programmed in it.My Reasons for reading this code.1 is more important to me than 2.how should I go about this?Start by learning about the Python C API. It is a large and rich API, and the Python source naturally uses it all over the place.  You won't get very far into the Python source code before you have to understand what is meant by Py_INCREF and so on.I gave a presentation at Pycon explaining the API:  that you might find helpful.  C extensions use the same API as the Python code itself.First, if you're mostly interested in 1, I'd start with reading the Python source of various modules (and not jump straight to the C). Whenever I found myself reading the source of some modules, I've always learned new things about Python programming.Second, if you're trying to learn C better, I'd personally suggest something completely different: program in it. Just statically reading source code is  going to make you understand C better (or at least, it's a limited approach; it might make you a little better, but there's only so much that reading source will get you).After programming at least a moderately sized project in C,  I'd start looking at Python source. That's really the only way to know C better, and I really think that reading the C source of Python without knowing C well won't get you very far.In fact, here's an idea for a C project: write a Python interpreter in C. Obviously it's not going to be even close to complete, and this is a pretty hard project, but if you only focus on some parts of the language, I think its a good idea.Not only will it help you learn C, it will help you understand Python a lot better even  looking at the source: you'll have to have a deeper understanding of a  of stuff in Python, you'll understand the design tradeoffs in how Python works, etc.Then, when you do finally read Python's code, not only will you understand why some things work that way, you'll probably learn a lot of really cool C techniques that solve problems you had.1) First make sure you can build your own Python and run it into a debugger.\nSo you can not only add print expressions but also break at points and follow the code flow.\nIf you have toolsl that let you trace function calls, perfect, you will need it.2) Start with the file that implement the data types. They are very easy to understand and you improve your C language language skills while reading the code.3) Make UML diagrams - simple drawing helper tools like Argo UML or MS Visio can help you here. Write down the code flow.4) Read the startup code for python. See what and how the basic infrastructure is initialized.6) Ty to understand the Python side 100% - even the harder implementation details, what an AST is and what bound and unbound methods are and how you would implement them. When you have a model in mind how you would write an python interpreter then you can go to the final master step.7) Write a debugger extension with the provided fast debugger C API.\nThis helps you to improve your C skills.8) Take the final master step and dive into the heart of the interpreter code. This is even hard to read and understand for a well skilled C programmer. Read how expressions are evaluation and method looksup are cached, frames are setup for scoping rules etc. It's difficult and complex - in terms of complexity and lines of code.9) Start Adobe Photoshop and create a nice looking \"Master of Python\" diploma and put it on your office wall.Download the  from the Python website. Say you unzipped the source into a directory named Python-3.1.1. I suggest you two starting points within Python source code that would help you explore how Python works under the hood:The question is quite broad so I guess the best answer is to just download the  and go nuts. Pick a module or section of python you know well and check whats under the hood.
Python

I have a dataframe with 2 index levels:Which I want to turn into this:How can I best do this?   I need this because I want to aggregate the data , but I can't select my columns like that if they are in use as indices.The  is a pandas DataFrame method that will transfer index values into the DataFrame as columns.  The default setting for the parameter is  (which will keep the index values as columns).All you have to do add  after the name of the DataFrame:
Python

I am getting an issue in Python 3.3.2 on OSX 10.9 where if I open Python in a terminal window, it exits with \"Segmentation error: 11\" after the second line I enter, regardless of what the two commands are. For example, if I enter:that works fine, but if I enter:then I get the error when I press enter on the second line. I can also run a script with more than 2 lines without any problems.I updated to OSX 10.9 this afternoon, so I suspect that may be it. However, I just recently installed IPython (along with several other packages) and have been using that the past couple of days, so it could be something else I installed recently. I had a couple unsuccessful attempts at installing PyQt where I ran configure.py but then the \"make\" command failed, which I was also suspicious of.I tried reinstalling Python, but it didn't resolve the issue. Both IPython and IDLE work with no problems. I'm just concerned about what could be the underlying issue.Any help is appreciated, thanks in advance.This is a bug in the readline compatibility in python, related to changes introduced in OSX10.9. This weekend, release candidates for Python2.7.6 and Python3.3.3 were released which fix this bug. The download links are below.Here's the issue, quoting from Ned Deily, writing on the .I had this problem after upgrading to OS X 10.9 and used the patch provided on the Python website: To use it, open a terminal session in Terminal.app (or other shell), then enter:then\n    Enter your password, if promptedI had this problem. Changing the  in my csv parser to 100 eliminated the error.I was encountering similar 'segmentation fault 11' errors but for me it was using mercurial(hg) This was trying to use Python 2.7.8 installed via the .mpkg installer and pip install mercurial\nOn OS X 10.9.5I thought updating to 2.7.8 would have resolved this but it seemed that mercurial was still looking for the System/Library/Frameworks/Python.framework/Versions/2.7Even after trying to follow this  Things still weren't working.  I would run would get 'segmentation fault 11'The first couple of lines of the stack trace point to this:In the end my solution seems to have come from (re)installing python with  using that to get the 2.7.8 release (as of Dec 2014)I then reinstalled mercurial with brew install mercurial which seems to have resolved whatever dependencies where causing this.  I wish I understood better what was happening with the Seg fault but couldn't get to the bottom of it./usr/local/bin:usr/local/git/bin:/Library/Frameworks/Python.framework/Versions/2.7/bin:/Library/Frameworks/Python.framework/Versions/3.4/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:~/Develop:/usr/local/git/bin: No such file or directory
Python

With python properties, I can make it such that calls a function rather than just returning a value.Is there a way to do this with modules? I have a case where I wantto call a function, rather than just returning the value stored there.Only instances of new-style classes can have properties.  You can make Python believe such an instance is a module by stashing it in .  So, for example, your m.py module file could be:I would do this in order to properly inherit all the attributes of a module, and be correctly identified by isinstance()And then you can insert this into sys.modules:A typical use case is: enriching a (huge) existing module with some (few) dynamic attributes - without turning all module stuff into a class layout.\nUnfortunately a most simple module class patch like  fails with . So module creation needs to be rewired.This approach does it without Python import hooks, just by having some prolog on top of the module code:Usage:Note: Something like  will produce a frozen copy of course - corresponding to 
Python

Is it possible to use Python to write cross-platform apps for both iOS and AndroidFor Android Google provides something called ASE (Android Scripting Environment) which allows scripting languages (Python included) to run on Android. More details For iOS, it might be quite a bit more complicated (and I'd advise to check the latest version of iOS SDK agreement to check the current state of the law - apple tends to allow & disallow such apps periodically). For the technical part you might need to interface between Python & Objective C as well as do some wizardry to statically link all the libraries Python requires; full details are available .\nAnother approach for iOS Python development would be to embed a Python interpreter into you app and distribute your Python script with it (so to play nicely with Apple rules). In this case your Python application would be a Python interpreter which is packaged with your script and runs it automatically.Second option is to use Kivy framework(kivy.org) - it's a framework to write touch-friendly applications in Python and package them for different platforms. It's had Android support for a while, and recently added iOS supportAn option is : a cool cross platform Python framework which works for Android, Win7, Linux, MacOSX and iOS.Update: kivy project is growing daily, now supports also Raspberry PiFor writing a GUI applicaion you can use the  library,then package it with  into a Android and/or iOS app (or Windows, Linux, macOS etc). the project is still in alpha state but under rapid development.
Python

When storing a bool in memcached through python-memcached I noticed that it's returned as an integer. Checking the code of the library showed me that there is a place where  is checked to flag the value as an integer.So I tested it in the python shell and noticed the following:But why exactly is  a subclass of ?It kind of makes sense because a boolean basically is an int which can just take two values but it needs much less operations/space than an actual integer (no arithmetics, only a single bit of storage space)....From a comment on Credit goes to dman13 for this nice explanation.See .  Relevent passage:
Python

I have a python list, say lI want to write a sql query to get the data for all the elements of the list, say\"select name from studens where id = |IN THE LIST l|\"How do i accomlish this?Answers so far have been templating the values into a plain SQL string. That's absolutely fine for integers, but if we wanted to do it for strings we get the escaping issue.Here's a variant using a parameterised query that would work for both:The SQL you want isIf you want to construct this from the python you could useThe  function will transform the list into a list of strings that can be glued together by commas using the  method.Alternatively:if you prefer  to the map function.UPDATE:  mentions in the comments that the Python SQLite bindings don't support sequences. In that case, you might wantGenerated by  the list values separated by commas, and use the  to form a query string.(Thanks, )Dont complicate it, Solution for this is simple.I hope this helped !!!I like bobince's answer:But I noticed this:Can be replaced with:I find this more direct if less clever and less general. Here  is required to have a length (i.e. refer to an object that defines a  method), which shouldn't be a problem. But placeholder must also be a single character. To support a multi-character placeholder use:For example, if you want the sql query:What about:Solution for @umounted answer, because that broke with a one-element tuple, since (1,) is not valid SQL.:Other solution for sql string:
Python

In my Python socket program, I sometimes need to interrupt it with ctrl-c. When I do this, it does close the connection using socket.close() however when I try to reopen it I have to wait what seems like a minute before I can connect again. How does one correctly close a socket? Or is this intended?Yes, it is intended. Here you can read . It is possible to override this behavior by setting SO_REUSEADDR option on a socket. For example:If you use a TCPServer, UDPServer or their subclasses in the SocketServer module, you can set this class variable (before instanciating a server):(via  )This causes the  (constructor) to:-> ps -fA | grep python501 81211 12368   0  10:11PM ttys000    0:03.12\npython -m SimpleHTTPServer-> kill 81211Nothing worked for me except running a subprocess with this command, before calling HTTPServer(('', 443), myHandler):kill -9 $(lsof -ti tcp:443)Of course this is only for linux-like OS!
Python

I just want to see the state of the process, is it possible to attach a console into the process, so I can invoke functions inside the process and see some of the global variables.It's better the process is running without being affected(of course performance can down a little bit)If you have access to the program's source-code, you can add this functionality relatively easily. See : To quote:Another implementation of roughly the same concept is provided by .  From the documentation:This will interrupt your process (unless you start it in a thread), but you can use the  module to start a Python console:This will block until the user exits the interactive console by executing .The  module is available in at least Python v2.6, probably others.I tend to use this approach in combination with signals for my Linux work (for Windows, see below). I slap this at the top of my Python scripts:And then trigger it from a shell with , where  is the process ID. The process then stops whatever it is doing and presents a console:Generally from there I'll load the server-side component of a remote debugger like the excellent .Windows is not a -compliant OS, and so does not provide the same signals as Linux. However,  (triggered by pressing +). This does  interfere with normal + () operation, and so is a handy alternative.Therefore a portable, but slightly ugly, version of the above is:Advantages of this approach:Here's the code I use in my production environment which will load the server-side of WinPDB (if available) and fall back to opening a Python console.Use . I can't believe it works so well, but it does. \"\".This launches the python shell with access to the globals() and locals() variables of that running python process, and other wonderful things.Only tested this personally on Ubuntu but seems to cater for OSX too.Adapted from .Note: The line switching off the  property is only necessary for kernels/systems that have been built with  on. Take care messing with ptrace_scope in sensitive environments because it could introduce certain security vulnerabilities. See  for details.Why not simply using the  module? It allows you to stop a script, inspect elements values, and execute the code line by line. And since it is built upon the Python interpreter, it also provides the features provided by the classic interpreter. To use it, just put these 2 lines in your code, where you wish to stop and inspect it:Another possibility, without adding stuff to the python scripts, is described here:Unfortunately, this solution also requires some forethought, at least to the extent that you need to be using a version of python with debugging symbols in it.Using PyCharm, I was getting a failure to connect to process in Ubuntu.  The fix for this is to disable YAMA.  For more info see 
Python

I was reading a question about the Python  statement (  ) and I was remembering about how often I used this statement when I was a Python beginner (I used  a lot) and how, nowadays, years later, I don't use it at all, ever. I even consider it a bit \"un-pythonic\".Do you use this statement in Python ? Has your usage of it changed with time ?I use 'global' in a context such as this:I use 'global' because it makes sense and is clear to the reader of the function what is happening. I also know there is this pattern, which is equivalent, but places more cognitive load on the reader:I've never had a legit use for the statement in any production code in my 3+ years of professional use of Python and over five years as a Python hobbyist. Any state I need to change resides in classes or, if there is some \"global\" state, it sits in some shared structure like a global cache.I've used it in situations where a function creates or sets variables which will be used globally.  Here are some examples:or In my view, as soon as you feel the need to use global variables in a python code, it's a great time to stop for a bit and work on refactoring of your code.\nPutting the  in the code and delaying the refactoring process might sound promising if your dead-line is close, but, believe me, you're not gonna go back to this and fix unless you really have to - like your code stopped working for some odd reason, you have to debug it, you encounter some of those  variables and all they do is mess things up.So, honestly, even it's allowed, I would as much as I can avoid using it. Even if it means a simple classes-build around your piece of code.Objects are the prefered way of having non-local state, so global is rarely needed. I dont think the upcoming nonlocal modifier is going to be widely used either, I think its mostly there to make lispers stop complaining :-)I use it for global options with command-line scripts and 'optparse':my main() parses the arguments and passes those to whatever function does the work of the script... but writes the supplied options to a global 'opts' dictionary.Shell script options often tweak 'leaf' behavior, and it's inconvenient (and unnecessary) to thread the 'opts' dictionary through every argument list. I avoid it and we even have a  rule that forbids it in our production code. I actually believe it shouldn't even exist at all.Rarely. I've yet to find a use for it at all.It can be useful in threads for sharing state (with locking mechanisms around it).However, I rarely if ever use it.I've used it in quick & dirty, single-use scripts to automate some one-time task. Anything bigger than that, or that needs to be reused, and I'll find a more elegant way.Once or twice. But it was always good starting point to refactor.If I can avoid it, no. And, to my knowledge, there is always a way to avoid it. But I'm not stating that it's totally useless either
Python

Just about everyone uses them, but many, including me simply take it for granted that they just work.I am looking for high-quality material. Languages I use are: Java, C, C#, Python, C++, so these are of most interest to me.Now, C++ is probably a good place to start since you can throw anything in that language. Also, C is close to assembly. How would one emulate exceptions using pure C constructs and no assembly?Finally, I heard a rumor that Google employees do not use exceptions for some projects due to speed considerations. Is this just a rumor? How can anything substantial be accomplished without them?Thank you.Exceptions are just a specific example of a more general case of advanced non-local flow control constructs. Other examples are:(I'm sure there's many others I missed.)An interesting property of these constructs is that they are all roughly equivalent in expressive power: if you have , you can pretty easily build all the others.So, how you best implement exceptions depends on what other constructs you have available: A very interesting use case, both of the  of exceptions  the  of exceptions is Microsoft Live Lab's Volta Project. (Now defunct.) The goal of Volta was to provide architectural refactoring for Web applications at the push of a button. So, you could turn your one-tier web application into a two- or three-tier application just by putting some  or  attributes on your .NET code and the code would then automagically run on the client or in the DB. In order to do that, the .NET code had to be translated to JavaScript source code, obviously.Now, you  just write an entire VM in JavaScript and run the bytecode unmodified. (Basically, port the CLR from C++ to JavaScript.) There are actually projects that do this (e.g. the HotRuby VM), but this is both inefficient and not very interoperable with other JavaScript code.So, instead, they wrote a compiler which compiles CIL bytecode to JavaScript sourcecode. However, JavaScript lacks certain features that .NET has (generators, threads, also the two exception models aren't 100% compatible), and more importantly it lacks certain features that compiler writers  (either  or continuations) and that could be used to implement the above-mentioned missing features.However, JavaScript  have exceptions. So, they used  to implement  and then they used  to implement ,  and even (!!!)So, to answer your original question:With Exceptions, ironically! At least in this very specific case, anyway.Another great example is some of the exception proposals on the Go mailing list, which implement exceptions using Goroutines (something like a mixture of concurrent coroutines ans CSP processes). Yet another example is Haskell, which uses Monads, lazy evaluation, tail call optimization and higher-order functions to implement exceptions. Some modern CPUs also support basic building blocks for exceptions (for example the Vega-3 CPUs that were specifically designed for the Azul Systems Java Compute Accelerators).Here is a common way C++ exceptions are implemented:\nIt is for the Itanium architecture, but the implementation described here is used in other architectures as well. Note that it is a long document, since C++ exceptions are complicated.Here is a good description on how LLVM implements exceptions:\nSince LLVM is meant to be a common intermediate representation for many runtimes, the mechanisms described can be applied to many languages.In his book ,  D. R. Hanson provides a nice implementation of exceptions in pure C using a set of macros and . He provides TRY/RAISE/EXCEPT/FINALLY macros that can emulate pretty much everything C++ exceptions do and more. The code can be perused  (look at except.h/except.c).P.S. re your question about Google. Their employees are actually allowed to use exceptions in new code, and the official reason for the ban in old code is because it was already written that way and it doesn't make sense to mix styles.Personally, I also think that C++ without exceptions isn't the best idea.C/C++ compilers use the underlying OS facilities for exception handling. Frameworks like .Net or Java also rely, in the VM, on the OS facilities. In Windows for instance, the real heavy lifting is done by SEH, the Structured Exception Handling infrastructure. You should absolutely read the old reference article: .As for the cost of not using exceptions, they are expensive but compared to what? Compared to return error codes? After you factor in the cost of correctness and the quality of code, exceptions will always win for commercial applications. Short of few very critical OS level functions, exceptions are always better overall. An last but not least there is the anti-pattern of using exceptions for flow control. Exceptions should be exceptional and code that abuses exceptions fro flow control will pay the price in performance.The best paper ever written on the  of exceptions (under the hood) is  by Barbara Liskov and Alan Snyder.  I have referred to it every time I've started a new compiler.For a somewhat higher-level view of an implementation in C using  and , I recommend Dave Hanson's  (like Eli Bendersky).The key thing an exception implementation needs to handle is how to return to the exception handler once an exception has been thrown. Since you may have made an arbitrary number of nested function calls since the try statement in C++, it must  searching for the handler. However implemented, this must incur the  of maintaining sufficient information in order to perform this operation (and generally means a table of data for calls that can take exceptions). It also means that the dynamic code  than simply returning from functions calls (which is a fairly inexpensive operation on most platforms). There may be other costs as well depending on the implementation.The relative cost will vary depending on the language used. The higher-level language used, the less likely the code size cost will matter, and the information may be retained regardless of whether exceptions are used.An application where the use of exceptions (and C++ in general) is often avoided for good reasons is embedded firmware. In typical small bare metal or RTOS platforms, you might have 1MB of code space, or 64K, or even smaller. Some platforms are so small, even C is not practical to use. In this kind of environment, the size impact is relevant because of the cost mentioned above. It also impacts the standard library itself. Embedded toolchain vendors will often produce a library without exception capability, which has a huge impact on code size. Highly optimizing compilers may also analyze the callgraph and optimize away needed call frame information for the unwind operation for considerable space reduction. Exceptions also make it more difficult to analyze hard real-time requirements.In more typical environments, the code size cost is almost certainly irrelevant and the performance factor is likely key. Whether you use them will depend on your performance requirements and how you want to use them. Using exceptions in non-exceptional cases can make an elegant design, but at a performance cost that may be unacceptable for high performance systems. Implementations and relative cost will vary by platform and compiler, so the best way to truly understand if exceptions are a problem is to analyze your own code's performance. and  usually.Exception catching does have a non-trivial cost, but for most purposes it's not a big deal.C++ code at Google (save for some Windows-specific cases) don't use exceptions: cfr , short form: \"We do not use C++ exceptions\".  Quoting from the discussion (hit the arrow to expand on the URL):This rule does not apply to Google code in other languages, such as Java and Python.Regarding performance - sparse use of exceptions will probably have negligible effects, but do not abuse them.I have personally seen Java code which performed two orders of magnitude worse than it could have (took about x100 the time) because exceptions were used in an important loop instead of more standard if/returns.Some runtimes like  have zero-cost 64-bit exceptions. What that means is that it doesn't cost anything to enter a try block. However, this is quite costly when the exception is thrown. This follows the paradigm of \"optimize for the average case\" - exceptions are meant to be exceptional, so it is better to make the case when there are no exceptions really fast, even if it comes at the cost of significantly slower exceptions.
Python

Much of my programming background is in Java, and I'm still doing most of my programming in Java. However, I'm starting to learn Python for some side projects at work, and I'd like to learn it as independent of my Java background as possible - i.e. I don't want to just program Java in Python. What are some things I should look out for?A quick example - when looking through the Python tutorial, I came across the fact that defaulted mutable parameters of a function (such as a list) are persisted (remembered from call to call). This was counter-intuitive to me as a Java programmer and hard to get my head around. (See  and  if you don't understand the example.)Someone also provided me with  list, which I found helpful, but short. Anyone have any other examples of how a Java programmer might tend to misuse Python...? Or things a Java programmer would falsely assume or have trouble understanding?: Ok, a brief overview of the reasons addressed by the article I linked to to prevent duplicates in the answers (as suggested by Bill the Lizard). (Please let me know if I make a mistake in phrasing, I've only  started with Python so I may not understand all the concepts fully. And a disclaimer - these are going to be  brief, so if you don't understand what it's getting at check out the link.)(And if you find this question at all interesting, check out the link anyway. :) It's quite good.)Just do this:The referenced article has some good advice that can easily be misquoted and misunderstood.  And some bad advice.Leave Java behind.   Start fresh.  \"do not trust your [Java-based] instincts\".  Saying things are \"counter-intuitive\" is a bad habit in any programming discipline.  When learning a new language, start fresh, and drop your habits.  Your intuition  be wrong.  Languages are .  Otherwise, they'd be the same language with different syntax, and there'd be simple translators.  Because there are not simple translators, there's no simple mapping.  That means that intuition is unhelpful and dangerous.One thing you might be used to in Java that you won't find in Python is strict privacy.  This is not so much something to look out for as it is something  to look for (I am embarrassed by how long I searched for a Python equivalent to 'private' when I started out!).  Instead, Python has much more transparency and easier introspection than Java.  This falls under what is sometimes described as the \"we're all consenting adults here\" philosophy.  There are a few conventions and language mechanisms to help prevent  use of \"unpublic\" methods and so forth, but the whole mindset of information hiding is virtually absent in Python.The biggest one I can think of is not understanding or not fully utilizing duck typing.  In Java you're required to specify very explicit and detailed type information upfront.  In Python typing is both dynamic and largely implicit.  The philosophy is that you should be thinking about your program at a higher level than nominal types.  For example, in Python, you don't use inheritance to model substitutability.  Substitutability comes by default as a result of duck typing.  Inheritance is only a programmer convenience for reusing implementation.Similarly, the Pythonic idiom is \"beg forgiveness, don't ask permission\".  Explicit typing is considered evil.  Don't check whether a parameter  a certain type upfront.  Just try to do whatever you need to do with the parameter.  If it doesn't conform to the proper interface, it will throw a very clear exception and you will be able to find the problem very quickly.  If someone passes a parameter of a type that was nominally unexpected but has the same interface as what you expected, then you've gained flexibility for free.The most important thing, from a Java POV, is that it's perfectly ok to not make classes for everything.  There are many situations where a procedural approach is simpler and shorter.The next most important thing is that you will have to get over the notion that the  of an object controls what it may do; rather, the  controls what objects must be able to support  (this is by virtue of duck-typing).  Oh, and use native lists and dicts (not customized descendants) as far as possible.The way exceptions are treated in Python is different from \nhow they are treated in Java. While in Java the advice\nis to use exceptions only for exceptional conditions this is not\nso with Python. In Python things like Iterator makes use of exception mechanism to signal that there are no more items.But such a design is not considered as good practice in Java.As Alex Martelli puts in his book \nthe exception mechanism with other languages (and applicable to Java) \nis  (Look Before You Leap) : \nis to check in advance, before attempting an operation, for all circumstances that might make the operation invalid. Where as with Python the approach is EAFP (it's easier to Ask for forgiveness than permission)A sensation of ?A corrollary to \"Don't use classes for everything\": callbacks. The Java way for doing callbacks relies on passing objects that implement the callback interface (for example  with its  method). Nothing of this sort is necessary in Python, you can directly pass methods or even locally defined functions:Or even lambdas:
Python

When I ran   (Mac OS X 10.9.2), I get the following warning message:Therefore, I ran  and followed the steps provided in the installation's caveats output to install Homebrew's version of . Running  confirms that Homebrew's version of it is indeed at the top of my . Output is .Despite all this, when I rerun , I am still getting the . How do I suppress this warning? Do I need to delete the /Library/Frameworks/Python.framework directory from my computer? Am I just supposed to ignore it? Is there a different application on my computer that may be causing this warning to emit?Note that I don't have any applications in particular that are running into errors due to this warning from . Also note that this warning message didn't always print out when I ran , it was something that started to appear recently. Also, I am using Python 2.7 on my computer, trying to stay away from Python 3.I had the same problem. When I upgraded python3 through Homebrew, I started getting this:I had the same conflict with Python somehow being installed in . I just did a  and everything is working fine now. There is some info about what to do with the Python version in the  .I guess you could try deleting that version as the link suggests, just make sure that version isn't being used. When I got into the Python.framework directory I was seeing some EPD version of Python, which I think is Enthought. You could delete it, but I if it isn't causing you any problems besides the unsightly Homebrew warning message, then I think you should just ignore it for now. Update:I did delete the Python.framework directory which, through some poking around inside that directory, I started seeing a few old versions of Python that I didn't install with Homebrew. One was from Enthought, and another was a distribution of Python3.3. I think some of these installs in the Framework directory are user installs. I installed R on my system, and there is also an R.framework directory, so I think most of these are user installs. After I deleted the directory, I just had to call brew prune to remove the old symlinks. I checked both brew versions of python 2.7.6 and 3.3.4, and they seem to be in good working order with all of my installed packages. I guess I leave the decision to remove that directory, or python version, to your discretion. I also received this message. Something, sometime installed on my machine (the folder date was about 4 years old).I've chosen to remove it.Please note that the Apple provided framework lives in per , enter this command:because there are multiple installations of Python on your computer, and this removes the one that may cause additional problems in the future.You can use this solution as I've put belowThat combo fixed it for me, even thought this error usually doesn't cause any major problems its just was annoying me to see them pop up under brew doctorRemoving directories manually can be a nightmare, but fortunately 'brew' can take care of that. Once you are done with the removal, put this:The above command will list the broken system links. In order to get rid of these broken symlinks, put this:Check with 'brew doctor' once more to ensure no links are broken. Your system will then be ready to brew.
Python

I haven't seen anything about Windows compatibility -- is this on the way or currently available somewhere if I put forth some effort? (I have a Mac and an Ubuntu box but the Windows machine is the one with the discrete graphics card that I currently use with theano). Today we released the first release candidate of TensorFlow 0.12, which includes support for Windows. You can install the Python bindings using the following command in a Python shell:...or, if you want GPU support:You can also build TensorFlow yourself using Microsoft Visual C++ and NVCC (for the CUDA parts). The easiest way to build on Windows is currently to use the , and we will soon provide support for . We haven't tried to build TensorFlow on Windows so far: the only supported platforms are Linux (Ubuntu) and Mac OS X, and we've only built binaries for those platforms.For now, on Windows, the easiest way to get started with TensorFlow would be to use Docker: It should become easier to add Windows support when Bazel (the build system we are using) adds support for building on Windows, which is .  You can see .In the meantime, you can follow .As @mrry suggested, it is easier to set up TensorFlow with Docker. Here's how I managed to set it up as well as getting iPython Notebook up and running in my Docker environment (I find it really convenient to use iPython Notebook for all testing purposes as well as documenting my experiments).I assume that you have installed both docker and boot2docker for Windows here.First, run TensorFlow docker on daemon and set it up so Jupyter server (iPython Notebook) can be accessed from your main Windows system's browser:Replace  with a path in your host you wish to mount i.e. where you can keep your iPython files. .  is the location in your TensorFlow docker where your host path's mounted against. basically means \"map port 8888 in docker to 8888 in host directory\". You can change the second part to other ports if you wish.When you got it running, you can access it by running the following code:Where [docker-id] can be found by running:To start your ipython notebook server from within TensorFlow's docker, run the following command:To allow ipython server to listen to all ip so your app may be accessible from host machine.Instead of viewing your app in , you can only view it in . To find  run this in your terminal (not boot2docker terminal):Another way to run it on Windows is to install for example Vmware (a free version if you are not using it commercially), install Ubuntu Linux into that and then install TensorFlow using the Linux instructions. That is what I have been doing, it works well.TensorFlow is not supporting Windows at this point, but Windows has changed. Windows 10 Build 14432 includes bash.You can download the build from After installation, just install/enable bash, and type  in cmd. That's it.\n(The image is from )Then, run this (Python is already installed):Happy tensorflowing in Windows!Initial support for building TensorFlow on Microsoft Windows was added on  2016-10-05 in commit :.TensorFlow is now officially available on Windows!
Python

In Matplotlib, I make dashed grid lines as follows:however, I can't find out how (or even if it is possible) to make the grid lines be drawn behind other graph elements, such as bars. Changing the order of adding the grid versus adding other elements makes no difference. Is it possible to make it so that the grid lines appear behind everything else?According to this -  - you can use Axis.set_axisbelow()(I am currently installing matplotlib for the first time, so have no idea if that's correct - I just found it by googling \"matplotlib z order grid\" - \"z order\" is typically used to describe this kind of thing (z being the axis \"out of the page\"))To me, it was unclear how to apply andrew cooke's answer, so this is a complete solution based on that:I had the same problem and the following worked:Increase to a higher value if it does not work.If you want to validate the setting for  figures, you may setor It works for Matplotlib>=2.0.
Python

I've got some example Python code that I need to mimic in C++. I do not require any specific solution (such as co-routine based yield solutions, although they would be acceptable answers as well), I simply need to reproduce the semantics in some manner.This is a basic sequence generator, clearly too large to store a materialized version.The goal is to maintain two instances of the sequence above, and iterate over them in semi-lockstep, but in chunks. In the example below the  uses the sequence of pairs to initialize the buffer, and the  regenerates the  and processes the buffer again.The only thing I can find for a solution in C++ is to mimic  with C++ coroutines, but I haven't found any good reference on how to do this. I'm also interested in alternative (non general) solutions for this problem. I do not have enough memory budget to keep a copy of the sequence between passes.Generators exist in C++, just under another name: . For example, reading from  is similar to having a generator of .You simply need to understand what a generator does:In your trivial example, it's easy enough. Conceptually:Of course, we wrap this as a proper class:So hum yeah... might be that C++ is a tad more verbose :)In C++ there are iterators, but implementing an iterator isn't straightforward: one has to consult the  and carefully design the new iterator class to implement them. Thankfully, Boost has an  template which should help implementing the iterators and iterator-compatible generators.Sometimes .P.S. See also  which mentions both a  hack by Christopher M. Kohlhoff and  by Oliver Kowalke. Oliver Kowalke's work  on  by Giovanni P. Deretta.P.S. I think you can also write a kind of generator :Or with a functor:P.S. Here's a generator implemented with the  coroutines:Since  now supports it very well (I found it because I wanted to solve exactly the same  problem), I am posting the C++ code that matches your original intention:In this example,  does not take additional arguments. If it needs to,  or a lambda should be used to generate a function object that takes only one argument (of ), when it is passed to the  constructor.You should probably check generators in std::experimental in Visual Studio 2015 e.g: I think it's exactly what you are looking for. Overall generators should be available in C++17 as this is only experimental Microsoft VC feature.If you only need to do this for a relatively small number of specific generators, you can implement each as a class, where the member data is equivalent to the local variables of the Python generator function. Then you have a next function that returns the next thing the generator would yield, updating the internal state as it does so.This is basically similar to how Python generators are implemented, I believe. The major difference being they can remember an offset into the bytecode for the generator function as part of the \"internal state\", which means the generators can be written as loops containing yields. You would have to instead calculate the next value from the previous. In the case of your , that's pretty trivial. It may not be for complex generators.You also need some way of indicating termination. If what you're returning is \"pointer-like\", and NULL should not be a valid yieldable value you could use a NULL pointer as a termination indicator. Otherwise you need an out-of-band signal.Something like this is very similar:Using the operator() is only a question of what you want to do with this generator, you could also build it as a stream and make sure it adapts to an istream_iterator, for example.Just as a function simulates the concept of a stack, generators simulate the concept of a queue.  The rest is semantics.  As a side note, you can always simulate a queue with a stack by using a stack of operations instead of data.  What that practically means is that you can implement a queue-like behavior by returning a pair, the second value of which either has the next function to be called or indicates that we are out of values.  But this is more general than what yield vs return does.  It allows to simulate a queue of any values rather than homogeneous values that you expect from a generator, but without keeping a full internal queue.More specifically, since C++ does not have a natural abstraction for a queue, you need to use constructs which implement a queue internally.  So the answer which gave the example with iterators is a decent implementation of the concept.What this practically means is that you can implement something with bare-bones queue functionality if you just want something quick and then consume queue's values just as you would consume values yielded from a generator.All answers that involve writing your own iterator are completely wrong. Such answers entirely miss the point of Python generators (one of the language's greatest and unique features). The most important thing about generators is that execution picks up where it left off. This does not happen to iterators. Instead, you must manually store state information such that when operator++ or operator* is called anew, the right information is in place  of the next function call. This is why writing your own C++ iterator is a gigantic pain; whereas, generators are elegant, and easy to read+write.I don't think there is a good analog for Python generators in native C++, at least not yet (there is a rummor that ). You can get something similarish by resorting to third-party (e.g. Yongwei's Boost suggestion), or rolling your own.I would say the closest thing in native C++ is threads. A thread can maintain a suspended set of local variables, and can continue execution where it left off, very much like generators, but you need to roll a little bit of additional infrastructure to support communication between the generator object and its caller. E.g.This solution has several downsides though:Something like :Example use:Will print the numbers from 0 to 99
Python

I've started to use my mac to install python packages in the same way I do with my Windows PC at work, however on my mac I've come across frequent  errors writing log files & sometimes writing to site-packages.Therefore I thought about running  under  but is that a safe/acceptable use of sudo considering I'm just wanting this to be installed under my current user account.Example traceback from a logfile I/O error;\nI am able to install if I use  Because I had the same problem, I want to stress that actually the first comment by  is the solution to the \"IOError: [Errno 13]\"-problem:If executed in the temp directory (), the IOError does not occur anymore if I run .Use a :You only use  or elevated permissions when you want to install stuff for the global, system-wide Python installation.It is best to use a virtual environment which isolates packages for you.  That way you can play around without polluting the global python install.As a bonus, virtualenv does not need elevated permissions.It's not safe and it's being frowned upon \u2013 see \nTo install Python package in your home directory you don't need root privileges. See  of  option to pip.It looks like your permissions are messed up. Type  in the Terminal and try  again? Let me know if you're sorted.Actually for this particular case (you not wanting to use  for installing python packages) and no need for global package installs you can use the  flag like this :and it will work just fine.Another approach  like in your case you want to do something like :or more generally  I had a problem installing  after successfully installing .My terminal complained after this:So, I unsuccessfully tried this ():Then, I  installed it with this:
Python

I have been developing a basic app. Now at the deployment stage it has become clear I have need for both a local settings and production settings.It would be great to know the following:My favorite way of doing this is to use the  environment variable and use two (or more) settings files, e.g.  and . You can then use a bootstrap script or a process manager to load the correct settings (by setting the environment). If you're using a virtualenv, you could even hack this into the virtualenv's activate script.You can take advantage of the  variable to store the settings in a completely different location (e.g. on a production server, storing them in  makes sense) \u2014 this allows for easier deployment as you totally separate configuration from application files (which is a good thing).If you're not fond of writing a bootstrap script that sets the environment (and there are very good reasons to feel that way!), I would recommend using a process manager:If using a virtualenv, you append this to your  script:And on your test server:I usually have one settings file per environment, and a shared settings file:Each of my environment files has:This allows me to override shared settings if necessary (by adding the modifications below that stanza).I then select which settings files to use by linking it in to settings.py:Create multiple  files, extrapolating the variables that need to change per environment. Then at the end of your master  file:You keep the separate  files for each stage.At the top of your  file, add this:To import variables that you need to modify.This  has more ideas on how to split your settings.By default use production settings, but create a file called  in the same folder as your  file. Add overrides there, such as .On the computer that will be used for development, add this to your  file:At the bottom of your  file, add the following.(Note that importing  should generally be avoided in Python, but this is a unique circumstance)By default the production servers will not override anything. Done!Compared to the other answers, this one is simpler because it doesn't require updating , or setting  which only allows you to work on one django project at a time.If you want to keep 1 settings file, and your development operating system is different than your production operating system, you can put this at the bottom of your settings.py:Read more: I use the awesome , and all the settings are stored in my :To configure the Django project I just followed the .This is my solution, with different environements for dev, test and prod
Python

I have a freshly installed Ubuntu on a freshly built computer. I just installed python-pip using apt-get. Now when I try to pip install Numpy and Pandas, it gives the following error.I've seen this error mentioned in quite a few places on SO and Google, but I haven't been able to find a solution. Some people mention it's a bug, some threads are just dead... What's going on?I had this exact problem recently and usedThis adds numpy to your system python interpreter.  I may have had to do the same for matplotlib.  To use in a virtualenv, you have to create your environment using theoptionFor me @Charles Duffy comment solved it.\nPut this in your env:You can add it to your .bashrc with a line like this:But take in care that you'll affect all other programs. So you may want to use it just for the pip run:Try updating pip:I had that problem with matplotlib package.\nI had to execute:For me this was solved by ignoring a (presumably) corrupted cache withas described here: I had a similar error when running  and it was due to a memory shortage.  I increased the memory in my virtual machine to 4G and that fixed things.A combination of and solved my problem. try  .\nIt worked out for me and same can be used for scipy,pandas etc by replacing them in place of numpy. (Y)In 'site-packages' directory, make 'sitecustomize.py' like thisNow you can get the file 'pip.log'If you want the pip version of numpy, you can build the dependencies for the package and then install it using pipThis should install everything needed at system level to install the package. Had a similar problem on a Jetson TK1 with Ubuntu.Works fine with  
Python

Given a DataFrame with a column \"BoolCol\", we want to find the indexes of the DataFrame in which the values for \"BoolCol\" == TrueI currently have the iterating way to do it, which works perfectly:But this is not the correct panda's way to do it.\nAfter some research, I am currently using this code:This one gives me a list of indexes, but they dont match, when I check them by doing:The result is actually False!!Which would be the correct Pandas way to do this? returns the  row of .  does not refer to the index label,  is a 0-based index.In contrast, , not numeric row-indices:or equivalently,You can see the difference quite clearly by playing with a DataFrame with\nan \"unusual\" index:, :Note that ::Use  to select rows by ordinal index:Can be done using numpy where() function:Though you don't always need index for a match, but incase if you need:
Python

I have two models like this:I need to do something if the user has Type1 or Type2 profile:But, for users that don't have either type1 or type2 profiles, executing code like that produces the following error:How can I check the type of profile a user has?ThanksTo check if the (OneToOne) relation exists or not, you can use the  function:It's possible to see if a nullable one-to-one relationship is null for a particular model simply by testing the corresponding field on the model for ness, but  if you test on the model where the one-to-one relationship originates. For example, given these two classes\u2026\u2026 to see if a  has a , we can use the following code:To see if a  has a , it's important to understand that referencing the  property on an instance of  raises a  exception if there is no corresponding restaurant. This happens because Django performs a lookup internally using . For example:In this scenario, Occam's razor prevails, and the best approach for making a determination about whether or not a  has a  would be a standard  /  construct as described .While joctee's suggestion to use  works in practice, it really only works by accident since  suppresses  exceptions (including ) as opposed to just s, like it should. As Piet Delport pointed out, this behavior was actually corrected in Python 3.2 per the following ticket: . Furthermore \u2014 and at the risk of sounding opinionated \u2014 I believe the above  /  construct is more representative of how Django works, while using  can cloud the issue for newbies, which may create FUD and spread bad habits.How about using try/except blocks?Then, use like this!I suppose you could use this as a generic function to get any reverse OneToOne instance, given an originating class (here: your profile classes) and a related instance (here: request.user).I like , because it's so simple.Other commenters have raised concerns that it may not work with certain versions of Python or Django, but  shows this technique as one of the options:Of course, the documentation also shows the exception catching technique:I agree with  that catching the exception makes it clearer what's happening, but it just seems messier to me. Perhaps this is a reasonable compromise?This is just querying the  objects by place. It returns  if that place has no restaurant.Here's an executable snippet for you to play with the options. If you have Python, Django, and SQLite3 installed, it should just run. I tested it with Python 2.7, Python 3.4, Django 1.9.2, and SQLite3 3.8.2.Use !
Python

I know Python doesn't have pointers, but is there a way to have this yield  instead?Here's an example: I want  and  to always have the same value. It's not completely necessary, but I think it would be nice.This is feasible, because it involves decorated names and indexing -- i.e.,  different constructs from the   and  that you're asking about, and for with your request is utterly impossible.  Why ask for something impossible  totally different from the (possible) thing you actually ?!Maybe you don't realize how drastically different barenames and decorated names are.  When you refer to a barename , you're getting exactly the object  was last bound to in this scope (or an exception if it wasn't bound in this scope) -- this is such a deep and fundamental aspect of Python that it can't possibly be subverted.  When you refer to a  name , you're asking an object (the object  refers to) to please supply \"the  attribute\" -- and in response to that request, the object can perform totally arbitrary computations (and indexing is quite similar: it also allows arbitrary computations to be performed in response).Now, your \"actual desiderata\" example is mysterious because in each case two levels of indexing or attribute-getting are involved, so the subtlety you crave could be introduced in many ways.  What other attributes is  suppose to have, for example, besides ?  Without that further  computations, possibilities would include:andThe presence of  suggests picking the first form, plus a kind-of-useless wrapper:If  such  is also supposed to set the entry in , then the wrapper must become more complex indeed, and not all that useless:The latter example is roughly as close as it gets, in Python, to the sense of \"a pointer\" as you seem to want -- but it's crucial to understand that such subtleties can ever only work with  and/or ,  with barenames as you originally asked!It's not a bug, it's a feature :-)When you look at the '=' operator in Python, don't think in terms of assignment. You don't assign things, you bind them. = is a binding operator.So in your code, you are giving the value 1 a name: a. Then, you are giving the value in 'a' a name: b. Then you are binding the value 2 to the name 'a'. The value bound to b doesn't change in this operation.Coming from C-like languages, this can be confusing, but once you become accustomed to it, you find that it helps you to read and reason about your code more clearly: the value which has the name 'b' will not change unless you explicitly change it. And if you do an 'import this', you'll find that the Zen of Python states that Explicit is better than implicit.Note as well that functional languages such as Haskell also use this paradigm, with great value in terms of robustness.There's no way you can do that changing only that line.  You can do: That creates a list, assigns the reference to a, then b also, uses the a reference to set the first element to 2, then accesses using the b reference variable.From one point of view,  is a pointer in Python.  Your example works a lot like the C++ code.(A closer equivalent would use some type of  instead of .)You can do this by overloading  in 's class.Yes! there is a way to use a variable as a pointer in python!I am sorry to say that many of answers were partially wrong. In principle every equal(=) assignation shares the memory address (check the id(obj) function), but in practice it is not such. There are variables whose equal(\"=\") behaviour works in last term as a copy of memory space, mostly in simple objects (e.g. \"int\" object), and others in which not (e.g. \"list\",\"dict\" objects).Here is an example of pointer assignationHere is an example of copy assignationPointer assignation is a pretty useful tool for aliasing without the waste of extra memory, in certain situations for performing comfy code,but one have to be aware of this use in order to prevent code mistakes.To conclude, by default some variables are barenames (simple objects like int, float, str,...), and some are pointers when assigned between them (e.g. dict1 = dict2). How to recognize them? just try this experiment with them. In IDEs with variable explorer panel usually appears to be the memory address (\"@axbbbbbb...\") in the definition of pointer-mechanism objects.I suggest investigate in the topic. There are many people who know much more about this topic for sure. (see \"ctypes\" module). I hope it is helpful. Enjoy the good use of the objects! Regards, Jos\u00e9 Crespo
Python

I have an existing file on disk (say /folder/file.txt) and a FileField model field in Django.When I do it re-saves the file as  (the next time it's , etc.).I understand why, but I don't want this behavior - I know the file I want the field to be associated with is really there waiting for me, and I just want Django to point to it.How?If you want to do this permanently, you need to create your own FileStorage classNow in your model, you use your modified MyFileStoragejust set  to the path of your filee.g.try this ():It's right to write own storage class. However  is not the right method to override. is called when Django sees a file with same name and tries to get a new available file name. It's not the method that causes the rename. the method caused that is . Comments in  is pretty good and you can easily find it opens file for writing with flag  which will throw an OSError if same file name already exists. Django catches this Error then calls  to get a new name.So I think the correct way is to override  and call os.open() without flag . The modification is quite simple however the method is a little be long so I don't paste it here. Tell me if you need more help :)I had exactly the same problem! then I realize that my Models were causing that. example I hade my models like this:Then, I wanted to have more the one tile referencing the same file in the disk! The way that I found to solve that was change my Model structure to this:Which after I realize that make more sense, because if I want the same file being saved more then one in my DB I have to create another table for it! I guess you can solve your problem like that too, just hoping that you can change the models! Also I guess you can use a different storage, like this for instance: SymlinkOrCopyStorage
Python

I have a dictionary which looks like this: I would like to apply it to the \"col1\" column of a dataframe similar to:to get:How can I best do this? For some reason googling terms relating to this only shows me links about how to make columns from dicts and vice-versa :-/ You can use .  For example:or directly on the , i.e. .There is a bit of ambiguity in your question. There are at least  two interpretations:Below is a solution for each case.\nIf the keys of  are meant to refer to index values, then you could use the  method:For example,yieldsI've modified the values from your original post so it is clearer what  is doing.\nNote how the keys in  are associated with index values. The order of the index values -- that is, the index  -- does not matter.\nIf the keys in  refer to  values, then @DanAllan and @DSM show how to achieve this with :yieldsNote how in this case the keys in  were changed to match  in .\nIf the keys in  refer to index locations, then you could usesinceyieldsHere, the first and third rows were altered, because the keys in  are  and , which with Python's 0-based indexing refer to the first and third locations.This is an alternative answer that can be much faster when your dictionary has more than a couple of keys.  If your dictionary exhaustively maps all possible values and the column is numeric (not object type), this takes a very simple form:Here are the timings on dataframe with 100,000 rows and 8 dictionary keys (it's about 10x faster).With some additional code, you can extend this method to more general cases as in the question (columns of object type (non-integer, non-float) with partial mappings):That will still be much faster, but obviously is not as simple or elegant as using .
Python

I am plotting two similar trajectories in matplotlib and I'd like to plot each of the lines with partial transparency so that the red (plotted second) doesn't obscure the blue.: Here's the image with transparent lines.Plain and simple:(I know I add nothing new, but the straightforward answer should be visible).After I plotted all the lines, I was able to set the transparency of all of them as follows: please see Joe's answer in the comments.It really depends on what functions you're using to plot the lines, but try see if the on you're using takes an alpha value and set it to something like 0.5. If that doesn't work, try get the line objects and set their alpha values directly.
Python

Normally Fabric quits as soon as a run() call returns a non-zero exit code. For some calls, however, this is expected. For example, PNGOut returns an error code of 2 when it is unable to compress a file.Currently I can only circumvent this limitation by either using shell logic ( or ), but I'd rather be able to keep my logic in plain Python (as is the Fabric promise).Is there a way to check for an error code and react to it rather than having Fabric panic and die? I still want the default behaviours for other calls, so changing its behaviour by modifying the environment doesn't seem like a good option (and as far as I recall, you can only use that to tell it to warn instead of dying anyway).You can prevent aborting on non-zero exit codes by using the  context manager and the  setting: My answer is outdated. See comments below. Yes, you can. Just change the environment's . For example:The documentation on  is .Apparently messing with the environment  the answer. can be used as a context manager (with ) to apply it to individual statements. The return value of ,  and  calls isn't just the output of the shell command, but also has special properties ( and ) that allow reacting to the errors.I guess I was looking for something closer to the behaviour of  or Python's usual exception handling.try this
Python

I have a list like below where the first element is the id and the other is a string:I want to create a list of ids only from this list of tuples as below:I'll use this list in  so it needs to be a list of integer values. Please help!Use the zip function to decouple elements.do you mean something like this?What you actually have is a list of  objects, not a list of sets (as your original question implied).  If it is actually a list of sets, then  because sets have no order.Here I've created a flat list because generally that seems more useful than creating a list of 1 element tuples.  However, you can easily create a list of 1 element tuples by just replacing  with .if the tuples are unique then this can workThis is what  is for. The  statement  that returns the index of the element you specify. It's exactly the same as writingBut I find that  is a clearer and . This is handy for making compact sort statements. For example,Those are tuples, not sets. You can do this:when I ran (as suggested above):instead of returning:I received this as the return:I found I had to use list():to successfully return a list using this suggestion. That said, I'm happy with this solution, thanks. (tested/run using Spyder, iPython console, Python v3.6)You can use \"tuple unpacking\":At iteration time each tuple is unpacked and its values are set to the variables  and . 
Python

Ordered dictionaries are extremely useful structures, but unfortunately these are quite recent only working in versions from  and . How can I use an ordered dictionary in older versions?I installed ordereddict on python 2.6 with pipAccording to the , for Python versions 2.4 or later  should be used. There is also some , one of the contributors to the . The code here is claimed to work under 2.6 and 3.0 and was made for the proposal.To import a OrderedDict class for different versions of Python, consider this snippet:Versions older than Python 2.6 will need to install  (using pip or other methods), but newer versions will import from the built-in collections module.Also, you could just program your way around it if your situation allows:You could embed the ordered keys in your Dictionary too, I suppose, as oDict['keyList'] = orderedKeysin python2.6 gave to me:but did.For those who can't depend on the user having pip for some reason, here is a  implementaiton of OrderedDict (it is immutable, has most of the features but none of the performance boost).
Python

I have output of a command in tabular form. I'm parsing this output from result file and storing it in a string. Each element in 1 row is seperated by one or more space. So I'm using regular expression to match 1 or more spaces and split it, but python is inserting a space between every element:Is there a better way to do this? After each split str2 is appended to list.By using ,, you are capturing the group, if you simply remove them you will not have this problem.However there is no need for regex,  without any delimiter specified will split this by whitespace for you. This would be the best way in this case.If you really wanted regex you can use this ( represents whitespace and it's clearer):or you can find all non-whitespace charactersThe  method will automatically remove all white space between items:Docs are here: When you use  and the split pattern contains capturing groups, the groups are retained in the output.  If you don't want this, use a non-capturing group instead.Its very simple actually. Try this:
Python

Suppose I have an  statement with a . From the efficiency perspective, should I useorShould I prefer one or another when using a compiled language (C) or a scripted one (Python)?Since the  statement terminates the execution of the current function, the two forms are equivalent (although the second one is arguably more readable than the first).The efficiency of both forms is comparable, the underlying machine code has to perform a jump if the  condition is false anyway.Note that Python supports a syntax that allows you to use only one  statement in your case:From  style guide:Don't use else after return:With any sensible compiler, you should observe no difference; they should be compiled to identical machine code as they're equivalent.Version A is simpler and that's why I would use it.And if you turn on all compiler warnings in Java you will get a warning on the second Version because it is unnecesarry and turns up code complexity.Regarding coding style:Most coding standards no matter language ban multiple return statements from a single function as bad practice. (Although personally I would say there are several cases where multiple return statements do make sense: text/data protocol parsers, functions with extensive error handling etc)The consensus from all those industry coding standards is that the expression should be written as:Regarding efficiency:The above example and the two examples in the question are all  in terms of efficiency. The machine code in all these cases have to compare A > B, then branch to either the A+1 or the A-1 calculation, then store the result of that in a CPU register or on the stack.Sources:I would always use:As it obeys both the good convention of having a single return statement as the last statement in the function (as already mentioned) and the good functional programming paradigm of avoiding imperative style intermediate results. For more complex functions I revert to using a imperative style variable called rval.  I never use multiple return statements, preferring to break the function into multiple sub-functions to avoid this if necessary.  I do not consider the question of efficiency at all, as its the efficiency of coding (i.e. writing error free code) that matters to me. 
Python

How do I create a file-like object (same duck type as File) with the contents of a string?For Python 2.x, use the  module.  For example:I use cStringIO (which is faster), but note that it doesn't .  (You can switch to StringIO by changing  \"from cStringIO\" to \"from StringIO\".)For Python 3.x, use the  module.In Python 3.0:Two good answers. I\u2019d add a little trick \u2014 if you need a real file object (some methods expect one, not just an interface), here is a way to create an adapter:
Python

I want to save the name of the error and the traceback details into a variable.  Here's is my attempt.P.S. I know this can be done easily using the traceback module, but I want to know usage of sys.exc_info()[2] object here.This is how I do it:You should however take a look at the , as you might find there more suitable methods, depending to how you want to process your variable afterwards...Use  if you want convenient access to module and function names and line numbers.Use  if you just want a string that looks like the  output.Notice that even with  you will get a multi-line string, since the elements of  contain .  See output below.Remember to .Here's the output from .  Formatting added for readability.Here's the output from .  Formatting added for readability.sys.exc_info() returns a tuple with three values (type, value, traceback). For Example, In the following programNow If we print the tuple the values will be this.The above details can also be fetched by simply printing the exception in string format. My  to another question may help illustrate the details - with links!  For canned strings, standard library traceback module seems okay.  If you want to get the details, read the source () for more info.
Python

The folder I want to get to is called python and is on my desktop.I get the following error when I try to get to itYou need to use a  string, double your slashes or use forward slashes instead:In regular python strings, the  character combination signals a extended Unicode codepoint escape.\nThis syntax worked for me.This usually happens in Python 3. One of the common reasons would be that while specifying your file path you need \"\\\\\" instead of \"\\\". As in:For Python 2, just using \"\\\" would work.f = open('C:\\\\Users\\\\Pooja\\\\Desktop\\\\trolldata.csv')...\nUse '\\\\' for python program in python version 3 and above..\nError will be resolved..All the three syntax work very well.Another way is to first writepath = r'C:\\user\\...................' (whatever is the path for you)and then passing it to os.chdir(path)
Python

I want to start writing unit tests for my Python code, and the  framework sounds like a better bet than Python's bundled . So I added a \"tests\" directory to my project, and added  to it. Now I want to configure PyCharm to run all the tests in my \"tests\" directory.PyCharm allegedly  in its test runner. You're supposed to be able to  to run your tests, and PyCharm allegedly has a . But that's the complete extent of their documentation on the subject, and I can't find this alleged dialog box anywhere.If I right-click the directory in the Project tool window, I'm  to see a \"Create <name>\" menu item, but the only menu item starting with \"Create\" is \"Create Run Configuration\". Okay, maybe the documentation is just wrong, and \"Create Run Configuration\" does sound promising. Unfortunately, the only two items in its submenu are \"Unittests in C:\\mypath...\" and \"Doctests in C:\\mypath...\", neither of which applies -- I'm using neither unittest nor doctest. There is no menu item for py.test.If I open my test_sample.py and right-click in the editor window, I do get the promised \"Create <name>\" menu items: there's \"Create 'Unittests in test_sa...'...\", followed by \"Run 'Unittests in test_sa...'\" and \"Debug 'Unittests in test_sa...'\". So again, it's all specific to the unittest framework; nothing for py.test.If I do try the menu items that say \"unittest\", I get a dialog box with options for \"Name\", \"Type\", a \"Tests\" group box with \"Folder\" and \"Pattern\" and \"Script\" and \"Class\" and \"Function\", etc. This sounds exactly like what's documented as the dialog to add a , and not like the \"Name\" and \"Test to run\" and \"Keywords\" options that are supposed to show up in the  dialog. There's nothing inside the dialog to switch which test framework I'm adding.I'm using PyCharm 1.5.2 on Windows with Python 3.1.3 and pytest 2.0.3. I can successfully run  on my tests from the command line, so it's not something simple like pytest not being installed properly.How do I configure PyCharm to run my py.test tests?Please go to File | Settings | Tools | Python Integrated Tools and change the default test runner to py.test. Then you'll get the py.test option to create tests instead of the unittest one.I think you need to use the Run/Debug Configuration item on the toolbar. Click it and 'Edit Configurations' (or alternatively use the menu item Run->Edit Configurations). In the 'Defaults' section in the left pane there is a 'py.test' item which I think is what you want.I also found that the manual didn't match up to the UI for this. Hope I've understood the problem correctly and that helps.It's poorly documented to be sure.   Once you get add a new configuration from defaults, you will be in the realm of running the \"/Applications/PyCharm CE.app/Contents/helpers/pycharm/pytestrunner.py\" script.   It's not documented and has its own ideas of command line arguments.You can:Oddly, you will find it hard to find any discussion as JetBrains does a good job of bombing Google algorithms with its own pages.With a special Conda python setup which included the pip install for py.test plus usage of the Specs addin (option --spec) (for Rspec like nice test summary language), I had to do ; 1.Edit the default py.test to  include option= --spec , which means use the plugin: 2.Create new test configuration, using py.test. Change its python interpreter to use ~/anaconda/envs/ your choice of interpreters, eg py27  for my namings.3.Delete the 'unittests' test configuration.4.Now the default test config is py.test with my lovely Rspec style outputs. I love it! Thank you everyone!p.s. Jetbrains' doc on run/debug configs is here: 
Python

I have a file called test_web.py containing a class TestWeb and many methods named like  test_something().I can run every test in the class like so:But I can\u2019t seem to run individual tests. These give me \u201cNo such test\u201d errors when run in the same PWD:What could be wrong here?You must specify it like so: , orSee You can also specify a module:Specifying names on the command line like the other answers suggest does work and is useful. However, when I'm in the midst of writing tests, I often find that I want to run just the test I'm working on, and the names that I would have to write on the command line get pretty long and cumbersome to write. In such case, I prefer to use a custom decorator and flag.I define  (\"work in progress decorator\") like this:This defines a decorator  which will set the  attribute on objects it decorates. For instance:Then  can be used at the command line to narrow the execution of the test to the ones marked with .I'm using the name  for the decorator rather than  to avoid this kind of problem:The  will make the  decorator a member , and  tests in the class will be selected. The  plugin checks the parent class of a test method to see if the attribute selected exists there too, and the attributes that are created and tested by  do not exist in a segregated space. So if you test with  and your class contains , then all tests in the class will be selected by the plugin.To run multiple specific tests, you can just add them to the command line, separated by space.
Python

Take a look at this:I ran a , but could not find the answer - what should I be using instead of ? is deprecated because of .Now you can  your changes using . This transforms your model changes into python code to make them deployable to another databases.After you created the migrations you have to  them: .So instead of using  you should use  and then .You should definitely use . Which lets you track changes in your , and create migrations for the database. The migration system uses the commands  to create migrations and  to migrate the database.If for whatever reason you need to create a database the same way  did it there is command flag that causes  to work the same way. You should only do this if you  need it and you know what you are doing. For example to create an empty database on for a continuous integration system of your choice.Tested on Django 1.9.1.You should use the  and  commands that were introduced in django 1.7 has some problem with db migration. so, after django 1.7  and  have been introduced. \nNow in django 1.9  has been deprecated.\ntry\n1.  which detects changes in db and creates one  file as inside migrations folder\n2.  will apply the migrations to the database
Python

Is there any way to get SQLAlchemy to do a bulk insert rather than inserting each individual object. i.e.,doing:rather than:I've just converted some code to use sqlalchemy rather than raw sql and although it is now much nicer to work with it seems to be slower now (up to a factor of 10), I'm wondering if this is the reason.May be I could improve the situation using sessions more efficiently. At the moment I have  and do a  after I've added some stuff. Although this seems to cause the data to go stale if the DB is changed elsewhere, like even if I do a new query I still get old results back?Thanks for your help!SQLAlchemy introduced that in version :With these operations, you can now do bulk inserts or updates!For instance, you can do:Here, a bulk insert will be made.As far as I know, there is no way to get the ORM to issue bulk inserts. I believe the underlying reason is that SQLAlchemy needs to keep track of each object's identity (i.e., new primary keys), and bulk inserts interfere with that. For example, assuming your  table contains an  column and is mapped to a  class:Since SQLAlchemy picked up the value for  without issuing another query, we can infer that it got the value directly from the  statement. If you don't need subsequent access to the created objects via the  instances, you can skip the ORM layer for your insert:SQLAlchemy can't match these new rows with any existing objects, so you'll have to query them anew to for any subsequent operations.As far as stale data is concerned, it's helpful to remember that the session has no built-in way to know when the database is changed outside of the session. In order to access externally modified data through existing instances, the instances must be marked as . This happens by default on , but can be done manually by calling  or . An example (SQL omitted): expires , so the first print statement implicitly opens a new transaction and re-queries 's attributes. If you comment out the first print statement, you'll notice that the second one now picks up the correct value, because the new query isn't emitted until after the update.This makes sense from the point of view of transactional isolation - you should only pick up external modifications between transactions. If this is causing you trouble, I'd suggest clarifying or  re-thinking your application's transaction boundaries instead of immediately reaching for .The sqlalchemy docs have a great writeup on the performance of various techniques that can be used for bulk inserts:Direct support was added to SQLAlchemy as of version 0.8As per the ,  should do the trick. (Note that this is  the same as  which results in many individual row inserts via a call to ). On anything but a local connection the difference in performance can be enormous.This is a way:This will insert like this:Reference: The SQLAlchemy  includes benchmarks for various commit methods.I usually do it using .SQLAlchemy introduced that in version :With these operations, you can now do bulk inserts or updates!For instance (if you want the lowest overhead for simple table INSERTs), you can use :Or, if you want, skip the  tuples and write the dictionaries directly into  (but I find it easier to leave all the wordiness out of the data and load up a list of dictionaries in a loop).Piere's answer is correct but one issue is that  by default does not return the primary keys of the objects, if that is of concern to you. Set  to  to get this behavior.The documentation is .
Python

When do I use each ?Also...is the NLTK lemmatization dependent upon Parts of Speech?\nWouldn't it be more accurate if it was?Short and dense: From the NLTK docs:: As MYYN pointed out, stemming is the process of removing inflectional and sometimes derivational affixes to a base form that all of the original words are probably related to.  Lemmatization is concerned with obtaining the single word that allows you to group together a bunch of inflected forms.  This is harder than stemming because it requires taking the context into account (and thus the meaning of the word), while stemming ignores context.As for when you would use one or the other, it's a matter of how much your application depends on getting the meaning of a word in context correct.  If you're doing machine translation, you probably want lemmatization to avoid mistranslating a word.  If you're doing information retrieval over a billion documents with 99% of your queries ranging from 1-3 words, you can settle for stemming.As for NLTK, the WordNetLemmatizer does use the part of speech, though you have to provide it (otherwise it defaults to nouns).  Passing it \"dove\" and \"v\" yields \"dive\" while \"dove\" and \"n\" yields \"dove\".The purpose of both stemming and lemmatization is to reduce morphological variation. This is in contrast to the the more general \"term conflation\" procedures, which may also address lexico-semantic, syntactic, or orthographic variations. The real difference between stemming and lemmatization is threefold:Lemmatization may also be backed up by a part-of-speech tagger in order to disambiguate homonyms.There are two aspects to show their differences:Reference ianacl\nbut i think Stemming is a rough hack people use to get all the different forms of the same word down to a base form which need not be a legit word on its own\nSomething like the Porter Stemmer can uses simple regexes to eliminate common word suffixesLemmatization brings a word down to its actual base form which, in the case of irregular verbs, might look nothing like the input word\nSomething like Morpha which uses FSTs to bring nouns and verbs to their base formAn example-driven explanation on the differenes between lemmatization and stemming: handles    handles  .
Python

I am looking for a fast way to preserve large numpy arrays. I want to save them to the disk in a binary format, then read them back into memory relatively fastly. cPickle is not fast enough, unfortunately. I found  and . But the weird thing is, numpy.load loads a npy file into \"memory-map\". That means regular manipulating of arrays really slow. For example, something like this would be really slow: more precisely, the first line will be really fast, but the remaining lines that assign the arrays to  are ridiculously slow:Is there any better way of preserving numpy arrays? Ideally, I want to be able to store multiple arrays in one file. I'm a big fan of hdf5 for storing large numpy arrays. There are two options for dealing with hdf5 in python:Both are designed to work with numpy arrays efficiently.I've compared performance (space and time) for a number of ways to store numpy arrays. Few of them support multiple arrays per file, but perhaps it's useful anyway.Npy and binary files are both really fast and small for dense data. If the data is sparse or very structured, you might want to use npz with compression, which'll save a lot of space but cost some load time.If portability is an issue, binary is better than npy. If human readability is important, then you'll have to sacrifice a lot of performance, but it can be achieved fairly well using csv (which is also very portable of course).More details and the code are available at .There is now a HDF5 based clone of  called !savez() save data in a zip file, It may take some time to zip & unzip the file. You can use save() & load() function:To save multiple arrays in one file, you just need to open the file first, and then save or load the arrays in sequence.Another possibility to store numpy arrays efficiently is :and the output for my laptop (a relatively old MacBook Air with a Core2 processor):that means that it can store really fast, i.e. the bottleneck is typically the disk.  However, as the compression ratios are pretty good here, the effective speed is multiplied by the compression ratios.  Here are the sizes for these 76 MB arrays:Please note that the use of the  compressor is fundamental for achieving this.  The same script but using 'clevel' = 0 (i.e. disabling compression):is clearly bottlenecked by the disk performance.The lookup time is slow because when you use  to does not load content of array to memory when you invoke  method. Data is lazy loaded when particular data is needed. \nAnd this happens in lookup in your case. But second lookup won`t be so slow.This is nice feature of  when you have a big array you do not have to load whole data into memory.To solve your can use  you can dump any object you want using  even two or more , see the example
Python

I'm trying to use Python to download the HTML source code of a website but I'm receiving this error. I'm following the guide here: I'm using Python 3, thanks for the help!This works in Python 2.x.For Python 3 look here:A Python 2+3 compatible solution is:In Python v3 the \"urllib.request\" is a module by itself, therefore \"urllib\" cannot be used here.
Python

I am using ConfigParser to read the runtime configuration of a script.I would like to have the flexibility of not providing a section name (there are scripts which are simple enough; they don't need a 'section'). ConfigParser will throw the  exception, and will not accept the file.How can I make ConfigParser simply retrieve the  tuples of a config file without section names? For instance:I would rather not write to the config file.Alex Martelli  for using  to parse  files (which are apparently section-less config files). is a file-like wrapper that will automagically insert a dummy section heading to satisfy 's requirements.Enlightened by , I come up with this solution:You can do this with a single additional line of code. (Two lines if you count  statements.)In python 3, use  to simulate a section header for .In python 2, prepend a section header line to the data you read from your config file, wrap the result in a  object, and pass it to .With either approach, your config settings will be available in .You could use  in python 3 as well, by importing it from its new home in the  package, but note that  is deprecated in python 3 and should therefore be avoided.You can use the ConfigObj library to do that simply : Updated: Find latest code .If you are under Debian/Ubuntu, you can install this module using your package manager :An example of use:Having ran into this problem myself, I wrote a complete wrapper to ConfigParser (the version in Python 2) that can read and write files without sections transparently, based on Alex Martelli's approach linked on the accepted answer. It should be a drop-in replacement to any usage of ConfigParser. Posting it in case anyone in need of that finds this page. The easiest way to do this is to use python's CSV parser, in my opinion.  Here's a read/write function demonstrating this approach as well as a test driver. This should work provided the values are not allowed to be multi-line.  :)Blueicefield's answer mentioned configobj, but the original lib only supports Python 2. It now has a Python 3+ compatible port: APIs haven't changed, see it's . lib can help in case  
Python

I want my Python script to copy files on Vista. When I run it from a normal  window, no errors are generated, yet the files are NOT copied. If I run  \"as administator\" and then run my script, it works fine.This makes sense since User Account Control (UAC) normally prevents many file system actions.Is there a way I can, from within a Python script, invoke a UAC elevation request (those dialogs that say something like \"such and such app needs admin access, is this OK?\")If that's not possible, is there a way my script can at least detect that it is not elevated so it can fail gracefully?As of 2017, an easy method to achieve this is the following:Some of the advantages here are:Documentation for the underlying ShellExecute call is . It took me a little while to get dguaraglia's answer working, so in the interest of saving others time, here's what I did to implement this idea:It seems there's no way to elevate the application privileges for a while for you to perform a particular task. Windows needs to know at the start of the program whether the application requires certain privileges, and will ask the user to confirm when the application performs any tasks that  those privileges. There are two ways to do this:This   explain in much more detail how this works.What I'd do, if you don't want to write a nasty ctypes wrapper for the CreateElevatedProcess API, is use the ShellExecuteEx trick explained in the Code Project article (Pywin32 comes with a wrapper for ShellExecute). How? Something like this:When your program starts, it checks if it has Administrator privileges, if it doesn't it runs itself using the ShellExecute trick and exits immediately, if it does, it performs the task at hand.As you describe your program as a \"script\", I suppose that's enough for your needs.Cheers.Recognizing this question was asked years ago, I think a more elegant solution is offered on  by frmdstryr using his module pyminutils: Excerpt:This utilizes the COM interface and automatically indicates that admin privileges are needed with the familiar dialog prompt that you would see if you were copying into a directory where admin privileges are required and also provides the typical file progress dialog during the copy operation.This may not completely answer your question but you could also try using the Elevate Command Powertoy in order to run the script with elevated UAC privileges.I think if you use it it would look like 'elevate python yourscript.py'If your script always requires an Administrator's privileges then:    You can make a shortcut somewhere and as the target use:\npython yourscript.py\nthen under properties and advanced select run as administrator. When the user executes the shortcut it will ask them to elevate the application.A variation on Jorenko's work above allows the elevated process to use the same console (but see my comment below):The following example builds on  excellent work and accepted answer. In particular, two enumerations are introduced. The first allows for easy specification of how an elevated program is to be opened, and the second helps when errors need to be easily identified. Please note that if you want all command line arguments passed to the new process,  should probably be replaced with a function call: .
Python

I have two dictionaries and I'd like to be able to make them one:Something like this pseudo-Python would be nice:If you're interested in creating a new dict without using intermediary storage: (this is faster, and in my opinion, cleaner than using dict.items())Or if you're happy to use one of the existing dicts:You are looking for the givesNote this doesn't actually return the combined dictionary, it just mutates .Please search the site before asking questions next time: The easiest way to do it is to simply use your example code, but using the items() member of each dictionary. So, the code would be:I tested this in IDLE and it works fine. \nHowever, the previous question on this topic states that this method is slow and chews up memory. There are several other ways recommended there, so please see that if memory usage is important.Here are quite a few ways to add dictionaries.Creates a new dict by adding both items.If your ok to modify If your  ok to modify If all the keys in one dict are ensured to be strings ( in this case, of course args can be swapped)In some cases it may be handy to use dict comprehensions (Python 2.7 or newer),Especially if you want to filter out or transform some keys/values at the same time.
Python

I am asking Python to print the minimum number from a column of CSV data, but the top row is the column number, and I don't want Python to take the top row into account. How can I make sure Python ignores the first line?This is the code so far:Could you also explain what you are doing, not just give the code? I am very very new to Python and would like to make sure I understand everything.You could use themodule's  class to detect whether a header row is present and the built-infunction to skip over it if necessary:You can also skip rows with a  call if you're using Python 2.x.Since  and  are hardcoded in your example, it would be slightly faster to read  this way:To skip the first line just call:Files in Python are iterators over lines.You would normally use  which advances the iterator one row, so you skip the header. The other (say you wanted to skip 30 rows) would be:In a similar use case I had to skip annoying lines before the line with my actual column names. This solution worked nicely. Read the file first, then pass the list to .use csv.DictReader instead of csv.Reader.\nIf the fieldnames parameter is omitted, the values in the first row of the csvfile will be used as field names. you would then be able to access field values using row[\"1\"] etcThe new 'pandas' package might be more relevant than 'csv'. The code below will read a CSV file, by default interpreting the first line as the column header and find the minimum across columns.Well, my  would do the job as well.Meanwhile, if you know what header column index one is, for example \"Column 1\", you can do this instead:just add example below:that works for me in iPythonPython 3.XHandles UTF8 BOM + HEADERIt was quite frustrating that the  module could not easily get the header, there is also a bug with the UTF-8 BOM (first char in file).\nThis works for me using only the  module:I would use  to get rid of the unwanted first line:
Python

I'm trying to generate a linear regression on a scatter plot I have generated, however my data is in list format, and all of the examples I can find of using  require using .  doesn't accept lists though. I have searched high and low about how to convert a list to an array and nothing seems clear. Am I missing something?Following on, how best can I use my list of integers as inputs to the ?here is the polyfit example I am following:  lists (well, numpy arrays); type  for the details.  You don't need to call it on existing lists.I should add that I tend to use  here rather than write out \"m*x+b\" and the higher-order equivalents, so my version of your code would look something like this:This code:gives out a list with the following:Another quick and dirty answer is that you can just convert your list to an array using: 
Python

I'm new to Python... and coming from a mostly Java background, if that accounts for anything.I'm trying to understand polymorphism in Python. Maybe the problem is that I'm expecting the concepts I already know to project into Python. But I put together the following test code:From the polymorphism I'm used to (e.g. java's ), I would expect both of these statements to print true, as an instance of dog  animal and also  dog. But my output is:What am I missing?The  operator in Python checks that the two arguments refer to the same object in memory; it is not like the  operator in C#.:What you're looking for in this case is .However, idiomatic Python dictates that you (almost) never do type-checking, but instead rely on  for polymorphic behavior.  There's nothing wrong with using  to understand inheritance, but it should generally be avoided in \"production\" code.phimuemue and Mark have answered your question. But this is ALSO an example of polymorphism in Python, but it's not as explicit as your inheritance based example.Try  resp. .
Python

Given a 3 times 3 numpy arrayTo normalize the rows of the 2-dimensional array I thought ofThere must be a better way, isn't there?Perhaps to clearify: By normalizing I mean, the sum of the entrys per row must be one. But I think that will be clear to most people.Broadcasting is really good for this: reshapes row_sums from being  to being . When you do ,  and  are broadcast against each other.You can learn more about   or even better .Scikit-learn has a normalize function that lets you apply various normalizations. The \"make it sum to 1\" is the L1 norm, and to take that do:Now your rows will sum to 1.I think this should work,it appears that this also worksIn case you are trying to normalize each row such that its magnitude is one (i.e. a row's unit length is one or the sum of the square of each element in a row is one):Verifying:Or using lambda function, likeeach vector of vec will have a unit norm.You could also use matrix transposition:
Python

I'm just starting to use NLTK and I don't quite understand how to get a list of words from text. If I use , I get a list of words and punctuation. I need only the words instead. How can I get rid of punctuation? Also  doesn't work with multiple sentences: dots are added to the last word.Take a look at the other tokenizing options that nltk provides . For example, you can define a tokenizer that picks out sequences of alphanumeric characters as tokens and drops everything else:Output:You do not really need NLTK to remove punctuation. You can remove it with simple python. For strings:Or for unicode:and then use this string in your tokenizer. string module have some other sets of elements that can be removed (like digits).As noticed in comments start with sent_tokenize(), because word_tokenize() works only on a single sentence. You can filter out punctuation with filter(). And if you have an unicode strings make sure that is a unicode object (not a 'str' encoded with some encoding like 'utf-8'). I just used the following code, which removed all the punctuation:I use this code to remove punctuation:And If you want to check whether a token is a valid English word or not, you may need Tutorial:I think you need some sort of regular expression matching (the following code is in Python 3):Output:Should work well in most cases since it removes punctuation while preserving tokens like \"n't\", which can't be obtained from regex tokenizers such as .Below code will remove all punctuation marks as well as non alphabetic characters. Copied from their book. output
Python

I have a date string of the form '2009/05/13 19:19:30 -0400'. It seems that previous versions of Python may have supported a %z format tag in strptime for the trailing timezone specification, but 2.6.x seems to have removed that.What's the right way to parse this string into a datetime object?You can use the parse function from dateutil:This way you obtain a datetime object you can then use.As , dateutil2.0 is written for Python 3.0 and does not work with Python 2.x. For Python 2.x dateutil1.5 needs to be used. is supported in Python 3.2+:On earlier versions:where  is a class based on :The problem with using dateutil is that you can't have the same format string for both serialization and deserialization, as dateutil has limited formatting options (only  and ).In my application, I store the format string in .INI file, and each deployment can have its own format. Thus, I really don't like the dateutil approach.Here's an alternative method that uses pytz instead:Here is a fix of the  issue for Python 2.7 and earlierInstead of using:Use the  to account for the timezone, like this:Note that the dates would be converted to , which would allow doing date arithmetic without worrying about time zones.If you are on Linux, then you can use the external  command to dwim:This is of course less portable than dateutil, but slightly more flexible, because  will also accept inputs like \"yesterday\" or \"last year\" :-)
Python

I need to iterate through the subdirectories of a given directory and search for files. If I get a file I have to open it and change the content and replace it with my own lines.I tried this:but I am getting an error. What am I doing wrong? The actual walk through the directories works as you have coded it. If you replace the contents of the inner loop with a simple  statement you can see that each file is found:If you still get errors when running the above, please provide the error message.Another way of returning all files in subdirectories is to use , introduced in Python 3.4, which provides an object oriented approach to handling filesystem paths (Pathlib is also available on Python 2.7 via ):Since Python 3.5, the  module also supports recursive file finding:The  from either of the above approaches can be iterated over without the need for a nested loop:
Python

I can give it floating point numbers, such asbut how accurate is it? If i give itwill it really sleep about 50 ms?The accuracy of the time.sleep function depends on the accuracy of your underlying OS's sleep accuracy.  For non-realtime OS's like a stock Windows the smallest interval you can sleep for is about 10-13ms.  I have seen accurate sleeps within several milliseconds of that time when above the minimum 10-13ms.Update:\nLike mentioned in the docs sited below, it's common to do the sleep in a loop that will make sure to go back to sleep if the wakes you up the early.I should also mention that if you are running Ubuntu you can try out a pseudo real-time kernel (with the RT_PREEMPT patch set) by installing the rt kernel package (at least in Ubuntu 10.04 LTS).EDIT: Correction non-realtime Linux kernels have minimum sleep interval much closer to 1ms then 10ms but it varies in a non-deterministic manner.People are quite right about the differences between operating systems and kernels, but I do not see any granularity in Ubuntu and I see a 1 ms granularity in MS7. Suggesting a different implementation of time.sleep, not just a different tick rate. Closer inspection suggests a 1\u03bcs granularity in Ubuntu by the way, but that is due to the time.time function that I use for measuring the accuracy.\nFrom the :And  w.r.t. :Why don't you find out:For the record, I get around 0.1ms error on my HTPC and 2ms on my laptop, both linux machines.Here's my follow-up to Wilbert's answer: the same for Mac OS X Yosemite, since it's not been mentioned much yet.Looks like a lot of the time it sleeps about 1.25 times the time that you request and sometimes sleeps between 1 and 1.25 times the time you request. It almost never (~twice out of 1000 samples) sleeps significantly more than 1.25 times the time you request.  Also (not shown explicitly) the 1.25 relationship seems to hold pretty well until you get below about 0.2 ms, after which it starts get a little fuzzy. Additionally, the actual time seems to settle to about 5 ms longer than you request after the amount of time requested gets above 20 ms.Again, it appears to be a completely different implementation of  in OS X than in Windows or whichever Linux kernal Wilbert was using.You can't really guarantee anything about sleep(), except that it will at least make a best effort to sleep as long as you told it (signals can kill your sleep before the time is up, and lots more things can make it run long).  For sure the minimum you can get on a standard desktop operating system is going to be around 16ms (timer granularity plus time to context switch), but chances are that the % deviation from the provided argument is going to be significant when you're trying to sleep for 10s of milliseconds.  Signals, other threads holding the GIL, kernel scheduling fun, processor speed stepping, etc. can all play havoc with the duration your thread/process actually sleeps.
Python

Note: I'm using virtualenvwrapper.Before activating the virtual environment:After activating the virtual environment:You probably already have lxml installed on your system, perhaps installed due to a system package. Thus, the first attempt ( without an active virtualenv) doesn't fail, but it also doesn't install it; it really doesn't do anything.In a virtualenv, by default, the system packages are ignored. Therefore, pip thinks that lxml is not installed. Therefore, it tries to install it into your virtual environment.lxml contains C modules that need to be compiled in order to install properly. However, the compilation of those C modules rely on your having some \"development libraries\" already installed as well. These development libraries are C libraries, not Python, and as such pip won't be able to automatically fetch them from the internet and install them for you.Therefore, you will need to install these development libraries on your own, most likely using your package manager. In a Debian system (like Ubuntu), this is...This will install the libxml2 and libxslt development libraries to your local system. If you try again to install lxml, the C module compilation step should work because now these development libraries are on your system.The error message you were receiving was due to the fact that these libraries were missing (the  part of the error message).See also: \nwhen getting:DO:If you have  installed at the system level, and want to migrate it into a  that you didn't create with , you can symlink it into your 's  folder.Outside your , in a python shell:In my case, it's found in . There'll be an lxml folder and egg-info file. Wherever your virtualenv is, go into its  folder (you may need to create ), and symlink both the library folder and egg into it.
Python

How does one check whether a task is running in celery (specifically, I'm using celery-django)?I've read the documentation, and I've googled, but I can't see a call like:My use-case is that I have an external (java) service for transcoding. When I send a document to be transcoded, I want to check if the task that runs that service is running, and if not, to (re)start it.I'm using the current stable versions - 2.4, I believe.Return the task_id (which is given from .delay()) and ask the celery instance afterwards about the state:When asking, get a new AsyncResult using this task_id:Every  object has a  property, which contains it  object. Accordingly, the following line gives the state of a Task :Creating an  object from the task id  the way recommended in the  to obtain the task status when the only thing you have is the task id.However, as of Celery 3.x, there are significant caveats that could bite people if they do not pay attention to them. It really depends on the specific use-case scenario.In order for Celery to record that a task is running, you must set  to . Here is a simple task that tests this:When  is , which is the default, the state show is  even though the task has started. If you set  to , then the state will be .An  with the state  does not mean anything more than that Celery does not know the status of the task. This could be because of any number of reasons.For one thing,  can be constructed with invalid task ids. Such \"tasks\" will be deemed pending by Celery:Ok, so nobody is going to feed  invalid ids to . Fair enough, but it also has for effect that  Again,  this can be a problem. Part of the issue hinges on how Celery is configured to keep the results of tasks, because it depends on the availability of the \"tombstones\" in the results backend. (\"Tombstones\" is the term use in the Celery documentation for the data chunks that record how the task ended.) Using  won't work at all if  is . A more vexing problem is that Celery expires the tombstones by default. The  setting by default is set to 24 hours. So if you launch a task, and record the id in long-term storage, and more 24 hours later, you create an  with it, the status will be . All \"real tasks\" start in the  state. So getting  on a task could mean that the task was requested but never progressed further than this (for whatever reason). Or it could mean the task ran but Celery forgot its state.I prefer to keep track of  than keep track of the . I do keep some task information but it is really secondary to keeping track of the goals. The goals are stored in storage independent from Celery. When a request needs to perform a computation depends on some goal having been achieved, it checks whether the goal has already been achieved, if yes, then it uses this cached goal, otherwise it starts the task that will effect the goal, and sends to the client that made the HTTP request a response that indicates it should wait for a result.You can also create custom states and update it's value duting task execution.\nThis example is from docs:Old question but I recently ran into this problem. If you're trying to get the task_id you can do it like this: Now you know exactly what the task_id is and can now use it to get the AsyncResult:Try: this will provide the Celery Task status. If Celery Task is already is under  state it will throw an Exception: for simple tasks, we can use  and  to do the monitoring. and for complicated tasks, say a task which deals with a lot other modules. We recommend manually record the progress and message on the specific task unit.
Python

I am working on Scrapy 0.20 with Python 2.7. I found PyCharm has a good Python debugger. I want to test my Scrapy spiders using it. Anyone knows how to do that please?Actually I tried to run the spider as a scrip. As a result, I built that scrip. Then, I tried to add my Scrapy project to PyCharm as a model like this:But I don't know what else I have to doThe  command is a python script which means you can start it from inside PyCharm.When you examine the scrapy binary () you will notice that this is actually a python script:This means that a command like \n can also be executed like this: Try to find the scrapy.cmdline package.\nIn my case the location was here: Create a run/debug configuration inside PyCharm with that script as script. Fill the script parameters with the scrapy command and spider. In this case . Like this:\nPut your breakpoints anywhere in your crawling code and it should work\u2122.You just need to do this.Create a Python file on crawler folder on your project. I used main.py.Inside your main.py put this code below.And you need to create a \"Run Configuration\" to run your main.py.Doing this, if you put a breakpoint at your code it will stop there.To add a bit to the accepted answer, after almost an hour I found I had to select the correct Run Configuration from the dropdown list (near the center of the icon toolbar), then click the Debug button in order to get it to work. Hope this helps! I am running scrapy in a virtualenv with Python 3.5.0 and setting the \"script\" parameter to  solved the issue for me.I am also using PyCharm, but I am not using its built-in debugging features.For debugging I am using . I set up a keyboard shortcut to insert  on any line I want the break point to happen.Then I can type  to execute the next statement,  to step in a function, type any object name to see its value, alter execution environment, type  to continue execution...This is very flexible, works in environments other than PyCharm, where you don't control the execution environment.Just type in your virtual environment  and place  on a line where you want the execution to pause.
Python

Following this Django by Example tutotrial here: The tutorial says:though, when I run , I get the error:Is this because I am using sqlite3 and not postgresql?The command:  returns the error:So I added 'todo' to my INSTALLED_APPS in settings.py, and ran  again, resulting in this error: has been replaced by  with Django 1.5, see:\nIt looks like the 'flush' answer will work for some, but not all cases.  I needed not just to flush the values in the database, but to recreate the tables properly.  I'm not using migrations yet (early days) so I really needed to drop all the tables.  On Heroku one can drop all the tables with pg:reset:And although manage.py 'reset' was replaced with 'flush', Django Extensions has a way to still do a complete reset:  Similar to LisaD's answer,  has a great reset_db command that totally drops everything, instead of just truncating the tables like \"flush\" does. You have to specify a router, so it may look like:Merely flushing the tables wasn't fixing a persistent error that occurred when I was deleting objects. Doing a reset_db fixed the problem.If you want to clean the whole database, you can use:\n\nIf you want to clean database table of a Django app, you can use:\nFor me this solved the problem.Just a follow up to  answer.\nAs of 2016 (), you need to type:This will give you a fresh new database within Heroku.
Python

I want to redirect the print to a .txt file using python. I have a 'for' loop, which will 'print' the output for each of my .bam file; while I want to redirect ALL these output to one file. So I tried to putat the beginning of my script. However I get nothing in the .txt file.\nMy script is like below:So what's the problem? Any other way besides this sys.stdout?\nthxedit:\nand i need my result look like:The most obvious way to do this would be to print to a file object:However, redirecting stdout also works for me.  It is probably fine for a one-off script such as this:What is the first filename in your script?  I don't see it initialized.My first guess is that glob doesn't find any bamfiles, and therefore the for loop doesn't run.  Check that the folder exists, and print out bamfiles in your script.Also, use  to manipulate paths and filenames.You can redirect print with the  operator.In most cases, you're better off just writing to the file normally.or, if you have several items you want to write with spaces between, like :Since  normally contains  method, all you need to do is to pass a  into its argument.This works perfectly:Now the hello will be written to the test.txt file. Make sure to close the  with a , without it the content will not be save in the fileThe easiest solution isn't through python; its through the shell.  From the first line of your file () I'm guessing you're on a UNIX system.  Just use  statements like you normally would, and don't open the file at all in your script.  When you go to run the file, instead ofto run the file, usewhere you replace  with the name of the file you want the output to go in to.  The  token tells (most) shells to set stdout to the file described by the following token.One important thing that needs to be mentioned here is that \"script.py\" needs to be made executable for  to run.So before running ,execute this command\n(make the script executable for all users)You may not like this answer, but I think it's the RIGHT one. Don't change your stdout destination unless it's absolutely necessary (maybe you're using a library that only outputs to stdout??? clearly not the case here).I think as a good habit you should prepare your data ahead of time as a string, then open your file and write the whole thing at once. This is because input/output operations are the longer you have a file handle open, the more likely an error is to occur with this file (file lock error, i/o error, etc). Just doing it all in one operation leaves no question for when it might have gone wrong.Here's an example:And then when you're all done collecting your \"data lines\" one line per list item, you can join them with some  characters to make the whole thing outputtable; maybe even wrap your output statement in a  block, for additional safety (will automatically close your output handle even if something goes wrong):However if you have lots of data to write, you  write it one piece at a time. I don't think it's relevant to your application but here's the alternative:Changing the value of sys.stdout does change the destination of all calls to print. If you use an alternative way to change the destination of print, you will get the same result.Your bug is somewhere else:
Python

The ElementTree.parse reads from a file, how can I use this if I already have the XML data in a string?Maybe I am missing something here, but there must be a way to use the ElementTree without writing out the string to a file and reading it again.If you're using  to parse from a file, then you can use  to parse from text.See You can parse the text as a string, which creates an Element, and create an ElementTree using that Element.I just came across this issue and the documentation, while complete, is not very straightforward on the difference in usage between the parse and fromstring methods.You need the xml.etree.ElementTree.fromstring(text)It's on the page you linked. Use fromstring.
Python

I have a CSV file and I want to bulk-import this file into my sqlite3 database using Python. the command is \".import .....\". but it seems that it cannot work like this. Can anyone give me an example of how to do it in sqlite3? I am using windows just in case.\nThanksCreating an sqlite connection to a file on disk is left as an exercise for the reader ... but there is now a two-liner made possible by the pandas libraryThe  command is a feature of the sqlite3 command-line tool. To do it in Python, you should simply load the data using whatever facilities Python has, such as the , and inserting the data as per usual.This way, you also have control over what types are inserted, rather than relying on sqlite3's seemingly undocumented behaviour.Many thanks for bernie's !  Had to tweak it a bit - here's what worked for me:My text file (PC.txt) looks like this:My 2 cents (more generic):You can do this using  &  efficientlyOdo will store the csv file to  (sqlite database) under the schema Or you use  directly, without . Either ways is fine. Read this 
Python

any tips on testing email sending? Other than maybe creating a gmail account, especially for receiving those emails?I would like to maybe store the emails locally, within a folder as they are sent.You can use a  which is a very handy solution for development and testing; emails are not sent but stored in a folder you can specify!Django test framework has some built in helpers to aid you with testing .Example from docs (short version):For any project that doesn't require sending attachments, I use , which has the benefit of all outbound emails ending up in a queue until I trigger their sending, and even after they've been sent, they are then logged - all of which is visible in the Admin, making it easy to quickly check what you emailing code is trying to fire off into the intertubes.Django also has an in-memory email backend. More details in the docs under . This is present in Django 1.6 not sure if it's present in anything earlier.If you are into unit-testing the best solution is to use the  provided by django.Take the case of use it as a  fixtureIn each test, the  is reset with the server, so there are no side effects between tests.Patching SMTPLib for testing purposes can help test sending mails without sending them.Using the file backend works well, but I find it a little a cumbersome to poke around the filesystem to look at emails.  You could use mailcatcher, , to capture emails and display them in a web UI.To use mailcatcher with Django you'll need to add something like the following to your settings.py:Use Also, it has a component called , the , which enables you to test sending emails with various problems happening:Read more about it .(Unlike original mailcatcher, which  and it WASN'T really fixed in the current release, MailHog just works.)Why not start your own really simple SMTP Server by inherit from  and :process_message is called whenever your SMTP Server receive a mail request, you can do whatever you want there.In the testing code, do something like this:Just remember to  the  by calling  to end the asyncore loop(stop the server from listening).Use Maildump.However it requires Python 2.I prefer real email sending via  service:My solution is write content to a html file. This way can help you see how email look like. I leave it here .Other tip: You can use  which can help you edit your email template with zero inline css.
Python

Let's pretend I have the following QueryDict: I'd like to have a dictionary out of this, eg:(I don't care if the unicode symbol  stays or goes.)If I do , as suggested by the , I lose the extra values belonging to , eg:I was thinking of doing this:Is there a better way? This should work: New in Django >= 1.4.This is what I've ended up using:From my usage this seems to get you a list you can send back to e.g. a form constructor. maybe this isn't the best method. It seems if you want to e.g. write  to a file for whatever crazy reason,  is the way to go. To reconstruct the  you simply do .I ran into a similar problem, wanting to save arbitrary values from a form as serialized values.My answer avoids explicitly iterating the dictionary contents: In order to retrieve a dictionary-like value that functions as the original, an inverse function uses  to populate a new  value.  In this case, I don't think the explicit iteration is avoidable.My helper functions look like this:If you do not want the values as Arrays you can do the following:zip is a powerful tool read more about it here Please Note : underscore  in iterlists method of . Django version :1.5.1 returns a weird python dictionary with array wrapped values.where as  returns expected output.
Python

What is the simplest way to get monitor resolution (preferably in a tuple)? On Windows:Based on this In Windows,\nyou can also use ctypes:so that you don't need to install the pywin32 package;\nit doesn't need anything that doesn't come with Python itself.If you're using wxWindows, you can simply do:FYI I created a PyPI module for this reason:The code:Result:. Its goal is to be cross platform; for now it supports Cygwin and X11 but pull requests are totally welcome.Taken directly from an answer to this post: And for completeness, Mac OS Xwill give you a list of tuples containing all screen sizes (if multiple monitors present)Here is a quick little Python program that will display the information about your multi-monitor setup:Here's an example of its output:On Windows 8.1 I am not getting the correct resolution from either ctypes or tk.\nOther people are having this same problem for ctypes: \nTo get the correct full resolution of a high DPI monitor on windows 8.1, one must call SetProcessDPIAware and use the following code:Full Details Below:I found out that this is because windows is reporting a scaled resolution. It appears that python is by default a 'system dpi aware' application. Types of DPI aware applications are listed here:\nBasically, rather than displaying content the full monitor resolution, which would make fonts tiny, the content is scaled up until the fonts are big enough.On my monitor I get:\nPhysical resolution: 2560 x 1440 (220 DPI)\nReported python resolution: 1555 x 875 (158 DPI)Per this windows site: \nThe formula for reported system effective resolution is:\n(reported_px*current_dpi)/(96 dpi) = physical_pxI'm able to get the correct full screen resolution, and current DPI with the below code.\nNote that I call SetProcessDPIAware() to allow the program to see the real resolution.Which returned:I am running windows 8.1 with a 220 DPI capable monitor.\nMy display scaling sets my current DPI to 158.I'll use the 158 to make sure my matplotlib plots are the right size with:\nfrom pylab import rcParams\nrcParams['figure.dpi'] = curr_dpiIf you are using the  toolkit specifically , you can do the following:Using Linux, the simplest way is to execute bash commandand parse its output using regexp. Also you can do it through PyGame: I am using a get_screen_resolution method in one of my projects like the one below, which is basically an import chain. You can modify this according to Your needs by removing those parts that are not needed and move more likely ports upwards in the chain.XWindows version:Try the following code:Try the following code:Using Linux\nInstead of regexp take the first line and take out the current resolution values.Current resolution of display :0 This was done on xrandr 1.3.5, I don't know if the output is different on other versions, but this should make it easy to figure out.To get bits per pixel:parameters in gdi32:Old question but this is missing. \nI'm new to python so please tell me if this is a \"bad\" solution.\nThis solution is supported for windows and mac only and it works just for the main screen - but the os is not mentioned in the question. Measure the size by taking a screenshot. As the screensize should not change this has to be done only once.\nThere are more elegant solutions if you have a gui toolkit like gtk, wx, ... installed. see Try pyautogui:    
Python

Following the documentation for setting up Sphinx documentation links between packages, I have added to my , but can't seem to get links to any project other than Python itself to work. For examplejust takes me to the index page, without adding the expected  anchor, and I can't even locate the glossary for  or figure out how to determine what s or s are supported by a package.Where can I find instructions on how to specify targets for s and s in , , and ?For that matter, how do I link to Sphinx itself? Addinganddoesn't work.I have a  with a handful of  mappings, which now includes all of ,  and .  You should be able to use these entries directly in , within your . If anyone has suggestions for further entries to be added to this list, please feel free to post requests into the comments of the Gist.For all of these packages, per  I highly recommend using  to decode and inspect the syntax of the  file for each library.  (Full disclosure: I am the author of .) Each line of the (decoded)  gives you all the information you need to construct a working  reference; see the  documentation . Sometimes you need a fully-qualified name, e.g.:Other times (for C functions, for example) you can just reference the function's base name BUT you have to explicitly indicate the domain, e.g.:Yet other times you may have to reference the custom  domain, e.g.:There's really no way to know what the right syntax is without consulting the .\u00a0 Things are further complicated by the introduction of numerous custom domains for the various  subpackages, e.g.:\u00a0 it appears you always have to provide the (quite verbose) fully-specified object name in the reference, e.g.:All of the  code objects seem to reside in the default  domain, however, which simplifies things somewhat.\u00a0 if you're having trouble getting a link to construct properly, the first thing I fall back to is using the generic  role, e.g.:This will construct an  link regardless of the role in which a particular object was defined, though I think you still have to correctly specify any relevant non-default domain. If the reference doesn't work properly with an  role, then there's an error in the object name or the domain somewhere. Check for typos in both places.It is possible to manually specify which inventory to look. For example, if \ndoes not work, you can always download the inventory and manually append it to the mapping (e.g. download from , save the binary file in your docs and append the path to it in the mapping; this will give something like:To verify if a reference exists within the inventory, you can explore the binary with the  python package and check where is the reference you want.This may not be a solution to your problem but can help to debug some things.
Python

My goal is to distribute a Python package that has several other widely used Python packages as dependencies.  My package depends on well written, Pypi-indexed packages like pandas, scipy and numpy, and specifies in the setup.py that certain versions or higher of these are needed, e.g. \"numpy >= 1.5\".I found that it's immensely frustrating and nearly impossible for Unix savvy users who are  experts in Python packaging (even if they know how to write Python) to install a package like mine, even when using what are supposed to be easy to use package managers.  I am wondering if there is an alternative to this painful process that someone can offer, or if my experience just reflects the very difficult current state of Python packaging and distribution.Suppose users download your package onto their system.  Most will try to install it \"naively\", using something like:Since if you google instructions on installing Python packages, this is usually what comes up.  This will fail for the vast majority of users, since most do not have root access on their Unix/Linux servers.  With more searching, they will discover the \"--prefix\" option and try:Since the users are not aware of the intricacies of Python packaging, they will pick an arbitrary directory as an argument to , e.g. .  It will not be a cleanly curated directory where all other Python packages reside, because again, most users are not aware of these details.  If they install another package \"myotherpackage\", they might pass it , and you can imagine how down the road this will lead to frustrating hacking of  and other complications.Continuing with the installation process, the call to  with  will also fail once users try to use the package, even though it appeared to have been installed correctly, since one of the dependencies might be missing (e.g. pandas, scipy or numpy) and a package manager is not used.  They will try to install these packages individually.  Even if successful, the packages will inevitably not be in the  due to the non-standard directories given to  and patient users will dabble with modifications of their  to get the dependencies to be visible.At this stage, users might be told by a Python savvy friend that they should use a package manager like , the mainstream manager, to install the software and have dependencies taken care of.  After installing , which might be difficult, they will try:This too will fail, since users again do not typically have permission to install software globally on production Unix servers.  With more reading, they will learn about the  option, and try:They will get the error:They will be extremely puzzled why their  does not have the  option where there are clearly pages online describing the option.  They might try to upgrade their  to the latest version and find that it still fails.If they continue and consult a Python packaging expert, they will discover that there are  of , both named \" so as to maximize confusion, but one part of \"distribute\" and the other part of \"setuptools\".  It happens to be that only the  of  supports  and the vast majority of servers/sys admins install 's  and so local installation will not be possible.  Keep in mind that these distinctions between  and  are meaningless and hard to understand for people who are not experts in Python package management.At this point, I would have lost 90% of even the most determined, savvy and patient users who try to install my software package -- and rightfully so!  They wanted to install a piece of software that happened to be written in Python, not to become experts in state of the art Python package distribution, and this is far too confusing and complex.  They will give up and be frustrated at the time wasted.The tiny minority of users who continue on and ask more Python experts will be told that they ought to use  instead of .  Installing  and  and figuring out how these tools work and how they are different from the conventional  or  calls is in itself time consuming and difficult, and again too much to ask from users who just wanted to install a simple piece of Python software and use it. Even those who pursue this path will be confused as to whether whatever dependencies they installed with  or  are still usable with  or if everything needs to be reinstalled from scratch.This problem is exacerbated if one or more of the packages in question depends on installing a different version of Python than the one that is the default.  The difficulty of ensuring that your Python package manger is using the Python version you want it to, and that the required dependencies are installed in the relevant Python 2.x directory and not Python 2.y, will be so endlessly frustrating to users that they will certainly give up at that stage.Is there a simpler way to install Python software that doesn't require users to delve into all of these technical details of Python packages, paths and locations?  For example, I am not a big Java user, but I do use some Java tools occasionally, and don't recall ever having to worry about X and Y dependencies of the Java software I was installing, and I have no clue how Java package managing works (and I'm happy that I don't -- I just wanted to use a tool that happened to be written in Java.)  My recollection is that if you download a Jar, you just get it and it tends to work.  Is there an equivalent for Python?  A way to distribute software in a way that doesn't depend on users having to chase down all these dependencies and versions?  A way to perhaps compile all the relevant packages into something self-contained that can just be downloaded and used as a binary?I would like to emphasize that this frustration happens even with the narrow goal of distributing a package to savvy Unix users, which makes the problem simpler by not worrying about cross platform issues, etc.  I assume that the users are Unix savvy, and might even know Python, but just aren't aware (and don't want to be made aware) about the ins and outs of Python packaging and the myriad of internal complications/rivalries of different package managers.  A disturbing feature of this issue is that it happens even when all of your Python package dependencies are well-known, well-written and well-maintained Pypi-available packages like Pandas, Scipy and Numpy.  It's not like I was relying on some obscure dependencies that are not properly formed packages: rather, I was using the most mainstream packages that many might rely on.Any help or advice on this will be greatly appreciated.  I think Python is a great language with great libraries, but I find it virtually impossible to distribute the software I write in it (once it has dependencies) in a way that is easy for people to install locally and just run.  I would like to clarify that the software I'm writing is not a Python library for programmatic use, but software that has executable scripts that users run as individual programs. Thanks.We also develop software projects that depend on numpy, scipy and other PyPI packages. Hands down, the best tool currently available out there for managing remote installations is . It is  easy to use. You download a bootstrapping script from their website and distribute that with your package. You write a \"local deployment\" file, called normally , that explains how to install the package locally. You ship both the  file and  with your package - we use the  file in our python packages to force the embedding of these two files with the zip or tar balls distributed by PyPI. When the user unpackages it, it should execute two commands:The package is compiled and all dependencies are installed , which means that the user installing your package doesn't even need root privileges, which is an added feature. The scripts are (normally) placed under , so the user can just execute them after that.  uses  for interaction with PyPI so everything you expect works out of the box.You can extend  quite easily if all that power is not enough - you create the so-called \"recipes\" that can help the user to create extra configuration files, download other stuff from the net or instantiate custom programs.  website contains a video tutorial that explains in details how to use buildout and how to extend it. Our project  makes extensive use of buildout for distributing packages for scientific usage. If you would like, please  that contains detailed instructions for our developers on how they can setup their python packages so other people can build and install them locally using .We're currently working to make it easier for users to get started installing Python software in a platform independent manner (in particular see  and )For right now, the problem with two competing versions of easy_install has been resolved, with the competing fork \"distribute\" being merged backing into the setuptools main line of development.The best currently available advice on cross-platform distribution and installation of Python software is captured here: 
Python

I'm just wondering what the differences and advantages are for the different CGI's out there. Which one would be best for python scripts, and how would I tell the script what to use?A part answer to your question, including scgi.Lazy and not writing it on my own. From the wikipedia: There's also a good background reader  on CGI, WSGI and other options, in the form of an official python HOWTO: In a project like , you can use a WSGI () server from the .A WSGI server wraps a back-end process using one or more protocol:
Python

I am trying to use imshow in matplotlib to plot data as a heatmap, but some of the values are NaNs. I'd like the NaNs to be rendered as a special color not found in the colormap.example:The resultant image is unexpectedly all blue (the lowest color in the jet colormap).  However, if I do the plotting like this:--then I get something better, but the NaN values are drawn the same color as vmin... Is there a graceful way that I can set NaNs to be drawn with a special color (eg: gray or transparent)?Hrm, it appears I can use a masked array to do this:This should suffice, though I'm still open to suggestions. :]It did not work for me. I was getting error message, so did workaround:
Python

I'm looking over the code for Python's  module, and it contains this line:instead ofthe subtle difference being the period before . What does that mean? Why the period?That's the new syntax for explicit . It means import from the current package.The dot in the module name is used for relative module import (see  and ,  section 6.4.2). You can use more than one dot, referring not to the curent package but its parent(s). This should only be used within packages, in the main module one should always use absolute module names.
Python

I've troubles setting VIM (7.1.xxx) for editing python files. \nIndenting seems to be broken (optimal 4 spaces).\nI've followed some tutorials I found via Google. Still no effect :/ \nPlease help.I use this on my macbook:(edited to only show stuff related to indent / tabs)I use:But but I'm going to try Daren's entriesI use the vimrc in the python repo among other things:I also addEnsure you are editing the correct configuration file for VIM. Especially if you are using windows, where the file could be named _vimrc instead of .vimrc as on other platforms.In vim typeand check your path to the _vimrc/.vimrc file withMake sure you are only using one file. If you want to split your configuration into smaller chunks you can source other files from inside your _vimrc file.for more advanced python editing consider installing the  vim plugin. it allows you do advanced code folding using regular expressions. i use it to fold my class and method definitions for faster editing.A simpler option: just uncomment the following part of the configuration (which is originally commented out) in the /etc/vim/vimrc file:
Python

Either interactively, such as from within an Ipython session, or from within a script, how can you determine which backend is being used by matplotlib?Use the  function to obtain a string denoting which backend is in use:Another way to determine the current backend is to read  dictionary:
Python

I've googled around for this, but I still have trouble relating to what Django defines as \"apps\". Should I create a new app for each piece of functionality in a site, even though it uses models from the main project? Do you guys have good rule of thumb of when to split off a new app, and when to keep functionality together with the \"main project\" or other apps?James Bennett has a wonderful  on how to organize reusable apps in Django.I prefer to think of Django applications as reusable modules or components than as \"applications\". This helps me encapsulate and decouple certain features from one another, improving re-usability should I decide to share a particular \"app\" with the community at large, and maintainability.My general approach is to bucket up specific features or feature sets into \"apps\" as though I were going to release them publicly. The hard part here is figuring out how big each bucket is. A good trick I use is to imagine how my apps would be used if they were released publicly. This often encourages me to shrink the buckets and more clearly define its \"purpose\".I tend to create new applications for each logically separate set of models. e.g.:Here is the updated presentation on 6 September 2008.The rule I follow is it should be a new app if I want to reuse the functionality in a different project.If it needs deep understanding of the models in your project, it's probably more cohesive to stick it with the models.An 'app' could be many different things, it all really comes down to taste. For example, let's say you are building a blog. Your app could be the entire blog, or you could have an 'admin' app, a 'site' app for all of the public views, an 'rss' app, a 'services' app so developers can interface with the blog in their own ways, etc.I personally would make the blog itself the app, and break out the functionality within it. The blog could then be reused rather easily in other websites.The nice thing about Django is that it will recognize any models.py file within any level of your directory tree as a file containing Django models. So breaking your functionality out into smaller 'sub apps' within an 'app' itself won't make anything more difficult.
Python

I'm working on a webapp where users can login to see their online wine cellar.I've got the Django REST models setup, as well as the front-end design in Angular but I'm having trouble putting the pieces together and my main issue is for user authentication.I've read many posts on here and various tutorials but I can't seem to find a step by step method to implement authentication:From what I understand Angular makes a POST request on a url where DRF verifies that username and password match and returns a token or other auth proof.I feel like I'm close but I need a more general view of how this works to put the pieces together.Thanks in advanceI imagine there are a lot of ways to do this, let me explain what I do, hopefully it is helpful. This is going to be a long post. I would love to hear how others do this, or better ways of implementing the same approach. You can also check out my seed project on Github, .I use token authentication with Witold Szczerba's . The beauty of his approach is that whenever a request is sent from your site without proper credentials, you are redirected to the login screen, but your request is queued to be re-fired on login complete.Here is a login directive used with the login form. It posts to Django's auth token endpoint, sets a cookie with the response token, sets the default header with the token so all requests will be authenticated, and fires the http-auth-interceptor login event.})I use the module .run method to set check for the cookie when a user comes to the site, if they have the cookie set I set the default authorization.Here is my interceptor directive that handles the authService broadcasts. If login is required, I hide everything and show the login form. Otherwise hide the login form and show everything else.To use it all my html was basically like this.Check out django-rest-auth and angular-django-registration-auth alsoWe've tried to solve most common Django auth/registration related things from a backend and angular perspective in these two libraries.Thanks!
Python

I have a bunch of classes I want to rename.  Some of them have names that are small and that name is reused in other class names, where I don't want that name changed.  Most of this lives in Python code, but we also have some XML code that references class names.Simple search and replace only gets me so far.  In my case, I want to rename AdminAction to AdminActionPlug and AdminActionLogger to AdminActionLoggerPlug, so the first one's search-and-replace would also hit the second, wrongly.Does anyone have experience with Python refactoring tools ? Bonus points if they can fix class names in the XML documents too.In the meantime, I've tried it two tools that have some sort of integration with vim.The first is , a python refactoring library that comes with a Vim (and emacs) plug-in.  I tried it for a few renames, and that definitely worked as expected.  It allowed me to preview the refactoring as a diff, which is nice.  It is a bit text-driven, but that's alright for me, just takes longer to learn.The second is  which I guess wins points on name.  Also plugs into vim and emacs.  Haven't played much with it yet, but I remember trying it a long time ago.Haven't played with both enough yet, or tried more types of refactoring, but I will do some more hacking with them.I would strongly recommend  - not just for refactorings. Since the first PyCharm answer was posted here a few years ago the refactoring support in PyCharm has improved significantly. (last checked 2016/07/27 in PyCharm 2016.2)XML refactorings (I checked in context menu in an XML file):Javascript refactorings:Your IDE can support refactorings !!\nCheck it Eric, Eclipse, WingIDE have build in tools for refactorings (Rename including). And that are very safe refactorings - if something can go wrong IDE wont do ref.Also consider adding few unit test to ensure your code did not suffer during refactorings.WingIDE 4.0 (WingIDE is my python IDE of choice) will support a few refactorings, but I just tried out the latest beta, beta6, and... there's still work to be done.  Retract Method works nicely, but Rename Symbol does not.Update: The 4.0 release has fixed all of the refactoring tools.  They work great now. have some refactoring features.You can use sed to perform this. The trick is to recall that regular expressions can recognize word boundaries. This works on all platforms provided you get the tools, which on Windows is Cygwin, Mac OS may require installing the dev tools, I'm not sure, and Linux has this out of the box. So grep, xargs, and sed should do the trick, after 12 hours of reading man pages and trial and error ;)
Python

I'm trying to pass a list of arguments to a python script using the argh library.  Something that can take inputs like these:My internal code looks like this:And here's how it behaves:The problem seems pretty straightforward: argh is only accepting the first argument, and treating it as a string.  How do I make it \"expect\" a list of integers instead?I see , but what about the (not-deprecated) argparse?  Or using argh's much nicer decorated syntax?  These seem much more pythonic.With , you just use Example output:Edit: I'm not familiar with , but it seems to be just a wrapper around  and this worked for me:Example output:I order to have access to each parameter value, the following code may be helpful.
Python

I didn't really pay as much attention to Python 3's development as I would have liked, and only just noticed some interesting new syntax changes. Specifically from  function parameter annotation:Not knowing anything about this, I thought it could maybe be used for implementing static typing in Python!After some searching, there seemed to be a lot discussion regarding (entirely optional) static typing in Python, such as that mentioned in , and  (and )..but, I'm not clear how far this has progressed. Are there any implementations of static typing, using the parameter-annotation? Did any of the parameterised-type ideas make it into Python 3?Thanks for reading my code!Indeed, it's not hard to create a generic annotation enforcer in Python. Here's my take:Given this simplicity, it's strange at the first sight that this thing is not mainstream. However, I believe there are good reasons why it's . Generally, type checking helps because if you add integer and dictionary, chances are you made some obvious mistake (and if you meant something reasonable, it's still ).But in real life you often mix quantities of the same  as seen by compiler but clearly different , for example the following snippet contains an obvious mistake:Any human should immediately see a mistake in the above line provided it knows the 'human type' of variables  and  even though it looks to computer as  multiplication of  and .There's more that can be said about possible solutions to this problem, but enforcing 'computer types' is apparently a half-solution, so, at least in my opinion, it's . It's the same reason why  is a terrible idea while  is a great one. There's more at the very informative .Now if somebody was to implement some kind of Pythonic third-party library that would automatically assign to real-world data its  and then took care to transform that type like  and enforce that check with function annotations, I think that would be a type checking people could really use!As mentioned in that PEP, static type checking is one of the possible applications that function annotations can be used for, but they're leaving it up to third-party libraries to decide how to do it. That is, there isn't going to be an official implementation in core python.As far as third-party implementations are concerned, there are some snippets (such as ), which seem to do the job pretty well.EDIT:As a note, I want to mention that checking behavior is preferable to checking type, therefore I think static typechecking is not so great an idea. My answer above is aimed at answering the question, not because I would do typechecking myself in such a way.\"Static typing\" in Python can only be implemented so that the type checking is done in run-time, which means it slows down the application. Therefore you don't want that as a generality. Instead you want some of your methods to check it's inputs. This can be easily done with plain asserts, or with decorators if you (mistakenly) think you need it a lot.There is also an alternative to static type checking, and that is to use an aspect oriented component architecture like The Zope Component Architecture. Instead of checking the type, you adapt it. So instead of:you do this:If theobject already implements IMyClass nothing happens. If it doesn't, an adapter that wraps whatever theobject is to IMyClass will be looked up, and used instead of theobject. If no adapter is found, you get an error.This combined the dynamicism of Python with the desire to have a specific type in a specific way.This is not an answer to question directly, but I found out a Python fork that adds static typing: , of course one can't rely on it as it's still small endeavor, but interesting.Sure, static typing seems a bit \"unpythonic\" and I don't use it all the time. But there are cases (e.g. nested classes, as in domain specific language parsing) where it can really speed up your development. Then I prefer using  explained in this *. It comes with a git repo, tests and an explanation what it can and what it can't do ... and I like the name ;) * Please don't pay attention to Cecil's rant about why Python doesn't come with batteries included in this case.
Python

I am looking for what type of code would I put in  files and what are the best practices related to this. Or, is it a bad practice in general ?Any reference to known documents that explain this is also very much appreciated.Libraries and frameworks usually use initialization code in  files to neatly hide internal structure and provide a uniform interface to the user. Let's take the example of Django forms module. Various functions and classes in forms module are defined in different files based on their classification.Now if you were to create a form, you would have to know in which file each function is defined and your code to create a contact form will have to look something like this (which is incovenient and ugly).Instead, in Django you can just refer to various widgets, forms, fields etc. directly from the forms namespace.How is this possible? To make this possible, Django adds the following statement to  file which import all the widgets, forms, fields etc. into the  namespace.As you can see, this simplifies your life when creating the forms because now you don't have to worry about in where each function/class is defined and just use all of these directly from  namespace. This is just one example but you can see examples like these in other frameworks and libraries.One of the best practices in that area is to import all needed classes from your library (look at , for example). So, a user of your library can do this:instead ofAlso, good practice is include in  version constant
Python

I've started working on a rather big (multithreaded) Python project, with loads of (unit)tests. The most important problem there is that running the application requires a preset environment, which is implemented by a context manager. So far we made use of a patched version of the unit test runner that would run the tests inside this manager, but that doesn't allow switching context between different test modules.Both nose and pytest do support such a thing because they support fixtures at many granularities, so we're looking into switching to nose or pytest. Both these libraries would also support 'tagging' tests and run only these tagged subsets, which is something we also would like to do.I have been looking through the documentation of both nose and pytest a bit, and as far as I can see the bigger part of those libraries essentially support the same functionality, except that it may be named differently, or require slightly different syntax. Also, I noted some small differences in the available plugins (nose has multiprocess-support, pytest doesn't seem to for instance)So it seems, the devil is in the detail, which means (often at least) in personal taste and we better go with the library that fits our personal taste best.So I'd to ask for a subjective argumentation why I should be going with nose or pytest in order to choose the library/community combo that best fits our needs.I used to use Nose because it was the default with Pylons.  I didn't like it at all.  It had configuration tendrils in multiple places, virtually everything seemed to be done with an underdocumented plugin which made it all even more indirect and confusing, and because it did unittest tests by default, it regularly broke with Unicode tracebacks, hiding the sources of errors.I've been pretty happy with py.test the last couple years.  Being able to just write a test with  out of the box makes me hate writing tests  less, and hacking whatever I need atop the core has been pretty easy.  Rather than a fixed plugin interface it just has piles of hooks, and pretty understandable source code should you need to dig further.  I even wrote an adapter for running Testify tests under py.test, and had more trouble with Testify than with py.test.That said, I hear nose has plugins for classless tests and assert introspection nowadays, so you'll probably do fine with either.  I still feel like I can hit the ground running with py.test, though, and I can understand what's going on when it breaks.
Python

In reading \"High performance MySQL\" from O'Reilly I've stumbled upon the followingI'm a bit confused, because I used to put \"SET NAMES utf8\" on the top of every script to let the db know that my queries are utf8 encoded.Can anyone comment the above quote, or, to put it more formally, what are your suggestions / best practices to ensure that my database workflow is unicode-aware.My target languages are php and python if this is relevant. would be an option - but an option limited to the . For  it is  and for  you need to specify a connection parameter.As using this function results in a MySQL API call, it should be considered much faster than issuing a query.In respect of performance the fastest way to ensure a UTF-8-based communiction between your script and the MySQL server is setting up the MySQL server correctly. As  is  to whereas  internally also executes  you can also set  statically in your .Please be aware of possible problems with other applications running on the same MySQL server instance and requiring some other character set.This answer has an emphasis on php's pdo library because it's so ubiquitous.A brief reminder - mysql is a client-server architecture. This is significant because there's not only the mysql server where the actual database is, but there's also the seperate mysql client driver, which is the thing that talks to the mysql server(they're separate entities). You could kinda sorta say the mysql client and pdo are mixed together.When you use , you issue a standard sql query to mysql. While the sql query does pass through pdo, and then through the mysql client library, and then finally it reaches the mysql server, ONLY the mysql server parses and interprets that sql query. This is significant because the mysql server doesn't send any message back to pdo or the mysql client letting it know the character set and encoding has changed, and so pdo is totally ignorant to fact that it happened.It's important not to do this because the client library cannot properly handle strings if it isn't aware of the current character set. Most common operations will work correctly without the client knowing the correct character set, but one that won't is string escaping, such as . You may think you don't need to worry about such manual primitive string escaping because you use prepared statements, but the truth is the vast majority of pdo:mysql users unknowingly use  because it's been the default setting for the pdo:mysql driver for a very long time now. An emulated prepared statement doesn't use real native mysql prepared statements as provided by the mysql api; instead, php does the equivalent of calling  on all your values, and str_replacing'ing all your placeholders with the quoted values for you.Since you can't properly escape a string unless you know the character set you're using, these emulated prepared statements are vulnerable to sql injection if you've changed to certain character sets via set names. Regardless of the possibility of sql injection, you can still break your strings if you use an escaping scheme intended for a different character set.For the pdo mysql driver, you can specify the character set when you connect, by . The client library will be aware of the character set if you do this.But improper string escaping isn't the only problem. For example, you can also have problems with using  because column names are specified as strings, and so again the encoding matters. An example could be a column name named (note the umlaut), and you switch from  to  via set names, and then you try to  with  being a utf8 encoded string because your php file is utf8 encoded. It won't work, you would need to encode the string as a latin1 variant... and now you have all kinds of crazy going on.Not sure about py, but php has  now, which states that this is the \"preferred way to change the charset [and] using mysql_query() to execute SET NAMES is not recommended.\" Note, that this function was introduced for MySQL 5.0.7, so it won't work with earlier versions.Where $link is a connection created with 
Python

I have been a Python programmer for almost two years, and I am used to writing small scripts to automate some repetitive tasks I had to do at the office. Now, apparently my colleagues noticed this, and they want those scripts too.Some of them have Macs, some Windows; I made these on windows. I investigated the possibility of using py2exe or even py2app to make natives of my script, but they never satisfied me...I came to know that all of them have JVM on their systems, so can I give them one single executable JAR file of my script using something like Jython may be?How feasible is this... I mean, I had no idea how to write scripts for Jython, neither did I care about it when I wrote them... what kind of problems will it give?The best current techniques for distributing your Python files in a jar are detailed in this article on Jython's wiki: For your case, I think you would want to take the jython.jar file that you get when you install Jython and zip the Jython Lib directory into it, then zip your .py files in, and then add a  file with your startup logic (this file is treated specially by Jython and will be the file executed when you call the jar with \"java -jar\").This process is definitely more complicated then in ought to be, and so we (the Jython developers) need to come up with a nice tool that will automate these tasks, but for now these are the best methods.  Below I'm copying the recipe at the bottom of the above article (modified slightly to fit your problem description) to give you a sense of the solution.Create the basic jar:Add other modules to the jar:Add the  module:On MS Windows, that last line, setting the CLASSPATH environment variable, would look something like this:Or, again on MS Windows, use the Control Panel and the System properties to set the CLASSPATH environment variable.Run the application:Or, if you have added your start-up script to the jar, use one of the following:The double -jar is kind of annoying, so if you want to avoid that and get the more pleasing:You'll have to do a bit more work until we get something like this into a future Jython [Update: JarRunner is part of Jython 2.5.1].  Here is some Java code that looks for the  automatically, and runs it.  Note that this is my first try at this class.  Let me know if it needs improvement!I put this code into the org.python.util package, since that's where it would go if we decide to include it in a future Jython.  To compile it, you'll need to put jython.jar (or your myapp.jar) into the classpath like:Then you'll need to add JarRunner.class to your jar (the class file will need to be in org/python/util/JarRunner.class) calling jar on the \"org\" directory will get the whole path into your jar.Add this to a file that you will use to update the manifest, a good name is manifest.txt:Then update the jar's manifest:Now you should be able to run your app like this:I experienced a similar issue in that I want to be able to create simple command line calls for my jython apps, not require that the user go through the jython installation process, and be able to have the jython scripts append library dependencies at runtime to sys.path so as to include core java code.When running the 'jython' launcher explicitly on the command line, on Unix systems, it just runs a big shell script to properly form a java command line call.  This jython launcher seems to have a dependency on reaching back to a core install of jython, and by some way of magic allows the proper handling of .jar files being added to the sys.path at runtime from within my .py scripts.  You can see what the call is and block execution by the following:But it's still just firing up a JVM and running a class file.  So my goal was to be able to make this java call to a standalone jython.jar present in my distribution's lib directory so users would not need to do any additional installation steps to start using my .py scripted utilities.Trouble is that the behavior is enough different that I would get responses like this:Now you might say that I should just add the jar files to the -classpath, which in fact I tried, but I would get the same result.The suggestion of bundling all of your .class files in a jython.jar did not sound appealing to me at all.  It would be a mess and would bind the Java/Python hybrid application too tightly to the jython distribution.  So that idea was not going to fly.  Finally, after lots of searching, I ran across bug #1776 at jython.org, which has been listed as critical for a year and a half, but I don't see that the latest updates to jython incorporate a fix.  Still, if you're having problems with having jython include your separate jar files, you should read this.In there, you will find the temporary workaround for this.  In my case, I took the Apache POI jar file and unjar'ed it into its own separate lib directory and then modified the sys.path entry to point to the directory instead of the jar:Now, when I run jython by way of java, referencing my local jython.jar, the utility runs just peachy.  Now I can create simple scripts or batch files to make a seamless command line experience for my .py utilities, which the user can run without any additional installation steps.The 'jythonc' command should be able to compile your .py source into JVM bytecode, which should make it portable to any Java install.  Or so I read at: For distributing your Python scripts in a way that doesn't require a native Python installation, you could also try , which basically translates your Python code to C++ code, which is then compiled to a true native binary.
Python

I have these models:Now I want to query Bars that are having active Foo's as such:I am getting error such asHow can I achieve this?You cannot query against model methods or properties. Either use the criteria within it in the query, or filter in Python using a list comprehension or genex.You could also use a custom manager. Then you could run something like this:And all you have to do is:Check out the .You can't filter on methods, however if the is_active method on Foo checks an attribute on Foo, you can use the double-underscore syntax like I had similar problem: I am using class-based view  and I had to filter by model's method. (storing the information in database wasn't an option because the property was based on time and I would have to create a cronjob and/or... )My answer is ineffective and I don't know how it's gonna scale on larger data; but, it works:May be you can use simple filter, for this type of conditions.
Python

EDIT: switched to a better example, and clarified why this is a real problem.I'd like to write unit tests in Python that continue executing when an assertion fails, so that I can see multiple failures in a single test. For example:Here, the purpose of the test is to ensure that Car's  sets its fields correctly. I could break it up into four methods (and that's often a great idea), but in this case I think it's more readable to keep it as a single method that tests a single concept (\"the object is initialized correctly\").If we assume that it's best here to not break up the method, then I have a new problem: I can't see all of the errors at once. When I fix the  error and re-run the test, then the  error appears. It would save me time to see both errors when I first run the test.For comparison, Google's C++ unit testing framework  between non-fatal  assertions and fatal  assertions:Is there a way to get -like behavior in Python's ? If not in , then is there another Python unit test framework that does support this behavior?Incidentally, I was curious about how many real-life tests might benefit from non-fatal assertions, so I looked at some  (edited 2014-08-19 to use searchcode instead of Google Code Search, RIP). Out of 10 randomly selected results from the first page, all contained tests that made multiple independent assertions in the same test method. All would benefit from non-fatal assertions.What you'll probably want to do is derive  since that's the class that throws when an assertion fails.  You will have to re-architect your  to not throw (maybe keep a list of failures instead). Re-architecting stuff can cause other issues that you would have to resolve.  For example you may end up needing to derive  to make changes in support of the changes made to your .Another way to have non-fatal assertions is to capture the assertion exception and store the exceptions in a list. Then assert that that list is empty as part of the tearDown.One option is assert on all the values at once as a tuple.For example:The output from this tests would be:This shows that both the model and the wheel count are incorrect.It is considered an anti-pattern to have multiple asserts in a single unit test. A single unit test is expected to test only one thing. Perhaps you are testing too much. Consider splitting this test up into multiple tests. This way you can name each test properly.Sometimes however, it is okay to check multiple things at the same time. For instance when you are asserting properties of the same object. In that case you are in fact asserting whether that object is correct. A way to do this is to write a custom helper method that knows how to assert on that object. You can write that method in such a way that it shows all failing properties or for instance shows the complete state of the expected object and the complete state of the actual object when an assert fails.Do each assert in a separate method.I liked the approach by @Anthony-Batchelor, to capture the AssertionError exception. But a slight variation to this approach using decorators and also a way to report the tests cases with pass/fail.Output from console:I don't think there is a way to do this with PyUnit and wouldn't want to see PyUnit extended in this way.I prefer to stick to one assertion per test function () and would rewrite  as four separate test functions. This would give more useful information on failure, :If you decide that this approach isn't for you, you may find  helpful.It looks like you are testing two concepts with your updated question and I would split these into two unit tests. The first being that the parameters are being stored on the creation of a new object. This would have two assertions, one for  and one for . If the first fails, the that clearly needs to be fixed, whether the second passes or fails is irrelevant at this juncture.The second concept is more questionable... You're testing whether some default values are initialised. ? It would be more useful to test these values at the point that they are actually used (and if they are not used, then why are they there?). Both of these tests fail, and both should. When I am unit-testing, I am far more interested in failure than I am in success as that is where I need to concentrate.
Python

In a module residing inside a package, i have the need to use a function defined within the  of that package. how can i import the package within the module that resides within the package, so i can use that function?Importing  inside the module will not import the package, but instead a module named , leading to two copies of things with different names...Is there a pythonic way to do this?Also, starting in Python 2.5, relative imports are possible. e.g.:Quoting from :Starting with Python 2.5, in addition to the implicit relative imports described above, you can write explicit relative imports with the from module import name form of import statement. These explicit relative imports use leading dots to indicate the current and parent packages involved in the relative import. From the surrounding module for example, you might use:This doesn't exactly answer your question, but I'm going to suggest that you move the function outside of the  file, and into another module inside that package. You can then easily import that function into your other module. If you want, you can have an import statement in the  file that will import that function (when the package is imported) as well.If the package is named  and your init file is therefore  and your module within the package is  then from within  file, you should just be able to say  and use whatever you want that's defined in testmod.In Django, the file manage.py has , but  is not a module. It is a function within the  module of the  directory.I'm not totally sure what the situation is, but this may solve your \"different name\" problem:Or maybe?:
Python

I have a list of 3-tuples representing a set of points in 3D space. I want to plot a surface that covers all these points. The plot_surface function in the mplot3d package requires as arguments X,Y and Z which are 2d arrays. Is plot_surface the right function to plot surface and how do I transform my data in to the required format ?For surfaces it's a bit different than a list of 3-tuples, you should pass in a grid for the domain in 2d arrays. If all you have is a list of 3d points, rather than some function , then you will have a problem because there are multiple ways to triangulate that 3d point cloud into a surface.  Here's a smooth surface example:I just came across this same problem.  I have evenly spaced data that is in 3 1-D arrays instead of the 2-D arrays that 's  wants.  My data happened to be in a  so here is the  with the modifications to plot 3 1-D arrays.  That is the original example.  Adding this next bit on creates the same plot from 3 1-D arrays.Here are the resulting figures:\ncheck the official example.\nX,Y and Z are indeed 2d arrays, numpy.meshgrid() is a simple way to get 2d x,y mesh out of 1d x and y values.here's pythonic way to convert your 3-tuples to 3 1d arrays.Here's mtaplotlib delaunay triangulation (interpolation), it converts 1d x,y,z into something compliant (?):In Matlab I did something similar using the  function on the ,  coords only (not the ), then plotting with  or , using  as the height.SciPy has the  class, which is based on the same underlying QHull library that the Matlab's  function is, so you should get identical results.From there, it should be a few lines of code to convert this  example into what you wish to achieve, as  gives you the specification of each triangular polygon.
Python

I am trying to iterate the lambda func over a list as in ,  and I want to get the call result of the lambda, not the function object itself. However, the following output really confused me. I modified the variable name when print the call result to  as following, and everything goes well. I am wondering what is all about of that. ?In Python 2 list comprehension 'leaks' the variables to outer scope:Note that the behavior is different on Python 3:When you define lambda it's bound to variable , not its' current value as your second example shows. \nNow when you assign new value to  the lambda will return whatever is the current value:Since the value of  within the loop is the lambda itself you'll get it as a return value:: Example on Python 2.7:Same on Python 3.4:For details about the change regarding the variable scope with list comprehension see Guido's .Closures in Python are , meaning that each lambda function in the list will only evaluate the variable  when invoked, and  when defined. That's why all functions return the same value, i.e. the last value of  (which is 4).To avoid this, one technique is to bind the value of  to a local named parameter:Another option is to create a  and bind the current value of  as its parameter: Sorry, misread the question initially, since these kind of questions are so often about late binding (thanks  for the comment).The second reason for the behavior is list comprehension's variable leaking in Python2 as others have already explained. When using  as the iteration variable in the  loop, each function prints the current value of  (for the reasons stated above), which is simply the function itself.\nWhen using a different name (e.g. ), functions print the last value of  as it was in the list comprehension loop, which is 4. is an anonymous function with no arguments that returns i. So you are generating a list of anonymous functions, which you can later (in the second example) bind to the name  and invoke with . Note you can do the same with non-anonymous functions:@plamut has just answered the implied other part of the question, so I won't.
Python

I have a module that conflicts with a built-in module.  For example, a  module defined in .I can reference  anywhere in my code without issue.  However, I need to reference the built-in email module from my email module.It only finds itself, and therefore raises an , since  doesn't have a  method.   causes the same issue when I try .Is there any native support to do this in Python, or am I stuck with renaming my \"email\" module to something more specific?You will want to read about  which addresses this very problem. Use:Using that, any unadorned package name will always refer to the top level package. You will then need to use relative imports () to access your own package. The above  line needs to be put into any 2.x Python  files above the  lines you're using. In Python 3.x this is the default behavior and so is no longer needed.
Python

What's better practice in a user-defined function in Python: raise an exception or return None?  For example, I have a function that finds the most recent file in a folder.Another option is leave the exception and handle it in the caller code, but I figure it's more clear to deal with a FileNotFoundError than an IndexError.  Or is it bad form to re-raise an exception with a different name?It's really a matter of semantics.  What does  ?Is it perfectly reasonable that there's no latest file?  Then sure, just return None.Are you expecting to always find a latest file?  Raise an exception.  And yes, re-raising a more appropriate exception is fine.If this is just a general function that's supposed to apply to any directory, I'd do the former and return None.  If the directory is, e.g., meant to be a specific data directory that contains an application's known set of files, I'd raise an exception.I would make a couple suggestions before answering your question as it may answer the question for you.As soon as I did this it became clear what it should return..  If there isn't a pdf raise an exception. But wait there more..Hope this helps!I usually prefer to handle exceptions internally (i.e. try/except inside the called function, possibly returning a None) because python is dynamically typed.  In general, I consider it a judgment call one way or the other, but in a dynamically typed language, there are small factors that tip the scales in favor of not passing the exception to the caller:Honestly, though, it's always a judgment call, and the situation you're describing, where the called function receives an error it can't help, is an excellent reason to re-raise an exception that is meaningful.  You have the exact right idea, but unless you're exception is going to provide more meaningful information in a stack trace thanwhich, nine times out of ten, is what the caller will see if you return an unhandled None, don't bother.(All this kind of makes me wish that python exceptions had the  attributes by default, as in java, which lets you pass exceptions into new exceptions so that you can rethrow all you want and never lose the original source of the problem.)In general, I'd say an exception should be thrown if something catastrophic has occured that cannot be recovered from (i.e. your function deals with some internet resource that cannot be connected to), and you should return None if your function should really return something but nothing would be appropriate to return (i.e. \"None\" if your function tries to match a substring in a string for example).
Python

When I create a fresh virtualenv,  shows that I have a couple of packages installed even though I've not installed anything into the environment. I was expecting  to return empty output until after my first  into the environment.  isn't it, so why does it show up at all? Some extra info:Everytime you create a virtualenv with --no-site-packages it installs  or . And the reason  appears is because python 2.5+ standard library provides egg info to  lib (and  does not know if it stdlib or 3rd party package).It seems to be solved on Python3.3+: To answer a slightly different question: you can exclude  (and any other similarly-problematic  files if you are unfortunate enough to have any for some reason) by doing  instead of . describes this option:
Python

 This is asking for the reverse of the usual tuple-to-array conversion.I have to pass an argument to a (wrapped c++) function as a nested tuple.  For example, the following workswhereas the following Unfortunately, the argument I would like to use comes to me as a numpy array.  That array always has dimensions 2xN for some N, which may be quite large.Is there an easy way to convert that to a tuple?  I know that I could just loop through, creating a new tuple, but would prefer if there's some nice access the numpy array provides.If it's not possible to do this as nicely as I hope, what's the prettiest way to do it by looping, or whatever?Here's a function that'll do it:And an example:Another optionIf you are passing NumPy arrays to C++ functions, you may also wish to look at using Cython or SWIG. I was not satisfied, so I finally used this:I don't know if it's quicker, but it looks more effective ;)
Python

Why is the  better than the ?I ask because I don't see them resulting in anything different.Borg:Singleton:What I want to display here is that the service object, whether implemented as Borg or Singleton, has a nontrivial internal state (it provides some service based on it) (I mean it has to be something useful it's not a Singleton/Borg just for fun).And this state has to be inited. Here the Singleton implementation is more straightforward, since we treat  as the set-up of the global state. I find it awkward that the Borg object has to query its internal state to see if it should update itself.It becomes worse the more internal state you have. For example, if the object has to listen to the Application's teardown signal to save its register to disk, that registration should only be done once as well, and this is easier with a Singleton.The real reason that borg is different comes down to subclassing.If you subclass a borg, the subclass' objects have the same state as their parents classes objects, unless you explicitly override the shared state in that subclass. Each subclass of the singleton pattern has its own state and therefore will produce different objects.Also in the singleton pattern the objects are actually the same, not just the state (even though the state is the only thing that really matters).In python if you want a unique \"object\" that you can access from anywhere just create a class  that only contains static attributes, s, and s; you could call it the Unique Pattern. Here I implement and compare the 3 patterns:UniqueSingletonBorgTestOutput:In my opinion, Unique implementation is the easiest, then Borg and finally Singleton with an ugly number of two functions needed for its definition.It is not. What is generally not recommended is a pattern like this in python:where you use a class method to get the instance instead of the constructor. Python's metaprogramming allows much better methods, e.g. the one on :It's only better in those few cases where you actually have a difference. Like when you subclass. The Borg pattern is extremely unusual, I've never needed it for real in ten years of Python programming.A class basically describes how you can access (read/write) the internal state of your object.In the singleton pattern you can only have a single class, i.e. all your objects will give you the same access points to the shared state.\nThis means that if you have to provide an extended API, you will need to write a wrapper, wrapping around the singletonIn the borg pattern you are able to extend the base \"borg\" class, and thereby more conveniently extend the API for your taste.
Python

I find myself repeatedly writing the same chunk of code:Is there any way I can write this function quicker/with less code?\nI usually use this in an if statement, like this:Yes, use :As the docs mention, this is pretty much equivalent to your function, but  can take generator expressions instead of just a string and a list, and  short-circuits. Once  is True, the function breaks (you can simply do this with your function if you just change  to . Remember that functions break when it returns a value).You should avoid naming strings  and lists . That will override the built-in types.
Python

I want to find all values in a Pandas dataframe that contain whitespace (any arbitrary amount) and replace those values with NaNs.Any ideas how this can be improved?Basically I want to turn this:Into this:I've managed to do it with the code below, but man is it ugly. It's not Pythonic and I'm sure it's not the most efficient use of pandas either. I loop through each column and do boolean replacement against a column mask generated by applying a function that does a regex search of each value, matching on whitespace.It could be optimized a bit by only iterating through fields that could contain empty strings:But that's not much of an improvementAnd finally, this code sets the target strings to None, which works with Pandas' functions like fillna(), but it would be nice for completeness if I could actually insert a NaN directly instead of None.Help!I think  does the job:Produces:How about:The  function applies a function to every cell of the dataframe.I will did this:orYou can strip all str, then replace empty str with .
Python

I have a base class with a property which (the get method) I want to overwrite in the subclass. My first thought was something like:This does not work (subclass bar.age returns 11). I found a solution with an lambda expression which works:So is this the right solution for using properties and overwrite them in a subclass, or are there other preferred ways to do this?I simply prefer to repeat the  as well as you will repeat the  decorator when overriding a class method. While this seems very verbose, at least for Python standards, you may notice:1) for read only properties,  can be used as a decorator:2) in Python 2.6,   and  which can be used to apply to general properties the shortcut already available for read-only ones:Another way to do it, without having to create any additional classes. I've added a set method to show what you do if you only override one of the two:This is a pretty contrived example, but you should get the idea.Yes, this is the way to do it; the property declaration executes at the time the parent class' definition is executed, which means it can only \"see\" the versions of the methods which exist on the parent class. So when you redefine one or more of those methods on a child class, you need to re-declare the property using the child class' version of the method(s).I don't agree that the chosen answer is the ideal way to allow for overriding the property methods.  If you expect the getters and setters to be overridden, then you can use lambda to provide access to self, with something like .This works (at least) for Python versions 2.4 to 3.4.If anyone knows a way to do this with by using property as a decorator instead of as a direct property() call, I'd like to hear it!Example:This way, an override can be easily performed:so that:I discovered this on .I agree with your solution, which seems an on-the-fly template method. \n deals with your problem and provides exactly your solution.Something like this will workSame as 's but with decorator.  This way, an override can be easily performed:I ran into problems setting a property in a parent class from a child class. The following workround extends a property of a parent but does so by calling the _set_age method of the parent directly. Wrinkled should always be correct. It is a little javathonic though.
Python

Caught an exception while rendering:  I was able to successfully import  from the shell and it worked so the path should be correct.Here is the urls.py:  This is where the error is being generated:  Which I can't understand because this works fine from the same file:  Here is the function definition:  I don't understand why Django would think that the function would not be able to find the Reverse for that function.I deleted all the  files and restarted Apache.What am I doing wrong?There are 3 things I can think of off the top of my head:Shell calls to  (as mentioned above) are very good to debug these problems, but there are two critical conditions:Yes, it's logical. Yes, it's also confusing because  will only throw the exception and won't give you any further hints.An example of URL pattern:And then what happens in shell:It doesn't work because I supplied no arguments.Now it worked, but...Now it didn't work because  didn't match the regexp (expected numeric, supplied string).You can use  with both positional arguments and keyword arguments. The syntax is:As it comes to the  template tag, there's funny thing about it. Django  gives example of using quoted view name:So I used it in a similar way in my HTML template:But this didn't work for me. But the exception message gave me a hint of what could be wrong - note the double single quotes around view name:It started to work when I  the quotes:And this  confusing.You need single quotes around the view nameinstead ofI had a similar problem and the solution was in the right use of the '$' (end-of-string) character:My main url.py looked like this (notice the $ character):and my url.py for my card_purchases app said: So a simple change worked:Notice the change in the second url! My url.py for my card_purchases app looks like this:Apart from this, I can confirm that quotes around named urls are crucial!I don't think you need the trailing slash in the URL entry. Ie, put this instead:This is assuming you have  enabled, which is the default.
Python

I have a Python file which might have to support Python versions < 3.x and >= 3.x. Is there a way to introspect the Python runtime to know the version which it is running (for example, )?Sure, take a look at  and .For example, to check that you are running Python 3.x, useHere,  is the major version number.  would give you the minor version number.In Python 2.7 and later, the components of  can also be accessed by name, so the major version number is .See also Try this code, this should work:Per  and :Here's some code I use with  to check the Python installation:The best solution depends on how much code is incompatible. If there are a lot of places you need to support Python 2 and 3,  is the compatibility module.  and  are two booleans if you want to check the version.However, a better solution than using a lot of  statements is to use  compatibility functions if possible. Hypothetically, if Python 3000 has a new syntax for , someone could update  so your old code would still work.CheersTo make the scripts compatible with Python2 and 3 i use :
Python

I like very much the  package and its comfortable way to handle JSON responses. Unfortunately, I did not understand if I can also process XML responses. Has anybody experience how to handle XML responses with the  package? Is it necessary to include another package such as  for the XML decoding? does not handle parsing XML responses, no. XML responses are much more complex in nature than JSON responses, how you'd serialize XML data into Python structures is not nearly as straightforward.Python comes with built-in XML parsers. I recommend you use the :or, if the response is particularly large, use an incremental approach:The external  builds on the same API to give you more features and power still.
Python

I want to host several sites with under the same server which uses Debian 5, say I have ,  and , and assume my ip is :Here is my apache default: And here is my wsgi config for , at :How can I add  and , which are Django-based sites and will be served like ?Your ServerName/ServerAlias directives are wrong. ServerName should be hostname. You probably should just delete ServerAlias.Then just do the obvious and duplicate VirtualHost/Listen directives, just changing the port number and locations of scripts in the file system.Finally, do not set DocumentRoot to be where your Django code is as it makes it easier to accidentally expose your source code to download if you stuff up Apache configuration. So, just remove DocumentRoot directive from VirtualHost for Django sites.I have also add missing Directory directive for allowing access to static files. You should review paths however.Make sure you read:\nfor further information.UPDATE 1BTW, since you are using PHP in same Apache, you would be much better off using mod_wsgi daemon mode and push each Django instance out into its own separate process. That allows those processes to be multithreaded, even though main Apache processes are forced to be single threaded because of PHP. End result will be much much less memory being used than if running multiple Django instances in each process under embedded mode with prefork MPM. Your Django code just needs to be thread safe. Configuration in addition to above would be to add WSGIDaemonProcess/WSGIProcessGroup to each Django VirtualHost, where name of daemon process group is different for each VirtualHost.This also allows you to more easily restart each Django instance without restart whole of Apache. Read:\nPutting all virtualHost configuration in one place works fine, but Debian has its own concept by separating them in a file for each site in /etc/apache2/sites-available, which are activated by symlinking them in ../sites-enabled. \nIn this way a server-admin could also assign separate access rights to the config file for each of the site-admin unix users, scripts can check if a site is active etc. Basically it would be nice to have one central howto for Django-Admin installations, the current multitude of separate docs, links and blog articles is not really helpful for the proliferation of Django. 
Python

How do I get a thread to return a tuple or any value of my choice back to the parent in Python?I suggest you instantiate a  before starting the thread, and pass it as one of the thread's args: before the thread finishes, it s the result on the queue it received as an argument.  The parent can  or  it at will.Queues are generally the best way to arrange thread synchronization and communication in Python: they're intrinsically thread-safe, message-passing vehicles -- the best way to organize multitasking in general!-)If you were calling join() to wait for the thread to complete, you could simply attach the result to the Thread instance itself and then retrieve it from the main thread after the join() returns.  On the other hand, you don't tell us how you intend to discover that the thread is done and that the result is available.  If you already have a way of doing that, it will probably point you (and us, if you were to tell us) to the best way of getting the results out.You should pass a Queue instance as a parameter then you should .put() your return object into the queue. You can gather the return value via queue.get() whatever object you put.Sample:Use for multiple threads:I use this implementation and it works great for me. I wish you do so.I'm surprised nobody mentioned that you could just pass it a mutable:perhaps this has major issues of which I'm unaware.Another approach is to pass a callback function to the thread. This gives a simple, safe and flexible way to return a value to the parent, anytime from the new thread.Use  to wrap your target thread function and pass its return value back to the parent thread using a .  (Your original target function remains unchanged without extra queue parameter.)Sample code:Output:POC:You can use synchronised  module.\nConsider you need to check a user infos from database with a known id:Now you can get your data like this:Well, in the Python threading module, there are condition objects that are associated to locks. One method  will return whatever value is returned from the underlying method. For more information: Based on jcomeau_ictx's suggestion. The simplest one I came across. Requirement here was to get exit status staus from three different processes running on the server and trigger another script if all three are successful. This seems to be working fineThe following wrapper function will wrap an existing function and return an object which points both to the thread (so that you can call ,, etc. on it) as well as access/view its eventual return value.It looks OK, and the  class seems to be easily extended(*) with this kind of functionality, so I'm wondering why it isn't already there. Is there a flaw with the above method?(*) Note that husanu's answer for this question does exactly this, subclassing  resulting in a version where  gives the return value.
Python

How can I make any use of PYTHONPATH? When I try to run a script in the path the file is not\nfound. When I cd to the directory holding the script the script runs. So what good is the\nPYTHONPATH?After cd to the file directory it runs ..Why can I not make any use of the PYTHONPATH?I think you're a little confused. PYTHONPATH sets the search path for  python modules, not for executing them like you're trying.What you're looking for is PATH. However, to run your python script as a program, you also need to set a  for Python in the first line. Something like this should work:And give execution privileges to it:Then you should be able to simply run  from anywhere. only affects  statements, not the top-level Python interpreter's lookup of python files given as arguments.Needing  to be set is not a great idea - as with anything dependent on environment variables, replicating things consistently across different machines gets tricky. Better is to use Python 'packages' which can be installed (using 'pip', or distutils) in system-dependent paths which Python already knows about.Have a read of [  - Broken Link]  - 'The Hitchhiker's Guide to Packaging', and also  - which explains PYTHONPATH and packages at a lower level.You're confusing PATH and PYTHONPATH. You need to do this:PYTHONPATH is used by the python interpreter to determine which modules to load. PATH is used by the shell to determine which executables to run.
Python

I've been using  for a Python program that can ,  or both:The program is meaningless without at least one parameter. How can I configure  to force at least one parameter to be chosen?Following the comments: What's the Pythonic way to parametrize a program with at least one option?If not the 'or both' part (I have initially missed this) you could use something like this:Though, probably it would be a better idea to use  instead.There are also some implicit requirements when living on command line:Try to run it:Show the help:And use it:There can be even shorter variant:Usage looks like this:Note, that instead of boolean values for \"process\" and \"upload\" keys there are counters.It turns out, we cannot prevent duplication of these words:Designing good command line interface can be challenging sometime.There are multiple aspects of command line based program: offers a lot, but restricts possible scenarios and can become very complex.With  things go much shorter while preserving readability and offering high degree of flexibility. If you manage getting parsed arguments from dictionary and do some of conversions (to integer, opening files..) manually (or by other library called ), you may find  good fit for command line parsing.If you require a python program to run with at least one parameter, add an argument that  have the option prefix  (- or -- by default) and set  (Minimum of one argument required). The problem with this method I found is that if you do not specify the argument, argparse will generate a \"too few arguments\" error and not print out the help menu. If you don't need that functionality, here's how to do it in code:I  that when you add an argument with the option prefixes, nargs governs the entire argument parser and not just the option. (What I mean is, if you have an  flag with , then  flag expects at least one argument. If you have  with , it expects at least one argument overall.)I know this is old as dirt, but the way to require one option but forbid more than one (XOR) is like this:Output:  For  I am exploring ways of generalizing the  concept to handle cases like this.With this development ,  \nI am able to write:which produces the following :This accepts inputs like '-u',  '-up', '--proc --up' etc.It ends up running a test similar to , though the error message needs to be clearer:I wonder:Use append_const to a list of actions and then check that the list is populated:You can even specify the methods directly within the constants.The best way to do this is by using python inbuilt module .If you want only one argument to be selected by command line just use required=True as an argument for group 
Python

I came across this example in the matplotlib websiteand I was wondering if it was possible to increase the figure size.I tried withbut it does nothing.If you already have the figure object use:But if you use the .subplots() command (as in the examples you're showing) to create a new figure you can also use:
Python

I have the following plot:and now I would like to give this plot common x-axis labels and y-axis labels. With \"common\", I mean that there should be one big x-axis label below the whole grid of subplots, and one big y-axis label to the right. I can't find anything about this in the documentation for , and my googlings suggest that I need to make a big  to start with - but how do I then put my 5*2 subplots into that using ?This looks like what you actually want. It applies the same approach of  to your specific case:Without  you get:With it you should get it nicer:But if you want to add additional labels, you should add them only to the edge plots:Adding label for each plot would spoil it (maybe there is a way to automatically detect repeated labels, but I am not aware of one).Since the command:you used returns a tuple consisting of the figure and a list of the axes instances, it is already sufficient to do something like (mind that I've changed to ):If you happen to want to change some details on a specific subplot, you can access it via  where  iterates over your subplots.It might also be very helpful to include aat the end of the file, before the , in order to avoid overlapping labels.I ran into a similar problem while plotting a grid of graphs. The graphs consisted of two parts (top and bottom). The y-label was supposed to be centered over both parts.I did not want to use a solution that depends on knowing the position in the outer figure (like fig.text()), so I manipulated the y-position of the set_ylabel() function. It is usually 0.5, the middle of the plot it is added to. As the padding between the parts (hspace) in my code was zero, I could calculate the middle of the two parts relative to the upper part.Downsides:There is probably a general solution that takes padding between figures into account.I discovered an alternative method; if you know the  and  kwargs that went into a  initialization, or you otherwise know the edges positions of your axes in , you can also specify the ylabel position in  coordinates with some fancy \"transform\" magic. For example:...and you should see that the label  to keep from overlapping with ticklabels, just like normal -- but now it will adjust to be always  the desired subplots.Furthermore, if you don't even use , the ylabel will show up by default . I'm guessing this is because when the label is finally drawn,  uses 0.5 for the -coordinate without checking whether the underlying coordinate transform has changed. 
Python

I'm trying to run a google search query from a python app. Is there any python interface out there that would let me do this? If there isn't does anyone know which Google API will enable me to do this. Thanks.There's a simple example  (peculiarly missing some quotes;-).  Most of what you'll see on the web is Python interfaces to the old, discontinued SOAP API -- the example I'm pointing to uses the newer and supported AJAX API, that's definitely the one you want!-): here's a more complete Python 2.6 example with all the needed quotes &c;-)...:Here is Alex's answer ported to Python3Here's my approach to this: A couple code examples:Note that this code does NOT use the Google API, and is still working to date (January 2012).I am new in python and I was investigating how to do this. None of the provided examples are working properly for me. Some are blocked by google if you make many (few) requests, some are outdated. \nParsing the google search html (adding the header in the request) will work until google changes the html structure again. You can use the same logic to search in any other search engine, looking into the html (view-source). Usage:(Edit 1: Adding a parameter to narrow the google search to a specific site)(Edit 2: When I added this answer I was coding a Python script to search subtitles. I recently uploaded it to Github: )
Python

Before jumping into python, I had started with some Objective-C / Cocoa books. As I recall, most functions required keyword arguments to be explicitly stated. Until recently I forgot all about this, and just used positional arguments in Python. But lately, I've ran into a few bugs which resulted from improper positions - sneaky little things they were. Got me thinking - generally speaking, unless there is a circumstance that specifically requires non-keyword arguments - is there any good reason NOT to use keyword arguments? Is it considered bad style to always use them, even for simple functions? I feel like as most of my 50-line programs have been scaling to 500 or more lines regularly, if I just get accustomed to always using keyword arguments, the code will be more easily readable and maintainable as it grows. Any reason this might not be so? The general impression I am getting is that its a style preference, with many good arguments that they should generally not be used for very simple arguments, but are otherwise consistent with good style. Before accepting I just want to clarify though - is there any specific non-style problems that arise from this method - for instance, significant performance hits? There isn't any reason not to use keyword arguments apart from the clarity and readability of the code. The choice of whether to use keywords should be based on whether the keyword adds additional useful information when reading the code or not.I follow the following general rule:In most cases, stable mandatory arguments would be positional, and optional arguments would be keyword.There's also a possible difference in performance, because in every implementation the keyword arguments would be slightly slower, but considering this would be generally a premature optimisation and the results from it wouldn't be significant, I don't think it's crucial for the decision.Keyword arguments can do everything that positional arguments can, and if you're defining a new API there are no technical disadvantages apart from possible performance issues. However, you might have little issues if you're combining your code with existing elements.Consider the following:None of these would be a real issue if you design your API well and document the use of keyword arguments, especially if you're not designing something that should be interchangeable with something that already exists.If your consideration is to improve readability of function calls, why not simply declare functions as normal, e.g.And simply call functions by declaring the names explicitly, like so:Which obviously gives you the output:or this exercise would be pointless.This avoids having arguments be optional and needing default values (unless you want them to be, in which case just go ahead with the keyword arguments! :) and gives you all the versatility and improved readability of named arguments that are not limited by order.Well, there are a few reasons why I would not do that.If all your arguments are keyword arguments, it increases noise in the code and it might remove clarity about which arguments are required and which ones are optionnal.Also, if I have to use your code, I might want to kill you !! (Just kidding), but having to type the name of all the parameters everytime... not so fun.I remember reading a very good explanation of \"options\" in UNIX programs: \"Options are meant to be optional, a program should be able to run without any options at all\". The same principle could be applied to  arguments in Python. \nThese kind of arguments should allow a user to \"customize\" the function call, but a function should be able to be called without any implicit keyword-value argument pairs at all. Just to offer a different argument, I think there are some cases in which named parameters might improve readability. For example, imagine a function that creates a user in your system:From that definition, it is not at all clear what these values might mean, even though they are all required, however with named parameters it is always obvious:When Python's built-in  and  functions , the same argument was made in favor of clarity. There appears to be no significant performance hit, if any.Now, if you make your functions  accept keyword arguments (as opposed to passing the positional parameters using keywords when calling them, which is allowed), then yes, it'd be annoying.Sometimes, things should be simple because they are simple.If you always enforce you to use keyword arguments on every function call, soon your code will be unreadable.I don't see the purpose of using keyword arguments when the meaning of the arguments is obviousOne downside I could see is that you'd have to think of a sensible default value for everything, and in many cases there might not be any sensible default value (including ).  Then you would feel obliged to write a whole lot of error handling code for the cases where a kwarg that logically should be a positional arg was left unspecified.  Imagine writing stuff like this every time..Keyword args are good when you have long parameter lists with no well defined order (that you can't easily come up with a clear scheme to remember); however there are many situations where using them is overkill or makes the program less clear.First, sometimes is much easier to remember the order of keywords than the names of keyword arguments, and specifying the names of arguments could make it less clear.  Take  from  with the following docstring:When wanting to generate a random int from [0,10) its clearer to write  than  in my view.  If you need to generate an array with 100 numbers in [0,10) you can probably remember the argument order and write .  However, you may not remember the variable names (e.g., is the first parameter low, lower, start, min, minimum) and once you have to look up the parameter names, you might as well not use them (as you just looked up the proper order).  Also consider variadic functions (ones with variable number of parameters that are anonymous themselves).  E.g., you may want to write something like:that can be applied a bunch of bare parameters ( ).  Sure you could have written the function to take an named keyword iterable  and called it like  but that may be less intuitive, especially when there's no potential confusion about the argument name or its contents.
Python

I would like a general way to generate column labels directly from the selected column names, and recall seeing that python's psycopg2 module supports this feature.From \"Programming Python\" by Mark Lutz:To , you can query the information_schema.columns table.To , you can use the description field of the cursor:  I also used to face similar issue. I use a simple trick to solve this.\nSuppose you have column names in a list likeThen you can do followingI have noticed that you must use  after the query to get the list of columns in  (i.e in )After executing SQL query write following python script written in 2.7
Python

I am writing a python package with modules that need to open data files in a  subdirectory. Right now I have the paths to the files hardcoded into my classes and functions. I would like to write more robust code that can access the subdirectory regardless of where it is installed on the user's system. I've tried a variety of methods, but so far I have had no luck. It seems that most of the \"current directory\" commands return the directory of the system's python interpreter, and not the directory of the module. This seems like it ought to be a trivial, common problem. Yet I can't seem to figure it out. Part of the problem is that my data files are not  files, so I can't use import functions and the like. Any suggestions? Right now my package directory looks like:I am trying to access  from Thanks!You can use underscore-underscore-file-underscore-underscore () to get the path to the package, like this:The standard way to do this is with setuptools packages and pkg_resources.You can lay out your package according to the following hierarchy, and configure the package setup file to point it your data resources, as per this link:You can then re-find and use those files using pkg_resources, as per this link: To provide a solution working today. Definitely use this API to not reinvent all those wheels.A true filesystem filename is needed. Zipped eggs will be extracted to a cache directory:Return a readable file-like object for the specified resource; it may be an actual file, a StringIO, or some similar object. The stream is in \u201cbinary mode\u201d, in the sense that whatever bytes are in the resource will be read as-is.Package Discovery and Resource Access using pkg_resourcesI think I hunted down an answer. I make a module data_path.py, which I import into my other modules containing:And then I open all my files with You need a name for your whole module, you're given directory tree doesn't list that detail, for me this worked:Notibly setuptools does not appear to resolve files based on a name match with packed data files, soo you're gunna have to include the  prefix pretty much no matter what. You can use  if you need alternate directory separators, Generally I find no compatibility problems with hard-coded unix style directory separators though.
Python

How would you write, in python:I've tried every way I can think of, and am finding it very frustrating.If  isn't an  or  but a ing, you need to convert it to an  first by doingor to a  by doingOtherwise, what you have in your question should work, butorwould be a bit clearer.Here's a boolean thing:but  , \nso both have to be false to equate to true\nis true only if a and be are both false.
Python

When I am writing code in Python, I often need to remove items from a list or other sequence type based on some criteria. I haven't found a solution that is elegant and efficient, as removing items from a list you are currently iterating through is bad.  For example, you can't do this:I usually end up doing something like this:This is innefficient, fairly ugly and possibly buggy (how does it handle multiple 'John Smith' entries?). Does anyone have a more elegant solution, or at least a more efficient one? How about one that works with dictionaries?Two easy ways to accomplish just the filtering are:Note that both cases keep the values for which the predicate function evaluates to , so you have to reverse the logic (i.e. you say \"keep the people who do not have the last name Smith\" instead of \"remove the people who have the last name Smith\"). Funny... two people individually posted both of the answers I suggested as I was posting mine.You can also iterate backwards over the list:This has the advantage that it does not create a new list (like  or a list comprehension) and uses an iterator instead of a list copy (like ).Note that although removing elements while iterating backwards is safe, inserting them is somewhat trickier.The obvious answer is the one that John and a couple other people gave, namely:But that has the disadvantage that it creates a new list object, rather than reusing the original object.  I did some profiling and experimentation, and the most efficient method I came up with is:Assigning to \"names[:]\" basically means \"replace the contents of the names list with the following value\".  It's different from just assigning to names, in that it doesn't create a new list object.  The right hand side of the assignment is a generator expression (note the use of parentheses rather than square brackets).  This will cause Python to iterate across the list.Some quick profiling suggests that this is about 30% faster than the list comprehension approach, and about 40% faster than the filter approach.: while this solution is faster than the obvious solution, it is more obscure, and relies on more advanced Python techniques.  If you do use it, I recommend accompanying it with a comment.  It's probably only worth using in cases where you really care about the performance of this particular operation (which is pretty fast no matter what).  (In the case where I used this, I was doing A* beam search, and used this to remove search points from the search beam.)Using There are times when filtering (either using filter or a list comprehension) doesn't work. This happens when some other object is holding a reference to the list you're modifying and you need to modify the list in place.The only difference from the original code is the use of  instead of  in the for loop. That way the code iterates over a (shallow) copy of the list and the removals work as expected. Since the list copying is shallow, it's fairly quick.filter would be awesome for this. Simple example: Corey's list comprehension is awesome too.Both solutions,  and  requires building a new list. I don't know enough of the Python internals to be sure, but I  that a more traditional (but less elegant) approach could be more efficient:Anyway, for short lists, I stick with either of the two solutions proposed earlier.To answer your question about working with dictionaries, you should note that Python 3.0 will include :In the mean time, you can do a quasi-dict comprehension this way:Or as a more direct answer:If the list should be filtered in-place and the list size is quite big, then algorithms mentioned in the previous answers, which are based on list.remove(), may be unsuitable, because their computational complexity is O(n^2). In this case you can use the following no-so pythonic function:Edit:\nActually, the solution at  is superior to mine solution. It is more pythonic and works faster. So, here is a new filter_inplace() implementation:The filter and list comprehensions are ok for your example, but they have a couple of problems:Your original solution is actually more efficient for very big lists, even if we can agree it's uglier. But if you worry that you can have multiple 'John Smith', it can be fixed by deleting based on position and not on value:We can't pick a solution without considering the size of the list, but for big lists I would prefer your 2-pass solution instead of the filter or lists comprehensions In the case of a set.  Here is my  implementation that can be used to filter items from a list in-place, I came up with this on my own independently before finding this page. It is the same algorithm as what PabloG posted, just made more generic so you can use it to filter lists in place, it is also able to remove from the list based on the  if reversed is set ; a sort-of of reversed filter if you will.Well, this is clearly an issue with the data structure you are using. Use a hashtable for example. Some implementations support multiple entries per key, so one can either pop the newest element off, or remove all of them.But this is, and what you're going to find the solution is, elegance through a different data structure, not algorithm. Maybe you can do better if it's sorted, or something, but iteration on a list is your only method here. one does realize he asked for 'efficiency'... all these suggested methods just iterate over the list, which is the same as what he suggested. 
Python

... the  keyword that can be used for equality in strings.I tried both  and  but they didn't work.Thanks for your help!Testing strings with  only works when the strings are interned. Unless you really know what you're doing and explicitly  the strings you should  use  on strings.  tests for , not . That means Python simply compares the memory address a object resides in.  basically answers the question \"Do I have two names for the same object?\" - overloading that would make no sense.For example,  is . Usually Python writes each string into a different memory location, interning mostly happens for string literals.The  operator is equivalent to comparing  values.  is currently implemented to use pointers as the comparison. So you can't overload  itself, and AFAIK you can't overload  either.So, you can't. Unusual in python, but there it is.The Python  keyword tests object identity.  You should NOT use it to test for string equality.  It may seem to work frequently because Python implementations, like those of many very high level languages, performs \"interning\" of strings.  That is to say that string literals and values are internally kept in a hashed list and those which are identical are rendered as references to the same object.  (This is possible because Python strings are immutable).However, as with any implementation detail, you should not rely on this.  If you want to test for equality use  the == operator.  If you truly want to test for object identity then use  --- and I'd be hard-pressed to come up with a case where you should care about string object identity.  Unfortunately you can't count on whether two strings are somehow \"intentionally\" identical object references because of the aforementioned interning.The  keyword compares objects (or, rather, compares if two references are to the same object).Which is, I think, why there's no mechanism to provide your own implementation.It happens to work sometimes on strings because Python stores strings 'cleverly', such that when you create two identical strings they are stored in one object.You can hopefully see the reference vs data comparison in a simple 'copy' example:If you are not afraid of messing up with bytecode, you can intercept and patch  with  argument to call your hook function on objects being compared. Look at  module documentation for start-in.And don't forget to intercept  too if someone will do  instead of .is fails to compare a string variable to string value and two string variables when the string starts with '-'. My Python version is 2.6.6You can't overload the  operator.  What you want to overload is the  operator.  This can be done by defining a  method in the class.You are using identity comparison.  is probably what you want. The exception to this is when you want to be checking if one item and another are the EXACT same object and in the same memory position. In your examples, the item's aren't the same, since one is of a different type (my_string) than the other (string). Also, there's no such thing as someclass. in python (unless, of course, you put it there yourself). If there was, comparing objects with  wouldn't be reliable to simply compare the memory locations.When I first encountered the  keyword, it confused me as well. I would have thought that  and == were no different. They produced the same output from the interpreter on many objects. This type of assumption is actually EXACTLY what ... is for. It's the python equivalent \"Hey, don't mistake these two objects. they're different.\", which is essentially what [whoever it was that straightened me out] said. Worded much differently, but one point == the other point.the\nfor some helpful examples and some text to help with the sometimes confusing differences\nvisit  written by \"Danny Yoo\"or, if that's offline, use the  I made of it's body.in case they, in some 20 or so blue moons (blue moons are a real event), are both down, I'll quote the code examples'is' compares object identity whereas == compares values.Example:Assertion Errors can easily arise with  keyword while comparing objects. For example, objects  and  might hold same value and share same memory address. Therefore, doing an is going to evaluate to But ifevaluates to you should probably check and These might be different and a reason for failure.
Python

I have 2 csv files. First one is data file and other one is mapping file. Mapping file has 4 columns \nThese are also the columns which are present in data file and need to be worked upon.Data file contains data with Device_Name column populated & rest 3 columns blank. Mapping file contains all columns populated. I want my Python code to open both files and for each device name in data file map its GDN, Device_Type & Device_OS value from mapping file.I know how to use dict when only 2 columns are present (1 is needed to be mapped) but I don't know how to accomplish this when 3 columns need to be mapped.Following is the code using which I tried to accomplish mapping of :It returns the .After some researching, I realized that I need to create a nested dict, but I don't have any idea on how to do this. \nPlease help me in resolving this or nudge me in the right direction to resolve this. A nested dict is a dictionary within a dictionary. A very simple thing.You can also use a  from the  package to facilitate creating nested dictionaries.You can populate that however you want.I would recommend in your code something  the following:According to your :My suggestion would be something  this (without using defaultdict):Please note though, that for parsing csv files there is a .: For an arbitrary length of a nested dictionary, go to .Use the defaultdict function from the collections. High performance: \"if key not in dict\" is very expensive when the data set is large.Low maintenance: make the code more readable and can be easily extended.For arbitrary levels of nestedness:It is important to remember when using defaultdict and similar nested dict modules such as nested_dict, that looking up a non existent key may inadvertently create a new key entry in the dict and cause a lot of havoc. Here is a Python3 example with nested_dict.Output is:
Python

Given a list of numbers how to find differences between every ()-th and ()-th of its elements? Should one better use lambda or maybe lists comprehension?Example:\nGiven a list  it is to find a list  because , , etc.The other answers are correct but if you're doing numerical work, you might want to consider numpy. Using numpy, the answer is:If you don't want to use  nor , you can use the simple (simplest in my opinion) solution:You can use  and  to efficiently build the result:Or using  instead:You can also avoid using the  module:All these solution work in constant space if you don't need to store all the results.\nThe first and last solution also works with infinite iterables, while the second one requires a finite sequence as input.Here are some micro-benchmarks of the solutions:And the other proposed solutions:Note that:Ok. I think I found the proper solution:My way
Python

How do you prevent PIP from re-downloading previously downloaded packages? I'm testing the install of matplotlib, an 11MB package that depends on several distro-specific packages. Everytime I run , it re-downloads matplotlib. How do I stop this?You can use a specific environment variable  and make it point to a directory where your packages will be stored. If they are to be installed again, they will be taken from this directory.There seems to be also an additional option for PIP  which ought to do something similar, but I have never tried it myself. For your example, to avoid re-downloading  every time, you would do the following:Does that answer your question?Newer Pip versions by default now cache downloads. See this documentation:Create a configuration file named , and add the following contents:In one command:You could Also, you could manually download the packageThen install it by un-tar and  later.The  works in a similar way w/ extra checking: it firstly search for the latest or specified version of the target package from web, if the search has result and there is cached package in the directory specified by , the cached package will be used instead of downloading. For example, will download pymongo package to current directory:
Python

I've discovered a new pattern.  Is this pattern well known or what is the opinion about it?Basically, I have a hard time scrubbing up and down source files to figure out what module imports are available and so forth, so now, instead ofI move all my imports into the function where they're actually used., like this:This does a few things.  First, I rarely accidentally pollute my modules with the contents of other modules.  I could set the  variable for the module, but then I'd have to update it as the module evolves, and that doesn't help the namespace pollution for code that actually lives in the module.Second, I rarely end up with a litany of imports at the top of my modules, half or more of which I no longer need because I've refactored it.  Finally, I find this pattern MUCH easier to read, since every referenced name is right there in the function body.The (previously)  to this question is nicely formatted but absolutely wrong about performance. Let me demonstrateAs you can see, it can be  efficient to import the module in the function. The reason for this is simple. It moves the reference from a global reference to a local reference. This means that, for CPython at least, the compiler will emit  instructions instead of  instructions. These are, as the name implies, faster.  The other answerer artificially inflated the performance hit of looking in  by . As a rule, it's best to import at the top but performance is  the reason if you are accessing the module a lot of times. The reasons are that one can keep track of what a module depends on more easily and that doing so is consistent with most of the rest of the Python universe.This does have a few disadvantages.On the off chance you want to test your module through runtime modification, it may make it more difficult. Instead of doingYou'll have to doThis means that you'll have to patch the othermodule globally, as opposed to just change what the reference in mymodule points to.This makes it non-obvious what modules your module depends on. This is especially irritating if you use many third party libraries or are re-organizing code.I had to maintain some legacy code that used imports inline all over the place, it made the code extremely difficult to refactor or repackage.Because of the way python caches modules, there isn't a performance hit. In fact, since the module is in the local namespace, there is a slight performance benefit to importing modules in a function.A few problems with this approach:So... the preferred way is to put all imports at the top of the file. I've found that if my imports get hard to keep track of, it usually means I have too much code that I'd be better off splitting it into two or more files.Some situations where I  found imports inside functions to be useful:Also: putting imports inside each function is actually  appreciably slower than at the top of the file. The first time each module is loaded it is put into , and each subsequent import costs only the time to look up the module, which is fairly fast (it is not reloaded).Another useful thing to note is that the  syntax inside of a function has been removed in Python 3.0.There is a brief mention of it under \"Removed Syntax\" here:I would suggest that you try to avoid  imports. I only use them inside packages, where the splitting into modules is an implementation detail and there won't be many of them anyway.In all other places, where you import a package, just use  and then reference it by the full name . This way you can always tell where a certain element comes from and don't have to maintain the list of imported elements (in reality this will always be outdated and import no longer used elements). If  is a really long name you can simplify it with  and then write . This is still far more convenient and explicit than maintaining all the  imports.People have explained very well why to avoid inline-imports, but not really alternative workflows to address the reasons you want them in the first place.To check for unused imports I use . It does static(ish)-analysis of Python code, and one of the (many) things it checks for is unused imports. For example, the following script....would generate the following message:As for checking available imports, I generally rely on TextMate's (fairly simplistic) completion - when you press Esc, it completes the current word with others in the document. If I have done ,  will expand to , if not I jump to the start of the file and add the import.From a performance point of view, you can see this: In general, I only use local imports in order to break dependency cycles.You might want to take a look at Import  in the python wiki. In short: if the module has already been loaded (look at ) your code will run slower. If your module hasn't been loaded yet, and will  will only get loaded when needed, which can be zero times, then the overall performance will be better.I believe this is a recommended approach in some cases/scenarios. For example in Google App Engine lazy-loading big modules is recommended since it will minimize the warm-up cost of instantiating new Python VMs/interpreters. Have a look at a  presentation describing this. However keep in mind this  mean you should lazy-load all your modules.Consider an environment where all of your Python code is located within a folder only a privileged user has access to. In order to avoid running your whole program as privileged user, you decide to drop privileges to an unprivileged user during execution. As soon as you make use of a function that imports another module, your program will throw an  since the unprivileged user is unable to import the module due to file permissions.
Python

This is my declarative model:However, when I try to import this module, I get this error:If I use an Integer type, I can set a default value. What's going on? doesn't have a default key as an input. The default key should be an input to the  function. Try this:For sanity, you probably want to have all  calculated by your DB server, rather than the application server. Calculating the timestamp in the application can lead to problems because network latency is variable, clients experience slightly different clock drift, and different programming languages occasionally calculate time slightly differently. SQLAlchemy allows you to do this by passing  or  (they are aliases of each other) which tells the DB to calculate the timestamp itself.Additionally, for a default where you're already telling the DB to calculate the value, it's generally better to use  instead of . This tells SQLAlchemy to pass the default value as part of the  statement.For example, if you write an ad hoc script against this table, using  means you won't need to worry about manually adding a timestamp call to your script--the database will set it automatically.SQLAlchemy also supports  so that anytime the row is updated it inserts a new timestamp. Again, best to tell the DB to calculate the timestamp itself: There is a  parameter, but unlike , it doesn't actually set anything serverside. It just tells SQLalchemy that your database will change the column when an update happens (perhaps you created a  ), so SQLAlchemy will ask for the return value so it can update the corresponding object. You might be surprised to notice that if you make a bunch of changes within a single transaction, they all have the same timestamp. That's because the SQL standard specifies that  returns values based on the start of the transaction. PostgreSQL provides the non-SQL-standard  and  which  change within a transaction. Docs here: You can also use sqlalchemy builtin function for default DateTimeThe  keyword parameter should be given to the Column object.Example:The default value can be a callable, which here I defined like the following.[enter link description here][1]You likely want to use  so that UPDATEs also change the  field.[1]: SQLAlchemy has two defaults for python executed functions.
Python

I am trying to learn how an application works. And for this I am inserting debug commands as the first line of each function's body with the goal of logging the function's name as well as the line number (within the code) where I send a message to the log output. Finally, since this application comprises of many files, I want to create a single log file so that I can better understand the control flow of the application.Here is what I know:I would greatly appreciate any help.Thanks!You have a few marginally related questions here.I'll start with the easiest: (3). Using  you can aggregate all calls to a single log file or other output target: they will be in the order they occurred in the process.Next up: (2).  provides a dict of the current scope. Thus, in a method that has no other arguments, you have  in scope, which contains a reference to the current instance. The trick being used that is stumping you is the string formatting using a dict as the RHS of the  operator.  will be replaced by whatever the value of  is.Finally, you can use some introspection tricks, similar to those used by  that can log more info:This will log the message passed in, plus the (original) function name, the filename in which the definition appears, and the line in that file. Have a look at  for more details.As I mentioned in my comment earlier, you can also drop into a  interactive debugging prompt at any time by inserting the line  in, and re-running your program. This enables you to step through the code, inspecting data as you choose.The correct answer for this is to use the already provided  variable Then anywhere you want, just add:Example output from a script I'm working on right now:
Python

Is Python slower than Java/C#?Here is a project that optimizes CPython:  Don't conflate Language and Run-Time.Python (the language) has many run-time implementations.Note that Python (the language) is not slow.  Some Python run-times (CPython, for example) will be slower than native-code C++.It is not really correct to ask why Python is slower than Java/C#. How fast is Java? Well, naive interpreters are around ten times slower than optimised compilers. I believe there is a Java bytcode interpreter written in JavaScript - that probably isn't very fast. So, the intended question appears to be \"Why is the CPython language system slower than the equivalent Sun, IBM and Oracle JRE and Microsoft .NET runtime?\"I believe the correct answer is non-technical. The fastest Java and .NET runtime are faster because they have large full time technical teams developing them in performance-competitive environment.Dynamic language systems are easy to implement. Any idiot can do it. I have. Static language systems are more complex to design and implement. A simple static system will tend to run much faster than the equivalent just-working dynamic equivalent. However, it is possible for highly optimised dynamic systems to run almost as fast. I understand some Smalltalk implementation were quite good. An often quoted example of a developed dynamic system is the .In addition if the real grunt is being done by library code, then the language system may not matter. Alternatively, the language may encourage (or give time(!)) to develop more efficient algorithms which can easily wipe out constant factor performance differences.As mentioned in the other answers this depends on the run-time system as well as the task at hand. So the standard (C)Python is not necessarily slower than Java or C#. Some of its modules are implemented in C. Thus combining speed of a  implementation with Python's language.We did a small experiment: We compared the execution time of a Factorial computation in different languages. The test was actually intended to evaluate the performance of arbitrary-precision integers implementations.The bar chart shows the results. Python is the clear winner. As far as I know Python uses the  to multiply large integers, which explains the speed.Besides, Python's \"arbitrary-precision integers\"-type is the built-in . Hence you don't even need special type handling which is required for Java's BigInteger-class.As suggested in comments, you should really provide a test case to reason about. Reasons behind performance differences will change depending on the test being executed.However, I'd suggest that the static vs dynamic nature may well have a lot to do with it. For non-virtual calls, the JIT-compiled C#/Java is extremely cheap as it can be determined accurately at JIT-time. Even virtual calls just involve a single level of redirection. When binding becomes dynamic, there's a wider range of things to consider.I don't know enough details about Python to claim to understand its exact runtime behaviour, which I suspect may vary with version and implementation too. There is such a thing as \"python byte code\" which is then executed by a virtual machine - whether this virtual machine actually performs JIT-compilation or not is another matter.It boils down to the fact that the compilation phase has lesser information to work with and hence the runtime needs to do more work in case of duck typed (dynamically typed) languages. Thus if I am making the method invocation foo.bar(), in case of Java or C++ the invocation to bar can be optimized in the compilation process by discovering the type of \"foo\" and then directly invoking the method at the memory location where the compiler knows it will be found. Since a python or any other dynamically typed language compiler does not know what type the object foo belongs to, it has to do a type check at runtime and then look up the address of the bar method and then invoke it. There are other difficulties a python compiler writer struggles with as well, though the one above hopefully adequately gives an indication. So even with the best compiler writers, statically typed languages are likely to perform much better at runtime.Where dynamically typed languages score are typically in the development time. Due to fewer lines of code to write and maintain, and no compile wait times for developers, the development often goes through much faster.Simply - . No matter what interpreter (currently available) you use, it is slower than Java and C. In various benchmarks, its slower than Ruby and PHP.\nDo not depend on other's answers, check and verify yourself. Personally I do not think, there is much serious contribution and development done on getting python faster. Since the productivity is good in python and it solves some of problem straight forward, speed/performance is not taken seriously. There are some architecture issues too preventing Python getting performance tweaks. - This answer probably will hurt Python lovers. I too am Python developer, loves developing webapps in Django/Flask/Pyramid rather than Spring (Java). But I see practically in my work and experience, how Python is slower. The speed is not always my priority. But I do stand with them, who says Python Interpreter should get oiling and greasing or total engine change to at least stand in marathon. It's a mainstream programming language.What you got there is clear example of writing Java in Python:A bit more pythonic:I think it's ultimately that Python doesn't go as far as it can with optimizations.  Most of the optimization techniques that are common are for static languages.  There  optimization techniques for dynamic languages, but the modern ones don't seem to make as much use of them as they could.  Steve Yegge has an excellent .:  I just wanted to point out that I'm not necessarily stating this to be critical of Python.  I prefer simplicity over unnecessary speed any day. It doesn't have anything to do with the languages themselves, it's just the fact that java  and  (JVM) are very high quality, and that lots of resources have been invested in stability, scalability and performance improvements over the years.Contrast that to the fact that CPython implementation just recently implemented eg threaded dispatch in its interpreter which gave it performance boost of up to 20% for certain problems. It's not a good thing as it sounds, it is bad because that kind of basic optimization should be there from the day one.This type of question can't be answered just by qualitative reasoning, you need good benchmarks to back it up.  Here's one set that compare  and find Python to be 3 to 300 times slower.  The Python vs. Java results are similar.  (The usual cautions about interpreting benchmarks apply.)These benchmarks also report the source code size, and Python was significantly more concise than Java and C#.I think opposite. I can do simple program in Python faster than in Java,\nand those Python scripts work really fast.Of course your question without examples is hard to answer. Maybe you have found slow library, bug etc. Give us more details please.I would argue that the ease and simplicity of writing Python code makes it possible to write more complex code; for example, code that takes advantage of multi-core processors.  Since per-core performance has been mostly stagnant for the past 5-10 years, I don't think it's clear that Python programs (whether they're running on CPython or something else) are slower in the long run.Since it's interpreted and not compiled.. it should be slower in execution time. As a table mentioned in  book, page 600, C# equals C++ in  (1:1). And Python is slower above hundred times than C++ in  (>100:1).And Java is slower than C++ by one time and a half (1.5:1). These statistics are on average. I don't know who made this study, but seems interesting.   
Python

I have two lists of objects. Each list is already sorted by a property of the object that is of the datetime type. I would like to combine the two lists into one sorted list. Is the best way just to do a sort or is there a smarter way to do this in Python?People seem to be over complicating this.. Just combine the two lists, then sort them:..or shorter (and without modifying ):..easy! Plus, it's using only two built-in functions, so assuming the lists are of a reasonable size, it should be quicker than implementing the sorting/merging in a loop. More importantly, the above is much less code, and very readable.If your lists are large (over a few hundred thousand, I would guess), it may be quicker to use an alternative/custom sorting method, but there are likely other optimisations to be made first (e.g not storing millions of  objects)Using the  (which repeats the functions 1000000 times), I loosely benchmarked it against  solution, and  is substantially quicker: took.. took..This hasn't been mentioned, so I'll go ahead - there is a  in the heapq module of python 2.6+. If all you're looking to do is getting things done, this might be a better idea. Of course, if you want to implement your own, the merge of merge-sort is the way to go.Here's the documentation Long story short, unless  use:Description of the figure and source code can be found . The figure was generated by the following command:This is simply merging. Treat each list as if it were a stack, and continuously pop the smaller of the two stack heads, adding the item to the result list, until one of the stacks is empty. Then add all remaining items to the resulting list.There is a slight flaw in  solution, making it O(n**2), rather than O(n).\nThe problem is that this is performing:With linked lists or deques this would be an O(1) operation, so wouldn't affect complexity, but since python lists are implemented as vectors, this copies the rest of the elements of l1 one space left, an O(n) operation.  Since this is done each pass through the list, it turns an O(n) algorithm into an O(n**2) one.  This can be corrected by using a method that doesn't alter the source lists, but just keeps track of the current position.I've tried out benchmarking a corrected algorithm vs a simple sorted(l1+l2) as suggested by I've tested these with lists generated withFor various sizes of list, I get the following timings (repeating 100 times):So in fact, it looks like dbr is right, just using sorted() is preferable unless you're expecting very large lists, though it does have worse algorithmic complexity.  The break even point being at around a million items in each source list (2 million total).One advantage of the merge approach though is that it is trivial to rewrite as a generator, which will use substantially less memory (no need for an intermediate list).\nI've retried this with a situation closer to the question - using a list of objects containing a field \"\" which is a datetime object.\nThe above algorithm was changed to compare against  instead, and the sort method was changed to:This does change things a bit.  The comparison being more expensive means that the number we perform becomes more important, relative to the constant-time speed of the implementation.  This means merge makes up lost ground, surpassing the sort() method at 100,000 items instead.  Comparing based on an even more complex object (large strings or lists for instance) would likely shift this balance even more.[1]: Note: I actually only did 10 repeats for 1,000,000 items and scaled up accordingly as it was pretty slow.The output:I bet this is faster than any of the fancy pure-Python merge algorithms, even for large data. Python 2.6's  is a whole another story.This is simple merging of two sorted lists. Take a look at the sample code below which merges two sorted lists of integers.This should work fine with datetime objects. Hope this helps.Python's sort implementation \"timsort\" is specifically optimized for lists that contain ordered sections.  Plus, it's written in C.  \nAs people have mentioned, it may call the comparison function more times by some constant factor (but maybe call it more times in a shorter period in many cases!).I believe the Python developers are committed to keeping timsort, or at least keeping a sort that's O(n) in this case.Right, sorting in the general case can't be faster than that.  But since O() is an upper bound, timsort being O(n log n) on arbitrary input doesn't contradict its being O(n) given sorted(L1) + sorted(L2).Use the 'merge' step of merge sort, it runs in O(n) time.From  (pseudo-code):Recursive implementation is below. Average performance is O(n).or generator with improved space complexity:If you want to do it in a manner more consistent with learning what goes on in the iteration try thisHave used merge step of the merge sort. But I have used .   Well, the naive approach (combine 2 lists into large one and sort) will be O(N*log(N)) complexity. On the other hand, if you implement the merge manually (i do not know about any ready code in python libs for this, but i'm no expert) the complexity will be O(N), which is clearly faster.\nThe idea is described wery well in post by Barry Kelly.Will sort the list in place. Define your own function for comparing two objects, and pass that function into the built in sort function.Do NOT use bubble sort, it has horrible performance.
Python

I've got a set of models that look like this:and an admin.py that looks like this:My goal is to get an admin interface that lets me edit everything on one page. The end result of this model structure is that things are generated into a view+template that looks more or less like:I know that the inline-in-an-inline trick fails in the Django admin, as I expected. Does anyone know of a way to allow this kind of three level model editing? Thanks in advance.You need to create a custom  and  for the .Something like this should work for the form:(That just came off the top of my head and isn't tested, but it should get you going in the right direction.)Your template just needs to render the form and form.link_formset appropriately.  is built for just this. Usage is simple.My recommendation would actually be to change your model.  Why not have a  in  to ?  Or, if it's not OneToMany, perhaps a  field?  The admin interface will generate that for free.  Of course, I don't recommend this if links don't logically have anything to do with link sections, but maybe they do?  If they don't, please explain what the intended organization is.  (For example, is 3 links per section fixed or arbitrary?)You can create a new class, similar to TabularInline or StackedInline, that is able to use inline fields itself.Alternatively, you can create new admin templates, specifically for your model. But that of course overrules the nifty features of the admin interface.
Python

The other day I came across a Python implementation called Jython.\nWith Jython you can write Java applications with Python and compile them to pure Java.  I was wondering: Android programming is done with Java.\nSo, is it possible to make Android apps with Jython?  Jython doesn't compile to \"pure java\", it compiles to  - ie, to  files. To develop for Android, one further compiles java bytecode to Dalvik bytecode. This means that, yes, Jython  let you use Python for developing Android, subject to you getting it to play nice with the Android SDK (I haven't personally tried this, so I don't know how hard it actually is) - you  need to make sure you don't depend on any Java APIs that Android doesn't provide, and  need to have some of the Android API  files around when you run jython. Aside from these niggles, your core idea should work - Jython does, indeed, let write code in Python that interacts with anything else that runs on the JVM.As long as it compiles to pure java (with some constraints, as some APIs are not available), but I doubt that python will be of much use in  development of android-specific stuff like activities and  UI manipulation code. You also have to take care of application size - that is serious constraint for mobile developement.Yes and no.  With jython you can use java classes to compile for the JVM. But Android use the DVM (Dalvik Virtual Machine) and the compiled code is different.  You have to use tools to convert from JVM code to DVM. brings scripting languages to Android by allowing you to edit and execute scripts and interactive interpreters directly on the Android device.It is possible jython compiles python to java bytecode(THIS IS DONE WITH JSE) then this java bytecode can be treated normally and converted to DVM operable code(.dex) with other xml files it is then packaged into an apk.\nThe process will be as follows-This will use JYTHON and android COMPILER(.apk)I am working on this projectIt's not possible. You can't use jython with android because the DVM doesn't understand it. DVM is not JVM.sadly No.Mobile phones only have Java ME (Micro Edition) but Jython requires Java SE (Standard Edition). There is no Jython port to ME, and there is not enough interest to make it worth the effort.
Python

I am interested in getting an install of Django running on IronPython, has anyone had any success getting this running with some level of success?  If so can you please tell of your experiences, performance, suggest some tips, resources and gotchas?Besides the Jeff Hardy blog post on  mentioned by Tony Meyer, it might be useful to also read Jeff's two other posts in the same series on his struggles with IronPython, easy_install and zlib. The first is  which discusses the absence of zlib for IronPython; hence, no easyinstall. Jeff reimplemented zlib based on ComponentAce's zlib.net. And finally, in  Jeff discusses some final tweaks that are needed before easy_install can be used with IronPython.This was  at last year's PyCon (the  are also available).  More recently, , including suggestions.I don't think Django is yet working on IronPython, but I'm not saying it cannot be done. project is a work currently underway to run Django on IronPython. The project has reported  with sqlite on 2nd of May 2010.  
Python

Why does ?Is this inconsistent with recommending spaces around every other occurrence of  in Python code?How is:better than:Any links to discussion/explanation by Python's  will be appreciated.Mind, this question is more about kwargs than default values, i just used the phrasing from PEP 8.I'm not soliciting opinions. I'm asking for reasons behind this decision. It's more like asking  would I use  on the same line as  statement in a C program, not  I should use it or not.I guess that it is because a keyword parameter is essentially different than a variable assignment.For example, there is plenty of code like this:As you see, it makes completely sense to assign a variable to a keyword argument named exactly the same, so it improves readability to see them without spaces. It is easier to recognize that we are using keyword arguments and not assigning a variable to itself.Also, parameters tend to go in the same line whereas assignments usually are each one in their own line, so saving space is likely to be an important matter there.I wouldn't use very_long_variable_name as a default argument. So consider this:over this:Also, it doesn't make much sense to use variables as default values. Perhaps some constant variables (which aren't really constants) and in that case I would use names that are all caps, descriptive yet short as possible. So no another_very_...IMO leaving out the spaces for args provides cleaner visual grouping of the arg/value pairs; it looks less cluttered.There are pros and cons.I very much dislike how PEP8 compliant code reads. I don't buy into the argument that  can ever be more human readable than\n.\nThis is not how people read. It's an additional cognitive load, particularly in the absence of syntax highlighting.There is a significant benefit, however. If the spacing rules are adhered to, it makes searching for parameters exclusively  much more effective.I think there are several reasons for this, although I might just be rationalizing:
Python

How can I use win32 API in Python?\nWhat is the best and easiest way to do it?\nCan you please provide some examples?PyWin32 is the way to go - but how to use it? One approach is to begin with a concrete problem you're having and attempting to solve it. PyWin32 provides bindings for the Win32 API functions for which there are many, and you really have to pick a specific goal first.In my Python 2.5 installation (ActiveState on Windows) the win32 package has a Demos folder packed with sample code of various parts of the library. For example, here's CopyFileEx.py:It shows how to use the CopyFileEx function with a few others (such as GetTempPath and GetTempFileName). From this example you can get a \"general feel\" of how to work with this library. PyWin32, as mentioned by @chaos, is probably the most popular choice; the alternative is  which is part of Python's standard library. For example,  will show the module-handle of the current module (EXE or DLL). A more extensive example of using ctypes to get at win32 APIs is .The important functions that you can to use in win32 Python are the message boxes, this is classical example of OK or Cancel.The collection: 
Python

Why does the  function call wipe out the dupes, but parsing a set literal does not?(Python 2.7.12.  Possibly same root cause as for  similar question)Sets test for equality, and until there are new Python releases, the order in which they do this can differ based on the form you hand the values to the set being constructed, as I'll show below.Since  is true   is true, but  is , the behaviour here is really , as the set assumes that  must be true if the first two tests were true too.If you  the list passed to , then you get the same output as using a literal, because the order of equality tests changes:and the same for reversing the literal:What's happening is that the set  loads the values onto the stack and then the stack values are added to the new set object in reverse order.As long as  is loaded , the other two objects are then tested against  already in the set. The moment one of the other two objects is loaded first, the equality test fails and you get two objects added:That set literals add elements in reverse is a bug present in all versions of Python that support the syntax, all the way until Python 2.7.12 and 3.5.2. It was recently fixed, see  (part of 2.7.13, 3.5.3 and 3.6, none of which have been released yet). If you look at 2.7.12, you can see that  reads the stack from the top down:while the bytecode adds elements to the stack in reverse order (pushing  on the stack first):The fix is to read the elements from the stack in reverse order; the  uses  instead of  (and a  to remove the elements from the stack afterwards):The equality testing issue has the same root cause as the other question; the  class is having some equality issues with  here, which was fixed in Python 3.2 (by making ).It's all down to the order in which the set is constructed, combined with the bug you discovered with .  It appears that the literal is constructed in the opposite order to conversion from a list.
Python

So I'm starting like Python a bit, but I'm having trouble erm...running it. LolI'm using IDLE for now, but its no use whatsoever because you can only run a couple of lines at a time.I'm also using Komodo Edit to create the actual .py files.My question is, how can I run the .py files to test out the actual program? I'm using Windows 7, and Komodo Edit 5 as my IDE. Pressing F5 in Komodo doesn't do anythin at all.I'm very glad you asked! I was just working on explaining this very thing  (which is obviously incomplete).  We're working with Python novices, and had to help a few through exactly what you're asking!   If you get this message:  then  (the  program that can translate Python into 'computer instructions') isn't on your path (see Putting Python in Your Path below).  Then try calling it like this (assuming Python2.6, installed in the usual location):> C:\\Python26\\python.exe first.py(Advanced users:  instead of first.py, you could write out first.py's full path of C:\\Documents and Settings\\Gregg\\Desktop\\pyscripts\\first.py)In order to run programs, your operating system looks in various places,\nand tries to match the name of the program / command you typed with some \nprograms along the way.  In windows:control panel > system >  advanced > |Environmental Variables| > system variables -> Paththis needs to include:  C:\\Python26; (or equivalent).  If you put it at the front,\nit will be the first place looked.  You can also add it at the end, which is possibly saner.Then restart your prompt, and try typing 'python'.  If it all worked, you should\nget a \">>>\" prompt.You can just callIn IDLE press F5You can open your .py file with IDLE and press F5 to run it. You can open that same file with other editor ( like Komodo as you said ) save it and press F5 again; F5 works with IDLE ( even when the editing is done with another tool ).If you want to run it directly from Komodo according to this article:  you have to:Python itself comes with an editor that you can access from the IDLE File > New File menu option.Write the code in that file, save it as [filename].py and then (in that same file editor window) press F5 to execute the code you created in the IDLE Shell window.Note: it's just been the easiest and most straightforward way for me so far.if you dont want call  you can add  to the PATHEXT, that way you will just call If this helps anyone, neither \"python [filename].py\" or \"python.exe [filename.py]\" worked for me, but \"start python [filename].py\" did. If anyone else is experiencing issues with the former two commands, try the latter one.
Python

Suppose I have pandas DataFrame like this:I want to get new DataFrame with top 2 records for each id, like this:I can do it with numbering records within group after group by:But is there more effective/elegant approach to do this? And also is there more elegant approach to number records within each group (like SQL window function ).Thanks in advance.Did you try Ouput generated: (Keep in mind that you might need to order/sort before, depending on your data)EDIT: As mentioned by the questioner, use  to remove the multindex and flatten the results., you can now do  and  on a  object:There's a slight weirdness that you get the original index in there as well, but this might be really useful depending on what your original index .If you're not interested in it, you can do  to get rid of it altogether.(Note:  you'll be able to do this on a DataFrameGroupBy too but for now it only works with  and .)
Python

I'd like a function, , which behaves like the following:How can I implement this function?I looked at the  attribute but it appears to be used for something else.If I know the first value that needs to be sent into the generator, I can do something like this:However, this seems abhorrent. This only works in Python 3.2+:So, the requested function is:Out of curiosity, I looked into CPython to figure out how it was determining this...  Apparently it looks at  which is the \"index of last attempted instruction in bytecode\".  If it's  then it hasn't started yet.Here's a py2 version:Make a new generator which simply yields from your generator of interest.  .  Afterwards, it can simply use  for the rest of the items.  Use the substitute generator as a drop in replacement for the generator you're interested in monitoring the \"is_just_started\" state.  This technique is non-intrusive, and can be used even on generators for which you have no control over the source code.  You may create a iterator and set the flag as the instance property to iterator class as:And your value check function would be like:Sample run:To know the difference between  and , check 
Python

Consider..I'd like to replace all dict keys with their respective dict values in .Using re:This will match whole words only. If you don't need that, use the pattern:Note that in this case you should sort the words descending by length if some of your dictionary entries are substrings of others.You could use the  function:Solution  (I like its simplicity):one way, without reAlmost the same as ghostdog74, though independently created. One difference,\nusing d.get() in stead of d[] can handle items not in the dict.I used this in a similar situation (my string was all in uppercase):hope that helps in some way... :)
Python

Using  on Windows 8 with Python 2.7 gives me the error: How can the error be resolved? Running  gives the same error...You could use ol' good  instead. isn't pip but one good aspect of it is the ability to download and install binary packages too, which would free you for the need having VC++ ready. This of course relies of the assumption that the binaries were prepared for your Python version.UPDATE:Yes, Pip can install binaries now!There's a new binary Python archive format () that is supposed to replace \"eggs\". Wheels are already supported by . This means you'll be able to install  with  without compiling it as soon as someone builds the wheel for your platform and uploads it to PyPI.The problem here is the line 292 (Using Python 3.4.3 here) in   which says:This only checks for the MSVC version that your python was built with. Just replacing this line with your actual Visual Studio version, eg.  for will fix the issue.UPDATE: Turns out that there is a good reason why this version is hardcoded. MSVC C runtime is not required to be compatible between major versions. Hence when you use a different VS version you might run into runtime problems. So I advise to use VS 2008 (for Python 2.6 up to 3.2) and VS2010 for (Python 3.3 and later) until this issue is sorted out.Binary compatibility will arrive with VS 2015 () along with Python 3.5 .For Python 2.7 users Microsoft released a special  which can be used without installing the whole VS 2008.If you are getting this error on Python 2.7 you can now get the  as a stand alone download.If you are on 3.3 or later you need to install Visual Studio 2010 express which is available for free here: If you are 3.3 or later and using a 64 bit version of python you need to install the Microsoft SDK 7.1 that ships a 64 bit compiler and follow the directions here First you should look for the file vcvarsall.bat in your system.If it does not exits I recommend you to install . This will create the vcvarsall.bat in \"C:\\Program Files (x86)\\Common Files\\Microsoft\\Visual C++ for Python\\9.0\" if you install it for all users.The problem now is that a function  in the  module is the one looking for vcvarsall.bat. If you follow the function calls you will see is looking in the registry for the directory of the vcvarsall.bat file and it won't never find it because the function is looking in other directories different from where the above mentioned installation placed it, and in my case the registry didn't exits.The easiest way to solve this problem is to remove the body (or just place in the first line) of the function   in the  file with the absolute path to vcvarsall.bat. For example:This solution worked for me.If you already have the vcvarsall.bat file you should check if you have the key  in the registry:Where If you don't have the key just do:To understand the exact behavior check  module starting in the  function.Simply because you don't have c++ compiler installed there in your machine, check the following : 0.9 in the registery directory is the currently installed version of your visual studio, if you running VS 2013, you have to find the path HKEY_LOCAL_MACHINE\\Software\\Wow6432Node\\Microsoft\\VisualStudio\\12.0....You need to have Visual Studio's bin dir in your path. Pip install is trying to compile some C code. I spent hours researching this vcvarsall.bat as well. Most answers on SO focus on Python 2.7 and / or creating workarounds by modifying system paths. None worked for me. This solution worked out of the box for Python 3.5 and (I think) is the \"correct\" way of doing it.Hope this saves someone some time!Thanks to \"msoliman\" for his hint, however his answer doesn't give clear solution for those who doesn't have VS2010\nFor example I have VS2012 and VS2013 and there are no such KEYs in system registry. Solution: \nEdit file: \"/Lib/distutils/msvc9compiler.py\"\nChange on line 224:to:and that should workIf you are trying to install matplotlib in order to work with graphs on python. Try this link.\n.\nThis is a set of scripts to build matplotlib from source on the MS Windows platform.To build & install matplotlib in your Python, do:The build script will auto-detect Python version & 32/64 bit automatically.I appreciate this might not be the answer to resolving on 3.4 but I tried a huge variety of things to fix this on 3.4 and thought this might be useful if someone is time pressed or doesn't have the know-how to correct it (in my case, work demands).With exactly the same setup, I found that my installation problems only happened with Python 3.4.  When I changed to 2.7, all my issues seemed to be resolved.  We have a rather overzealous security setup though so I'm going to try the same on my home version (still 3.4) and see if I have any more joy.  My inclination is that my VS version has somehow been restricted and the answers above should help.  If I find anything more tonight I'll add further detail.This is my first reply, not the most technical I'm afraid!
Python

I have a Django app that requires a  attribute in the form of:Then hooks their post_save signal to update some other fixed model depending on the  defined.I would like to test this behaviour and tests should work even if this app is the only one in the project (except for its own dependencies, no other wrapper app need to be installed). How can I create and attach/register/activate mock models just for the test database? (or is it possible at all?)Solutions that allow me to use test fixtures would be great.You can put your tests in a  subdirectory of the app (rather than a  file), and include a  with the test-only models.Then provide a test-running script () that includes your  \"app\" in . (This doesn't work when running app tests from a real project, which won't have the tests app in , but I rarely find it useful to run reusable app tests from a project, and Django 1.6+ doesn't by default.)(: The alternative dynamic method described below only works in Django 1.1+ if your test case subclasses  - which slows down your tests significantly - and no longer works at all in Django 1.7+. It's left here only for historical interest; don't use it.)At the beginning of your tests (i.e. in a setUp method, or at the beginning of a set of doctests), you can dynamically add  to the INSTALLED_APPS setting, and then do this:Then at the end of your tests, you should clean up by restoring the old version of INSTALLED_APPS and clearing the app cache again. encapsulates the pattern so it doesn't clutter up your test code quite as much.@paluh's answer requires adding unwanted code to a non-test file and in my experience, @carl's solution does not work with django.test.TestCase which is needed to use fixtures.  If you want to use django.test.TestCase, you need to make sure you call syncdb before the fixtures get loaded.  This requires overriding the _pre_setup method (putting the code in the setUp method is not sufficient).  I use my own version of TestCase that let's me add apps with test models.  It is defined as follows:This solution works only for earlier versions of  (before ). You can check your version easily:Original response:It's quite strange but form me works very simple pattern:Below I've put some code which defines Article model which is needed only for tests (it exists in someapp/tests.py and I can test it just with:  ):Unit tests also working with such model definition.I chose a slightly different, albeit more coupled, approach to dynamically creating models just for testing. I keep all my tests in a  subdirectory that lives in my  app. The  file in the  subdirectory contains my test-only models. The coupled part comes in here, where I need to add the following to my  file:I also set db_table in my test model, because otherwise Django would have created the table with the name , which may have caused a conflict with other test models in another app. Here's my my test model:Quoting from :I've figured out a way for test-only models for django 1.7+.The basic idea is, make your  an app, and add your  to .Here's an example:And I have different  for different purposes(ref: ), namely:And in , you can modify ::And make sure that you have set a proper label for your tests app, namely, , set up proper (ref: ).Then, generate db migration byFinally, you can run your test with param . If you use py.test, you can even drop a  file along with django's .I shared my  that I use in my projects. Maybe it helps someone.Two simple steps to create fake model:1) Define model in any file (I usualy define model in test file near a test case)2) Add decorator  to your  or to test function.This decorator creates table in your database before each test and remove the table after test.Also you may / table manually:  / Here's the pattern that I'm using to do this. I've written this method that I use on a subclassed version of TestCase.  It goes as follows:Then, I create a special test-specific models.py file in something like  that's not included in INSTALLED_APPS. In my setUp method, I call create_models_from_app('myapp.tests') and it creates the proper tables.The only \"gotcha\" with this approach is that you don't really want to create the models ever time  runs, which is why I catch DatabaseError.  I guess the call to this method could go at the top of the test file and that would work a little better. Combining your answers, specially @slacy's, I did this:With this, you don't try to create db tables more than once, and you don't need to change your INSTALLED_APPS.If you are writing a reusable django-app, !add both  and  to the , create your models there and it's good to go!I have gone through all these answers as well as django ticket , and I finally went for a totally different approach. \nI wanted my app (somehow extending queryset.values() ) to be able to be tested in isolation; also, my package does include some models and I wanted a clean distinction between test models and package ones.That's when I realized it was easier to add a very small django project in the package!\nThis also allows a much cleaner separation of code IMHO:In there you can cleanly and without any hack define your models, and you know they will be created when you run your tests from in there!If you are not writing an independent, reusable app you can still go this way: create a  app, and add it to your INSTALLED_APPS only in a separate !
Python

I just installed a linux system (Kubuntu) and was wondering if there is a program to make python programs executable for linux.Just put this in the first line of your script :Make the file executable withExecute withIf you want to obtain a stand-alone binary application in Python try to use a tool like py2exe or .You can use PyInstaller. It generates a build dist so you can execute it as a single \"binary\" file.Python 3 has the native option of create a build dist also:Putting these lines at the starting of the code will tell your operating systems to look up the binary program needed for the execution of the python script i.e it is the python interpreter.So it depends on your operating system where it keeps the python interpreter. As I have Ubuntu as operating system it keeps the python interpreter in  so I have to write this line at the starting of my python script;After completing and saving your codeAnother way to do it could be by creating an alias.\nFor example in terminal write:Writing  will run hello_world.py, but this is only temporary.\nTo make aliases permanent, you have to add them to bashrc, you can edit it by writing this in the terminal:On the top of your code first write: or \nThen create a new  file called  and write:Therefore removing the issue of not having python and installing any missing packages. To make a desktop shortcut do this:Please, note that if your code isn't made to create a GUI you will have to run your code from terminal with 
Python

Is it possible to have overloaded functions in Python? In C# I would do something likeand then when I call the function it would differentiate between the two based on the number of arguments. Is it possible to do something similar in Python?  For the new single dispatch generic functions in Python 3.4, see You generally don't need to overload functions in Python. Python is , and supports optional arguments to functions.in normal python you can't do what you want.  there are two close approximations:however, if you  want to do this, you can certainly make it work (at the risk of offending the traditionalists ;o).  in short, you would write a  function that checks the number of arguments and delegates as appropriate.  this kind of \"hack\" is usually done via decorators.  in this case you could achieve something like:and you'd implement this by making the   (or constructor) return a callable object where the   does the delegation explained above and the   adds extra functions that can be delegated to.you can see an example of something similar here  but that is overloading methods by type.  it's a very similar approach...UPDATE: and something similar (using argument types) is being added to python 3 - Yes, it's possible. I wrote code below in Python 3.2.1:Usage:Note that the lambda returned by the  functions choose function to call depending on number of  arguments.The solution isn't perfect, but at the moment I can't write anything better.Not possible directly. You can use explicit type checks on the arguments given though, although this is generally frowned upon.Python is dynamic. If you are unsure what an object can do, just try: and call a method on it, then except: errors.If you don't need to overload based on types but just on number of arguments, use keyword arguments.overloading methods is tricky in python. However, there could be usage of passing the dict, list or primitive variables.I have tried something for my use cases, this could help here to understand people to overload the methods.Let's take the example use in one of the stackoverflow thread:a class overload method with call the methods from different class.pass the arguments from remote class:OR  So, handling is being achieved for list, Dictionary or primitive variables from method overloading.try it out for your codes
Python

I have a non-negative int and I would like to efficiently convert it to a big-endian string containing the same data.  For example, the int 1245427 (which is 0x1300F3) should result in a string of length 3 containing three characters whose byte values are 0x13, 0x00, and 0xf3.My ints are on the scale of 35 (base-10) digits.How do I do this? You can use the  module: is a format string.  means big endian and  means unsigned int. Check the documentation for more format chars.In Python 3.2+, you can use :This is fast and works for small and (arbitrary) large ints:Probably the best way is via the built-in :Alternatively -- and I wouldn't usually recommend this, because it's mistake-prone -- you can do it \"manually\" by shifting and the  function:Out of curiosity, why do you only want three bytes? Usually you'd pack such an integer into a full 32 bits (a C ), and use  but skip the  step?Single-source Python 2/3 compatible version based on :Using the  module:Note though that for this method you need to specify the length in bits of the bitstring you are creating.Internally this is pretty much the same as Alex's answer, but the module has a lot of extra functionality available if you want to do more with your data.The shortest way, I think, is the following:This converts an integer to a byte-swapped integer.
Python

Python has a built in function , which is effectively equivalent to:for all types of parameters except strings. It works for numbers and lists, for example:Why were strings specially left out?I seem to remember discussions in the Python list for the reason, so an explanation or a link to a thread explaining it would be fine.: I am aware that the standard way is to do . My question is why the option of using sum for strings was banned, and no banning was there for, say, lists.: Although I believe this is not needed given all the good answers I got, the question is: Python tries to discourage you from \"summing\" strings. You're supposed to join them:It's a lot faster, and uses much less memory.A quick benchmark:Edit (to answer OP's edit): As to why strings were apparently \"singled out\", I believe it's simply a matter of optimizing for a common case, as well as of enforcing best practice: you can join strings much faster with ''.join, so explicitly forbidding strings on  will point this out to newbies.BTW, this restriction has been in place \"forever\", i.e., since the  was added as a built-in function ()You can in fact use  to concatenate strings, if you use the appropriate starting object! Of course, if you go this far you have already understood enough to use  anyway..From :By making  refuse to operate on strings, Python has encouraged you to use the correct method.Here's the source: In the builtin_sum function we have this bit of code:So.. that's your answer.It's explicitly checked in the code and rejected.Short answer: Efficiency.Long answer: The  function has to create an object for each partial sum.Assume that the amount of time required to create an object is directly proportional to the size of its data.  Let N denote the number of elements in the sequence to sum.s are always the same size, which makes 's running time O(1)\u00d7N = . (formerly known as ) is arbitary-length.  Let M denote the absolute value of the largest sequence element.  Then 's worst-case running time is lg(M) + lg(2M) + lg(3M) + ... + lg(NM) = N\u00d7lg(M) + lg(N!) = .For  (where M = the length of the longest string), the worst-case running time is M + 2M + 3M + ... + NM = M\u00d7(1 + 2 + ... + N) = .Thus, ming strings would be much slower than ming numbers. does not allocate any intermediate objects.  It preallocates a buffer large enough to hold the joined strings, and copies the string data.  It runs in  time, much faster than .@dan04 has an excellent explanation for the costs of using  on large lists of strings.The missing piece as to why  is not allowed for  is that many, many people were trying to use  for strings, and not many use  for lists and tuples and other O(n**2) data structures. The trap is that  works just fine for short lists of strings, but then gets put in production where the lists can be huge, and the performance slows to a crawl. This was such a common trap that the decision was made to ignore duck-typing in this instance, and not allow strings to be used with . Moved the parts about immutability to history.Basically, its a question of preallocation. When you use a statement such as and expect it to work similar to a  statement, the code generated looks something likeIn each of these steps a new string is created, which for one might give some copying overhead as the strings are getting longer and longer. But that\u2019s maybe not the point here. What\u2019s more important, is that every new string on each line must be  to it\u2019s specific size (which. I don\u2019t know it it must allocate in every iteration of the  statement, there might be some obvious heuristics to use and Python might allocate a bit more here and there for reuse \u2013 but at several points the new string will be large enough that this won\u2019t help anymore and Python must allocate again, which is rather expensive.A dedicated method like , however has the job to figure out the real size of the string before it starts and would therefore in theory only allocate once, at the beginning and then just fill that new string, which is much cheaper than the other solution.I dont know why, but this works!
Python

Very basic question - how to get one value from a generator in Python?So far I found I can get one by writing . I just want to make sure this is the right way?Yes, or  in 2.6+.In Python <= 2.5, use . This will work for all Python 2.x versions, but not Python 3.xIn Python >= 2.6, use . This is a built in function, and is clearer. It will also work in Python 3.Both of these end up calling a specially named function, , which can be overridden by subclassing. In Python 3, however, this function has been renamed to , to be consistent with other special functions.This is the correct way to do it.You can also use .In python 3 you don't have gen.next(), but you still can use next(gen).\nA bit bizarre if you ask me but that's how it is.Use (for python 3)Here is an exampleshould print
Python

This is the raw request for an API call:This request returns a success (2xx) response.Now I am trying to post this request using :Everything looks fine to me and I am not quite sure what I posting wrong to get a 400 response. is for GET-style URL parameters,  is for POST-style body information. It is perfectly legal to provide  types of information in a request, and your request does so too, but you encoded the URL parameters into the URL already.Your raw post contains  data though, you better use the  module to properly encode that:You could split out the URL parameters too:Then post this with:If you are using  version 2.4.2 or newer, you can have the library do the JSON encoding for you; it'll set the correct Content-Header too; all you need to do is pass in the Python object to be encoded as JSON into the  keyword argument:Set data to this: Assign the response to a value and test the attributes of it. These should tell you something useful.
Python

Jinja2 and Mako are both apparently pretty fast.How do these compare to (the less featured but probably good enough for what I'm doing) string.Template ?Here are the results of the popular template engines for rendering a 10x1000 HTML table.The benchmark is based on  with some added template engines and added iterations to increase accuracy. The list and generator concat at the end are hand coded Python to get a feel for the upper limit of performance achievable by compiling to Python bytecode. The optimized versions use string interpolation in the inner loop.But before you run out to switch your template engine, make sure it matters. You'll need to be doing some pretty heavy caching and really optimized code before the differences between the compiling template engines starts to matter. For most applications good abstraction facilities, compatibility with design tools, familiarity and other things matter much much more.From the , it seems that string.Template is the fastest if that's all you need.If you can throw caching in the mix (like memcached) then choose based on features and ease of use rather than optimization.I use Mako because I like the syntax and features. Fortunately it is one of the fastest as well.In general you will have to do profiling to answer that question, as it depends on how you use the templates and what for.string.Template is the fastest, but so primitive it can hardly be called a template in the same breath as the other templating systems, as it only does string replacements, and has no conditions or loops, making it pretty useless in practice.I think Cheetah might be the fastest, as it's implemented in C.
Python

I have what I think should be a very easy task that I can't seem to solve.How do I write a Python dictionary to a csv file?  All I want is to write the dictionary keys to the top row of the file and the key values to the second line.The closest that I've come is the following (that I got from somebody else's post):The problem is, the above code seems to only be writing the keys to the first line and that's it.  I'm not getting the values written to the second line.Any ideas?You are using  which expects a list of dicts, not a dict. You want  to write a single row.You will also want to use  if you want a header for you csv file.You also might want to check out  for . It's not only more pythonic and readable but handles closing for you, even when exceptions occur.Example with these changes made:Which produces:Your code was  close to working.  Try using a regular  rather than a .  The latter is mainly used for writing a list of dictionaries.Here's some code that writes each key/value pair on a separate row:If instead you want all the keys on one row and all the values on the next, that is also easy::  When developing code like this, set the writer to  so you can more easily see what is being generated.  When the logic is perfected, switch back to .Why use csv for this simple task?I use python in two ways:My answer is only useful for the 2nd purpose. And also considers the pain to remember all these modules and their individual functions :P
Python

I would like to include image in a jupyter notebook.If I did the following, it works :But I would like to include the images in a markdown cell and the following code gives a 404 error :I also triedBut I still get the same error :You mustn't use quotation marks around the name of the image files in markdown!If you carefully read your error message, you will see the two  parts in the link. That is the html encoded quotation mark. You have to change the lineto There are several ways to post an image in Jupyter notebooks:You retain the ability to use HTML tags to resize, etc...You can also display images stored locally, either via relative or absolute path. use  to disable max-width confinement of the imageas shown by @cristianmtr\nPaying attention not to use either these quotes  or those  around the url.demonstrated by @SebastianAlternatively, you can use a plain HTML , which allows you to change height and width and is still read by the markdown interpreter:Here's how you can do it with Markdown:If you want to use the Jupyter Notebook API (and not the IPython one anymore), I find the  Jupyter's sub-project. You have an  widget. Docstring specifies that you have a  parameter which is a bytes. So you can do:I agree, it's simpler to use the Markdown style. But it shows you the Image display Notebook API. You can also resize the image with the  and  parameters.Here is a Solution for  and :I droped my images in a folder named . \nMy directory is:To show the image I used this expression:Also watch out for  and  I'm surprised no one here has mentioned the html cell magic option.\nfrom the  (IPython, but same for Jupyter)
Python

I am working on a project using Hadoop and it seems to natively incorporate Java and provide streaming support for Python. Is there is a significant performance impact to choosing one over the other?  I am early enough in the process where I can go either way if there is a significant performance difference one way or the other.Java is less dynamic than Python and more effort has been put into its VM, making it a faster language. Python is also held back by its Global Interpreter Lock, meaning it cannot push threads of a single process onto different core.Whether this makes any significant difference depends on what you intend to do. I suspect both languages will work for you.With Python you'll probably develop faster and with Java will definitely run faster.Google \"benchmarksgame\" if you want to see some very accurate speed comparisons between all popular languages, but if I recall correctly you're talking about 3-5x faster.That said, few things are processor bound these days, so if you feel like you'd develop better with Python, have at it!In reply to comment (how can java be faster than Python):All languages are processed differently.  Java is about the fastest after C & C++ (which can be as fast or up to 5x faster than java, but seems to average around 2x faster).  The rest are from 2-5+ times slower.  Python is one of the faster ones after Java.  I'm guessing that C# is about as fast as Java or maybe faster, but the benchmarksgame only had Mono (which was a tad slower) because they don't run it on windows.Most of these claims are based on the  which tends to be pretty fair because advocates of/experts in each language tweak the test written in their specific language to ensure the code is well-targeted.For example,  shows all tests with Java vs c++ and you can see the speed ranges from about equal to java being 3x slower (first column is between 1 and 3), and java uses much more memory!Now  shows java vs python (from the point of view of Python).  So the speeds range from python being 2x slower than Java to 174x slower, python generally beats java in code size and memory usage though.Another interesting point here--tests that allocated a lot of memory, Java actually performed significantly better than Python in memory size as well.  I'm pretty sure java usually loses memory because of the overhead of the VM, but once that factors out, java is probably more efficient than most (again, except the C's).This is Python 3 by the way, the other python platform tested (Just called Python) faired much worse.If you really wanted to know  it is faster, the VM is amazingly intelligent.  It compiles to machine language AFTER running the code, so it knows what the most likely code paths are and optimizes for them.  Memory allocation is an art--really useful in an OO language. It can perform some amazing run-time optimizations which no non-VM language can do.  It can run in a pretty small memory footprint when forced to, and is a language of choice for embedded devices along with C/C++.I worked on a Signal Analyzer for Agilent (think expensive o-scope) where nearly the entire thing (aside from the sampling) was done in Java.  This includes drawing the screen including the trace (AWT) and interacting with the controls.Currently I'm working on a project for all future cable boxes.  The Guide along with most other apps will be written in Java.  Why wouldn't it be faster than Python? You can write Hadoop mapreduce transformations either as \"streaming\" or as a \"custom jar\". If you use streaming, you can write your code in any language you like, including Python or C++. Your code will just read from STDIN and output to STDOUT.  However, on hadoop versions before 0.21, hadoop streaming used to only stream text - not binary - to your processes.  Therefore your files needed to be text files, unless you do some funky encoding transformations yourself. But now it appears a  has been added that now allows the use of binary formats with hadoop streaming.If you use a \"custom jar\" (i.e. you wrote your mapreduce code in Java or Scala using the hadoop libraries), then you will have access to functions that allow you to input and output binary (serialize in binary) from your streaming processes (and save the results to disk). So future runs will be much faster (depending on how much your binary format is smaller than your text format).So if your hadoop job is going to be I/O bound, then the \"custom jar\" approach will be faster (since both Java is faster as previous posters have shown and reading from disk will also be faster).But you have to ask yourself how valuable is your time. I find myself far more productive with python, and writing map-reduce that reads STDIN and writes to STDOUT is really straightforward. So I personally would recommend going the python route - even if you have to figure the binary encoding stuff out yourself. Since hadoop 0.21 handles non-utf8 byte arrays, and since there is a binary (byte array) alternative to use for python (), which shows the python code only being about 25% slower than the \"custom jar\" java code, I would definitely go the python route.
Python

The simple task of adding a row to a  object seems to be hard to accomplish. There are 3 stackoverflow questions relating to this, none of which give a working answer.Here is what I'm trying to do. I have a DataFrame of which I already know the shape as well as the names of the rows and columns.Now, I have a function to compute the values of the rows iteratively. How can I fill in one of the rows with either a dictionary or a  ? Here are various attempts that have failed:Apparently it tried to add a column instead of a row.Very uninformative error message.Apparently that is only for setting individual values in the dataframe.Well, I don't want to ignore the index, otherwise here is the result:It did align the column names with the values, but lost the row labels.That also failed miserably.So how do you do it ? will set a columnsince you want to set a row, use Note that  is equivalent here, yours failed because you tried to assign a dictionary\nto each element of the row  probably not what you want; converting to a Series tells pandas\nthat you want to align the input (for example you then don't have to to specify all of the elements)More simpler versionMy approach was, but I can't guarantee that this is the fastest solution.
Python

I'm fairly new to actual programming languages, and Python is my first one. I know my way around Linux a bit, enough to get a summer job with it (I'm still in high school), and on the job, I have a lot of free time which I'm using to learn Python.One thing's been getting me though. What exactly is different in Python when you have expressions such asI know what methods do and stuff, and I get what they do, but my question is: How are those double underscore methods above different from their simpler looking equivalents?P.S., I don't mind being lectured on programming history, in fact, I find it very useful to know :) If these are mainly historical aspects of Python, feel free to start rambling.Well, power for the programmer is good, so there should be a way to customize behaviour. Like operator overloading (, , , ...), attribute access (,  (those two are differnt), , ...) etc. In many cases, like operators, the usual syntax maps 1:1 to the respective method. In other cases, there is a special procedure which at some point involves calling the respective method - for example,  is only called if the object doesn't have the requested attribute and  is not implemented or raised AttributeError. And some of them are really advanced topics that get you deeeeep into the object system's guts and are rarely needed. So no need to learn them all, just consult the reference when you need/want to know. Speaking of reference, .Here is the creator of Python :...When you start a method with two underscores (and no trailing underscores), Python's  rules are applied. This is a way to loosely simulate the  keyword from other OO languages such as C++ and Java. (Even so, the method is still technically not private in the way that Java and C++ methods are private, but it is \"harder to get at\" from outside the instance.)Methods with two leading and two trailing underscores are considered to be \"built-in\" methods, that is, they're used by the interpreter and are generally the concrete implementations of overloaded operators or other built-in functionality.They are used to specify that the Python interpreter should use them in specific situations.E.g., the  function allows the  operator to work for custom classes. Otherwise you will get some sort of not defined error when attempting to add. From an historical perspective, leading underscores have often been used as a method for indicating to the programmer that the names are to be considered internal to the package/module/library that defines them.  In languages which do not provide good support for private namespaces, using underscores is a convention to emulate that.  In Python, when you define a method named '__foo__' the maintenance programmer knows from the name that something special is going on which is not happening with a method named 'foo'.  If Python had choosen to use 'add' as the internal method to overload '+', then you could never have a class with a method 'add' without causing much confusion.  The underscores serve as a cue that some magic will happen. A number of other questions are now marked as duplicates of this question, and at least two of them ask what either the  methods are called, or what the convention is called, and none of the existing answers cover that, so:There actually is no official name for either. Many developers unofficially call them \"dunder methods\", for \"Double UNDERscore\". Some people use the term \"magic methods\", but that's somewhat ambiguous between meaning dunder methods, special methods (see below), or something somewhere between the two.There  an official term \"special attributes\", which overlaps closely but not completely with dunder methods. The  chapter in the reference never quite explains what a special attribute is, but the basic idea is that it's at least one of the following:Most special attributes are methods, but not all (e.g.,  isn't). And most use the \"dunder\" convention, but not all (e.g., the  method on iterators in Python 2.x).And meanwhile, most dunder methods are special attributes, but not all\u2014in particular, it's not that uncommon for stdlib or external libraries to want to define their own protocols that work the same way, like the  protocol. Python was influenced by ,  possibly used Algol68 at the  where Algol68 has a similar \"\" called \"Quote stropping\". In Algol68 the   appear in a different typeface (usually ****, or __), in sourcecode files this typeface is achieved with quotes, e.g. 'abs' (quoting similar to quoting in '')In Algol68 these were refered to as , e.g. , but \"under-under-abs\" __abs__ in python.My 2 cents:  \u00a2 So sometimes \u2014 like a ghost \u2014 when you cut and paste python classes into a wiki you will magically reincarnate Algol68's  keywords. \u00a2
Python

I'm trying to understand how  works.I see in their documentation that they use a pre-populated list of users. I want to play with a database-stored users list.However, I don't understand some things in this  module.This code will be called at every request? This is used to load all the details of my user object?For now, I have this code:When I access /make-login, I want to log in.My user class:Also, I wrote another two functions for authenticate/registerI don't know how to make this  work with MySQL. Also, I don't know if the user are logged-in. How can I get the user ID or the username?Anyone can explain me in some rows how this  works?Flask-login doesn't actually have a user backend, it just handles the session machinery to help you login and logout users. You have to tell it (by decorating methods), what represents a user and it is also up to you to figure out how to know if a user is \"active\" or not (since being \"active\" can mean different things in different applications).You should read the  and be sure what it does . Here I am only going to concentrate on wiring it up with the db backend.To start off with, define a user object; which represents properties for your users. This object can then query databases, or LDAP, or whatever and it is the hook that connects the login mechanism with your database backend.I will be using the  script for this purpose.Once you have the user object created, you need to write a method that loads the user (basically, creates an instance of the  class from above). This method is called with the user id.Once you have these steps, your login method does this:Flask-login will try and load a user BEFORE every request. So yes, your example code below will be called before every request. It is used to check what userid is in the current session and will load the user object for that id.If you look at the Flask-login source code on github, there is a line under function init_app which goes:So before every request, the _load_user function is called. The _load_user functions actually calls another function \"reload_user()\" based on conditions. And finally, reload_user() function calls your callback function that you wrote (load_user() in your example).Also, flask-login only provides the mechanism to login/logout a user. It does not care if you are using mysql database. You might want to use , which combines Flask-Login with SQLAlchemy for database access and automates much of the back-end handling of user records.The  tutorial will get you started. Set app.config['SQLALCHEMY_DATABASE_URI'] to your MySQL database connection string.As per from the 's document a user object must be returned and if the user id is not found it should return None instead of Exception.Here is a Flask example of using login:   You need to use @login_required for every method that requires login.  For example, 
Python

I have a model that I would like to contain a subjects name and their initials.  (The data is somewhat anonymized and tracked by initials.)  Right now, I wrote As indicated by the last line, I would prefer to be able to have the initials actually get stored in the database as a field (independent of name), but that is initialized with a default value based on the name field.  However, I am having issues as django models don't seem to have a 'self'.  If I change the line to , I can do the syncdb, but can't create new subjects.Is this possible in django, having a callable function give a default to some field based on the value of another field?(For the curious, the reason I want to separate my store initials separately is in rare cases where weird last names may have different than the ones I am tracking.  E.g., someone else decided that Subject 1 Named \"John O'Mallory\" initials are \"JM\" rather than \"JO\" and wants to fix edit it as an administrator.)Models certainly do have a \"self\"!  It's just that you're trying to define an attribute of a model class as being dependent upon a model instance; that's not possible, as the instance does not (and cannot) exist before your define the class and its attributes.To get the effect you want, override the save() method of the model class.  Make any changes you want to the instance necessary, then call the superclass's method to do the actual saving.  Here's a quick example.This is covered in  in the documentation.I don't know if there is a better way of doing this, but you can use a  handler:
Python

I've been successfully using Python properties, but I don't see how they could work. If I dereference a property outside of a class, I just get an object of type :But if I put a property in a class, the behavior is very different:I've noticed that unbound  is still the  object, so class instantiation must be doing the magic, but what magic is that?As others have noted, they use a language feature called descriptors.The reason that the actual property object is returned when you access it via a class  lies in how the property implements the  special method. If a descriptor is accessed on an , then that instance is passed as the appropriate argument, and  is the  of that instance.On the other hand, if it is accessed through the class, then  is None and only  is passed. The  object recognizes this and returns .Besides the , see also the documentation on  and  in the Language Guide.In order for @properties to work properly the class needs to be a subclass of . \nwhen the class is not a subclass of  then the first time you try access the setter it actually makes a new attribute with the shorter name instead of accessing through the setter. The following does  work correctly.The following will work correctlyProperties are , and descriptors behave specially when member of a class instance.  In short, if  is an instance of type , and  is a descriptor, then  is equivalent to .The  object just implements the descriptor protocol: 
Python

I was planning to move from Django to Pylons, but then I bumped into Pyramid.What are the differences between Pylons and Pyramid?I read some text in , which currently covers Pylons 0.9.7, and wonder if it is a to start for Pylons and Pyramid.Pylons isn't being \"cancelled\", and it will continue to receive updates. That said, the \"future\" per se is in Pyramid. On the mailing list is has been referred to as Pylons 2.0. It is fully tested and better documented than Pylons 1.0, so you might as well jump aboard if you're fresh.Pyramid is essentially the merger of Pylons and Repoze.bfg.  Read more about this on the  email list.Especially, in  introductory email. If you have deeper questions, hang out in the #pylons, #pyramid, or #repoze irc (freenode) channels.You want to go with Pyramid most probably. It may seem like it's a more complicated system, but it's actually much cleaner and very intuitive. Furthermore, the documentation for the project is simply awesome and in my opinion, even better then the django project which is well known for it's documentation.That does not make it \"like django\" however. It is still lightly coupled and you can use whatever template, database, form, session management system, etc that you like.It's worth noting that Pyramid is a base framework and Pylons is being built on top of it.If you plan to start new project, migrate or just to learn framework I recommend to use Pyramid.Pylons will stop it's development.\nMeanwhile Pyramid is a continuation of Pylons. Thus, it's code is stable. It includes most features from Pylons, adds some new usefull features.
Python

I was looking through my codebase today and found this:It seems to take a dict of parameters and turn them into a list of parameters for a shell command. It looks like it's using yield inside a generator comprehension, which I thought would be impossible...?How does it work?Since Python 2.5,  is an expression, not a statement.  See .The code is hideously and unnecessarily ugly, but it's legal.  Its central trick is using  inside the generator expression.  Here's a simpler example of how this works:Basically, using  in the generator expression causes it to produce two values for every value in the source iterable.  As the generator expression iterates over the list of strings, on each iteration, the  first yields a string from the list.  The target expression of the genexp is , so for every value in the list, the \"result\" of the generator expression is the value of .  But  just ignores its argument and always returns the option string .  So on every step through the generator, it yields first the key-value string (e.g., ), then .  The outer  just makes a list out of this generator and then reverses it so that the s will come before each option instead of after.However, there is no reason to do it this way.  There are a number of much more readable alternatives.  Perhaps the most explicit is simply:Even if you like terse, \"clever\" code, you could still just doThe  list comprehension itself is a bizarre mix of attempted readability and unreadability.  It is more simply written:You should consider arranging an \"intervention\" for whoever put this in your codebase.Oh god. Basically, it boils down to this,:So when iterated over, thegenerator yields  (a member of ) and then the return value of , which is always , all in one iteration over . Whatever  returns and what gets passed to  is ignored.Equivalents:There are lots of ways to do this much simpler, of course. Even with the original double-yield trick, the entire thing could've been 
Python

Why is numpy giving this result:when I'd expect it to do this:Clearly my understanding of the function is lacking.According to  indicates that the smallest element is at index 2, the next smallest at index 3, then index 1, then index 0.There are  to get the result you are looking for:For example,This checks that they all produce the same result:These IPython  benchmarks suggests for large arrays  is the fastest:For small arrays,  may be faster:Note also that  gives you more control over how to handle elements of equal value. As  says, :That means the first element of the argsort is the index of the element that should be sorted first, the second element is the index of the element that should be second, etc.What you seem to want is the rank order of the values, which is what is provided by .  Note that you need to think about what should happen if there are ties in the ranks.
Python

Is there a ready-to-use English grammar that I can just load it and use in NLTK? I've searched around examples of parsing with NLTK, but it seems like that I have to manually specify grammar before parsing a sentence. Thanks a lot!You can take a look at , a simple python statistical parser that returns NLTK parse Trees. It comes with public treebanks and it generates the grammar model only the first time you instantiate a Parser object (in about 8 seconds). It uses a CKY algorithm and it parses average length sentences (like the one below) in under a second.My library, , provides a high performance dependency parser.Installation:Usage: found spaCy to be the fastest dependency parser available. It processes over 13,000 sentences a second, on a single thread. On the standard WSJ evaluation it scores 92.7%, over 1% more accurate than any of CoreNLP's models.There is a Library called . It is quite fast and easy to use.There are a few grammars in the  distribution. In your Python interpreter, issue .Use the MaltParser, there you have a pretrained english-grammar, and also some other pretrained languages.\nAnd the Maltparser is a dependency parser and not some simple bottom-up, or top-down Parser.Just download the MaltParser from  and use the NLTK like this:I've tried NLTK, PyStatParser, Pattern. IMHO Pattern is best English parser introduced in above article. Because it supports pip install and There is a fancy document on the website (). I couldn't find reasonable document for NLTK (And it gave me inaccurate result for me by its default. And I couldn't find how to tune it). pyStatParser is much slower than described above in my Environment. (About one minute for initialization and It took couple of seconds to parse long sentences. Maybe I didn't use it correctly).  
Python

As I understand the g variable in Flask, it should provide me with a global place to stash data like holding the current user after login.  Is this correct?I would like my navigation to display my user's name, once logged in, across the site.My views containDuring login, I assign It doesn't seem I can access g.user.  Instead, when my base.html template has the following...I get the error:The login otherwise works fine.  What am I missing? is a  and is per-request (See ).  The  is  a thread local, but in the default context is persisted to a MAC-signed cookie and sent to the client.The problem that you are running into is that  is rebuilt on each request (since it is sent to the client and the client sends it back to us), while data set on  is only available for the lifetime of  request.The  thing to do (note  - if you need secure take a look at ) is to simply add the user's ID to the session and load the user on each request:Minor correction, the g object is bound to the application context now instead of the request context.I would try to get rid of globals all together, think of your applications as a set of functions that perform tasks, each function has inputs and outputs, and should not touch globals. Just fetch your user and pass it around, it makes your code much more testable. Better yet: get rid of flask, flask promotes using globals such as 
Python

I've asked  before about killing a process that uses too much memory, and I've got most of a solution worked out.However, there is one problem: calculating massive numbers seems to be untouched by the method I'm trying to use. This code below is intended to put a 10 second CPU time limit on the process.What I  to see when I run this script (on a Unix machine) is this:Instead, I get no output. The only way I get output is with  + , and I get this if I  +  after 10 seconds:If I  +   10 seconds, then I have to do it twice, and the console output looks like this:In the course of experimenting and trying to figure this out, I've also put  between the print and large number calculation. It doesn't seem to have any effect. If I change  to , then the print and sleep statements work as expected. Adding  to the print statement or  after the print statement don't work either. How can I fix or at least mitigate this?Additional information:Python version: Linux information:  Python precomputes constants in the code. If any very large number is calculated with at least one intermediate step, the process  be CPU time limited.It took quite a bit of searching, but I have discovered evidence that Python 3  precompute constant literals that it finds in the code before evaluating anything. One of them is this webpage: . I've quoted some of it below.The fact that  is used as an example very strongly suggests that not only small constants are being precomputed and cached, but also any constant literals in the code. I also found  on another Stack\u00a0Overflow question ():These are supported by the fact that replacingwith this  hangs, even though I never call the function!Luckily for me, I don't have any such giant literal constants in my code. Any computation of such constants will happen later, which can be and is limited by the CPU time limit. I changedto this,and got this output, as desired! Limiting a process by CPU time or memory consumption (or some other method)  if there is not a large literal constant in the code that Python tries to precompute.Use a function.It does seem that Python tries to precompute integer literals (I only have empirical evidence; if anyone has a source please let me know). This would normally be a helpful optimization, since the vast majority of literals in scripts are probably small enough to not incur noticeable delays when precomputing. To get around this, you need to make your literal be the result of a non-constant computation, like a function call with parameters.Example:This gives the expected result:
Python

I get this error:when running my code, I don't really see what I'm doing wrong here though:You are calling the wrong class name in your super() call:Essentially what you are resolving to is the  of the object base class which takes no params.Its a bit redundant, I know, to have to specify the class that you are already inside of, which is why in python3 you can just do:  
Python

I'm trying to replicate (and if possible improve on) Python 2.x's sorting behaviour in 3.x, so that mutually orderable types like ,  etc. are sorted as expected, and mutually unorderable types are grouped within the output.Here's an example of what I'm talking about:My previous attempt at this, using a class for the key parameter to  (see \n) is fundamentally broken, because its approach ofcan lead to intransitive ordering, as explained by .A na\u00efve approach, which I initially rejected without even trying to code it, would be to use a key function that returns a  tuple:However, this doesn't do what I want. In the first place, it breaks the natural ordering of mutually orderable types:Secondly, it raises an exception when the input contains two objects of the same intrinsically unorderable type:... which admittedly is the standard behaviour in both Python 2.x and 3.x \u2013 but ideally I'd like such types to be grouped together (I don't especially care about their ordering, but it would seem in keeping with Python's guarantee of stable sorting that they retain their original order).I can work around the first of these problems for numeric types by special-casing them:... which works as far as it goes:... but doesn't account for the fact that there may be other distinct (possibly user-defined) types which are mutually orderable, and of course still fails with intrinsically unorderable types:Is there another approach which solves  the problem of arbitrary, distinct-but-mutually-orderable types  that of intrinsically unorderable types?Stupid idea: make a first pass to divide all the different items in groups that can be compared between each other, sort the individual groups and finally concatenate them. I assume that an item is comparable to all members of a group, if it is comparable with the first member of a group. Something like this (Python3):This will have quadratic running time in the pathetic case that none of the items are comparable, but I guess the only way to know that for sure is to check all possible combinations. See the quadratic behavior as a deserved punishment for anyone trying to sort a long list of unsortable items, like complex numbers. In a more common case of a mix of some strings and some integers, the speed should be similar to the speed of a normal sort. Quick test:It seems to be a 'stable sort' as well, since the groups are formed in the order the incomparable items are encountered.This answer aims to faithfully re-create the Python 2 sort order, in Python 3, in every detail.The actual Python 2 implementation is quite involved, but  does the final fallback after instances have been given a chance to implement normal comparison rules. This is after individual types have been given a chance to compare (via the  or  hooks).Implementing that function as pure Python in a wrapper, plus emulating the exceptions to the rules ( and complex numbers specifically) gives us the same Python 2 sorting semantics in Python 3:I incorporated , since that'd be supported by the type itself via a  hook. I've stuck to the Python 2 ordering for the keys and values as well, naturally.I've also added special casing for complex numbers, as Python 2 raises an exception when you try sort to these:You may have to add more special cases if you want to emulate Python 2 behaviour exactly.If you wanted to sort complex numbers  you'll need to consistently put them with the non-numbers group; e.g.:Some test cases:Not running Python 3 here, but maybe something like this would work.  Test to see if doing a \"less than\" compare on \"value\" creates an exception and then do \"something\" to handle that case, like convert it to a string.Of course you'd still need more special handling if there are other types in your list that are not the same type but are mutually orderable.To avoid the use of exceptions and going for a type based solution, i came up with this:Note that an additional dictionary to hold the different types in list and a type holding variable (notImpl) is needed. Further note, that floats and ints aren't mixed here.Output:One way for Python 3.2+ is to use .\nWith this you can quickly implement a solution that tries to compare the values and then falls back on comparing the string representation of the types. You can also avoid an error being raised when comparing unordered types and leave the order as in the original case:Examples (input lists taken from ):This has the disadvantage that the three-way compare is always conducted, increasing the time complexity. However, the solution is low overhead, short, clean and I think  was developed for this kind of Python 2 emulation use case.We can solve this problem in the following way.We can get a deterministic and orderable key function from types by using . Note that the 'type hierarchy' here is determined by the repr of the types themselves. A flaw in this method is that if two types have identical  (the types themselves, not the instances), you will 'confuse' types. This can be solved by using a key function that returns a tuple , but I have not implemented that in this solution.The advantage of my method over Bas Swinkel's is a cleaner handling of a group of un-orderable elements. We do not have quadratic behavior; instead, the function gives up after the first attempted ordering during sorted()).My method functions worst in the scenario where there are an extremely large number of different types in the iterable. This is a rare scenario, but I suppose it could come up.I'd like to recommend starting this sort of task (like imitation of another system's behaviour very close to this one) with detailed clarifying of the target system. How should it work with different corner cases. One of the best ways to do it - write a bunch of tests to ensure correct behaviour. Having such tests gives:One can write such test cases:Next one may have such sorting function:Usage is quite simple and is documented in tests:Here is one method of accomplishing this:
Python

What is the typical underlying data structure used to implement Python's built-in list data type?See also:\nBtw, I find it interesting that the Python tutorial on data structures recommends using pop(0) to simulate a queue but does not mention O(n) or the deque option.CPython:As can be seen on the following line, the list is declared as an array of pointers to .In the , it's an .
Python

I started learning a bit of python and would now like to toy around a bit with gui-building. Qt seems to be a good choice because of its cross-platformishness.\nNow there seem to be two bindings available: PyQt by Riverbank Computing and PySide, originally developed by Nokia.\nSo which one should I choose? All I can find are two year old feature comparisons, but what differences are there nowadays?\nWhich one is easier to use, has more/better documentation? Are both still in active development?\nLicensing isn't of much concern to me since I don't intend to write commercial applications.Both toolkits are actively maintained, and by now more or less equal in features and quality.  There are only few, rather unimportant differences.Still, I'd recommend PySide for Python 2.  It has a more reasonable API, mainly it doesn't expose Qt types, which have a direct equivalent in Python (e.g. QString, QList, etc.) or which are completely superfluous due to Python's dynamic nature, like QVariant.  This avoids many tedious conversions to and from Qt types, and thus eases programming and avoids many errors.  PyQt also supports this modern API, and uses it by default for Python 3, but not for Python 2 to maintain backwards compatibility.There is also the licensing difference.  PySide is LGPL while PyQt is GPL.  This could make a difference if you don't wish to make your project opensource. Although PyQt always has the propriety version available for a fairly reasonable price.I tend to find the PySide documentation more intuitive.  The API, in my opinion is slightly more Pythonic and the rate of bug fixes is quite impressive at the moment.PyQt has the advantage of Python 3 support and incumbency.  There is a lot more 3rd party documentation/tutorials for it.I recently ported a significant code base (over 8,000 lines of code) from PyQt to PySide.Right now I'd say PyQt is a much more mature, performant and stable project. I hit a number of bugs in PySide, and suspect that any big project will hit issues. Having said that, I reported a bug to the project and it was fixed and in a new release within a few weeks. I'm also having a problem where the app takes about 15 seconds to quit. I've not yet spent the time to find out why. However it's only a matter of time before there will be no reasons for choosing PyQt over PySide.If you do decide to go with PyQt for now, make sure you use API v2 throughout. It is a better API, and will ease any future transition to PySide. Also if you do port, just follow the guidelines on the PySide wiki. Even for an 8+ kloc app consisting of about 20 source files it just took an afternoon.An important fact is that PyQt4 has two versions of its APIs for some things. Version 1 items are such things as using  instead of , and  (basically just a wrapper, I believe - I've never actually done anything which uses it) instead the wrapped. Version 2, which can be enabled in Python 2 and is enabled in Python 3, is much better (though still unpythonic in many places - PySide is too, but it's getting distinctly better. There are still some remaining incompatibilities with them; PyQt4 has , PySide has .For a project of my own, I decided that I wanted to support both with no changes to the code. I prefer PySide, but on Windows I distribute with PyQt4 as at present it's quite a bit smaller for distribution at present. My solution is to check for PySide and if it's there insert an import hook to redirect PyQt4 imports to PySide, or if it's not, fix up PyQt4 to work like it should.The files used:Then you just  and  (as in  in that repository). And after that you can just .Aside: it was also stated a few days ago on the PySide mailing list that they are planning on supporting Python 3 fully within the next few months.Although they might have similar interface for Qt/C++ classes, their interface for Qt/C++ macros such as signal/slot/property are very different.\nPorting one to another is not an easy job. It would be better to make the right decision at the very beginning.Beyond the grammar/license differences, I just want to point out some deficiency of PyQt in language binding, which might be essential to write QML project in Python.\nThese differences finfally push me to PySide from PyQt.I have a 20k line Python app that I unsuccessfully tried to convert to PySide.\nConversion is easy and most of the functionality works.\nThere are several methods that are not implemented because they are 'deprecated', so I had to fix those.  That was OK.\nOn Windows, using PySide-1.1.2, the '==' operator is not implemented for many Qt objects.  One workaround is to say: \"if id(item1) == id(item2):\".\nThe other observation is that PySide seemed noticeably slower.  I did not isolate PySide as the cause of the slowness, but the problem went away when I reverted back to PyQt.Lastly, as of now, the Android kit with PySide does not seem ready for prime time.
Python

I have a list in Python\ne.g.I want to print the array in a single line without the normal \" []Will give the output as;That is not the format I want instead I want it to be like this;Note: It must be in a single row.This, like it sounds, just takes all the elements of the list and joins them with .General solution, works on arrays of non-strings:Here is a simple one. the star unpacks the list and return every element in the list. This is what you needIf the input array is  then you need to first convert array into  array and then use  method for joining with  or  whatever you want. e.g:Direct using of join which will join the integer and string will throw error as show above.You need to loop through the list and use to keep it on one lineI don't know if this is efficient as others but simple logic always works:Output:There are two answers , First is use 'sep' settingThe other is belowdisplaysSam, Peter, James, Julian, Ann
Python

I have installed firefox and Xvfb on my centos6.4 server to use selenium webdriver.But, when I run the code, I got an error.I read some related pages on stackoverflow and someone suggested to remove all files in tmp folder, so I did it. But, it still doesn't work.Could anyone please give me a help?Thank you in advance!for Googlers, this answer didn't work for me, and I had to use  instead. I am using AWS Ubuntu. Basically, I needed to install Xvfb and then pyvirtualdisplay:Once I had done that, this python code worked:Thanks to @That1Guy for the first answerI was running into this on an (headless) Ubuntu 14.04 server with Jenkins and xvfb installed. I had installed the latest stable Firefox (47) which started a build failing that ran a python script which used the Firefox driver for selenium (version 2.53).Apparently Firefox 47+ is not compatible with the driver used in Selenium 2.53, and Selenium 3+ will be using a new driver called \"Marionette\" or \"Gecko Driver\" (which isn't officially released yet).This page explains how to use the new driver pretty well, in several languages: Basically:For Python, step 4 looked something like the following for me:I too had faced same problem.  I was on Firefox 47 and Selenium 2.53; I downgraded Firefox to 45. This worked.Check your  environment variable. Run  in the command line.If nothing is printed, then you are running FireFox without any DISPLAY assigned. You should assign one! Run  in the command line before running your python script.Check this thread for more information: I think the simplest solution here is just run Python with :Rollback your Firefox to the previous working version. I suggest 2 versions back. Disable Firefox Maintenance Service. I was working on a solution and the Firefox Maintenance Service updated Firefox to the latest build in the background. This broke my code and it was giving me this error. Now it is fixed!Thank you everyone!This error is due to your Xvfb is not running. So restart your xvfb:then check.\nThis works for me.Instead of downgrading firefox from 47 version to 45 or something I'll suggest to upgrade to  or above since they seem to fix an issue.But if your OS doesn't have new packages in repo (for example Ubuntu 14.04 in time of this answer), you can use debs from ubuntuzilla project:For x86 use  postfix.\nThat sold problem for meI fixed this by running a recursive chown against not only the python script using selenium, but against the entire virtualenv that script was running in. I changed the ownership to the user running the file. After that, this error went away.I also faced the same issue, what I did was:update your selenuim version ---> pip install -U seleniumIt can be solved by changing the file permission of the output file ( or related files to the program).\nI used Firefox's webdriver.  Try:This solved me the same trouble you have.
Python

I have a simple script which parses a file and loads it's contents to a database. I don't need a UI, but right now I'm prompting the user for the file to parse using  which is most unfriendly, especially because the user can't copy/paste the path.  I would like a quick and easy way to present a file selection dialog to the user, they can select the file, and then it's loaded to the database.  (In my use case, if they happened to chose the wrong file, it would fail parsing, and wouldn't be a problem even if it was loaded to the database.)This code is close to what I want, but it leaves an annoying empty frame open (which isn't able to be closed, probably because I haven't registered a close event handler).I don't have to use tkInter, but since it's in the Python standard library it's a good candidate for quickest and easiest solution.Whats a quick and easy way to prompt for a file or filename in a script without any other UI?Tkinter is the easiest way if you don't want to have any other dependencies.\nTo show only the dialog without any other GUI elements, you have to hide the root window using the  method:You can use :To install , you can use :It is a single pure Python module () that uses .Try with :If you don't need the UI or expect the program to run in a CLI, you could parse the filepath as an argument. This would allow you to use the autocomplete feature of your CLI to quickly find the file you need.This would probably only be handy if the script is non-interactive besides the filepath input.Check out EasyGUI, a very easy to use module that should do the job - You would use the fileopenbox function - 
Python

I am receiving the following error:Error says that  is local variable but i thought that this variable is globalSo is it global or local and how to solve this error without passing global  as argument to ?In order for you to modify test1 you need to do the following:If you only needed to read that global varaible you could have just printed it without using the keyword  as so:But whenever you need to modify a global variable you have let python know using the reserved keyword  Best solution: Don't use sYou have to specify that test1 is global:\n
Python

Which is a better way to check for the existence of an attribute? provided this answer:I see that it can also be done this way:Is one approach typically used more than others? because you are never just checking to see if an attribute exists; it is always a part of some larger program.  There are several correct ways and one notable incorrect way.Here is a demonstration which shows this technique failing:Output:Most of the time, you don't want to mess with .  It's a special attribute for doing special things, and checking to see if an attribute exists is fairly mundane.A common idiom in Python is \"easier to ask for forgiveness than permission\", or EAFP for short.  You will see lots of Python code that uses this idiom, and not just for checking attribute existence.Note that this is exactly the same idiom for opening a file that may not exist.Also, for converting strings to integers.Even importing optional modules...The  method, of course, works too.  This technique is called \"look before you leap\", or LBYL for short.(The  builtin actually behaves strangely in Python versions prior to 3.2 with regard to exceptions -- it will catch exceptions that it shouldn't -- but this is probably irrelevant, since such exceptions are unlikely.  The  technique is also slower than , but you don't call it often enough to care and the difference isn't very big.  Finally,  isn't atomic so it could throw  if another thread deletes the attribute, but this is a far-fetched scenario and you'll need to be very careful around threads anyway.  I don't consider any of these three differences to be worth worrying about.)Using  is much simpler than , as long as all you need to know is whether the attribute exists.  The big issue for me is that the LBYL technique looks \"strange\", since as a Python programmer I'm more used to reading the EAFP technique.  If you rewrite the above examples so that they use the  style, you get code that is either clumsy, outright incorrect, or too difficult to write.And LBYL is sometimes outright incorrect:If you want to write a LBYL function for importing optional modules, be my guest... it sounds like the function would be a total monster.If you just need a default value,  is a shorter version of .If the default value is expensive to construct, then you'll end up with something like this:Or if  is a possible value,Internally, the  and  builtins just use  technique (except written in C).  So they all behave the same way where it counts, and picking the right one is due to a matter of circumstances and style.The  EAFP code will always rub some programmers the wrong way, and the  LBYL code will irk other programmers.  They're both correct, and there's often no truly compelling reason to pick one or the other.  (Yet other programmers are disgusted that you would consider it normal for an attribute to be undefined, and some programmers are horrified that it's even possible to have an undefined attribute in Python.) is the way.  is ugly and it doesn't work in many cases.  actually tries to get attribute and catches  internally so it works even if you define custom  method.To avoid requesting the attribute twice the third argument for  could be used:You could just use a default value instead of  sentinel if it is more appropriate in your case.I don't like  it might hide  inside  function. (not only ) if it is not desirable  should be used. is the Pythonic way to do it. Learn it, love it. is to check whether the variable name is in  or :I personally hate to catch exceptions in order to check something. It looks and feels ugly. It's identical to checking if a string contains only digits that way:Instead of gently using . Eww.Very old question but it really needs a good answer. For even a short program, I'd say use a custom function!Here's an example. It's not perfect for all application but it is for mine, for parsing responses from countless APIs and using Django. It's easy to fix for everyone's own requirements.
Python

I'm starting an open source Python project shortly and I'm trying to decide in advance how to write my docstrings. The obvious answer would be using reStructuredText and Sphinx with autodoc, because I  like the idea of simply properly documenting my code in my docstrings then have Sphinx automatically construct an API doc for me.The problem is the reStructuredText syntax it uses - I think it's completely unreadable before it's rendered. For instance:You have to  slow down and take a minute to make any sense out of that syntactic jumble. I like much more the Google way (), which counterpart to the above looks like this: nicer! But of course, Sphinx will have none of that and renders all the text after \"Args:\" in one long line.So to summarize - before I go and defile my code base with this reStructuredText syntax I would like to know if there are any real alternatives to using it and Sphinx, short of just writing my own API doc. For instance, is there an extension for Sphinx that handles Google Style Guide's docstring style?I don't think that there is something better than  for documenting python projects at the moment.To have a clearer docstring my favorite choice is using  together with . Based on your example this would look like:(a full example is ), \nHTML output will look like I think the structure of the rst-file is clearer and more readable. The  gives some more information and conventions. The  extension works with  as well.I have created a  that parses both Google style and NumPy style docstrings, and converts them to standard reStructuredText.To use it, simply install it:And enable it in conf.py:More documentation on napoleon .I use  and not sphinx, so this answer may not apply.The reStructuredText syntax you describe for documenting methods and functions is not the only possible one. By far, I prefer describing parameters using a , which is very similar to the Google way:I would try out if sphix supports it. If it doesn't you may also consider using epydoc just for that (although it is not that actively maintaned right now).Actually,  as well as the style guide from  apply mostly for coding the Python's standard library itself, albeit a lot of third party programmers conform to that as well.I agree with you that the Google's style for arguments is much better from an in-code perspective. But you should be able to  as well, . It doesn't output as nice as  though.Anyway, you don't  use sphinx, and by the way, the  module of sphinx is definitely just a small part of it. You can virtually use any documentation generator which is capable of retrieving the content of docstrings, like  (which support  as well as ) or , or even a more universal one like .But definitely, sphinx is quite , very convenient to use with Python, and make your code consistent with the Python's ecosystem. I think you are  who think this is a \"lack\". Maybe they will take these complaints into account in the future, or maybe you might even consider modyfying the  module by yourself, should not be very difficult, it's in Python, it would be a good exercise.You  write docstrings in any format you like. However, for the sake of every other Python programmer, it's best to use markup and tools that they already know. Their lives is easier if you stick to reST and Sphinx.Python makes the contents of the docstrings available as a  attribute attached to the function/class/variable object.So, you could trivially write a Python program which converts the documentation from whatever format you like into whatever format you like. You could even use Javadoc styling, or XML, or whatever.Incidentally, since Sphinx is written in Python, making it take non-RST input is just a matter of writing a small amount of Python code.you just need to start a new line and add a tap after each variable name. Then it is rendered in several lines with consucutive bold variable names:
Python

I'm trying to build a one-file EXE with PyInstaller which is to include an image and an icon. I cannot for the life of me get it to work with .If I do  it works all works very well.\nWhen I use , it can't find the referenced additional files (when running the compiled EXE). It finds the DLLs and everything else fine, just not the two images.I've looked in the temp-dir generated when running the EXE ( for example) and the files are indeed in there. When I drop the EXE in that temp-directory it finds them. Very perplexing.This is what I've added to the  fileI should add that I have tried not putting them in subfolders as well, didn't make a difference. Newer versions of PyInstaller do not set the  variable anymore, so Shish's excellent  will not work. Now the path gets set as :pyinstaller unpacks your data into a temporary folder, and stores this directory path in the  environment variable. To get the  dir in packed-mode and use the local directory in unpacked (development) mode, I use this:Instead for rewriting all my path code as suggested, I changed the working directory:Just add those two lines at the beginning of your code, you can leave the rest as is.Slight modification to the accepted answer.I found the existing answers confusing, and took a long time to work out where the problem is. Here's a compilation of everything I found.When I run my app, I get an error  (if  is the main file). To troubleshoot this, don't run PyInstaller with  (or edit  to change  => ). With this, run the executable from a command-line, and you'll see the failure.The first thing to check is that it's packaging up your extra files correctly. You should add tuples like  if you want the folder  to be included.After it crashes,  If you're on Windows, you can use . Look for one of your files (eg. ). You should find the temporary path where it unpacked the files (eg. ). You can browse this directory and make sure it included everything. If you can't find it this way, look for something like  (Windows) or  (if you're using Python 3.5).If the installer includes everything, the next likely problem is file I/O: your Python code is looking in the executable's directory, instead of the temp directory, for files.To fix that, any of the answers on this question work. Personally, I found a mixture of them all to work: change directory conditionally first thing in your main entry-point file, and everything else works as-is:All of the other answers use the  in the case where the application is not PyInstalled (i.e.  is not set). That is wrong, as it prevents you from running your application from a directory other than the one where your script is.A better solution:Perhaps i missed a step or did something wrong but the methods which are above, didn't bundle data files with PyInstaller into one exe file. Let me share the steps what i have done.Conclusion: There's still more than one file in the dist folder.Note: I'm using Python 3.5.EDIT: Finally it works with After the 6. step your one file is ready to use.
Python

I have the following shell script for very simple http serverand I was wondering how I can enable /add [ Access-Control-Allow-Origin: * ] on this server?Unfortunately,  is really that simple that it does not allow any customization, especially not of the headers it sends. You can however create a simple HTTP server yourself, using most of , and just add that desired header.Simply create a file  (or whatever) and put the following inside:Then you can do  and it will launch your modified server which will set the CORS header for every response.With the shebang at the top, make the file executable and put it into your PATH, and you can just run it using  too.For a solution that works with Python 3, you could simple change the imports above to import from the  (all the types are there).Alternatively, you could use this which works on both Python 3 and Python 2. The script first tries to import from the Python 3 locations and falls back to Python 2:As SimpleHTTPServer is not really the kind of server you deploy to production, I'm assuming here that you don't care that much about which tool you use as long as it does the job of exposing your files at  with CORS headers in a simple command lineYou'll need to provide your own instances of do_GET() (and do_HEAD() if choose to support HEAD operations). something like this:
Python

Is there a generic notion of asynchronous programming in python? Could I assign a callback to a function, execute it and return to the main program flow immediately, no matter how long the execution of that function would take?Take a look here:Worth checking out:What you describe (the main program flow resuming immediately while another function executes) is not what's normally called \"asynchronous\" (AKA \"event-driven\") programming, but rather \"multitasking\" (AKA \"multithreading\" or \"multiprocessing\").  You can get what you described with the standard library modules  and  (the latter allows actual concurrent execution on multi-core machines).Asynchronous (event-driven) programming is supported in the standard Python library in the  and  modules, which are very oriented to networking tasks (indeed they internally use the  module, which, on Windows, only supports sockets -- though on Unixy OSs it can also support any file descriptor).For a more general (though also mostly networking oriented, but not  to that) support for asynchronous (event-driven) programming, check out the  third-party package.Good news everyone! It is currently called  and already has an .As described in  and : Here is the  of it's abilities.The other respondents are pointing you to Twisted, which is a great and very comprehensive framework but in my opinion it has a very un-pythonic design. Also, AFAICT, you have to use the Twisted main loop, which may be a problem for you if you're already using something else that provides its own loop.Here is a contrived example that would demonstrate using the  module:However, in pretty much every useful case, you will want to communicate between threads. You should look into , and become familiar with the concept of  and the related issues.The  module provides many such primitives for you to use, if you know how to use them.You may well want to checkout the Twisted library for Python. They provide many useful tools.You may see my Python Asynchronous Programming tool: 
Python

How do I find multiple occurrences of a string within a string in Python? Consider this:So the first occurrence of  is at 1 as expected. How do I find the next occurrence of it?Same question is valid for a list. Consider:How do I find all the  with their indexes? Using regular expressions, you can use  to find all (non-overlapping) occurences:Alternatively, if you don't want the overhead of regular expressions, you can also repeatedly use  to get the  index:This also works for lists and other sequences.I think what you are looking for is Hope this helps \nNOTE: this only captures non-overlapping occurencesFor the list example, use a comprehension:Similarly for strings:this will list adjacent runs of \"ll', which may or may not be what you want:FWIW, here are a couple of non-RE alternatives that I think are neater than .The first uses  and checks for :The second tests uses  and checks for the sentinel of  by using :To apply any of these functions to a list, tuple or other  of strings, you can use a  \u2014one that takes a function as one of its arguments\u2014 like this one:For your list example:If you wanted all the items in a list that contained 'll', you could also do that.Brand new to programming in general and working through an online tutorial. I was asked to do this as well, but only using the methods I had learned so far (basically strings and loops). Not sure if this adds any value here, and I know this isn't how you would do it, but I got it to work with this:This version should be linear in length of the string, and should be fine as long as the sequences aren't too repetitive (in which case you can replace the recursion with a while loop).bstpierre's list comprehension is a good solution for short sequences, but looks to have quadratic complexity and never finished on a long text I was using.For a random string of non-trivial length, the two functions give the same result:But the quadratic version is about 300 times slowerThis program counts the number of all substrings even if they are overlapped without the use of regex. But this is a naive implementation and for better results in worst case it is advised to go through either Suffix Tree, KMP and other string matching data structures and algorithms.Here is my function for finding multiple occurrences. Unlike the other solutions here, it supports the optional start and end parameters for slicing, just like :A simple iterative code which returns a list of indices where the substring occurs.You can split to get relative positions then sum consecutive numbers in a list and add (string length * occurence order) at the same time to get the wanted string indexes.  This can be done in one line using list comprehensions:Similar technique works for lists:Maybe not so Pythonic, but somewhat more self-explanatory. It returns the position of the word looked in the original string. This  explains how to do the whole thing in O(n) and includes a solution in python as well.If you go further down the sets to '' you'd be able to do the same thing if you had one big string but wanted to search for 1000s of patterns in it.
Python

Python noob, as in this is my first project, so excuse my unfamiliarity.The site was working very well until I clicked \"log out\" on my app. After that, the website would give me this error:\nDoesNotExist at /login/\nSite matching query does not exist.I searched everywhere and the only solution I get relates to setting up the site framework, SITE_ID, etc. I think those items on my computer are fine, but I can't find a walkthrough/guide to help me check on them.Can anyone tell me what the problem is and how to fix it? Thanks in advance :3}If you don't have a site defined in your database and django wants to reference it, you will need to create one. From a  :Now set that site ID in your settings.py to SITE_IDTable  must contain a row with the same value of  (by default equals to ), as  is set to (inside your ).
Python

I have a string in base64 format, which represents PNG image. Is there a way to save this image to the filesystem, as a PNG file?I encoded the image using flex. Actually this is what I get on server\n(can't see any image after any of proposed methods :( )Starting withDecoded the data using the base64 codec, and then write it to the filesystem. Modernizing this example to Python 3, which removed arbitrary codec support from string/bytes  and  functions:If the imagestr was bitmap data (which we now know it isn't) you could use this is the base64 encoded string\n is the width of the image\n is the height of the image  Since the imagestr is just the encoded png dataYou can also save it to a string buffer and then do as you wish with it, In django, you can save it as an uploaded file to save to a model:Or send it as an email:You could probably use the  to do this - decode the base64 string into a regular string (via the  standard library), and pass it to the constructor.
Python

I've been working on a new dev platform using nginx/gunicorn and Flask for my application.Ops-wise, everything works fine - the issue I'm having is with debugging the Flask layer. When there's an error in my code, I just get a straight 500 error returned to the browser and nothing shows up on the console or in my logs.I've tried many different configs/options.. I guess I  be missing something obvious.My gunicorn.conf:An example of some Flask code that borks- testserver.py:And finally, the command to run the flask app in gunicorn:Thanks y'allThe acception solution doesn't work for me.Gunicorn is a pre-forking environment and apparently . Even if you set , you will still only get an empty page with the message  if you run with . The best you can do with gunicorn is to run it with . That gives you the trace in addition to the  message. However, this is just the same text trace that you see in the terminal and not the Flask debugger.Adding the  section to the testserver.py and running  to start the server in development gets you the Flask debugger. Personally I still like to use , instead of  since . To get this to work:Also, dont forget to change the  line in  to something that won't run Flask in debug mode in production.The Flask config is entirely separate from gunicorn's. Following , a good solution would be change my source to this:And in config.py:, there is a simpler solution than creating a bin/web script like suggested by Nick.Instead of , just use   if you want to debug your application in development.Try setting the debug flag on the run command like so  and keep the  in your Flask application. There must be a reason why your debug option is not being applied from the config file but for now the above note should get you going.
Python

I'm looking for an equivalent to  in Python. I want to parse  files, in C I could do something like this:I thought at first to use , however it doesn't split on the given characters, but the  string as a whole:Which should be returning 17, as explained above.Is there a Python equivalent to  (not RE), or a string splitting function in the standard library that splits on any of a range of characters that I'm not aware of?Python doesn't have an  equivalent built-in, and most of the time it actually makes a whole lot more sense to parse the input by working with the string directly, using regexps, or using a parsing tool. Probably mostly useful for translating C, people have implemented , such as in this module: In this particular case if you just want to split the data based on multiple split characters,  is really the right tool.When I'm in a C mood, I usually use zip and list comprehensions for scanf-like behavior.  Like this:Note that for more complex format strings, you do need to use regular expressions:There is also the  module. is designed to be the opposite of  (the newer string formatting function in Python 2.6 and higher).You can split on a range of characters using the  module.You can parse with module  using . It won't parse the substrings to their actual datatypes (e.g. ) but it's very convenient when parsing strings.Given this sample line from :An example mimicking your sscanf example with the variable could be:There is an ActiveState recipe which implements a basic scanf\nyou can turn the \":\" to space, and do the split.egno regex needed (for this case)Upvoted orip's answer. I think it is sound advice to use re module. The Kodos application is helpful when approaching a complex regexp task with Python. Update: The Python documentation for its regex module, , includes a section on simulating scanf, which I found more useful than any of the answers above.If the separators are ':', you can split on ':', and then use x.strip() on the strings to get rid of any leading or trailing whitespace. int() will ignore the spaces.There is a .
Python

Is there a way to compress an if/else statement to one line in Python? I oftentimes see all sorts of shortcuts and suspect it can apply here too.An example of Python's way of doing \"ternary\" expressions:translates intoThis actually comes in handy when using list comprehensions, or sometimes in return statements, otherwise I'm not sure it helps that much in creating readable code. The readability issue was discussed at length in this recent SO question .It also contains various other  (and somewhat ) ways to accomplish the same task. It's worth a read just based on those posts.Python's  can be used as a :Only for using as a value:orThere is the conditional expression:but this is an expression, not a statement.In if statements, the  (or  or ) can be written on the same line as the body of the block if the block is just one like:but this is discouraged as a matter of formatting-style.
Python

Will google Go use less resources than Python and Java on Appengine? Are the instance startup times for go faster than Java's and Python's startup times? Is the go program uploaded as binaries or source code and if it is uploaded as source code is it then compiled once or at each instance startup?In other words: Will I benefit from using Go in app engine from a cost perspective? (only taking to account the cost of the appengine resources not development time)Yes, Go instances have a lower memory than Python and Java (< 10 MB).Yes, Go instances start faster than Java and Python equivalent because the runtime only needs to read a single executable file for starting an application.Also even if being atm single threaded, Go instances handle incoming request concurrently using goroutines, meaning that if  1 goroutine is waiting for I/O another one can process an incoming request.Go program is uploaded as source code and compiled (once) to a binary when deploying a new version of your application using the SDK.The Go runtime has definitely an edge when it comes to performance / price ratio, however it doesn't affect the pricing of other API quotas as described by Peter answer.The cost of instances is only part of the cost of your app.  I only use the Java runtime right now, so I don't know how much more or less efficient things would be with Python or Go, but I don't imagine it will be orders of magnitude different.  I do know that instances are not the only cost you need to consider.  Depending on what your app does, you may find API or storage costs are more significant than any minor differences between runtimes.  All of the API costs will be the same with whatever runtime you use.The question is mostly irrelevant.The minimum memory footprint for a Go app is less than a Python app which is less than a Java app.  They all cost the same per-instance, so unless your application performs better with extra heap space, this issue is irrelevant.Go startup time is less than Python startup time which is less than Java startup time.  Unless your application has a particular reason to churn through lots of instance startup/shutdown cycles, this is irrelevant from a cost perspective.  On the other hand, if you have an app that is  bursty in , the startup time may be an advantage.As mentioned by other answers, many costs are identical among all platforms - in particular, datastore operations.  To the extent that Go vs Python vs Java will have an effect on the instance-hours bill, it is related to:All three languages have their virtues and curses.  For the most part, you're better off letting other issues dominate - which language do you enjoy working with most?It's probably more about how you allocate the resources than your language choice. I read that GAE was built the be language-agnostic so there is probably no builtin advantage for any language, but you can get an advantage from choosing the language you are comfortable and motivated with. I use python and what made my deployment much more cost-effective was the upgrade to python 2.7 and you can only make that upgrade if you use the correct subset of 2.6, which is good. So if you choose a language you're comfortable with, it's likely that you will gain an advantage from your ability using the language rather than the combo language + environment itself. In short, I'd recommend python but that's the only app engine language I tried and that's my choice even though I know Java rather well the code for a project will be much more compact using my favorite language python. My apps are  to  sized and they cost like nothing:I haven't used Go, but I would strongly suspect it would load and execute instances much faster, and use less memory purely because it is compiled. Anecdotally from the group, I believe that Python is more responsive than Java, at least in instance startup time. Instance load/startup times are important because when your instance is hit by more requests than it can handle, it spins up another instance. This makes that request take much longer, possibly giving the impression that the site is generally slow. Both Java and Python have to startup their virtual machine/interpreter, so I would expect Go to be an order of magnitude faster here.There is one other issue - now Python2.7 is available, Go is the only option that is single-threaded (ironically, given that Go is designed as a modern multi-process language). So although Go requests should be handled faster, an instance can only handle requests serially. I'd be very surprised if this limitation last long, though.
Python

I'm new to Mustache.Many templating languages (e.g.,  / ) will let you extend a \"parent\" template like so...I'm aware of Mustache's  (e.g., ), but those seem to be just .Does template extension exist for Mustache? Or, failing that, is there at least some design pattern that effectively turns  into template extension equivalents.I recently found myself in the same boat, except I came from a mako background.  Mustache does not allow for template extension/inheritance but there are a few options available to you that I know of.I wouldn't, however, use the triple mustache because I don't want unescaped HTML to be appearing anywhere, it's just too risky in my opinion.If someone else has a better solution to this problem I'd love to hear it as well, since I haven't yet taken the plunge in any one of these directions.I've proposed this to the specification for Mustache here:Currently mustache.java, hogan.js and phly_mustache support template inheritance.You could use variables containing HTML. A \"triple mustache\" like  will return unescaped HTML. It's not exactly the same as template extensions, but you could render  and then put its output in a  variable that gets passed to .(I added  to the  filename with the expectation that such a naming pattern will help keep the filenames manageable.)Mustache doesn't do template extension. If you really want template extension then you may want to use a library purpose built with this functionality for you language/framework of choice.FYI, I'm using Node.js/Express, so I will probably end up using I'm playing around with this right now in Python (note I'm the creator of Mako), adding in a dynamic context that captures sections seems to be doing the right thing, though I'd need to test this a lot more.Basically we are using lambdas, where a \"<\" prefix indicates \"inherit from this template\" (similar to the syntax discussed at ) and a \"$\" prefix indicates \"this is an inherited section\".So here's some templates.   base.mustache:hello.mustache:and then to play with three levels deep, subhello.mustache:Rendering hello.mustache like this:output:Rendering subhello.mustache:output:I just wrote this in twenty minutes, and I've only used handlebars.js a little bit in the past and pystache for the first time just now so the whole \"mustache\" idea is not deep for me yet.  But this seems to work ?   In mustache php, template inheritance is supported since version 2.7.0.You can figure out your current version from the file Mustache/Engine.php and search for the line containing:If you're happy with a server-side only code,  - modelled on django. While it works, however, it is no longer maintained by its author.In node.js you can use  or  to have layouts inna mustache templates, but the way they do things is different, in none of them you set the layout at the template itself, layouts are registered in your app code.
Python

I want to get the  in a variable after running the  call.Lets take this line as an example:  will contain the error code (  under Windows or  under some linux for the above example).How can I get the  for the above command without using redirection in the executed command?      If all you need is the  output, then take a look at  (added in Python 2.7):Because you were using , you'd have to set  to get the same behaviour. You do want to heed the  about passing untrusted arguments to your shell.If you need to capture  as well, simply add  to the call:to redirect the error output to the default output stream.These answers didn't work for me. I had to use the following:Or as a function (using shell=True was required for me on Python 2.6.7 and check_output was not added until 2.7, making it unusable here):I would like to expand on the Windows solution. Using IDLE with Python 2.7.5, When I run this code from file Expts.py:...in the Python Shell, I ONLY get the output corresponding to \"cmd.exe\"; the \"dir\" part is ignored. HOWEVER, when I add a switch such as /K or /C ......then in the Python Shell, I get all that I expect including the directory listing. Woohoo !Now, if I try any of those same things in DOS Python command window, without the switch, or with the /K switch, it appears to make the window hang because it is running a subprocess cmd.exe and it awaiting further input - type 'exit' then hit [enter] to release. But with the /K switch it works perfectly and returns you to the python prompt. Allrightee then.Went a step further...I thought this was cool...When I instead do this in Expts.py:...a new DOS window pops open and remains there displaying only the results of \"cmd.exe\" not of \"dir\". When I add the /C switch, the DOS window opens and closes very fast before I can see anything (as expected, because /C terminates when done). When I instead add the /K switch, the DOS window pops open and remain, AND I get all the output I expect including the directory listing.If I try the same thing (subprocess.call instead of subprocess.check_output) from a DOS Python command window; all output is within the same window, there are no popup windows. Without the switch, again the \"dir\" part is ignored, AND the prompt changes from the python prompt to the DOS prompt (since a cmd.exe subprocess is running in python; again type 'exit' and you will revert to the python prompt). Adding the /K switch prints out the directory listing and changes the prompt from python to DOS since /K does not terminate the subprocess. Changing the switch to /C gives us all the output expected AND returns to the python prompt since the subprocess terminates in accordance with /C.Sorry for the long-winded response, but I am frustrated on this board with the many terse 'answers' which at best don't work (seems because they are not tested - like Eduard F's  response above mine which is missing the switch) or worse, are so terse that they don't help much at all (e.g., 'try subprocess instead of os.system' ... yeah, OK, now what ??). In contrast, I have provided solutions which I tested, and showed how there are subtle differences between them. Took a lot of time but...\nHope this helps.
Python

If it is environment-independent, what is the theoretical maximum number of characters in a python string?Also if it differs with version number I'd like to know it for python 2.5.2With a 64-bit Python installation, and (say) 64 GB of memory, a Python 2 string of around 63 GB should be quite feasible (if not maximally fast).  If you can upgrade your memory much beyond that (which will cost you an arm and a leg, of course), your maximum feasible strings should get proportionally longer.  (I don't recommend relying on virtual memory to extend that by much, or your runtimes will get simply ridiculous;-).With a typical 32-bit Python installation, of course, the total memory you can use in your application is limited to something like 2 or 3 GB (depending on OS and configuration), so the longest strings you can use will be much smaller than in 64-bit installations with ridiculously high amounts of RAM.I ran this code on an EC2 instance.and this is the outputmemory error after 116GB.Tested on EC2 r3.4xlarge instance running 64-bit Amazon Linux AMI 2016.09Short answer would be: if you have over 100GB of RAM, one Python string can use up that much memory.
Python

I haveBut I wantWhat magic param forces no tagging?You can use  instead of . Just keep in mind that it won't be able to represent arbitrary Python objects then. Also, when you  the YAML, you will get a  object instead of .How about this:This seems to make dumping unicode objects work the same as dumping str objects for me (Python 2.6).You need a new dumper class that does everything the standard Dumper class does but overrides the representers for str and unicode.Which leads toGranted, I'm still stumped on how to keep this pretty.And it breaks a later yaml.load()little addition to interjay's excellent answer, you can keep your unicode on a reload if you take care of your file encodings. contents in my editor:print outputs:Plus, after reading  I am pretty sure that safe_load/safe_dump is where I want to be anyway.I've just started with Python and YAML, but probably this may also help. Just compare outputs:
Python

I'm trying to make a list with numbers 1-1000 in it. Obviously this would be annoying to write/read, so I'm attempting to make a list with a range in it. In python 2 it seems that\n    some_list = range(1,1000)\nwould have worked, but in python 3 the range is similar to the xrange of python 2?\nCan anyone provide some insight into this?You can just construct a list from the range object:This is how you do it with generators in python2.x as well.  Typically speaking, you probably don't need a list though since you can come by the value of  more efficiently (), and if you just need to iterate over it, you can just fall back on .Also note that on python2.x,  is still indexable.  This means that  on python3.x also has the same propertyin Python 3.x, the  function got its own type. so in this case you must use iteratorActually, if you want 1-1000 (inclusive), use the  function with parameters 1 and 1001: , because the  function goes from start to (end-1), inclusive.You really shouldn't need to use the numbers 1-1000 in a list. But if for some reason you really do need these numbers, then you could do:List Comprehension in a nutshell:The above list comprehension translates to:This is just the list comprehension syntax, though from 2.x. I know that this will work in python 3, but am not sure if there is an upgraded syntax as wellRange starts inclusive of the first parameter; but ends Up To,  the second Parameter (when supplied 2 parameters; if the first parameter is left off, it'll start at '0')  
Python

When running....I get the following output:It's prompting to save the login details, despite  already containing this. It then fails to upload files for a package I own, and have full write-access to.Just found , which solves the issue:The above content goes into the  in the user's home directory.Ugh.. I think this may be a good time to give  a try..None of the changes to ~/.pypirc listed here worked for me.This worked for me, with no changes to ~/.pypirc.  I added \"-r \" to the command line:My ~/.pypirc looks like thisI have the same problem\uff0c This is my solution.The python version is 2.7.7, my windows version is Windows-7-6.1.7601-SP1.here is my .pypirc fileIn windows, A file is not allowed named as \u201c.pypirc\u201d\uff0cplz\uff0crefer to\uff1a Then put you \".pypirc\" file in the same folder with \"setup.py\"At last:run : or:I hope this will be help,thank you!I have this problem and solved it by putting the file .pypirc under my home directory (~/), as the last past of the first comment suggests. I didn't have the need to modify the name of the section \"pypi\" of the file pypirc for \"server-login\", as suggested also in the first comment.I changed  to  as per the  and this worked for me.Here is my  file:I had this problem, due to my own fault but hopefully this may help someone else who makes this same mistake.I'm using python 3 on Linux Ubuntu, during registration I issued the setup command using sudo! The result was the .pypirc file in my home directory was owned by root and wasn't readable when trying to perform a module upload immediately after as a none privileged user.By changing the ownership of the file to myself, the issue was resolved.I ran into the same problem. I'm on a new OS X Sierra. Adding [server-login] entry to ~/.pypirc seemed to fix it 
Python

Can someone please explain why the code below does not work when setting the facecolor of the figure?When I specify the height and width of the figure using   these are picked up by the command . However, the facecolor setting is not picked up. Why?Thanks for your help.It's because  overrides the facecolor for the background of the figure.  (This is deliberate, actually... The assumption is that you'd probably want to control the background color of the saved figure with the  kwarg to . It's a confusing and inconsistent default, though!)The easiest workaround is just to do  (I'm specifying the edgecolor here because the default edgecolor for the actual figure is white, which will give you a white border around the saved figure)Hope that helps!I had to use the transparent keyword to get the color I chose with my initial like this: has its own parameter for .\nI think an even easier way than the accepted answer is to set them globally , instead of putting  every time:
Python

I need to replace part of a string. I was looking through the Python documentation and found re.sub.I was expecting this to print  and not 'bar'. Could anybody tell me what I did wrong?Instead of capturing the part you want to  you can capture the parts you want to  and then refer to them using a reference  to include them in the substituted string.Try this instead:Also, assuming this is HTML you should consider using an HTML parser for this task, for example .Or you could just use the search function instead:
Python

I'm running an update on my MongoDB from Python. I have this line:But it throws this error:But  looks like an instance of bool to me!How should I correctly write this update?The third argument to PyMongo's  is  and must be passed a boolean, not a dictionary. Change your code to:Or pass  as a keyword argument:Your mistake was likely caused by reading about  in the . The JavaScript version of  takes an object as its third argument containing optional parameters like  and . But since Python allows passing keyword arguments to a function (unlike JavaScript which only has positional arguments), this is unnecessary and PyMongo takes these options as optional function parameters instead.According to  you should indeed pass upsert as a keyword rather than just True, that isOris a better approach than just passing True as if you ever wish to pass other kwargs such as  or  code might break if order of args is not kept.upsert should be passed as either positional parameter, like soor as a keyword argument, like so
Python

I find particularly difficult reading binary file with Python. Can you give me a hand?\nI need to read this file, which in Fortran 90 is easily read byIn detail, the file format is:How can I read this with Python? I tried everything but it never worked. Is there any chance I might use a f90 program in python, reading this binary file and then save the data that I need to use?Read the binary file content like this:then \"unpack\" binary data using :The start bytes: The body: ignore the heading bytes and the trailing byte (= 24); The remaining part forms the body, to know the number of bytes in the body do an integer division by 4; The obtained quotient is multiplied by the string  to create the correct format for the unpack method:The end byte: In general, I would recommend that you look into using Python's  module for this. It's standard with Python, and it should be easy to translate your question's specification into a formatting string suitable for .Do note that if there's \"invisible\" padding between/around the fields, you will need to figure that out and include it in the  call, or you will read the wrong bits.Reading the contents of the file in order to have something to unpack is pretty trivial:This unpacks the first two fields, assuming they start at the very beginning of the file (no padding or extraneous data), and also assuming native byte-order (the  symbol). The s in the formatting string mean \"unsigned integer, 32 bits\".You could use , which can read data from both text and binary files. You would first construct a data type, which represents your file format, using , and then read this type from file using .
Python

Is there is any easy way or function to determine the greatest number in a python list?  I could just code it, as I only have three numbers, however it would make the code a lot less redundant if I could tell the greatest with a built in function or something.What about max()You can use the inbuilt function  with multiple arguments:or a list:or in fact anything iterable.Use 
Python

If yes are there any frameworks/Tutorials/tips/etc recommended? N00b at Python but I have tons of PHP experience and wanted to expand my skill set.I know Python is great at server side execution, just wanted to know about client side as well.Have you seen skulpt?You can use  to convert Python code to JS code that runs in the browser (note that pyjamas also offers much more). So YES, you can use Python for client side web development.Pyjamas is basically a port of the , which allows you to write client side code in Java.Silverlight can run IronPython, so you can make Silverlight applications. Which is client-side.Python isn't really used for client side, because no major web browsers have Python built in.However, Javascript has become more and more Python-like as it has evolved.  You might want to study Python and Javascript together.Take a look at  and notice the Python-like nature of the new features.  \"array comprehensions\" are just like Python list comprehensions; iterators and generators are straight out of Python; \"destructuring assignments\" are a standard Python idiom.Javascript is kind of like Python with curly braces.  It uses a very different inheritance model, but libraries are available that implement a more Python-like class system on top of the built-in system in Javascript.Noone has mentioned it yet, but  is/was pretty coolNo. Browsers don't run Python.Have a look at this:It's an interactive python console + tutorial written with Silverlight+IronPython.On Windows, any language that registers for the Windows Scripting Host can run in IE. At least the ActiveState version of Python could do that; I seem to recall that has been superseded by a more official version these days.But that solution requires the user to install a python interpreter and run some script or .reg file to put the correct \"magic\" into the registry for the hooks to work.Python is available for the client: If its client side your interested may be worth checking out
Python

I have a situation like so...How can I access the  class's method from the  class? -- Thanks for the responses.  I'm concluding that I need to re-assess how I had designed this to be implemented and come up with a more robust method.The methods of a nested class cannot directly access the instance attributes of the outer class. Note that it is not necessarily the case that an instance of the outer class exists even when you have created an instance of the inner class.In fact, it is often recommended against using nested classes, since the nesting does not imply any particular relationship between the inner and outer classes.You're trying to access Outer's class instance, from inner class instance. So just use factory-method to build Inner instance and pass Outer instance to it.maybe I'm mad but this seems very easy indeed - the thing is to make your inner class inside a method of the outer class... Plus... \"self\" is only used by convention, so you could do this:It might be objected that you can't then create this inner class from outside the outer class... but this ain't true:then, somewhere miles away:even push the boat out a bit and extend this inner class (NB to get super() to work you have to change the class signature of mooble to \"class mooble( object )\"Do you mean to use inheritance, rather than nesting classes like this? What you're doing doesn't make a heap of sense in Python.You can access the 's some_method by just referencing  within the inner class's methods, but it's not going to work as you expect it will. For example, if you try this:...you'll get a TypeError when initialising an  object, because  expects to receive an  instance as its first argument. (In the example above, you're basically trying to call  as a class method of .)Building on the great idea an answer for the same question my answer is for (at ) explained, as I wanted to create my own good quality solution to the question, I came up with a Python answer that should be quite simple to understand.The main code, \"production ready\" (without comments, etc.). Remember to replace all of each value in angle brackets (e.g. ) with the desired value.\n  Insert before line 12 in the main code:\nThen insert into this function lines 5-6 (of the main code) and replace lines 4-7 with the following code:\nReplace line 6 with the following code:\nA class, named \"a\" () is created. It has subclasses that need to access it (the parent). One subclass is called \"x1\". In this subclass, the code  is run.Then another class, named \"b\" is created,  from class \"a\" (). After that, some code runs  (calling the sub function \"x1\" of b, a derived sub-class). This function runs , calling the function \"run_func\" of class \"a\",  the function \"run_func\" of its parent, \"b\" (as it should), because the function which was defined in class \"a\" is set to refer to the function of class \"a\", as that was its parent.This would cause problems (e.g. if function  has been deleted) and the only solution without rewriting the code in class  would be to redefine the sub-class  with updated code for all classes derived from class \"a\" which would obviously be difficult and not worth it.i found .Tweaked to suite your question, it is the answer:I\u2019m sure you can somehow write a decorator for this or something :)\n/edit: Another possibility:Expanding on @tsnorri's cogent thinking, that the outer method may be a :Now the line in question should work by the time it is actually called.The last line in the above code gives the Inner class a static method that's a clone of the Outer static method.  This takes advantage of two Python features, that , and ....or current  in our case. So objects \"local\" to the definition of the Outer class ( and ) may be referred to directly within that definition.You can easily access to outer class using metaclass: after creation of outer class check it's attribute dict for any classes (or apply any logic you need - mine is just trivial example) and set corresponding values:Using this approach, you can easily bind and refer two classes between each other.
Python

In the example code below, I'd like to recover the return value of the function .  How can I go about doing this?  Where is this value stored?I can't seem to find the relevant attribute in the objects stored in .Thanks in advance,\nblzUse  to communicate. For example like this:I think the approach suggested by @sega_sai is the better one. But it really needs a code example, so here goes:Which will print the return values:If you are familiar with  (the Python built-in) this should not be too challenging. Otherwise have a look at .Note how little code is needed. (Also note how processes are re-used).It seems that you should use the multiprocessing.Pool class instead and use the methods .apply() .apply_async(), map()You can use the  built-in to set the exit code of a process. It can be obtained from the  attribute of the process:This example shows how to use a list of  instances to return strings from an arbitrary number of processes:This solution uses fewer resources than a  which usesor a  which usesIt is very instructive to look at the source for each of these types.For anyone else who is seeking how to get a value from a  using :
Python

I am new to Python, and I have a question about how to use Python to read and write CSV files. My file contains like Germany, French, etc. According to my code, the files can be read correctly in Python, but when I write it into a new CSV file, the unicode becomes some strange characters.The data is like:\nAnd my code is:And the result is like:\nWould you please tell me what I should do to solve the problem? Thank you very much!Make sure you encode and decode as appropriate.This example will roundtrip some example text in utf-8 to a csv file and back out to demonstrate:Prints:There is an example at the end of the  that demonstrates how to deal with Unicode.  Below is copied directly from that .  Note that the strings read or written will be Unicode strings.  Don't pass a byte string to , for example.Input (UTF-8 encoded):Output:Another alternative: Use the code from the unicodecsv package ...This module is API compatible with the STDLIB csv module.I had the very same issue. The answer is that you are doing it right already. It is the problem of MS Excel. Try opening the file with another editor and you will notice that your encoding was successful already. To make MS Excel happy, move from UTF-8 to UTF-16. This should work:I couldn't respond to Mark above, but I just made one modification which fixed the error which was caused if data in the cells was not unicode, i.e. float or int data.  I replaced this line into the UnicodeWriter function: \"self.writer.writerow([s.encode(\"utf-8\") if type(s)==types.UnicodeType else s for s in row])\" so that it became:You will also need to \"import types\".
Python

In python how can you extend a class? For example if I havecolor.pycolor_extended.pyBut this doesn't work...\nI expect that if I work in , then when I make a color object and use the  function then it will return the object with the string \" extended!\" in the end. Also it should have gotton the init from the import.Assume python 3.1ThanksUse:If this were Python 2.x, you would also want to derive  from , to make it a :This is not necessary in Python 3.x.
Python

I need to package my python application, its dependencies and python into a single MSI installer. The end result should desirably be:Kind of a dup of this question about . It boils down to:  on windows,  on Linux, and\n on Mac.I use  (the svn version) to create a stand-alone  version of my program that includes Python and all the dependencies. It takes a little fiddling to get it to work right and include everything (as does py2exe and other similar programs, see ), but then it works very well.You then need to create an installer.  Works great for that and is free, but it creates .exe files not .msi. If .msi is not necessary, I highly recommend it. Otherwise check out the answers to  question for other options.My company uses the free InnoSetup tool.  It is a moderately complex program that has tons of flexibility for building installers for windows.  I believe that it creates .exe and not .msi files, however.  InnoSetup is not python specific but we have created an installer for one of our products that installs python along with dependencies to locations specified by the user at install time.I've had much better results with dependencies and custom folder structures using , and it lets you find and specify hidden imports and hooks for larger dependencies like numpy and scipy.  Also a PITA, though.py2exe is the best way to do this.  It's a bit of a PITA to use, but the end result works very well. will make windows executables with python bundled in.Ok, I have used py2exe before and it works perfectly except for one thing... It only works on executable windows machines. I then learned about Jython which turn a python script into a .Jar file. Which as you know is executable from any machine that has Java (\"To your latest running version\") installed. Which is great because both unix, windows, and ios (Most of the time) Run java. That means its executable from all of the following machines. As long as they run Java. No need for \"py2mac + py2exe + freeze\" just to run on all operating systems. Just JythonFor more information on how it works and how you can use it click here. \n
Python

Is there a simple way / module to  measure the elapsed time in python? I know that I can simply call  twice and take the difference, but that will yield wrong results if the system time is changed. Granted, that doesn't happen very often, but it does indicate that I'm measuring the wrong thing.Using  to measure durations is incredibly roundabout when you think about it. You take the difference of two absolute time measurements which are in turn constructed from duration measurements (performed by timers) and known absolute times (set manually or via ntp), that you aren't interested in at all.So, is there a way to query this \"timer time\" directly? I'd imagine that it can be represented as a millisecond or microsecond value that has no meaningful absolute representation (and thus doesn't need to be adjusted with system time). Looking around a bit it seems that this is exactly what  does in Java, but I did not find a corresponding Python function, even though it should (hardware-technically) be easier to provide than .Edit: To avoid confusion and address the answers below: This is not about DST changes, and I don't want CPU time either - I want elapsed physical time. It doesn't need to be very fine-grained, and not even particularly accurate. It just shouldn't give me negative durations, or durations which are off by several orders of magnitude (above the granularity), just because someone decided to set the system clock to a different value. Here's what the Python docs say about 'time.time()':This is exactly what I want to avoid, since it can lead to strange things like negative values in time calculations. I can work around this at the moment, but I believe it is a good idea to learn using the proper solutions where feasible, since the kludges will come back to bite you one day.Edit2: Some research shows that you can get a system time independent measurement like I want in Windows by using GetTickCount64(), under Linux you can get it in the return value of times(). However, I still can't find a module which provides this functionality in Python.What you seem to be looking for is a . A  does not jump or go backwards. There have been several attempts to implement a cross platform monotomic clock for Python based on the OS reference of it. (Windows, POSIX and BSD are quite different) See the discussions and some of the attempts at monotonic time in . Mostly, you can just use os.times():But that does not fill in the needed elapsed real time (the fifth tuple) on Windows. If you need Windows support, consider  and you can call GetTickCount64() directly, as has been done in .For measuring elapsed CPU time, look at . This is the equivalent of Linux's  user time field. For benchmarking, use . The , , also has microsecond time if supported by the platform.  Example:If you are concerned about system time changes (from DS -> ST) just check the object returned by datetime.Presumably, the system time could have a small adjustment from an  reference adjustment. , and corrections are , but ntp sync beats can have an effect with very small (millisec or microsec) time references. You can also reference  if you want something of that resolution. I would not go too far to reinvent the wheel. Accurate time is basic and most modern OS's do a pretty good job. Based on your clarifications, it sounds like you need a simple side check if the system's clock has changed. Just compare to a friendly, local ntp server:NTP is accurate to milliseconds over the Internet and has representation resolution of resolution of 2\u221232 seconds (233 picoseconds). Should be good enough?  Be aware that the NTP 64 bit data structure  -- if you really want a robust solution, better check for overflow...Python 3.3 added a  into the standard library, which does exactly what I was looking for. Thanks to Paddy3118 for pointing this out in .Using UTC avoids those embarassing periods when the clock shifts due to daylight saving time.As for using an alternate method rather than subtracting two clocks, be aware that the OS does actually contain a clock which is initialized from a hardware clock in the PC. Modern OS implementations will also keep that clock synchronized with some official source so that it doesn't drift. This is much more accurate than any interval timer the PC might be running.The example functions you state in your edit are two completely different things: Although two different functions, both (potentially) could be used to reveal a system clock that had a \"burp\" with these methods:You could take both a system time with  and a CPU time with . Since wall clock time will ALWAYS be greater than or equal to CPU time, discard any measurements where  the interval between the two  readings is less than the paired  check readings.Example:Getting system uptime is also promising if you are concerned about the system's clock, since a user reset does not reset the uptime tick count in most cases. (that I am aware of...)Now the harder question: getting system uptime in a platform independent way -- especially without spawning a new shell -- at the sub second accuracy. Hmmm...Probably the best bet is . , they use  for Windows and  for BSD / OS X, etc. Unfortunately, these are all 1 second resolution. 
Python

I have an OO hierarchy with docstrings that take as much maintenance as the code itself. E.g.,Now, the problem is that  does not inherit the superclass method's docstring. I know I can keep the docstring using the template method pattern, i.e.and implementing  in each subclass. However, I was wondering whether there's another way to have docstrings be inherited, perhaps some decorator that I hadn't discovered yet?Write a function in a class-decorator style to do the copying for you.  In Python2.5, you can apply it directly after the class is created.  In later versions, you can apply with the  notation.Here's a first cut at how to do it:In newer Python versions, the last part is even more simple and beautiful:This is a Pythonic technique that exactly matches the design of existing tools in the standard library.  For example, the  class decorator add missing rich comparison methods to classes.  And for another example,  the  decorator copies metadata from one function to another.This is a variation on .F.Y.I for people just now stumbling on this topic: As of Python 3.5,  automatically retrieves docstrings from the inheritance hierarchy.The responses above are thus useful for Python 2, or if you want to be more creative with merging the docstrings of parents and children.  I've also created some . These support some nice default docstring styles (numpy, google, reST) out of the box. You can easily use your own docstring style as well The following adaptation also handles properties and mixin classes. I also came across a situation where I had to use  (for \"instancemethod\"s), but I'm not completely sure why the other solutions didn't encouter that problem.
Python

From what I've been aware of, using  or  to instantiate objects returns a new instance of  or  respectively; a new instance object with . This was pretty clear to me until I actually tested it and I noticed that  actually returns  instead of the expected :as expected, this behavior is also manifested when creating objects with ,  and  respectively:The only relevant piece of information I could find in  states:Suffice to say, this isn't sufficient for answering my question. So, why do empty tuples have the same identity whilst others like lists or dictionaries do not?Python internally creates a  list of tuple objects whose first element contains the empty tuple. Every time  or  is used, Python will return the existing object contained in the aforementioned  list and not create a new one.Such mechanism does not exist for  or  objects which are, on the contrary, .This is most likely related to the fact that immutable objects (like tuples) cannot be altered and, as such, are guaranteed to not change during execution. This is further solidified when considering that  returns ; like  an empty  . With mutable objects,  and, as such, there's no incentive to cache their zero element instances (i.e their contents could change with the identity remaining the same).  In the most common case, the implementation of  is compiled with two macros  and  set to positive integers. The positive value for these macros results in the creation of an  with size .When  is called with the parameter  it makes sure to  to the list if it doesn't already exist:Then, if a new empty tuple is requested, the one that is located in the  is going to get returned instead of a new instance: One additional reason causing an incentive to do this is the fact that function calls construct a tuple to hold the positional arguments that are going to be used. This can be seen in the  function in :which is called via  in the same file. If the number of arguments  is zero, an empty tuple is going to be returned. In essence, this might be an operation that's performed frequently so it makes sense to not reconstruct an empty tuple every single time.A couple more answers shed light on 's caching behaviour with immutables:
Python

Building on:\n1 - ease of design / integration - learning curve2 - support / availability for *nix, Windows, Mac, extra points for native l&f, support for mobile or web3 - pythonic API4 - quality of documentation - I want to do something a bit more complicated, now what?5 - light weight packaging so it's not necessary to include a full installer (py2exe, py2app would ideally work as-is and not generate a gazillion MBs file)6 - licensing7 - others? (specify)1 - tkinter, as currently supported (as of 2.6, 3.0)2 - pyttk library3 - pyGTK4 - pyQt5 - wxPython6 - HTML-CGI via Python-based framework (Django, Turbogears, web.py, Pylons...) or Paste7 - others? (specify)Please don't hesitate to expand this answer.Tkinter is the toolkit that comes with python. That means you already have everything you need to write a GUI. What that also means is that if you choose to distribute your program, most likely everyone else already has what they need to run your program.Tkinter is mature and stable, and is (at least arguably) quite easy to use.I found it easier to use than wxPython, but obviously that's somewhat subjective. Tkinter gets a bad rap for looking ugly and out of date. While it's true that it's easy to create ugly GUIs with Tkinter, it's also pretty easy to create nice looking GUIs. Tkinter doesn't hold your hand, but it doesn't much get in the way, either. Tkinter looks best on the Mac and Windows since it uses native widgets there, but it looks OK on linux, too. The other point about the look of Tkinter is that, for the most part, look isn't as important as people make it out to be. Most applications written with toolkits such as Tkinter, wxPython, PyQT, etc are special-purpose applications. For the types of applications these toolkits are used for, usability trumps looks. If the look of the application is important, it's easy enough to polish up a Tkinter application.Tkinter has some features that other toolkits don't come close to matching. Variable traces, named fonts, geometry (layout) managers, and the way Tkinter processes events are still the standard to which other toolkits should be judged.   On the downside, Tkinter is a wrapper around a Tcl interpreter that runs inside python. This is mostly invisible to anyone developing with Tkinter, but it sometimes results in error messages that expose this architecture. You'll get an error complaining about a widget with a name like \".1245485.67345\" which will make almost no sense to anyone unless you're also familiar with how Tcl/tk works.Another downside is that Tkinter doesn't have as many pre-built widgets as wxPython. The hierarchical tree widget in Tkinter is a little weak, for example, and there's no built-in table widget. On the other hand, Tkinter's canvas and text widgets are extremely powerful and easy to use. For most types of applications you will write, however, you'll have everything you need. Just don't expect to replicate Microsoft Word or Photoshop with Tkinter. I don't know what the license is for Tkinter, I assume the same as for python as a whole. Tcl/tk has a BSD-style license. It's build on top of , a C++ framework. It's quite advanced and has some good tools like the Qt Designer to design your applications. You should be aware though, that it doesn't feel like Python 100%, but close to it. The  is excellentThis framework is really good. It's being actively developed by Trolltech, who is owned by Nokia. The bindings for Python are developed by Riverbank.PyQt is available under the GPL license or a commercial one. The price of a riverbank PyQt license is about 400 euro per developer.Qt is not only a GUI-framework but has a lot of other classes too, one can create an application by just using Qt classes. (Like SQL, networking, scripting, \u2026)Qt used to emulate GUI elements on every platform but now uses native styles of the platforms (although not native GUI toolkits): see  and Packaging is as simple as running py2exe or pyInstaller. The content of my PyQt app looks like this on windows (I have used InnoSetup on top of it for proper installation):QT comes with a widget designer and even in recent versions with an  to help design Qt software.PySide is a LGPL binding to Qt. It's developed by nokia as a replacement for the GPL PyQt.wxPython is a binding for Python using the -Framework. This framework is under the LGPL licence and is developed by the open source community.What I'm really missing is a good tool to design the interface, they have about 3 but none of them is usable.One thing I should mention is that I found a bug in the tab-view despite the fact that I didn't use anything advanced. (Only on Mac OS X) I think  isn't as polished as .wxPython is really only about the GUI-classes, there isn't much else.wxWidgets uses native GUI elements.An advantage wxPython has over Tkinter is that wxPython has a much larger library of widgets from which to choose from. I haven't got any experience with other GUI frameworks, maybe someone else has.I would definitely appreciate it if anyone knows of something better than what's commonly discussed; I see to have headaches finding something appropriate...Qt is great, but PyQt doesn't seem to have the same development resources. It seems to have some clever way to generate bindings, but isn't complete (e.g. PyKDE terminal kpart) and there is a dearth of documentation (as the developers admit). Compatibility with Qt's UI designer is nice.wxpython - controls aren't as nice looking, widget library isn't as large as KDE.OpenGL - doesn't even support fonts by default... pygame is okay, but opengl being a state machine is too annoying (object oriented models prevent making the a call in the wrong state).XUL - neat idea, I wish it worked. The  tutorial didn't work for me, though -- first I had to add the xulrunner /usr/lib path to LD_LIBRARY_PATH, then it still had problems with \"from xpcom import components\"...my wishlist for a ui library would beIn my experience, html is so much easier to get something good-looking up than UI libraries. - after working with PyQt 4 for a while, it gets the job done for simple UI's. I'm currently not developing for end users, so looks don't matter. The QTextBrowser is very useful for displaying basic HTML tables and generating HTML links..You can use either Swing, Applet, or other GUI frameworks available to Java platform. See  for  and . There are plenty of books and  such as .Here's a Hello world Swing application from .Here's a Jython  (60 lines).If you are just interested in drawing lines and circles you can probably cut it down to half.I'm just weighing in to say that TKinter sucks. It sadly seems that it is packed with Python because of backwards compatibility. The documentation is horrible. It looks horrible. I have run into some bizarre bugs that will actually crash Python.Pro wxPython
Python

I'm running Python 2.5, so this question may not apply to Python 3. When you make a diamond class hierarchy using multiple inheritance and create an object of the derived-most class, Python does the Right Thing (TM). It calls the constructor for the derived-most class, then its parent classes as listed from left to right, then the grandparent. I'm familiar with Python's ; that's not my question. I'm curious how the object returned from super actually manages to communicate to calls of super in the parent classes the correct order. Consider this example code:The code does the intuitive thing, it prints:However, if you comment out the call to super in B's init function, neither A nor C's init function is called. This means B's call to super is somehow aware of C's existence in the overall class hierarchy. I know that super returns a proxy object with an overloaded get operator, but how does the object returned by super in D's init definition communicate the existence of C to the object returned by super in B's init definition? Is the information that subsequent calls of super use stored on the object itself? If so, why isn't super instead self.super?Edit: Jekke quite rightly pointed out that it's not self.super because super is an attribute of the class, not an instance of the class. Conceptually this makes sense, but in practice super isn't an attribute of the class either! You can test this in the interpreter by making two classes A and B, where B inherits from A, and calling . It has no  or  attributes.Change your code to this and I think it'll explain things (presumably  is looking at where, say,  is in the ?):If you run it you'll see:Also it's worth checking out .I have provided a bunch of links below, that answer your question in more detail and more precisely than I can ever hope to. I will however give an answer to your question in my own words as well, to save you some time. I'll put it in points -\n\n\n\n\n\n\n\n\n  I hope this helps clear it up.just guessing: in all the four methods refer to the same object, that is, of class .\nso, in , the call to to  knows the whole diamond ancestry of  and it has to fetch the method from 'after' . in this case, it's the  class. knows the  class hierarchy.  This is what happens inside B's init:This resolves the central question,Namely, in B's init definition,  is an instance of , and thus communicates the existence of .  For example  can be found in .
Python

I'm looking for a python library for finding the longest common substring from a set of python strings.I'have read that it exist to way to solve this problem :\n- one using suffix trees\n- the other using dynamic programming.The method implemented is not important. Otherwise, it is important to have a implementation that can be use for a set of strings and not only two stringsThese paired functions will find the longest common string in any arbitrary array of strings:No doubt the algorithm could be improved and I've not had a lot of exposure to Python, so maybe it could be more efficient syntactically as well, but it should do the job. in-lined the second is_substr function as demonstrated by J.F. Sebastian. Usage remains the same. Note: no change to algorithm.Hope this helps,Jason.I prefer this for , as I find it a bit more readable and intuitive:From You could use the SuffixTree module that is a wrapper based on an ANSI C implementation of generalised suffix trees. The module is easy to handle....Take a look at:  This adds very little to jtjacques' answer. However, hopefully, this should be more readable  faster  it didn't fit in a comment, hence why I'm posting this in an answer. I'm not satisfied about , to be honest.This can be done shorter:set's are (probably) implemented as hash-maps, which makes this a bit inefficient. If you (1) implement a set datatype as a trie and (2) just store the postfixes in the trie and then force each node to be an endpoint (this would be the equivalent of adding all substrings), THEN in theory I would guess this baby is pretty memory efficient, especially since intersections of tries are super-easy.Nevertheless, this is short and premature optimization is the root of a significant amount of wasted time.If someone is looking for a generalized version that can also take a list of sequences of arbitrary objects:
Python

It is universally agreed that a list of n  symbols has n! permutations. However, when the symbols are not distinct, the most common convention, in mathematics and elsewhere, seems to be to count only distinct permutations. Thus the permutations of the list  are usually considered to be\n. Indeed, the following C++ code prints precisely those three:On the other hand, Python's  seems to print something else:This printsAs user Artsiom Rudzenka pointed out in an answer, the  says so:My question: why was this design decision made? It seems that following the usual convention would give results that are more useful (and indeed it is usually exactly what I want)... or is there some application of Python's behaviour that I'm missing? [Or is it some implementation issue? The algorithm as in  \u2014 for instance explained on StackOverflow  and  \u2014 seems efficient and implementable in Python, but is Python doing something even more efficient since it doesn't guarantee lexicographic order based on value? And if so, was the increase in efficiency considered worth it?]I can't speak for the designer of  (Raymond Hettinger), but it seems to me that there are a couple of points in favour of the design:First, if you used a -style approach, then you'd be restricted to passing in objects that support a linear ordering. Whereas  provides permutations of  kind of object. Imagine how annoying this would be:Second, by not testing for equality on objects,  avoids paying the cost of calling the  method in the usual case where it's not necessary.Basically,  solves the common case reliably and cheaply. There's certainly an argument to be made that  ought to provide a function that avoids duplicate permutations, but such a function should be in addition to , not instead of it. Why not write such a function and submit a patch?I'm accepting the answer of Gareth Rees as the most appealing explanation (short of an answer from the Python library designers), namely, that Python's  doesn't compare the values of the elements. Come to think of it, this is what the question asks about, but I see now how it could be seen as an advantage, depending on what one typically uses  for.Just for completeness, I compared three methods of generating all  permutations. Method 1, which is very inefficient memory-wise and time-wise but requires the least new code, is to wrap Python's , as in zeekay's answer. Method 2 is a generator-based version of C++'s , from . Method 3 is something I wrote that is even closer to ; it modifies the list in-place (I haven't made it too general).Here are some results. I have even more respect for Python's built-in function now: it's about three to four times as fast as the other methods when the elements are all (or almost all) distinct. Of course, when there are many repeated elements, using it is a terrible idea.The code is  if anyone wants to explore.It's fairly easy to get the behavior you prefer by wrapping , which might have influenced the decision. As described in the documentation,  is designed as a collection of building blocks/tools to use in building your own iterators.However, as pointed out in the comments, this might not be quite as efficient as you'd like:Perhaps if there is enough interest, a new function or an optional argument to  could be added to , to generate permutations without duplicates more efficiently.I find also surprising that  doesn't have a function for the more intuitive concept of unique permutations. Generating repetitive permutations only to select the unique among them is out of the question for any serious application.I have written my own iterative generator function which behaves similarly to  but does not return duplicates. Only permutations of the original list are considered, sublists may be created with the standard  library.Maybe i am wrong but seems that reason for this is in  \nYou have specified (1,1,2) and from your point of view 1 at the 0 index and 1 at the 1 index are the same - but this in not so since permutations python implementation used indexes instead of values.So if we take a look at the default python permutations implementation we will see that it uses indexes:For example if you change your input to [1,2,3] you will get correct permutations([(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]) since the values are unique.
Python

CPython has a strange behaviour where it sets modules to None during shutdown. This screws up error logging during shutdown of some multithreading code I've written.I can't find any documentation of this behaviour. It's mentioned in passing in :There are  and the .I've also found a  and a :Where is this behaviour documented? Is it Python 2 specific?The behaviour is  well documented, and is present in all versions of Python from about 1.5-ish :The only documentation for the behaviour is the :Note that setting the values to  is an optimisation; the alternative would be to delete names from the mapping, which would lead to different errors ( exceptions rather than s when trying to use globals from a  handler).As you found out on the mailinglist, the behaviour predates the cyclic garbage collector; it was , while the cyclic garbage collector was . Since function objects always reference the module  all function objects in a module involve circular references, which is why the  needed clearing before GC came into play.It was kept in place even when cyclic GC was added, because there might be objects with  methods involved in cycles. These , and cleaning out the module dictionary would at least remove the module  from such cycles. Not doing that would keep  referenced globals of that module alive.The changes made for  now make it possible for the garbage collector to clear cyclic references with objects that provide a  finalizer, removing the need to clear the module  . The code is  but this is only triggered if the  attribute is still alive even after moving the contents of  to weak references and starting a GC collection run when the interpreter is shutting down; the module finalizer simply decrements their reference count.There is a small amount of related documentation at the :
Python

I don't understand the difference between  and  in pymongo. On the , it saysHowever in pymongo there are two different commands  and , and the documentation for create index has:Am I right in understanding that  will create a permanent index, or do I need to use  for this?Keep in mind that in Mongo 3.x  is deprecated and should be discouraged.The same is in :Which means that you should always use .@andreas-jung is right in that  is a wrapper over , I think the confusion arises with the phrase:It's not that the index is temporary or \"transient\", what happens is that during the specified amount of seconds, a call to  trying to create the same index again will  have any effect and will  call  underneath, but after that \"cache\" expires, a call to   again call  underneath.I perfectly understand your confusion because quite frankly PyMongo's docs don't make a very good job at explaining how this works, but if you head over to the , the explanation is a little clearer:I'm not claiming drivers work exactly the same, it's just that for illustration purposes their explanation is a little better IMHO.The  method in the Interactive Shell and  in the python driver are different things, although the same word is used. Both the  and  method from the python driver create an index permanently.Maybe one would use  with a reasonable TTL in such a situation, because I am not sure if  would recreate the index each time you call it. Recreation normally is not desired and it could be a heavy operation. But even  (of the python or also ruby driver) could possibly recreate the index whenever the TTL is expired or when you call it from a different client instance or after a restart. I am not sure about this.Maybe an even better possibility is to first check, using the method , if the index already exists. If it already exists you would not create it again.I am now demonstrating how the term  (or ) is used with 2 different meanings:This is what the  method  does:Also the  behaves this way:(Search for  in the file .)The same identifier is used with a different meaning here, which I find confusing.The python and the ruby driver store information in memory about indexes that were created recently, and they call this behaviour 'caching'. They do not tell the database about this caching. The result of this mechanism is, if you call  or  for the first time with a TTL value (time to live), then the driver will insert the index in the database and will remember this insertion and also store the TTL information in memory. What is cached here is the time and which index it was.The next time you call  with the same index of the same collection on the same driver instance, the  command will only insert the index again, if TTL seconds have not yet passed since the first call.If you call , the index will always be inserted, no matter how much time passed since the first call, and of course also if this is the first call.This is the python driver, search for  in the file :And the ruby driver, search for  in the file :(Note that different client instances do not know about the caching of the others, this information is kept in memory only and it is per instance. If you restart the client application the new instance does not know about the old 'cached' index inserts. Also other clients do not know, they do not tell each other.)I was not yet able to fully understand, what happens in the db, when the python driver or the ruby driver insert an index that is already there. I would suspect they do nothing in this case, which makes more sense and would also match the behaviour of the  and the JS driver. indexes are permanent.\nensure_index() is just a tiny wrapper around create_index().\"\"\"\nThe ensureIndex() function only creates the index if it does not exist.\n\"\"\"There is nothing like a transient index or a temporary index.I would recommend creating metaclass and ORM.\nFrom metaclass  call init_schema method for initializing the counters, schema, keys etc.\nThis way you prevent calling ensure_index every query or collection update :)
Python

With Python 3:I wanted to check for equality:But:Do you know why values are not equal?I've tested this with Python 3.4 and 3.5.In Python 3,  and  return special iterable classes - respectively a  and a . The first one inherit it's  method from , the second uses the default  which tests on object identity. In python3,  and  are  objects:Don't compare them as an  object, c\nonvert them to lists and then compare them:Investigating why it works for comparing keys, in  of CPython,  is inheriting from  while  does not:Unfortunately, both current answers don't address why this is but focus on how this is done. That mailing list discussion was amazing, so I'll sum things up:For / and /: Now, about /:As stated in a comment by  and by  in the mailing list, / is a multiset, a generalization of sets that allows multiple instances of it's elements. \nTrying to compare these is not as trivial as comparing  or  due to the inherent duplication, the ordering and the fact that you probably need to take into consideration the keys that correspond to those values. Should  that look like this: actually be equal even though the values that correspond to the keys isn't the same? Maybe? Maybe not? It isn't straight-forward either way and will lead to inevitable confusion.The point to be made though is that it isn't trivial to compare these as is with  and , to sum up, with another comment from @abarnett on :
Python

I want to remove a Python installed in location that brew complains about, when I run The message from the brew git : \nSpecifically, I want to remove the entire Python.framework, those files located here. \n/Library/Frameworks/Python.framework/I have Python 2.7.5 installed natively with Mavericks that I'll use instead - located in the path below. (The difference being -- I believe -- that its put in the  instead of the .) The good, native location is here:\nand I already installed python 3.x with , which put it here:Can I just delete these files or are their consequences (beyond having to relink)?\nHere are steps to remove python from a  and a Is that approach still sound? Is there anything I should be aware of?I'll self-answer. I went through steps and it's straight forward. Pycharms (the IDE I'm use) automatically found the new libraries too. Here are the steps I followed to remove the extra Python libraries on Mavericks that were not native to it and not installed by brew.\nThe native Python 2.7.x version lives here  (or 2.6, etc), so you can remove any Python that got installed elsewhere.Or, according to this , you should brew install both python 2.7 and python 3.x,\nand avoid using system python in Mavericks.\nRemove python in Applications directory (the one where all your apps are). cd into folder  and  to see what have. Then remove:\nsample output: Run steps recommended by Sample output
Python

I'm getting an error when trying to execute python program that uses multiprocessing package:It looks like the user doesn't have permission to access shared memory. When executing with root privileges it works fine.Is there any solution to run it as normal user(not root)?Python version 2.6.2 , OS is Linux 2.6.18 (CentOS release 5.4) and it's VPS machine.For POSIX semaphores to work, the users need r/w access to shared memory ().Check the permissions to . On my laptop (Ubuntu) it looks like this:To permanently set the correct permissions (even after a reboot), add the following to your :Haven't tried this, just copied from a .In my OVH VPS Classic, this error was caused by a loop in /dev/shm and /run/shm.\nBoth were symlinks linking to each other.\nSo as root here is what I did:Then I modified the shm line from:To:Restarted the server... And that fixed the problem!\nAlternatively you can mount shm manually:Hope this helps :-)
Python

In my view function I want to call another view and pass data to it :, where backend is of registration.backends object, and form.cleaned_data is a dict of form data (but both must be either sent as *args or **kwargs to prevent raising  error). From what I've found in the docs :It looks like I need to provide 'some-view-name' argument, but is it just the name of the view function, or the name of the url ? So I would like to make it similar to the way it's done in django-registration, where :Ok so now, can I call directly my view function or do I need to provide a url for it ? And what more important, how my funciotn call (and a url if needed) should look like ? Both backend, and cleaned_data are just passed through this view for a later usage. I've tried this, but it's improper :  As well as this :still NoReverseMatch . But in django-registration, I've seen something like this :Firstly, your URL definition does not accept any parameters at all. If you want parameters to be passed from the URL into the view, you need to define them in the urlconf.Secondly, it's not at all clear what you are expecting to happen to the cleaned_data dictionary. Don't forget you can't redirect to a POST - this is a limitation of HTTP, not Django - so your cleaned_data either needs to be a URL parameter (horrible) or, slightly better, a series of GET parameters - so the URL would be in the form:and so on. In this case, field1, field2 and field3 are  included in the URLconf definition - they are available in the view via .So your urlconf would be:and the view would look like:and the reverse would be (after importing ):The whole point of using redirect and reverse, as you have been doing, is that you go to the URL - it returns an Http code that causes the browser to redirect to the new URL, and call that.If you simply want to call the view from within your code, just do it directly - no need to use reverse at all.That said, if all you want to do is store the data, then just put it in the session:urls.py:views.py:
Python

I have a vpn connection and when I'm running python -m SimpleHTTPServer, it serves on 0.0.0.0:8000, which means it can be accessed via localhost  via my real ip.\nI don't want robots to scan me and interested that the server will be accessed only via localhost.Is it possible? Any other simple http server which can be executed instantly using the command line is also welcome.If you read the source you will see that only the port can be overridden on the command line.  If you want to change the host it is served on, you will need to implement the  method of the  and  yourself.  But that should be really easy.Here is how you can do it, pretty easily:And to use it:  As  explained, simply doing it by using the nice  method won't be possible, because the IP address is hardcoded in the implementation of the  function.A way of doing it from the command line without writing code to a file first would beIf that still counts as a one liner depends on your terminal width ;-) It's certainly not very easy to remember.In Python versions 3.4 and higher, the  module accepts a  parameter.According to the docs:
Python

So I want to create a list which is a sublist of some existing list.For example,, I want to create a sublist  such that  contains all the elements in  at odd positions.While I can do it byBut I want to know if there is another way to do the same efficiently and in fewer number of steps. Yes, you can:And this is all. The result will contain the elements placed on the following positions (-based, so first element is at position , second at  etc.):so the result (actual numbers) will be:The  at the end is just a notation for list slicing. Usually it is in the following form:If we omitted , the default () would be used. So the first element (at position , because the indexes are -based) would be selected. In this case the second element will be selected.Because the second element is omitted, the default is being used (the end of the list). So the list is being iterated .We also provided third argument () which is . Which means that one element will be selected, the next will be skipped, and so on...So, to sum up, in this case  means:: @PreetKukreti gave a link for another explanation on Python's list slicing notation. See here: In your code, you explicitly create and increase the counter. In Python this is not necessary, as you can enumerate through some iterable using :The above serves exactly the same purpose as the code you were using:More on emulating  loops with counter in Python: For the  positions, you probably want:I like List comprehensions because of their Math (Set) syntax. So how about this:Basically, if you enumerate over a list, you'll get the index  and the value . What I'm doing here is putting the value  into the output list (even or odd) and using the index  to find out if that point is odd ().
Python

I am re-factoring my Flask application by scattering the models, blueprints but I am having a runtime error. I have the following problem(the sample project are hosted here: ):I did a research on this topic. The re-factoring is suggested here:The same problem was raised here:And the above thread(2010) suggested a hack like this:Did anyone know how to do this properly? How did you solve it?ThanksThis has to do with Flask's . When initialized with , Flask-SQLAlchemy doesn't know which app is the \"current\" app (remember, Flask allows for  in the same interpreter). You could have multiple apps using the same  instance in the same process, and Flask-SQLAlchemy would need to know which is the \"current\" one (due to Flask's  nature of everything).If you need to do this during runtime, you must explicitly say which app is the \"current\" app for all calls. You can do this by changing your code to do the following:If you are writing a standalone script that needs the app context, you can push the context at the beginning rather than putting everything in a  block.If you write a command for Flask's  the command will automatically have access to the context.Mark's answer was great and it helped me a lot.  However, another way to approach this is to run the code that relies on the app context in a function decorated with @app.before_first_request.  See  for more information.  That's in fact how I ended up doing it, largely because I wanted to be able to call the initialization code outside of flask as well, which I handle this way.In my case I want to be able to test SQLAlchemy models as plain SQLAlchemy models without Flask-SQLAlchemy, though the db in the code below is simply a (Flask) SQLAlchemy db.
Python

Both my professor and  claim that  creates a list of values. I believe this is to be inaccurate because:Furthermore, the only apparent way to access the integers created by  is to iterate through them, which leads me to believe that labeling  as a lists is incorrect.In Python 2.x,  returns a list, but in Python 3.x  returns an immutable sequence, of type .In Python 2.x, if you want to get an iterable object, like in Python 3.x, you can use  function, which returns an immutable sequence of type .Advantage of  over  in Python 2.x:Nope. Since  objects in Python 3 are immutable sequences, they support indexing as well. Quoting from the  function documentation,For example,All these are possible with that immutable  sequence.Recently, I faced a problem and I think it would be appropriate to include here. Consider this Python 3.x codeOne would expect this code to print every ten numbers as a list, till 99. But, it would run infinitely. Can you reason why?In python-2.x,  actually creates a list (which is also a sequence) whereas  creates an  object that can be used to iterate through the values.On the other hand, in python-3.x,  creates an iterable (or more specifically, a sequence)range creates a list if the python version used is 2.x .\nIn this scenario range is to be used only if its referenced more than once otherwise use xrange which creates a generator there by redusing the memory usage  and sometimes time as it has lazy approach. xrange is not there in python 3.x rather range stands for what xrange is for python 2.xrefer to question\n 
Python

For an exercise I'm doing, I'm trying to read the contents of a given file twice using the  method. Strangely, when I call it the second time, it doesn't seem to return the file content as a string?Here's the codeOf course I know that this is not the most efficient or best way, this is not the point here. The point is, why can't I call  twice? Do I have to reset the file handle? Or close / reopen the file in order to do that?Calling  reads through the entire file and leaves the read cursor at the end of the file (with nothing more to read). If you are looking to read a certain number of lines at a time you could use  ,  or iterate through lines with .To answer your question directly, once a file has been read, with  you can use  to return the read cursor to the start of the file (docs are ). If you know the file isn't going to be too large, you can also save the  output to a variable, using it in your findall expressions.Ps. Dont forget to close the file after you are done with it ;)The read pointer moves to after the last read byte/character. Use the  method to rewind the read pointer to the beginning.Everyone who has answered this question so far is absolutely right -  moves through the file, so after you've called it, you can't call it again.What I'll add is that in your particular case, you don't need to seek back to the start or reopen the file, you can just store the text that you've read in a local variable, and use it twice, or as many times as you like, in your program:yeah, as above...i'll write just an example:Every open file has an associated position.\nWhen you read() you read from that position.\nFor example  reads the first 10 bytes from a newly opened file, then another  reads the next 10 bytes.\n without arguments reads all of the contents of the file, leaving the file position at the end of the file. Next time you call  there is nothing to read.You can use  to move the file position. Or probably better in your case would be to do one  and keep the result for both searches. . So, you could  the file, or  to the start before re-reading. Or, if it suites your task, you can use  to consume only  bytes.I always find the read method something of a walk down a dark alley. You go down a bit and stop but if you are not counting your steps you are not sure how far along you are. Seek gives the solution by repositioning, the other option is Tell which returns the position along the file. May be the Python file api can combine read and seek into a read_from(position,bytes) to make it simpler - till that happens you should read .
Python

Say I have an array :I would like to convert it to a 1D array (i.e. a column vector):but this returnswhich is not the same as:I can take the first element of this array to manually convert it to a 1D array:but this requires me to know how many dimensions the original array has (and concatenate [0]'s when working with higher dimensions)Is there a dimensions-independent way of getting a column/row vector from an arbitrary ndarray?Use  (for a 1D view) or  (for a 1D copy) or  (for an 1D iterator):Note that  returns a  of  when possible. So modifying  also modifies .  returns a  when the 1D elements are contiguous in memory, but would return a  if, for example,  were made from slicing another array using a non-unit step size (e.g. ).If you want a copy rather than a view, useIf you just want an iterator, use :or, simply:
Python

I'm trying to write a custom filter method that takes an arbitrary number of  and returns a list containing the elements of a database-like list that contain those .For example, suppose  and  = the same thing.  results in True. But suppose  = the same thing plus a bunch of other things. My method needs to be able to tell if , but Python can't do that with dictionaries.Context:I have a Word class, and each object has properties like , , , and so on. I want to be able to call a filter method on the main list of these words, like . I can't figure out how to manage these keys and values at the same time. But this could have larger functionality outside this context for other people.Convert to item pairs and check for containment.Optimization is left as an exercise for the reader.Note for people that need this for unit testing: there's also an  method in Python's  class.It's however deprecated in 3.2, not sure why, maybe there's a replacement for it.for keys and values check use: \nif you need to check only keys:\n        context:For completeness, you can also do this:However, I make no claims whatsoever concerning speed (or lack thereof) or readability (or lack thereof).In Python 3, you can use  to get a set-like view of the dict items.  You can then use the  operator to test if one view is a \"subset\" of the other:In Python 2.7, use the  to do the same:In Python 2.6 and below you will need a different solution, such as using :This seemingly straightforward issue costs me a couple hours in research to find a 100% reliable solution, so I documented what I've found in this answer.My function for the same purpose, doing this recursively:In your example,  should return True even if d2 has other stuff in it, plus it applies also to lower levels:Notes:  There could be even better solution which avoids the  clause and applies to even wider range of cases (like lists of hashes etc).  Also recursion is not limited here so use at your own risk. ;)This function works for non-hashable values. I also think that it is clear and easy to read.
Python

I have a named tuple class in python What I'd like to do is turn this into a dictionary. I'll admit python is not one of my stronger languages. The key is that I dont want it to be rigidly tied to the name or numbers of the fields I have. Is there a way to write it such that I could add more fields, or pass an entirely different named tuple in and get a dictionary.Edit: I cant not alter the original class definition as its in someone elses code. So I need to take an instance of a Town and convert it to a dictionary.Here is a demonstration of the usage:This is a  of namedtuples, i.e. unlike the usual convention in python .  Along with the other methods added to namedtuples, , , , , it has the underscore only to try and prevent conflicts with possible field names.  For some 2.7.5 < python version < 3.5.0 code out in the wild, you might see this version:For a while the documentation had mentioned that  was obsolete (see ), and suggested to use the built-in method .  That advice is now outdated; in order to fix  related to subclassing, the  property which was present on namedtuples has again been removed by .  There's a built in method on  instances for this, .As discussed in the comments, on some versions  will also do it, but it's apparently highly dependent on build details, whereas  should be reliable. In some versions  was marked as deprecated, but comments indicate that this is no longer the case as of 3.4.On Ubuntu 14 LTS versions of python2.7 and python3.4 the  property worked as expected. The   also worked, but I'm inclined to use the standards-defined, uniform, property api instead of the localized non-uniform api.$ python2.7Seeing as  is the semantic way to get a dictionary representing soemthing, (at least to the best of my knowledge).It would be nice to accumulate a table of major python versions and platforms and their support for , currently I only have one platform version and two python versions as posted above.Python 3. Allocate any field to the dictionary as the required index for the dictionary, I used 'name'. 
Python

this is just for academic interest. I encounter the following situation a lot.is there any pythonic way of doing it, or in general better programming way of doing it.\nBasically do something3 executes only if or elif is true.Your code is  optimal, as far as code repetition and evaluation are concerned. The only thing I can think of to avoid repetition would be:This removes one assignment, although the total number of lines doesn't change.The advantage is that this works with  conditions, without adding any other assignment, while your current solution requires an  for every condition.In my opinion they have about the same degree of readability, but the above code will be better with more conditions.Also there's no \"pythonic\" way other then a readable solution that avoids code repetition and is optimal in terms of efficiency, and I don't know of any kind of \"better programming\" to achieve the same result.You could also omit the  flag completely if  is a single line of code (e.g. a function call):It maintains the nice property of evaluating  and  at most once (and  won't be evaluated if  is true).I would handle this by using nested if statements i.e.As some comments have pointed out, the best solution will depend on what x & y are. If easy readability / concise code is your goal then this or other answers given should be fine. If however x & y were expensive function calls then it would be better to do something more like what you have done to avoid calling the function twice.You could wrap some of it in a function:Or all of it in a function:In the spirit of offering a completely different solution to those already proposed, you could set up a list structured dictionaries which allows you to set up multiple cases bound to your predefined \"somethings\"I actually really like this method (and I've only just discovered it when trying to come up with a unique answer to this question, thanks!) - it's really obvious which case is bound to which action, and it's easy to add several more cases without adding any more if/else statements. Of course, this does evaluate  twice.  Usually that's not a big deal, but if it is expensive, you can always evaluate that upfront and save it to a temporary variable.For all of these suggestions and any others you come up with, note that if  and  are expensive expressions:you can assign the values these expressions return to quick-to-evaluate variables first:I would wrap the ..do somethings in functions and write one if-elif:This is nice if the .. do somethings involve a lot of stuff.if do something is quite short, like do(1), do(2) or something like that, you can just do it like this:
Python

I need to make some command line calls to linux and get the return from this, however doing it as below is just returning  when it should return a time value, like , I am testing the exact same call in regular command line and it returns the time value  so I am confused as to what I am doing wrong as I thought this was how to do it in python. Any advice is appreciated.What gets returned is the return value of executing this command. What you see in while executing it directly is the output of the command in stdout. That 0 is returned means, there was no error in execution.Use popen etc for capturing the output .Some thing along this line:or ON SO : If you're only interested in the output from the process, it's easiest to use subprocess'  function:Then output holds the program output to stdout. Check the link above for more info.Your code returns  if the execution of the commands passed is successful and non zero if it fails. The following program works on python2.7, haven checked 3 and versions above. Try this code.Yes it's counter-intuitive and does not seem very pythonic, but it actually just mimics the unix API design, where these calld are C POSIX functions. Check  && Somewhat more convenient snippet to replace  that I use: The simplest way is like this:This will be returned as a listThis is an old thread, but purely using , the following's a valid way of accessing the data returned by the  call. Note: it does use a pipe to write the data to a file on disk.  OP didn't specifically ask for a solution using . accordingly,No idea why they are all returning zeroes though.For your requirement, Popen function of subprocess python module is the answer. For example,I can not add a comment to  because I do not have \"50 reputation\" so\nI will add a new entry.  My apologies.   is the best for multiple/complicated commands (my opinion) and also for getting the return value in addition to getting stdout like the following more complicated multiple commands:This will list all python files that have the word  anywhere in their name.  The  is a list comprehension to remove (strip) the newline character from each entry.  The  is a shell command to show the return status of the last command executed which will be the grep command and the last item of the list in this example.  the  says to print the  of the  command to  so it does not show up in the output.  The  before the  command is to use the raw string so the shell will not interpret metacharacters like  incorrectly.  This works in python 2.7.  Here is the sample output:okey I believe the fastest way it would be
Python

Suppose I have a model like this:Can I create a dictionary, and then insert or update the model using it?Here's an example of create using your dictionary d:To update an existing model, you will need to use the QuerySet  method.  Assuming you know the  of the Book you want to update:If you know you want to create it:Assuming you need to check for an existing instance, you can find it with get or create:As mentioned in another answer, you can also use the  function on the queryset manager, but i believe that will not send any signals out (which may not matter to you if you aren't using them). However, you probably shouldn't use it to alter a single object:Use  for creating a new model. Loop through the dictionary and use  in order to update an existing model.From Tom Christie's Django Rest Framework
Python

I have a long sequence of hex digits in a string, such as only much longer, several kilobytes.  Is there a builtin way to convert this to a bytes object in python 2.6/3?Works in Python 2.7 and higher including python3: There seems to be a bug with the  function in Python 2.6. The python.org documentation states that the function accepts a string as an argument, but when applied, the following error is thrown: You can do this with the hex codec.  ie:Try the 
Python

Problem: When POSTing data with Python's urllib2, all data is URL encoded and sent as Content-Type: application/x-www-form-urlencoded.  When uploading files, the Content-Type should instead be set to multipart/form-data and the contents be MIME encoded. A discussion of this problem is here:\nTo get around this limitation some sharp coders created a library called MultipartPostHandler which creates an OpenerDirector you can use with urllib2 to mostly automatically POST with multipart/form-data. A copy of this library is here:\nI am new to Python and am unable to get this library to work. I wrote out essentially the following code. When I capture it in a local HTTP proxy, I can see that the data is still URL encoded and not multi-part MIME encoded. Please help me figure out what I am doing wrong or a better way to get this done. Thanks :-)EDIT1: Thanks for your response. I'm aware of the ActiveState httplib solution to this (I linked to it above). I'd rather abstract away the problem and use a minimal amount of code to continue using urllib2 how I have been. Any idea why the opener isn't being installed and used?It seems that the easiest and most compatible way to get around this problem is to use the 'poster' module.This worked perfect and I didn't have to muck with httplib. The module is available here:\nFound this recipe to post multipart using  directly (no external libraries involved)Just use , it will set proper headers and do upload for you:I what a coincide, 2 years, 6 months ago I create the project  , that fix MultipartPostHandler for utf-8 systems. I also have done some minor improvements , you are welcome to test it :) I ran into the same problem and I needed to do a multipart form post without using external libraries. I wrote a whole .I ended up using a modified version of . The code in that url actually just appends the content of the file as a string, which can cause problems with binary files. Here's my working code.To answer the OP's question of why the original code didn't work, the handler passed in wasn't an instance of a class.  The lineshould read
Python

I have:I wanted to make the  statements into a few statements. No. The method for appending an entire sequence is .No.First off,  is a function, so you can't write  because you're trying to get a slice of a thing that isn't a sequence. (You can't get an element of it, either:  is wrong for the same reason.) When you call a function, the argument goes in , i.e. the round ones: . Second, what you're trying to do is \"take a sequence, and put every element in it at the end of this other sequence, in the original order\". That's spelled .  is \"take this thing, and put it at the end of the list, , \". (Recall that a list is a kind of sequence.)But then, you need to be aware that  is a special construct that appears only inside square brackets (to get a slice from a sequence) and braces (to create a  object). You cannot pass it to a function. So you can't  with that. You need to make a sequence of those values, and the natural way to do this is with the  function.You could also:
Python

So let's say I wanna make a dictionary. We'll call it . But there are multiple ways to initialize a dictionary in Python! For example, I could do this:Or I could do this:Or this, curiously:Or this:And a whole other multitude of ways with the  function. So obviously one of the things  provides is flexibility in syntax and initialization. But that's not what I'm asking about.Say I were to make  just an empty dictionary. What goes on behind the scenes of the Python interpreter when I do  versus ? Is it simply two ways to do the same thing? Does using  have the  call of ? Does one have (even negligible) more overhead than the other? While the question is really completely unimportant, it's a curiosity I would love to have answered.dict() is apparently some C built-in. A really smart or dedicated person (not me) could look at the interpreter source and tell you more. I just wanted to show off dis.dis. :)As far as performance goes:@Jacob: There is a difference in how the objects are allocated, but they are not copy-on-write.  Python allocates a fixed-size \"free list\" where it can quickly allocate dictionary objects (until it fills).  Dictionaries allocated via the  syntax (or a C call to ) can come from this free list.  When the dictionary is no longer referenced it gets returned to the free list and that memory block can be reused (though the fields are reset first).This first dictionary gets immediately returned to the free list, and the next will reuse its memory space:If you keep a reference, the next dictionary will come from the next free slot:But we can delete the reference to that dictionary and free its slot again:Since the  syntax is handled in byte-code it can use this optimization mentioned above.  On the other hand  is handled like a regular class constructor and Python uses the generic memory allocator, which does not follow an easily predictable pattern like the free list above.Also, looking at compile.c from Python 2.6, with the  syntax it seems to pre-size the hashtable based on the number of items it's storing which is known at parse time.Basically, {} is syntax and is handled on a language and bytecode level. dict() is just another builtin with a more flexible initialization syntax. Note that dict() was only added in the middle of 2.x series.: thanks for the responses.  Removed speculation about copy-on-write.One other difference between  and  is that  always allocates a new dictionary (even if the contents are static) whereas  doesn't  do so (see  for when and why):produces:I'm not suggesting you try to take advantage of this or not, it depends on the particular situation, just pointing it out.  (It's also probably evident from the  if you understand the opcodes).dict() is used when you want to create a dictionary from an iterable, like :In order to create an empty set we should use the keyword set before it \ni.e  this creates an empty set where as in dicts only the flower brackets can create an empty dictLets go with an example 
Python

I'm trying to write an  function for one of my models so that I can create an object by doingWhen I write the model, I have This works, and I can save the object to the database, but when I do 'User.objects.all()', it doesn't pull anything up unless I take out my  function.  Any ideas?Relying on Django's built-in functionality and passing named parameters would be the simplest way to go.But if you're set on saving some keystrokes, I'd suggest adding a static convenience method to the class instead of messing with the initializer.Django expects the signature of a model's constructor to be , or some reasonable facsimile. Your changing the signature to something completely incompatible has broken it.The correct answer is to avoid overriding  and write a classmethod as described in the .But this could be done like you're trying, you just need to add in  to be accepted by your , and pass them on to the super method call.Don't create models with args parameters.  If you make a model like so:It becomes very unreadable very quickly as most models require more than that for initialization. You could very easily end up with:Another problem here is that you don't know whether 'Bert' is the first or the last name.  The last two numbers could easily be a phone number and a system id.  But without it being explicit you will more easily mix them up, or mix up the order if you are using identifiers.  What's more is that doing it order-based will put yet another constraint on other developers who use this method and won't remember the arbitrary order of parameters.You should prefer something like this instead:If this is for tests or something like that, you can use a factory to quickly create models.  The factory boy link may be useful: 
Python

I've tried different methods from other questions but still can't seem to find the right answer for my problem.  The critical piece of this is that if the person is counted as Hispanic they can't be counted as anything else.  Even if they have a \"1\" in another ethnicity column they still are counted as Hispanic not a two or more races.  Similarly, if the sum of all the ERI columns is greater than 1 they are counted as two or more races and can't be counted as a unique ethnicity(accept for Hispanic).  Hopefully this makes sense.  Any help will be greatly appreciated. Its almost like doing a for loop through each row and if each record meets a criteria they are added to one list and eliminated from the original.  From the dataframe below I need to calculate a new column based off of the following:=========================  CRITERIA  ===============================Comment: If the ERI Flag for Hispanic is True (1), then employee is classified as \u201cHispanic\u201dComment: If more than 1 non-Hispanic ERI Flag are true, return \u201cTwo or More\u201d======================  DATAFRAME ===========================In [13]: df1Out [13]: OK, two steps to this - first is to write a function that does the translation you want - I've put an example together based on your pseudo-code:You may want to go over this, but it seems to do the trick - notice that the parameter going into the function is considered to be a Series object labelled \"row\".Next, use the apply function in pandas to apply the function - e.g.Note the axis=1 specifier, that means that the application is done at a row, rather than a column level. The results are here:If you're happy with those results, then run it again, posting the results into a new column in your original dataframe.The resultant dataframe looks like this (scroll to the right to see the new column):
Python

I am interested to trigger a certain action upon receiving an email from specific \naddress with specific subject. In order to be able to do so I need to implement \nmonitoring of my mailbox, checking every incoming mail (in particular, i use gmail).\nwhat is the easiest way to do that?Gmail provides the ability to connect over POP, which you can turn on in the gmail settings panel. Python can make connections over POP pretty easily:You would just need to run this script as a cron job. Not sure what platform you're on so YMMV as to how that's done.Gmail provides an atom  for new email messages. You should be able to monitor this by authenticating with py cURL (or some other net library) and pulling down the feed. Making a GET request for each new message should mark it as read, so you won't have to keep track of which emails you've read.While not Python-specific, I've always loved  wherever I could install it...!Just use as some of your action lines for conditions of your choice  (vertical bar AKA pipe followed by the script you want to execute in those cases) and your mail gets piped, under the conditions of your choice, to the script of your choice, for it to do whatever it wants -- hard to think of a more general approach to \"trigger actions of your choice upon receipt of mails that meet your specific conditions!!  Of course there are no limits to how many conditions you can check, how many action lines a single condition can trigger (just enclose all the action lines you want in  braces), etc, etc.People seem to be pumped up about Lamson:It's an SMTP server written entirely in Python.  I'm sure you could leverage that to do everything you need - just forward the gmail messages to that SMTP server and then do what you will.However, I think it's probably easiest to do the ATOM feed recommendation above.EDIT: Lamson has been abandonedI found a  when I wanted to do this same thing (and the example uses gmail). Also check out the  on this.I recently solved this problem by using procmail and pythonRead the documentation for procmail. You can tell it to send all incoming email to a python script like this in a special procmail config filePython has an \"email\" package available that can do anything you could possibly want to do with email. Read up on the following ones....
Python

I'm using the sqlite3 module in Python 2.6.4 to store a datetime in a SQLite database. Inserting it is very easy, because sqlite automatically converts the date to a string. The problem is, when reading it it comes back as a string, but I need to reconstruct the original datetime object. How do I do this?If you declare your column with a type of timestamp, you're in clover:See? both int (for a column declared integer) and datetime (for a column declared timestamp) survive the round-trip with the type intact.It turns out that sqlite3 can do this and it's even , kind of - but it's pretty easy to miss or misunderstand.What I had to do is:If I pass in \"datetime\" instead it's silently ignored and I still get a string back. Same if I omit the quotes.
Python

If I had a dictionary  and I wanted to check for  I could either do so in a  block (bleh!) or use the  method, with  as a default value.I'd like to do the same thing for . That is, I already have object to return  if it hasn't been set, but then that gives me errors likeA more direct analogue to  than  is .(Where  is optional, raising an exception on no attribute if not found.)For your example, you would pass .Do you mean  perhaps?You can also do this, which is a bit more cluttered and doesn't work for methods.For checking if a key is in a dictionary you can use : .For checking for attributes in object use the  function: 
Python

Python has a nice  function. Is there a PHP equivalent?As long as all the arrays are the same length, you can use  with  as the first argument.If some of the arrays are shorter, they will be padded with nulls to the length of the longest, unlike python where the returned result is the length of the shortest array.Try this function to create an array of arrays similar to Python\u2019s :You can pass this function as many array as you want with as many items as you want. comes close.Otherwise nothing like coding it yourself:This , and is compatible also with PHP < 5.3:It merges the arrays in the manner Python's  does and does not return elements found after reaching the end of the shortest array.The following:gives the following result:and the following:gives the following result:Check  for a proof of the above.: Added support for receiving single argument ( behaves differently in that case; thanks ).The solution matching  very closely, and using builtin PHP functions at the same time, is:As I , I tend to favor nabnabit's solution (), but in a slightly modified way (shown above).In general this:is counterpart for Python's:(wrap it in  if you want list instead of iterator). Because of this, it does not exactly fit the requirement to mimic 's behaviour (unless all the arrays have the same length).I wrote a  functions for my .\n The code has been modified to allow for a Python-style  as well as Ruby-style. The difference is explained in the comments:Example:you can see  method:output:You can find  as well as other Python functions in . Including  and .To overcome the issues with passing a single array to , you can pass this function...unfortunately you can't pass  as it's not a real function but a builtin thingy.Dedicated to those that feel like it should be related to array_combine:
Python

I am looking for an efficient way to remove unwanted parts from strings in a DataFrame column.Data looks like:I need to trim these data to:I tried  and ., but got an error:  Any pointers would be greatly appreciated!i'd use the pandas replace function, very simple and powerful as you can use regex. Below i'm using the regex \\D to remove any non-digit characters but obviously you could get quite creative with regex.There's a bug here: currently cannot pass arguments to  and :EDIT: 2012-12-07 this works now on the dev branch:In the particular case where you know the number of positions that you want to remove from the dataframe column, you can use string indexing inside a lambda function to get rid of that parts:Last character:First two characters:I've found big differences in performance between the various methods for doing things like this (i.e. modifying every element of a series within a DataFrame). Often a list comprehension can be fastest - see code race below:Put this right of result column and get the result.
Python

I want to print a character or string like '-' n number of times.Can I do it without using a loop?.. Is there a function like..which would mean printing the  3 times, like this:Python 2.x:Python 3.x:To print a string 3 times in Python 3.x, in this case the string is \"hello\"
Python

Is it possible to call a function without first fully defining it? When attempting this I get the error: \" is not defined\". I am coming from a C++ background so this issue stumps me. Declaring the function before works:However, attempting to call the function without first defining it gives trouble:In C++, you can declare a function after the call once you place its header before it.Am I missing something here?One way that is sort of idiomatic in Python is writing:This allows you to write you code in the order you like as long as you keep calling the function  at the end.When a Python module (.py file) is run, the top level statements in it are executed in the order they appear, from top to bottom (beginning to end). This means you can't reference something until you've defined it. For example the following will generate the error shown:Unlike with many other languages,  and  statements are executable in Python\u2014not just declarative\u2014so you can't reference either until that happens and they're defined. This is why your first example has trouble\u2014you're referencing the  function before its  statement has executed and body have been processed and the resulting function object bound to the function's name, so it's not defined at that point in the script.Programs in languages like C++ are usually preprocessed before being run and during this compilation stage the entire program and any  files it refers to are read and processed all at once. Unlike Python, this language features declarative statements which allow the name and calling sequence of functions (or static type of variables) to be declared (but not defined), before use so that when the compiler encounters their name it has enough information to check their usage, which primarily entails type checking and type conversions, none of which require their actual contents or code bodies to have been defined yet.This isn't possible in Python, but quite frankly you will soon find you don't need it at all. The Pythonic way to write code is to divide your program into modules that define classes and functions, and a single \"main module\" that imports all the others and runs. For simple throw-away scripts get used to placing the \"executable portion\" at the end, or better yet, learn to use an interactive Python shell.Python is a dynamic languuage and the interpreter always takes the state of the variables (functions,...) as they are at the moment of calling them. You could even redefine the functions in some if-blocks and call them each time differently. That's why you have to define them before calling them.
Python

Given  - 2D array - this is the bit of code that does the trick for me at the moment:But it's so ugly that I suspect that somewhere within NumPy there must be a function that does the same with something looking like:but if something like the above exists, I've been unable to find it.It's only worth trying to do this in-place if you are under significant space constraints. If that's the case, it is possible to speed up your code a little bit by iterating over a flattened view of the array. Since  returns a new view , the data itself isn't copied (unless the original has unusual structure). I don't know of a better way to achieve bona fide in-place application of an arbitrary Python function.Some timings:It's about twice as fast as the nested loop version:Of course vectorize is still faster, so if you can make a copy, use that:And if you can rewrite  using built-in ufuncs, then please, please, don't : does operations like  in place, just as you might expect -- so you can get the speed of a ufunc with in-place application at no cost. Sometimes it's even faster! See  for an example.By the way, my original answer to this question, which can be viewed in its edit history, is ridiculous, and involved vectorizing over indices into . Not only did it have to do some funky stuff to bypass 's , it turned out to be just as slow as the nested loop version. So much for cleverness!Q: Is it possible to map a numpy array in place?\nA: . You have to write your own code.Below a script that compares the various implementations discussed in the thread:The output of the above script - at least in my system - is:As you can observe,  compared with the second best and worst alternatives respectively.If using  is not an option, here's a comparison of the other alternatives only:HTH!Why not using numpy implementation, and the out_ trick ?got:if ufuncs are not possible, you should maybe consider using cython. \nit is easy to integrate and give big speedups on specific use of numpy arrays.
Python

I'm trying to teach Komodo to fire up  when I hit the right keystrokes.  I can use the exact path of the shortcut in start menu in the Windows Explorer location bar to launch IDLE so I was hoping Komodo would be able to use it as well.  But, giving this path to Komodo causes it to say that 1 is returned.  This appears to be a failure as IDLE doesn't start up.I thought I'd avoid the shortcut and just use the exact path.  I go to the start menu, find the shortcut for IDLE, right click to look at the properties.  The target is grayed out, but says \"Python 2.5.2\".  The \"Start in\" is set to, \"C:\\Python25\\\".  The \"Open File Location\" button is also grayed out.How do I find out where this shortcut is really pointing?  I have tried starting python.exe and pythonw.exe both in C:\\Python25, but neither starts up IDLE.There's a file called idle.py in your Python installation directory in Lib\\idlelib\\idle.pyIf you run that file with Python, then IDLE should start.In Python 3.2.2, I found  which was useful because it would let me open python files supplied as args in IDLE.Here's another path you can use.  I'm not sure if this is part of the standard distribution or if the file is automatically created on first use of the IDLE.If you just have a Python shell running, type:Python installation folder > Lib > idlelib > idle.pywDouble click on it and you're good to go.You can also assign hotkeys to Windows shortcuts directly (at least in Windows 95 you could, I haven't checked again since then, but I think the option should be still there ^_^).The idle shortcut is an \"Advertised Shortcut\" which breaks certain features like the \"find target\" button. Google for more info.You can view the link with a hex editor or download  to see where it points to.In my case it runs:\nthere is a .bat script to start it (python 2.7).I setup a short cut (using windows) and set the target toworks greatAlso found this works
Python

I have the following code:but I am getting 500 errors. I am trying to send what XML is being generated and received through SUDs, to the wsdl developer, but I can't figure how to output it? I have been looking in the documentation of SUDs, but can't seem to find it :/ Does anyone know how to output the raw xml that is sent and received? SUDS provides some convenience methods to do just that:These should provide you with what you need. I use them for error logging.\n for Client class should have any extra info you need.You can use the MessagePlugin to do this (this will work on the newer Jurko fork where last_sent and last_received have been removed)Suds supports internal logging, as you have been doing.I am setting info levels like you:And I also sometimes need to override the root logger logging level, depending on the framework being used under Suds calls (Django, Plone). If the root logger has a higher logging threshold, log messaegs may never appear (not sure how logger hierarchies should go). Below is an example how to override:To get only the generated message this also works:try changingto If you want to reduce logging by jurko-suds
Python

I am trying  to do the following insert operation:The structure of my MYSQL table is:However when I run my program, I get the error The format string is not really a normal Python format string. You must always use  for all fields. Since his data is in integer or decimal format how can you use %s which is usually used for string format %d or %i should be used for integer or decimal values.try this :
Python

In the  there is a list of notes on using .  I am thoroughly confused by the 1st and 6th items, because they seem to be contradicting each other. It seems to me these items could be better worded or shown through code, but I have been trying to wrap my head around this and am still coming up confused. I do understand how  are , and I am trying to get a better grasp on how they work.Can someone please explain to me in plain language what the conditions are for inheritance of slots when subclassing? (Simple code examples would be helpful but not necessary.)As others have mentioned, the sole reason for defining  is to save some memory, when you have simple objects with a predefined set of attributes and don't want each to carry around a dictionary.  This is meaningful only for classes of which you plan to have many instances, of course.The savings may not be immediately obvious -- consider...:From this, it would seem the with-slots size is  than the no-slots size!  But that's a mistake, because  doesn't consider \"object contents\" such as the dictionary:Since the dict alone takes 140 bytes, clearly the \"32 bytes\" object  is alleged to take are not considering all that's involved in each instance.  You can do a better job with third-party extensions such as :This shows much more clearly the memory footprint that's saved by : for a simple object such as this case, it's a bit less than 200 bytes, almost 2/3 of the object's overall footprint.  Now, since these days a megabyte more or less doesn't really matter all that much to most applications, this also tells you that  is not worth the bother if you're going to have just a few thousand instances around at a time -- however, for millions of instances, it sure does make a very important difference. You can also get a microscopic speedup (partly due to better cache use for small objects with ):but this is somewhat dependent on Python version (these are the numbers I measure repeatably with 2.5; with 2.6, I see a larger relative advantage to  for  an attribute, but none at all, indeed a tiny advantage, for  it).Now, regarding inheritance: for an instance to be dict-less,  classes up its inheritance chain must also have dict-less instances.  Classes with dict-less instances are those which define , plus most built-in types (built-in types whose instances have dicts are those on whose instances you can set arbitrary attributes, such as functions). Overlaps in slot names are not forbidden, but they're useless and waste some memory, since slots are inherited:as you see, you can set attribute  on an  instance --  itself only defines slot , but it inherits slot  from .  Repeating the inherited slot isn't forbidden:but does waste a little memory:so there's really no reason to do it.You probably won't need to use  in the near future. It's only intended to save memory at the cost of some flexibility. Unless you have tens of thousands of objects it won't matter.From the answer you linked:\"When inheriting from a class without , the  attribute of that class will always be accessible\", so adding your own  cannot prevent objects from having a , and cannot save space.The bit about  not being inherited is a little obtuse.  Remember that it's a magic attribute and doesn't behave like other attributes, then re-read that as saying this magic slots behavior isn't inherited.  (That's really all there is to it.)My understanding is as follows:Those items don't actually contradict each other. The first regards subclasses of classes that don't implement , the second regards subclasses of classes that  implement .I am increasingly aware that as great as the Python docs are (rightly) reputed to be, they are not perfect, especially regarding the less used features of the language. I would alter the  as follows: is still meaningful for such a class. It documents the expected names of attributes of the class. It also  slots for those attributes - they will get the faster lookups and use less space. It just allows for other attributes, which will be assigned to the .Well that's not quite right either. The action of a  declaration is  entirely limited to the class where it is defined. They can have implications for multiple inheritance, for example.I would change that to:(For more on , .)
Python

I'm trying to encode data to JSON in Python and I been having a quite a bit of trouble. I believe the problem is simply a misunderstanding. I'm relatively new to Python and never really got familiar with the various Python data types, so that's most likely what's messing me up. Currently I am declaring a list, looping through and another list, and appending one list within another:So I either: Python  translate to JSON . What it is giving you is a perfectly valid JSON string that could be used in a Javascript application. To get what you expected, you would need to use a :I think you are simply exchanging  and . The first returns as a (JSON encoded) string its data argument:The second does the opposite, returning the data corresponding to its (JSON encoded) string argument:In  (or the library  in Python 2.6 and later),  takes a JSON string and returns a Python data structure,  takes a Python data structure and returns a JSON string. JSON string can encode Javascript arrays, not just objects, and a Python list corresponds to a JSON string encoding an array. To get a JSON string such asthe Python object you pass to  could be:though the JSON string is also valid Python syntax for the same . I believe the specific string you say you expect is simply invalid JSON syntax, however.The data you are encoding is a keyless array, so JSON encodes it with [] brackets. See www.json.org for more information about that. The curly braces are used for lists with key/value pairs.From www.json.org:JSON uses square brackets for lists (  ) and curly brackets for key/value dictionaries (also called objects in JavaScript, ).The dump is quite correct, you get a list of three elements, each one is a list of two strings.if you wanted a dictionary, maybe something like this:your expected string ('') isn't valid JSON.  ASo, simplejson.loads takes a json string and returns a data structure, which is why you are getting that type error there.simplejson.dumps(data) comes back with Which is a json array, which is what you want, since you gave this a python array.If you want to get an \"object\" type syntax you would instead dowhich is javascript will come out as an object.Try:NB: Based on Paolo's answer.
Python

I have a numpy array that contains some image data. I would like to plot the 'profile' of a transect drawn across the image. The simplest case is a profile running parallel to the edge of the image, so if the image array is , then the profile at a selected point  is simply  (horizontal) or  (vertical).Now, I want to take as input two points  and , both lying inside . I would like to plot the profile of the values along the line connecting these two points.What is the best way to get values from a numpy array, along such a line? More generally, along a path/polygon?I have used slicing and indexing before, but I can't seem to arrive at an elegant solution for such a where consecutive slice elements are not in the same row or column. Thanks for your help.@Sven's answer is the easy way, but it's rather inefficient for large arrays.  If you're dealing with a relatively small array, you won't notice the difference, if you're wanting a profile from a large (e.g. >50 MB) you may want to try a couple of other approaches. You'll need to work in \"pixel\" coordinates for these, though, so there's an extra layer of complexity.There are two more memory-efficient ways.  1) use  if you need bilinear or cubic interpolation.  2) if you just want nearest neighbor sampling, then just use indexing directly.As an example of the first:The equivalent using nearest-neighbor interpolation would look something like this:However, if you're using nearest-neighbor, you probably would only want samples at each pixel, so you'd probably do something more like this, instead...Probably the easiest way to do this is to use :I've been testing the above routines with galaxy images and think I found a small error. I think a transpose needs to be added to the otherwise great solution provided by Joe. Here is a slightly modified version of his code that reveals the error. If you run it without the transpose, you can see the profile doesn't match up; with the transpose it looks okay. This isn't apparent in Joe's solution since he uses a symmetric image.Here's the version WITHOUT the transpose. Notice that only a small fraction on the left should be bright according to the image but the plot shows almost half of the plot as bright.Here's the version WITH the transpose. In this image, the plot seems to match well with what you'd expect from the red line in the image.For a canned solution look into 's  function.It's built on top of  as in 's  and has some extra useful functionality baked in.Combining this answer with the , here's the code to allow for GUI-based dragging to draw/update your slice, by dragging on the plot data (this is coded for pcolormesh plots):This results in the following (after adding axis labels etc.), after dragging on the pcolor plot:\n
Python

When I add a # in insert mode on an empty line in Vim while editing python files, vim moves the # to the beginning of the line, but I would like the # to be inserted at the tab level where I entered it.For example, when writing this in vimthe # does not stay there where I entered it.It is moved like so, by vim.Does anyone know of a configuration item in vim that would change this?If it helps, I am using Ubuntu 8.10.I found an answer here It seems that the vim smartindent option is the cause of the problem.\nThe referenced page above describes work-a-rounds but after reading the help in smartindent in vim itself (:help smartindent), I decided to try cindent instead of smartindent.I replaced with in my .vimrc fileand so far it is working perfectly.This changed also fixed the behavior of '<<' and '>>' for indenting visual blocks that include python comments.There are more configuration options for and information on indentation in the vim help for smartindent and cindent (:help smartindent and :help cindent).@PolyThinker Though I see that response a lot to this question, in my opinion it's not a good solution. The editor still thinks it should be indented all the way to left - check this by pushing == on a line that starts with a hash, or pushing = while a block of code with comments in it is highlighted to reindent.I would strongly recommend , and remove the  and  (or ) lines from your vimrc. Someone else (appparently David Bustos) was kind enough to write a full indentation parser for us; it's located at $VIMDIRECTORY/indent/python.vim.(Paul's  solution probably works for python, but  is much more generally useful.)I have the following lines in my .vimrc, seems to be installed by default with my Ubuntu 8.10And I don't observe the problem. Maybe you can try this. (Note that ^H should be entered by Ctrl-V Ctrl-H)It's caused by the 'smartindent' feature. If you have  in your .vimrc you need to remove it.My solution to the unindenting of #:If you use cindent, recognize that it is designed for C and C++ coding.  Here, a # means you are creating a #DEFINE or #MACRO(), so the behavior is correct.  But for other languages where # is a comment, it is irritating.The following worked for me:My Vim configuration doesn't do that.  You might try the python.vim script available from this link:  I removed  from  but it still didn't disable smartindent. When I opened a .py file and ran  it displayed .Turns out that further down in the  was this line:Once I deleted \"smartindent\" from that line, then smartindent was finally disabled and my comments were indented properly again.
Python

My organization currently delivers a web application primarily based on a SQL Server 2005/2008 back end, a framework of Java models/controllers, and ColdFusion-based views.  We have decided to transition to a newer framework and after internal explorations and mini projects have narrowed the choice down to between Python and C#/.NET.Let me start off by saying that   These languages have a lot in common, and a lot not--I'm looking for your take on their key differences.While it seems you can accomplish more with less code and be more creative with Python, since .NET is more structured it may be easier to take over understanding and modifying code somebody else wrote.Our engineering team is about 20 large and we work in small teams of 5-7 of which we rotate people in and out frequently.  We work on code that somebody else wrote as much as we write new code.With python we would go the Django route, and with .NET we would go with MVC2.  Our servers are windows servers running IIS.Some things we like about ColdFusion include that its very easy to work with queries and that we can \"hot-deploy\" fixes to our webservers without having to reboot them or interrupt anybody on them.I've read some of the other X vs Y threads involving these two languages and found them very helpful, but would like to put Python head-to-head against .Net directly.  Thanks in advance for letting me tap your experiences for this difficult question!\".NET\" is not a language. Perhaps it's Python vs. C# or Python/Django vs C#/ASP.NET (or pick whatever \"webwork\" you want; there are many, many different solutions for both Python and \".NET\" and picking Django or MVC2 of the bat might severely limiting better viable options). As a counter to the Python vs. \".NET\": There is  (Python \"in .NET\")I would consider:  with a language and, if they are equal in Python and \".NET\", then I would consider turnaround times for development and choose the language/\"webwork\" that minimized this (again, it need not be previous constraints).While unit/integration-testing is a must for any [sizable] project, I find that a  (C#/F#) can  the number of \"stupid bugs\" relating to types.Open up the playing field :-)Then you're just comparing languages.In which case, C# is a very boring imperative statically typed language with Single-Inheritance/Interface Class-Based OO (but a few more neat tricks than Java, which is just downright stone-age). This is  and excluding the static/dynamic bit,  (the mechanics are different, but the end result is quite similar in the language spectrum). Actually, python has MI, but that seems less accepted in python as the use of the 'lambda' keyword and since python is dynamically typed there is no compile-time support for determining interface/type contracts (there are, however, some modules that try to provide this). It's not a paradigm shift. Some keywords here, braces there, need to say what type you mean there, a different base library... different environment (you have to fight some to get to a REPL, but it's doable in VS.) How developers like/learn/use it is another story. While I did call C# imperative before, it's nice to see the addition of some \"functional-like\" features such as LINQ/IEnumerable extensions and closures-without-delegates, even if the basic C# syntax is very procedural -- once again, pretty much like python (for-expressions, nested functions, statement/expression divide).While the new 'dynamic' does blur the line (there is very rarely a good use for it -- in about all the same places one might have had to fall back to reflection in prior C# versions -- this isn't true, but the point is it's generally \"the wrong way\", except in the few cases when it just happens to be \"the best/only way\"), 'var' does not. That is, the type of a 'var' variable is  and ; it is all type inference. Some language like F#/SML and Haskell have much, much more powerful type inference removing the need for \"all those ugly type declarations\" (although explicitly annotating allowed types or set of types can make intent more clear) while preserving static typing.Personally, , I would use a statically typed language. I'm not saying C# (and I'm definitely not saying Java!), but  (this is a big, big win for me). While you do miss out on some neat dynamic tricks, there is almost always a better way to perform the same action in the target language -- you just have to think in terms of that language and use a screwdriver for a screw and a hammer for a nail. E.g. don't expect to bring Python code relying on the (ab)use of local() or global() into C# as-is.On the \"down-side\", most statically typed languages (C# here) require an explicit compile-first (but this isn't so bad as it makes pretty assemblies) and tools like the \"REPL\" aren't taken as first-class citizens (it is a first-class citizen in F#/VS2010). Also, if you have an essential library for Python/C# (and it isn't available in the other language), that may be a deciding factor as to why to choose one language over the other.I wrote a very comprehensive answer on Quora about this: I would also suggest we must compare runtimes and not limit to language features before making such moves. Python runs via interpreter CPython where C# runs on CLR in their default implementations. Multitasking is very important in any large scale project; .NET can easily handle this via threads... and also it can take benefits of worker processes in IIS (ASP.NET). CPython doesn't offer true threading capabilities because of GIL...a lock that every thread has to acquire before executing any code, for true multitasking you have to use multiple processes.When we host ASP.NET application on IIS on single worker process, ASP.NET can still take advantage of threading to serve multiple web requests simultaneously on different cores where CPython depends on multiple work processes to achieve parallel computing on different cores. All of this leads to a big question, how we are going to host Python/Django app on windows. We all know forking process on windows is much more costly than Linux. So ideally to host Python/Django app; best environment would be Linux rather than windows.If you choose Python, the right environment to developed and host Python would be Linux...and if you are like me coming from windows, choosing Python would introduce new learning curve of Linux as well...although is not very hard these days...The main problem in industrie is the dynamic nature of python.\nBecause you have some kind of safety with a static typed language.But now we have modern IDE's like PyCharm. They integrate pylint and pep8 \"code-checking\" and \"styleguide-check\" when you type in your code. That eliminates the most stupid errors. So you have almost have the same safety in python now.The other thing is, if you need \"static type checking\" do it by yourself\nwhen you need it. That's the pragmatic nature of python.The GIL is a problem, but you can use gevent or ZMQ to do a kind of threading. But work in progress on PyPy STM.Python runs almost anywhere and you have the choice of different, mostly compatible, runtimes (12 on Wikipedia)\n
Python

How to debug python programs in emacs? I use python-mode.elI get reference like \n   import pdb; pdb.set_trace();but not sure how to use it.Type  to change directory to the location of the program you wish to debug.\nType . You'll be prompted with . Enter the name of the program (e.g. ). At the  prompt, type  to learn about how to use pdb.Alternatively, you can putright inside your program (e.g. ). Now type  to get a shell prompt. When you run your program, you'll be dumped into  at the point where  is executed.For me, I needed to replace the default \"pdb\" with The  package (available from MELPA) supports PDB (among a gazillion other debuggers), and has a host of neat features that Emac's PDB doesn't have.The one I like best is the shortkeys mode. Once you start debugging a program, you can press , ,  etc. right in the source window, instead of having to type these commands in the PDB buffer. It also supports Visual-Studio style keybindings with function keys (, , , etc).After installing RealGUD, you need to run  to load it, and you can start  with .
Python

Generally speaking, what should the unary  do in Python?I'm asking because, so far, I have never seen a situation like this:Where  is a generic object implementing .So I'm wondering: why do  and  exist? Can you provide a real-world example where the expression above evaluates to ?Here's a \"real-world\" example from the  package:I believe that Python operators where inspired by C, where the  operator was introduced  for symmetry (and also some useful hacks, see comments).In weakly typed languages such as PHP or Javascript, + tells the runtime to coerce the value of the variable into a number. For example, in Javascript:Python is strongly typed, so strings don't work as numbers, and, as such, don't implement an unary plus operator.It is certainly possible to implement an object for which +obj != obj :As for an example for which it actually makes sense, check out the\n. They are a superset of the reals which includes\ninfinitesimal values (+ epsilon, - epsilon), where epsilon is \na positive value which is smaller than any other positive number, but\ngreater than 0; and infinite ones (+ infinity, - infinity). You could define , and .While  is still undefined,  is , and  = . It is \nnothing more than taking limits of  as  aproaches  from the right (+) or from the left (-).As  and  behave differently, it makes sense that . In Python 3.3 and above,  uses the  operator to remove non-positive counts.So if you use negative counts in a , you have a situation where .For symmetry, because unary minus is an operator, unary plus must be too. In most arithmetic situations, it doesn't do anything, but keep in mind that users can define arbitrary classes and use these operators for anything they want, even if it isn't strictly algebraic.I know it's an old thread, but I wanted to extend the existing answers to provide a broader set of examples:That, plus all the typecasting reasons mentioned by others.And after all... it's nice to have one more operator in case you need it. exists in  to give programmers similar possibilities as in  - to , in this case the  .( operators means give them a , e . g.  behaves differently for  and for  - numbers are  while strings are .)Objects may implement (beside others) these  functions (methods):So  means the same as  - they are interchangeable. However  is more easy on the eye.Creator of a particular object has free hands to implement these functions as he wants - as other people showed in their real world's examples. And my contribution -   .
Python

Is there any way to get the effect of running python -u from within my code? Failing that, can my program check if it is running in -u mode and exit with an error message if not? This is on linux (ubuntu 8.10 server)The best I could come up with:Tested on GNU/Linux. It seems it should work on Windows too. If I knew how to reopen sys.stdout, it would be much easier:References:\n\n\n[Edit]Note that it would be probably better to close sys.stdout before overwriting it.You could always pass the -u parameter in the shebang line:You might use the fact that stderr is never buffered and try to redirect stdout to stderr:Assuming you're on Windows:
Python

I am putting together the admin for a satchmo application. Satchmo uses OneToOne relations to extend the base  model, and I'd like to edit it all on one page.It is possible to have a OneToOne relation as an Inline? If not, what is the best way to add a few fields to a given page of my admin that will eventually be saved into the OneToOne relation?for example:I tried this for my admin but it does not work, and seems to expect a Foreign Key:Which throws this error: Is the only way to do this a ? Just tried the following code to add the fields directly... also does not work:It's perfectly possible to use an inline for a OneToOne relationship. However, the actual field defining the relationship has to be on the inline model, not the parent one - in just the same way as for a ForeignKey. Switch it over and it will work.: you say the parent model is already registered with the admin: then unregister it and re-register.Maybe use inheritance instead OneToOne relationshipOr use proxy classesin admin.pyIn this variant your product will be in inline.Referring to the last question, what would be the best solution for multiple sub-types. E.g class Product with sub-type class Book and sub-type class CD. The way shown here you would have to edit a product the general items plus the sub-type items for book AND the sub-type items for CD. So even if you only want to add a book you also get the fields for CD. If you add a sub-type e.g. DVD, you get three sub-type field groups, while you actually only want one sub-type group, in the mentioned example: books.You can also try setting 'parent_link=True' on your OneToOneField?
Python

Is there a way to write an aggregation function as is used in  method, that would have access to more than one column of the data that is being aggregated? Typical use cases would be weighted average, weighted standard deviation funcs.I would like to be able to write something likeYes; use the  function, which will be called on each sub-. For example:The following (based on Wes McKinney' answer) accomplishes exactly what I was looking for.  I'd be happy to learn if there's a simpler way of doing this within .The function  returns a dataframe that's grouped by the \"groupby\" column, and that returns the sum of the weights for the weights column.  Other columns are either the weighted averages or, if non-numeric, the  function is used for aggregation.I do this a lot and found the following quite handy:This will compute the weighted average of all the numerical columns in the  and drop non-numeric ones.Accomplishing this via  is non-performant. Here's a solution that I use all the time (essentially using kalu's logic).
Python

I'm writing some code that takes a filename, opens the file, and parses out some data. I'd like to do this in a class. The following code works:But it involves me putting all of the parsing machinery in the scope of the  function for my class. That looks fine now for this simplified code, but the function  has quite a few levels of indention as well. I'd prefer to define the function  as a class function like below:Of course this code doesn't work because the function  is not within the scope of the  function. Is there a way to call a class function from within  of that class? Or am I thinking about this the wrong way?Call the function in this way:You also need to define your parse_file() function like this:The parse_file method has to be bound to an object upon calling it (because it's not a static method). This is done by calling the function on an instance of the object, in your case the instance is .If I'm not wrong, both functions are part of your class, you should use it like this:replace your line:with:How about:By the way, if you have variables named , , etc., the situation is begging for a tuple:\n.So let  return a tuple, and store the tuple in\n.Then, for example, you can access what used to be called  with .In , take the  argument (just like in ). If there's any other context you need then just pass it as additional arguments as usual.You must declare parse_file like this; . The \"self\" parameter is a hidden parameter in most languages, but not in python. You must add it to the definition of all that methods that belong to a class.\nThen you can call the function from any method inside the class using your final program is going to look like this:I think that your problem is actually with not correctly indenting  function.It should be like this
Python

Is it possible to start an interactive python shell inside a python program?I want to use such an interactive python shell (which is running  my program's execution) to inspect some program-internal variables.The  module provides an interactive console:In ipython 0.13+ you need to do this:I've had this code for a long time, I hope you can put it to use.To inspect/use variables, just put them into the current namespace. As an example, I can access  and  from the command line. if you wanted to strictly debug your application, I'd  suggest using an IDE or .Using IPython you just have to call:Another trick (besides the ones already suggested) is opening an interactive shell and importing your (perhaps modified) python script. Upon importing, most of the variables, functions, classes and so on (depending on how the whole thing is prepared) are available, and you could even create objects interactively from command line. So, if you have a  file, you could open Idle or other shell, and type  (if it is in current working directory).
Python

I'm running pylint on some code, and receiving the error \"Too few public methods (0/2)\". What does this message mean? The  are not helpful: The error basically says that classes aren't meant to  store data, as you're basically treating the class as a dictionary. Classes should have at least a few methods to operate on the data that they hold.If your class looks like this:Consider using a dictionary or a  instead. Although if a class seems like the best choice, use it. pylint doesn't always know what's best.If you are extending a class, then my suggestion is to systematically disable this warning and move on, e.g., in the case of Celery tasks:Even if you are only extending a single function, you definitely need a class to make this technique function, and extending is definitely better than hacking on the third-party classes!
Python

Since Java doesn't allow passing methods as parameters, what trick do you use to implement Python like list comprehension in Java ?I have a list (ArrayList) of Strings. I need to transform each element by using a function so that I get another list. I have several functions which take a String as input and return another String as output. How do I make a generic method which can be given the list and the function as parameters so that I can get a list back with each element processed. It is not possible in the literal sense, but what trick should I use ?The other option is to write a new function for each smaller String-processing function which simply loops over the entire list, which is kinda not so cool.Basically, you create a Function interface:and then pass in an anonymous subclass to your method.Your method could either apply the function to each element in-place:or create a new  (basically creating a mapping from the input list to the output list):Which one is preferable depends on your use case. If your list is extremely large, the in-place solution may be the only viable one; if you wish to apply many different functions to the same original list to make many derivative lists, you will want the  version.The  has lots of classes for working with collections and iterators at a much higher level than plain Java supports, and in a functional manner (filter, map, fold, etc.). It defines Function and Predicate interfaces and methods that use them to process collections so that you don't have to. It also has convenience functions that make dealing with Java generics less arduous. I also use ** for filtering collections.The two libraries are easy to combine with adapter classes.** Declaration of interest: I co-wrote HamcrestIn Java 8 you can use method references:Or, if you want to create a new list instance:Apache Commons   is another option.I'm building this project to write list comprehension in Java, now is a proof of concept in ExamplesAnd if we want to transform the output expression in some way likeYou can use lambdas for the function, like so:the usage:will return:
Python

I am trying to extract the content of a single \"value\" attribute in a specific \"input\" tag on a webpage. I use the following code:I get a TypeError: list indices must be integers, not streven though from the Beautifulsoup documentation i understand that strings should not be a problem here... but i a no specialist and i may have misunderstood. Any suggestion is greatly appreciated!\nThanks in advance. returns list of all found elements, so: is a list (probably containing only one element). Depending on what you want exactly you either should do:or use  method which returns only one (first) found element:If you want to retrieve multiple values of attributes from the source above, you can use  and a list comprehension to get everything you need:I would actually suggest you a time saving way to go with this assuming that you know what kind of tags have those attributes.suppose say a tag xyz has that attritube named \"staininfo\"..And i wan't you to understand that full_tag is a listThus you can get all the attrb values of staininfo for all the tags xyzIn , simply use  on your tag object that you get using :against XML file  that looks like:prints:
Python

Consider a dict likeHow do I access for instance a particular element of this dictionary ?\nfor instance I would like to print first element after some formatting the first element of Apple which in our case is 'American' only ?Additional information\nThe above data structure was created by parsing an input file in a python function. Once created however it remains the same for that run.I am using this data structure in my function.So if the file changes, the next time this application is run the contents of file are different and hence the contents of this data structure will be different but the format would be same.\nSo you see I in my function I don't know that the first element in Apple is 'American' or anything else\nso I can't directly use 'American' as a key Given that it is a dictionary you access it by using the keys. Getting the dictionary stored under \"Apples\", do the following:And getting how many of them are American (16), do like this:If the questions is, if I know that I have a dict of dicts that contains 'Apple' as a fruit and 'American' as a type of apple, I would use:as others suggested. If instead the questions is, you don't know whether 'Apple' as a fruit and 'American' as a type of 'Apple' exist when you read an arbitrary file into your dict of dict data structure, you could do something like:or better yet so you don't unnecessarily iterate over the entire dict of dicts if you know that only Apple has the type American:In all of these cases it doesn't matter what order the dictionaries actually store the entries. If you are really concerned about the order, then you might consider using an :As I noticed your description, you just know that your parser will give you a dictionary that its values are dictionary too like this:So you have to iterate over your parent dictionary. If you want to print out or access all first dictionary keys in  list, you may use something like this:If you want to just access first key of the first item in , this may be useful:If you use the example you gave in the question, I mean:The output for the first code is:And the output for the second code is:You can use  to get the first key in the  dictionary, but there's no guarantee that it will be . The order of keys in a dictionary can change depending on the contents of the dictionary and the order the keys were added.You can't rely on order on dictionaries. But you may try this:If you want the order to be preserved you may want to use this:\nAs a bonus, I'd like to offer kind of a different solution to your issue. You seem to be dealing with nested dictionaries, which is usually tedious, especially when you have to check for existence of an inner key.There are some interesting libraries regarding this on pypi, here is a  for you.In your specific case,  seems suited.
Python

In Python we can \"dir\" a module, like this:And it lists all functions in the module. Is there a similar way to do this in Ruby?As far as I know not exactly but you get somewhere withI like to have this in my .irbrc:So when I'm in irb:Or even cuter - with grep:You can take a module, such as , and send the  method which lists all the methods the module defines. Classes that include this module will respond to these methods.Tip for \"searching\" for a method in irb: Tip for trying out methods on a value for comparison:Also, note that you won't get all the same information as Python's dir with object.methods. You have to use a combination of object.methods and class.constants, also class.singleton_methods to get the class methods.I'd go for something like this:Which will give you a yaml representation of the sorted array of methods. Note that this can be used to list the methods of both classes and objects.Not really.  Like the others said, you can get part of what you want by listing class instance methods (e.g. ) but that doesn't help you if a file you open reopens a class (unless you check before and after).If you don't need programmatic access to the list of methods, consider checking out the documentation for a class, module or method using the  command line tool.I would have made this a comment to jonelf's answer, but apparently I don't have enough rep.some_object.methods.sort - Object.new.methodsThis isn't exactly what you were asking as others have said, but it gives you the info you are after.If I stricly read your question, I must answer it that way: a file as specified by  in Ruby is just a container and does not have necessarely have any relation with a class.  The content can be:or any combination of the above, several times. So you can not directly ask for all methods in a given file.If you meant to list all methods of a given module or class, then the other answers are what you seek (mainly using the  method on a module name or class).Maybe not answering the original question (depends on the use case), but for those who are looking for this to be used in the  only, you can use \"double-TAB\" for autocompletion. Which, effectively, can also list (almost all) the methods available for a given object.Put the following line into your  file:Now, (re)start the , start typing a method and hit TAB twice - irb autocompletes the input!I actually learned it here: 
Python

I have a directory, 'Dst Directory', which has files and folders in it and I have 'src Directory' which also has files and folders in it. What I want to do is move the contents of 'src Directory' to 'Dst Directory' and overwrite anyfiles that exist with the same name. So for example 'Src Directory\\file.txt' needs to be moved to 'Dst Directory\\' and overwrite the existing file.txt. The same applies for some folders, moving a folder and merging the contents with the same folder in 'dst directory'I'm currently using shutil.move to move the contents of src to dst but it won't do it if the files already exist and it won't merge folders; it'll just put the folder inside the existing folder.Update: To make things a bit clearer; What I'm doing is unzipping an archive to the Dst Directory and then moving the contents of Src Directory there and rezipping, effectively updating files in the zip archive. This will be repeated for adding new files or new versions of files etc which is why it needs to overwrite and mergeSolved: I solved my problem by using distutils.dir_util.copy_tree(src, dst), this copies the folders and files from src directory to dst directory and overwrites/merges where neccesary. Hope that helps some people!Hope that makes sense,\nthanks!Use  instead, which is willing to overwrite destination files. If you then want the first tree to go away, just  it separately once you are done iterating over it.Do an  over the source tree. For each directory, check if it exists on the destination side, and  it if it is missing. For each file, simply  and the file will be created or overwritten, whichever is appropriate.This will go through the source directory, create any directories that do not already exist in destination directory, and move files from source to the destination directory:Any pre-existing files will be removed first (via ) before being replace by the corresponding source file. Any files or directories that already exist in the destination but not in the source will remain untouched.Since none of the above worked for me, so I wrote my own recursive function. Call Function copyTree(dir1, dir2) to merge directories. Run on multi-platforms Linux and Windows. If you also need to overwrite files with read only flag use this:Have a look at:  to remove existing files.I had a similar problem. I wanted to move files and folder structures and overwrite existing files, but not delete anything which is in the destination folder structure.I solved it by using , recursively calling my function and using  on files which I wanted to overwrite and folders which did not exist.It works like , but with the benefit that existing files are only overwritten, but not deleted.
Python

MySQL ResultSets are by default retrieved completely from the server before any work can be done. In cases of huge result sets this becomes unusable. I would like instead to actually retrieve the rows one by one from the server.In Java, following the instructions  (under \"ResultSet\"), I create a statement like this:This works nicely in Java. My question is: is there a way to do the same in python?One thing I tried is to limit the query to a 1000 rows at a time, like this:However, this seems to get slower the higher start_row is.And no, using  instead of  doesn't change anything.The naive code I use to reproduce this problem looks like this:On a ~700,000 rows table, this code runs quickly. But on a ~9,000,000 rows table it prints \"Executing Query\" and then hangs for a long long time. That is why it makes no difference if I use  or .I think you have to connect passing :The default cursor fetches all the data at once, even if you don't use .Edit:  or any other cursor class that supports server side resultsets - check the module docs on .The limit/offset solution runs in quadratic time because mysql has to rescan the rows to find the offset.  As you suspected, the default cursor stores the entire result set on the client, which may consume a lot of memory.Instead you can use a server side cursor, which keeps the query running and fetches results as necessary.  The cursor class can be customized by supplying a default to the connection call itself, or by supplying a class to the cursor method each time.But that's not the whole story.  In addition to storing the mysql result, the default client-side cursor actually fetches every row regardless.  This behavior is undocumented, and very unfortunate.  It means full python objects are created for all rows, which consumes far more memory than the original mysql result.In most cases, a result stored on the client wrapped as an iterator would yield the best speed with reasonable memory usage.  But you'll have to roll your own if you want that.Did you try this version of fetchone?  Or something different?Also, did you try this?Not all drivers support these, so you may have gotten errors or found them too slow.Edit.When it hangs on execute, you're waiting for the database.  That's not a row-by-row Python thing; that's a MySQL thing.  MySQL prefers to fetch all rows as part of it's own cache management.  This is turned off by providing a the fetch_size of Integer.MIN_VALUE (-2147483648L).The question is, what part of the Python DBAPI becomes the equivalent of the JDBC fetch_size?I think it might be the arraysize attribute of the cursor.  TryAnd see if that forces MySQL to stream the result set instead of caching it.Try to use I found the best results mixing a bit from some of the other answers. This included setting  (for MySQLdb) or  (for PyMySQL) as part of the connection settings. This will let the server hold the query/results (the \"SS\" stands for server side as opposed to the default cursor which brings the results client side) and build a dictionary out of each row (e.g. {'id': 1, 'name': 'Cookie Monster'}). Then to loop through the rows, there was an infinite loop in both Python 2.7 and 3.4 caused by  because even when  was called and there were no results left, the method returned an empty list () instead of None. Actual example:
Python

I thought I had a pretty good handle on Python's scoping rules, but this problem has me thoroughly stymied, and my google-fu has failed me (not that I'm surprised - look at the question title ;)I'm going to start with a few examples that work as expected, but feel free to skip to example 4 for the juicy part.Straightforward enough: during class definition we're able to access the variables defined in the outer (in this case global) scope.Again (ignoring for the moment  one might want to do this), there's nothing unexpected here: we can access functions in the outer scope.: as Fr\u00e9d\u00e9ric pointed out below, this function doesn't seem to work. See Example 5 (and beyond) instead. As , I botched this example in my original posting. I believe this fails because only functions (not other code blocks, like this class definition) can access variables in the enclosing scope. For non-function code blocks, only local, global and built-in variables are accessible. A more thorough explanation is available in One more:Um...excuse me?What makes this any different from example 2?I'm completely befuddled. Please sort me out.\nThanks!P.S. on the off-chance that this isn't just a problem with my understanding, I've tried this on Python 2.5.2 and Python 2.6.2. Unfortunately those are all I have access to at the moment, but they both exhibit the same behaviour.\nAccording to : at any time during execution, there are at least three nested scopes whose namespaces are directly accessible:#4. seems to be a counter-example to the second of these.As @Fr\u00e9d\u00e9ric pointed out the assignment of to a variable of the same name as it has in the outer scope seems to \"mask\" the outer variable, preventing the assignment from functioning.So this modified version of Example 4 works:However this doesn't:I still don't fully understand why this masking occurs: shouldn't the name binding occur when the assignment happens?This example at least provides some hint (and a more useful error message):So it appears that the local variable is defined at function creation (which succeeds), resulting in the local name being \"reserved\" and thus masking the outer-scope name when the function is called.Interesting.Thanks Fr\u00e9d\u00e9ric for the answer(s)!For reference, from :This seemingly confusing behaviour is caused by Python's . It actually has nothing to do with .From PEP 227:Lets run two simpler versions of Tim's example:when  doesn't find  in its inner scope, it dynamically searches outwards, finding the  in 's scope, which has been bound to  through the  assignment.But changing the order the final two statements in  causes an error:Remembering that PEP 227 said \"The name resolution rules are typical for statically scoped languages\", lets look at the (semi-)equivalent C version offer:compile and run:So while C will happily use an unbound variable (using whatever happens to have been stored there before: 134520820, in this case), Python (thankfully) refuses.As an interesting side-note, statically nested scopes enable what  \"the single most important optimization the Python compiler does: a function's local variables are not kept in a dict, they're in a tight vector of values, and each local variable access uses the index in that vector, not a name lookup.\"That's an artifact of Python's name resolution rules:  The above was poorly worded, you  have access to the variables defined in outer scopes, but by doing  or  from a non-global namespace, you're actually masking the outer variable with the one you're defining locally.In example 2, your immediate outer scope is the global scope, so  can see , but in example 4 your immediate outer scope is , so it can't, because the outer definition of  is already masked by its local definition.See  for more details about nonlocal name resolution.Also note that, for the reasons explained above, I can't get example 3 to run under either Python 2.6.5 or 3.1.2:But the following would work:This post is a few years old, but it is among the rare ones to discuss the important problem of scope and static binding in Python. However, there is an important misunderstanding of the author for example 3 that might confuse readers. (do not take as granted that the other ones are all correct, it is just that I only looked at the issues raised by example 3 in details).\nLet me clarify what happened.In example 3 must return an error, unlike what the author of the post said. I believe that he missed the error because in example 1  was assigned to  in the global scope. Thus a wrong understanding of what happened. The explanation is extensively described in this post\n
Python

I seem to be getting an IOError: request data read error quite a lot when i'm doing an Ajax upload. For example out of every 5 file uploads it errors out on atleast 3. Other people seem to have had the same issue. Eg. Some other observations:I get this exception, too. In the Apache error logfile I see this:Versions:First I was confused, because the last line \"failed to  data\" does not fit to the django code \"load post data\". But I guess that django wants to write an error page to the client. But the client has canceled the tcp connection. And now http 500 page can't be written to the client.The client disconnected after sending the request, and before getting the response:I have seen this only with POST-Requests (not GET). If POST is used, the webserver does read at least twice: First to get the headers, the second to get the data. The second read fails.It is easy to reproduce:Insert some code which waits before the first access to request.POST happens (be sure, that no middleware accesses request.POST before time.sleep()):Now do a big POST (e.g. file upload). I don't know the apache buffer size. But 5 MB should be enough. When the browser shows the hourglass, browse to an other page. The browser will cancel the request and the exception should be in the logfile.This is my Middleware, since I don't want to get the above traceback in our logfiles:as you might think, this is no django error.see have the error myself (but IE ajax requests only, no file upload, just post data).will add an complete answer if i ever find out how to fix this.We were seeing this error on uploads to Django Rest Framework when the content-type header was incorrectly set to application/json. The post was actually multipart form data. The errors stopped when we removed the incorrect content-type header.This happened to me recently. I was using  and small files were uploading successfully but large files e.g. 100MB were breaking in between with .I checked my Apache configuration and found these setting  which means .File is received in chunks at backend, which means if file size is big  seconds are not enough for some uploads. So how to determine the best value (seconds) for the requests?So I have used this setting:Defining the  solves the issue for me. The above setting states that:As the client is sending data continuously (ajax upload) it makes sense to automatically increase the timeout if data is received. More information/variations about the  can be found .Taking this from the thread: Extending the possible solution by @dlowe for Django 1.3, to suppress the IOError in concern, we can write the full working example as:I got this error when validating my site on a Win8 machine with IE 10. When I tested file upload from IE the upload was stucked on 1% and after +/- 1 minute I got the error on server logs. I just discovered that it was caused by the TrendMicro complement. Once I disabled the complement the upload occurred without any problem.This issue has been open for a long time and has something to do with lower level libraries. I was using boto to upload files to S3. A temporary stopgap I found was to add an explicit HTTP socket timeout of 10 seconds. I haven't seen the error after that. You can do that by creating a boto config on the server:Also make sure the file is readable by the app. \nSee my original post on google group: 
Python

 is a new documentation tool for Python. It looks very nice. What I'm wondering is:As mentioned  and , [Edit inserted below]: I tested the doxygen+breathe+sphinx toolchain on a multi-10k \nC++ library consisting of 10 different modules/domains. My bottom\nline is: Let me elaborate these points:As a final pointer, also note the  contrib project for sphinx,\nwhich may provide an intermediate solution: build up a surrounding tutorial-like\nstructure which references the (css-style matched) old doxygen documentation\n(i think you could even inject the same header into sphinx and on top of the\n doxygen documentation for look'n'feels). That way, your project keeps an\naffinity to sphinx, and when breathe is fully there, you are prepared to\njump on. But again: consider showing breathe some love if it fits your agenda.First, keep two directory trees,  and .  Put  under version control.  Don't put  under version control, rebuild it as part of installation.Second, read .Use the  to build a practice documentation tree.  Play with this for a few days to learn how it works.  Then use it again to build the real thing in SVN directories.Organize your documentation in a well-planned tree.  Some sections need an \"index.rst\" for that section, some don't.  It depends on how \"stand-alone\" the section is.Our top-level  looks like this.Note, we don't \"include\" the API, we just reference it with an ordinary HTML link.Sphinx has a very cool add-on, called automodule, which picks the docstrings out of Python modules.  As of Sphinx 1.0, C and C++ are supported.  Have a look at  for an XML approach.
Python

I'm using  and the autodoc plugin to generate API documentation for my Python modules.  Whilst I can see how to nicely document specific parameters, I cannot find an example of how to document a  parameter.Does anyone have a good example of a clear way to document these?I think  is a good example. Give an exhaustive list of all parameters for a . Then just refer to that list for all other occurrences of .After finding this question I settled on the following, which is valid Sphinx and works fairly well:The  is required to make this a \"raw\" docstring and thus keep the  intact (for Sphinx to pick up as a literal  and not the start of \"emphasis\").The chosen formatting (bulleted list with parenthesized type and m-dash-separated description) is simply to match the automated formatting provided by Sphinx.Once you've gone to this effort of making the \"Keyword Arguments\" section look like the default \"Parameters\" section, it seems like it might be easier to roll your own parameters section from the outset (as per some of the other answers), but as a proof of concept this is one way to achieve a nice look for supplementary  if you're already using Sphinx.Disclaimer: not tested.From this cutout of the , the  and  are left :I would  the following solution for compactness:Notice how,  is not required for  arguments. , you can try to explicitly list the *args under  and  under the  (see parsed ):If anyone else is looking for some valid syntax.. Here's an example docstring. This is just how I did it, I hope it's useful to you, but I can't claim that it's compliant with anything in particular.There is a  for Sphinx in their documentation. \nSpecifically they show the following: Though you asked about  explicitly, I would also point to the . Their docstring example seems to imply that they don't call out kwargs specifically. (other_silly_variable=None) A-B-B has a question about the accepted answer of referencing the subprocess management documentation. If you import a module, you can quickly see the module docstrings via inspect.getsource. An example from the python interpreter using Silent Ghost's recommendation: Of course you can also view the module documentation via help function. For example help(subprocess) I'm not personally a fan of the subprocess docstring for kwargs as an example, but like the Google example it doesn't list kwargs seperately as shown in the Sphinx documentation example. I'm including this answer to A-B-B's question because it's worth noting that you can review any module's source or documentation this way for insights and inspiration for commenting your code.
Python

I sometimes write Python programs which are very difficult to determine how much memory it will use before execution. As such, I sometimes invoke a Python program that tries to allocate massive amounts of RAM causing the kernel to heavily swap and degrade the performance of other running processes.Because of this, I wish to restrict how much memory a Python heap can grow. When the limit is reached, the program can simply crash. What's the best way to do this? If it matters, much code is written in Cython, so it should take into account memory allocated there. I am not married to a pure Python solution (it does not need to be portable), so anything that works on Linux is fine.Check out .  It only works on Unix systems but it seems like it might be what you're looking for, as you can choose a maximum heap size for your process and your process's children with the resource.RLIMIT_DATA parameter.EDIT: Adding an example:I'm not sure what your use case is exactly but it's possible you need to place a limit on the size of the stack instead with resouce.RLIMIT_STACK.  Going past this limit will send a SIGSEGV signal to your process, and to handle it you will need to employ an alternate signal stack as described in the setrlimit Linux .  I'm not sure if sigaltstack is implemented in python, though, so that could prove difficult if you want to recover from going over this boundary.Have a look at . It allows resource quotas to be set. May need appropriate kernel settings as well.
Python

I was unsuccessful browsing web for a solution for the following simple question:How to draw 3D polygon (say a filled rectangle or triangle) using vertices values?\nI have tried many ideas but all failed, see:I appreciate in advance any idea/comment.  Here is the result:\nI think you've almost got it.   Is this what you want?\nYou might also be interested in art3d.pathpatch_2d_to_3d.
Python

How can I convert  time to  time and the other way round in ,  or  or ? I know I can convert to  and . But  is not an option.To be more specific, I'm talking about the Hindu lunar calendar. The following website is working and does exactly what I want: . For example, it 'translates'  (Gregorian) to  (Hind. Lun.). How can I accomplish the same task? And if there are absolutely no scrips out there, how can I write it myself?Paper: \nProvides Common Lisp code in the appendix.While a Python (or other language) solution could be written according to the paper, the authors enumerate the Indian calendar rules pretty well, so it's a pretty solid paper if you're willing to consider taking the provided Common Lisp code.Did you check  family of modules? At least  \nseems to have a method to convert traditional date into UTC values (utc_rd_values).I suppose  may be useful as well for many users (as I have known, it's the Indian national calendar), in particular,  and  methods.For Python, use  (note: this is not the built-in calendar module).Sample use:Seems to be a difficult task. According to  there is no clear way to accomplish a 100% correct conversion. But it seems that they are wrong when they assume that the Hindu calendar has only 364 days instead of 365 (or 366 in leap years).Here you can find a good conversion table including the handling of leap years: If it is as easy as written there you can try something like this (php code):Output of this code:But according to the calculator of , it should be 05-11-2068 instead of 07-11-2068. So, there are still some conversion rules missing. Maybe you can give me some more information so that i can correct the code above.I dont know whether it is correct approach or not but\nPlease go to  site and download two javascript files astro.js and calendar.js and follow onchange events of Gregorian Date and fetch Indian Civil Date parameters.
Python

I'm trying to catch an exception in a thread and re-raise it in the main thread:This basically works and yields the following output:However, the source of the exception points to line 16, where the re-raise occurred. The original exception comes from line 7. How do I have to modify the  thread so that the output reads:You need to use all three arguments to raise:passing the traceback object in as the third argument preserves the stack.From :In this particular case you cannot use the no expression version.Could you write it somewhat like this:and then use the stacktrace from the exception?This code snippet works in both python 2 & 3:
Python

This code almost does what I need it to..Except it removes all the '>' delimiters.So,Turns intoIs there a way to use the split() method but  the delimiter, instead of removing it?With these results..If you are parsing HTML with splits, you are most likely doing it wrong, except if you are writing a one-shot script aimed at a fixed and secure content file. If it is supposed to work on any HTML input, how will you handle something like ?Anyway, the following works for me:How about this:Just split it, then for each element in the array/list (apart from the last one) add a trailing \">\" to it.
Python

In , I could pass custom function to sorted and .sort functionsBecause, in  language, consonents are comes with this orderBut In , looks like I could not pass  keywordIs there any alternatives or should I write my own sorted function too?Use the  argument (and follow the  on how to convert your old  function to a  function).Use the  keyword and  to transform your comparison function:Instead of a customsort(), you need a function that translates each word into something that Python already knows how to sort.  For example, you could translate each word into a list of numbers where each number represents where each letter occurs in your alphabet.  Something like this:Since your language includes multi-character letters, your custom_key function will obviously need to be more complicated.  That should give you the general idea though.I don't know if this will help, but you may check out the  module.  It looks like you can set the locale to your language and use  to compare strings using your language's sorting rules.Use the  argument instead. It takes a function that takes the value being processed and returns a single value giving the key to use to sort by.
Python

Is there a way to integrate background unit tests with the Pydev Eclipse environment?My unit tests run well, but I would like to integrate them to run in the background based on source file changes (e.g. with nose) and to integrate the result back to Eclipse (I'm thinking big red X when tests fail with a console and trace log view).No, a command prompt running nose on the side does not count.I have had this Eclipse integration when developing RoR stuff.Thanks,Tal. Check out the new Pydev (1.6.4) This feature has been added to PyDev 2.0.1 with an option to relaunch the tests in the last test run whenever a python file change, with an additional option to rerun only the errors -- although it'll run the full test suite if no errors were found, as the idea is that you work through your errors and when all pass a final launch for the whole suite is done (then you can move on to another task).The current nightly build has this feature incorporated.Pydev does have some unit-test integration, but that's only as a run configuration...so...This is not a very elegant way, but if you:Then at least you will get something that outputs the test results to the console on resource saves.I just realized that PyDev has rather powerful scripting support. Unfortunately I don't have the time to do it all for you (but if you complete this, please post it here :)If you create a file named  that looks like this in an otherwise empty folder :and set up Preferences->PyDev->Scripting Pydev to point to this directory you will get all projects in your workspace marked with an error every time a file is saved.By executing a script that returns the test results in some easy to parse format rather than  and parsing the output you should be able to put your markers in the right places.See this for some starting points:I enhanced the \"nosy\" script to automatically build documentation and runs tests \ncontinuously. Nothing stellar, but gets the job done. Posting it here because the original\nlink went down. Unlike the original nosy script, this one scans the directory recursively\nand allows looking for multiple patterns.Hope this helps.=)I run the test by hand the first time (). After that, I use\n to have the files saved and the tests executed, instead of saving with  and expecting some magic to happen. The  key combination relaunches the last run configuration.: I'm new to Eclipse and to PyDev, so I may be suggesting something silly/obvious/wrongI use  (available on pypi): 
Python

How can I get the class that defined a method in Python?I'd want the following example to print \"\":Thanks Sr2222 for pointing out I was missing the point...Here's the corrected approach which is just like Alex's but does not require to import anything. I don't think it's an improvement though, unless there's a huge hierarchy of inherited classes as this approach stops as soon as the defining class is found, instead of returning the whole inheritance as  does. As said, this is a  unlikely scenario.And the Example:Alex solution returns the same results. As long as Alex approach can be used, I would use it instead of this one.I started doing something somewhat similar, basically the idea was checking whenever a method in a base class had been implemented or not in a sub class. Turned out the way I originally did it I could not detect when an intermediate class was actually implementing the method.My workaround for it was quite simple actually; setting a method  and testing its presence later. Here's an simplification of the whole thing:UPDATE: Actually call  from  (isn't that the spirit?) and have it pass all arguments unmodified to the method.P.S.: This answer does not directly answer the question. IMHO there are two reasons one would want to know which class defined a method; first is to point fingers at a class in debug code (such as in exception handling), and the second is to determine if the method has been re-implemented (where method is a stub meant to be implemented by the programmer). This answer solves that second case in a different way.
Python

I just read about , i.e. zip files that contain very large amount of highly compressible data (00000000000000000...).When opened they fill the server's disk.How can I detect a zip file is a zip bomb  unzipping it? Can you tell me how is this done in Python or Java?Try this in Python:Zip is, erm, an \"interesting\" format. A robust solution is to stream the data out, and stop when you have had enough. In Java, use  rather than . The latter also requires you to store the data in a temporary file, which is also not the greatest of ideas.Reading over the description on Wikipedia - Deny any compressed files that contain compressed files.\n\u00a0\u00a0\u00a0\u00a0 Use  to retrieve a list of files, then  to find the file extension.\nDeny any compressed files that contain files over a set size, or the size can not be determined at startup.\n\u00a0\u00a0\u00a0\u00a0 While iterating over the files use  to retrieve the file size.Check a zip header first :)If the ZIP decompressor you use can provide the data on original and compressed size you can use that data. Otherwise start unzipping and monitor the output size - if it grows too much cut it loose.Don't allow the upload process to write enough data to fill up the disk, ie solve the problem, not just one possible cause of the problem.Make sure you are not using your system drive for temp storage. I am not sure if a virusscanner will check it if it encounters it. Also you can look at the information inside the zip file and retrieve a list of the content. How to do this depends on the utility used to extract the file, so you need to provide more information hereWhy would you want to? The moment you zip the first layer and find so many multiple files with weird numbering, you'd automatically know. There is no autoextracting sfx archive zip bomb that I know of.
Python

In their , the original authors of Julia mention the following: What do they mean by saying that Julia does not support ? What is a native thread?Do other interpreted languages such as  or  support this type of parallelism? Is Julia alone in this?\"Native threads\" are separate contexts of execution, managed by the operating system kernel, accessing a shared memory space and potentially executing concurrently on separate cores. Compare this with separate processes, which may execute concurrently on multiple cores but have separate memory spaces. Making sure that processes interact nicely is easy since they can only communicate with each other via the kernel. Ensuring that threads don't interact in unpredictable, buggy ways is very hard since they can read and write to the same memory in an unrestricted manner.The R situation is fairly straightforward: . Python is a little more complicated: Python does support threading, but due to the , no actual concurrent execution of Python code is possible. Other popular open source dynamic languages are in various mixed states with respect to native threading (Ruby: ; Node.js: ), but in general, the answer is no, they do not support fully concurrent native threading, so Julia is not alone in this.When we do add shared-memory parallelism to Julia,  \u2013 whether using native threads or multiple processes with shared memory \u2013\u00a0it will be true concurrency and there will be no GIL preventing simultaneous execution of Julia code. However, this is an incredibly tricky feature to add to a language, as attested by the non-existent or limited support in other very popular, mature dynamic languages. Adding a shared-memory concurrency model is technically difficult, but the real problem is designing a programming model that will allow programmers to make effective use of hardware concurrency in a productive and safe way. This problem is generally unsolved and is a very active area of research and experimentation \u2013 there is no \"gold standard\" to copy. We could just add POSIX threads support, but that programming model is general considered to be dangerous and incredibly difficult to use correctly and effectively. Go has an excellent concurrency story, but it is designed for writing highly concurrent servers, not for concurrently operating on large data, so it's not at all clear that simply copying Go's model is a good idea for Julia.
Python

I keep seeing functions and documentation like  and   which operate on or refer to .I'm quite aware of what exactly an actual list is (), and can deduce what () methods from a list are necessary in most references to a \"list-like object\", however the number of times I see it referenced has left me with the following question:    Is it as simple as actualizing, or is it agreed that additional things like  and are required as well? This may seem like semantics, but I can't help but think that if there does not exist a standard minimal interface requirement, various ideas of  could cause some issues/improper handling. Perhaps this is just a slight downside to Python's duck typing? See the  module. Of the abstract base classes listed there,  in Python implements , , ,  and . Now, of these, ,  and  could be casually called .However, I would understand the term  to mean that it is a  - has at least the methods , ,  and , expecting also it to have the  mixin methods mentioned in the documentation, such as .If there is no need for  and  it should be called a sequence instead - the assumption is that if something accepts a sequence, it does not need to be mutable, thus , ,  etc also work there.Your two links highlight the vagueness of the term:The plotly API requires that the  objects will be serialized to a JSON array by the internal  that delegates most of the encoding to the Python . However, the latter encodes only  and  (and subclasses) to a JSON array; thus the  here means a , a  or subclasses thereof. A custom sequence object that is not a subclass of either will result in .The  you linked to requires an object that behaves like a , (mutability is not required), thus a  or , or any custom object implementing  will do there.TL;DR  is a vague term. It is preferable to use the terms iterable, sequence and mutable sequence instead, now that these are defined in .The technical term for a \"list-like object\" is . At the very least it supports ordering (i.e. two objects with the same elements but different order are not equal), indexing ( such that  is an integer less than the length of the sequence), and containment checking (), and has a given length. It  support iteration, but if not then Python will simulate it using indexing.Pretty much any time you see \"-like object\" in Python documentation the author is being deliberately vague. The author has decided that enumerating all the required interfaces would be too much trouble, and is only saying that some of its interfaces are required. An object that implemented all the interfaces is guaranteed to work, but in most cases it will work with an object that implements much less.With a \"list-like object\" probably the best you can do, short of inspecting the source code, is to infer whether it needs any of the mutable interfaces. If it only needs read-only access to the list, you can be pretty sure you don't need to implement any of the mutable sequence operations. If it says \"list-like object or iterator\" you can provide something that implements the much simpler iterator interface.
Python

Can I extend syntax in python for dict comprehensions for other dicts, like the OrderedDict in  module or my own types which inherit from ?  Just rebinding the  name obviously doesn't work, the  comprehension syntax still gives you a plain old dict for comprehensions and literals.  So, if it's possible how would I go about doing that?  It's OK if it only works in CPython.  For syntax I guess I would try it with a  prefix like we have on the .  Of course we can use a generator expression instead, but I'm more interested seeing how hackable python is in terms of the grammar.There is no direct way to change Python's syntax from within the language. A dictionary comprehension (or plain display) is always going to create a , and there's nothing you can do about that. If you're using CPython, it's using special bytecodes that generate a dict directly, which ultimately call the  API functions and/or the same underlying functions used by that API. If you're using PyPy, those bytecodes are instead implemented on top of an RPython  object which in turn is implemented on top of a compiled-and-optimized Python . And so on.There is an  way to do it, but you're not going to like it. If you read the docs on , you'll see that it's the importer that searches for cached compiled code or calls the compiler, and the compiler that calls the parser, and so on. In Python 3.3+, almost everything in this chain either is written in pure Python, or has an alternate pure Python implementation, meaning you can fork the code and do your own thing. Which includes parsing source with your own PyParsing code that builds ASTs, or compiling a dict comprehension AST node into your own custom bytecode instead of the default, or post-processing the bytecode, or\u2026In many cases, an  is sufficient; if not, you can always write a custom finder and loader.If you're not already using Python 3.3 or later, I'd strongly suggest migrating before playing with this stuff. In older versions, it's harder, and less well documented, and you'll ultimately be putting in 10x the effort to learn something that will be obsolete whenever you do migrate.Anyway, if this approach sounds interesting to you, you might want to take a look at . You could borrow some code from it\u2014and, maybe more importantly, learn how some of these features (that have no good examples in the docs) are used.Or, if you're willing to settle for something less cool, you can just use  to build an \"odict comprehension macro\" and use that. (Note that MacroPy currently only works in Python 2.7, not 3.x.) You can't quite get , but you can get, say, , which isn't too bad. Download , , and , and run  to see it working. The key is this code, which takes a  AST, converts it to an equivalent  on key-value s, and wraps it in a  to :A different alternative is, of course, to modify the Python interpreter.I would suggest dropping the  syntax idea for your first go, and just making normal dict comprehensions compile to odicts. The good news is, you don't really need to change the grammar (which is beyond hairy\u2026), just any one of:The bad news, while all of those are a lot easier than changing the grammar, none of them can be done from an extension module. (Well, you can do the first one by doing basically the same thing you'd do from pure Python\u2026 and you can do any of them by hooking the .so/.dll/.dylib to patch in your own functions, but that's the exact same work as hacking on Python plus the extra work of hooking at runtime.)If you want to hack on , the code you want is in , , and , and the  tells you how to find everything you need. But you might want to consider hacking on  instead, since it's mostly written in (a subset of) Python rather than C.As a side note, your attempt wouldn't have worked even if everything were done at the Python language level.  creates a binding named  in your module's globals, which  the name in builtins, but doesn't replace it. You  replace things in builtins (well, Python doesn't guarantee this, but there are implementation/version-specific things-that-happen-to-work for every implementation/version I've tried\u2026), but what you did isn't the way to do it.Sorry, not possible. Dict literals and dict comprehensions map to the built-in dict type, in a way that's hardcoded at the C level. That can't be overridden.You can use this as an alternative, though:Slightly modifying the response of @Max Noel, you can use list comprehension instead of a generator to create an OrderedDict in an ordered way (which of course is not possible using dict comprehension).
Python

For example purposes...So I end up with string1, string2, string3... all equaling \"Hello\"Sure you can; its called a :I said this somewhat tongue in check, but really the best way to associate one value with another value is a dictionary. That is what it was designed for!    It is really bad idea, but...and then for example:will give you:However this is bad practice. You should use dictionaries or lists instead, as others propose. Unless, of course, you really wanted to know how to do it, but did not want to use it.It's simply pointless to create variable variable names. Why? Using a list is much easier:I would use a list:This way, you would have 9 \"Hello\" and you could get them individually like this:Where  would identify which \"Hello\" you want.So,  would print .Don't do this use a dictionarydon't do this use a dictglobals() has risk as it gives you what the namespace is currently pointing to but this can change and so modifying the return from  globals() is not a good idea
Python

I want to log how long something takes in real walltime. Currently I'm doing this:But that will fail (produce incorrect results) if the time is adjusted while the SQL query (or whatever it is) is running.I don't want to just benchmark it. I want to log it in a live application in order to see trends on a live system.I want something like clock_gettime(CLOCK_MONOTONIC,...), but in Python. And preferably without having to write a C module that calls clock_gettime().That function is simple enough that you can use ctypes to access it:Now, in Python 3.3 you would use .As pointed out in , avoiding NTP readjustments on Linux requires CLOCK_MONOTONIC_RAW. That's defined as 4 on Linux (since 2.6.28).Portably getting the correct constant #defined in a C header from Python is tricky; there is h2py, but that doesn't really help you get the value at runtime. might be useful:
Python

I need to completely remove elements, based on the contents of an attribute, using python's lxml.  Example:I would like this to print:Is there a way to do this without storing a temporary variable and printing to it manually, as:Use the  method of an xmlElement : If I had to compare with the @Acorn version, mine will work even if the elements to remove are not directly under the root node of your xml.You're looking for the  function. Call the tree's remove method and pass it a subelement to remove.I met one situation: will remove the  part which I didn't mean to.following the answer , I found that  is a better solution for me, which you can control whether you will remove the text behind with  param.But I still don't know if this can use xpath filter for tag. Just put this for informing.Here is the doc:
Python

I am a bit confused on what  does in Python. For example, why does the below trials do what they do (consistently)? I couldn't find good documentation on this. Thanks in advance!Pseudo-random number generators work by performing some operation on a value. Generally this value is the previous number generated by the generator. However, the first time you use the generator, there is no previous value.Seeding a pseudo-random number generator gives it its first \"previous\" value. Each seed value will correspond to a sequence of generated values for a given random number generator. That is, if you provide the same seed twice, you get the same sequence of numbers twice.Generally, you want to seed your random number generator with some value that will change each execution of the program. For instance, the current time is a frequently-used seed. The reason why this doesn't happen automatically is so that if you want, you can provide a specific seed to get a known sequence of numbers.All the other answers don't seem to explain the use of random.seed(). \nHere is a simple example ():You try this. Let's say 'random.seed' gives a value to random value generator ('random.randint()') which generates these values on the basis of this seed. One of the must properties of random numbers is that they should be reproducible. Once you put same seed you get the same pattern of random numbers. So you are generating them right from the start again. You give a different seed it starts with a different initial (above 3).You have given a seed now it will generate random numbers between 1 and 10 one after another. So you can assume one set of numbers for one seed value.                    In this case, random is actually pseudo-random. Given a seed, it will generate numbers with an equal distribution. But with the same seed, it will generate the same number sequence every time. If you want it to change, you'll have to change your seed. A lot of people like to generate a seed based on the current time or something.Imho, it is used to generate same random course result when you use  again.Here is a small test that demonstrates that feeding the  method with the same argument will cause the same pseudo-random result:
Python

Python uses the reference count method to handle object life time. So an object that has no more use will be immediately destroyed.But, in Java, the GC(garbage collector) destroys objects which are no longer used at a specific time.Why does Java choose this strategy and what is the benefit from this?Is this better than the Python approach?There are drawbacks of using reference counting. One of the most mentioned is circular references: Suppose A references B, B references C and C references B. If A were to drop its reference to B, both B and C will still have a reference count of 1 and won't be deleted with traditional reference counting. CPython (reference counting is not part of python itself, but part of the C implementation thereof) catches circular references with a separate garbage collection routine that it runs periodically...Another drawback: Reference counting can make execution slower. Each time an object is referenced and dereferenced, the interpreter/VM must check to see if the count has gone down to 0 (and then deallocate if it did). Garbage Collection does not need to do this.Also, Garbage Collection can be done in a separate thread (though it can be a bit tricky). On machines with lots of RAM and for processes that use memory only slowly, you might not want to be doing GC at all! Reference counting would be a bit of a drawback there in terms of performance...Actually reference counting and the strategies used by the Sun JVM are all different types of garbage collection algorithms.There are two broad approaches for tracking down dead objects: tracing and reference counting. In tracing the GC starts from the \"roots\" - things like stack references, and traces all reachable (live) objects. Anything that can't be reached is considered dead. In reference counting each time a reference is modified the object's involved have their count updated. Any object whose reference count gets set to zero is considered dead.With basically all GC implementations there are trade offs but tracing is usually good for high through put (i.e. fast) operation but has longer pause times (larger gaps where the UI or program may freeze up). Reference counting can operate in smaller chunks but will be slower overall. It may mean less freezes but poorer performance overall.Additionally a reference counting GC requires a cycle detector to clean up any objects in a cycle that won't be caught by their reference count alone. Perl 5 didn't have a cycle detector in its GC implementation and could leak memory that was cyclic.Research has also been done to get the best of both worlds (low pause times, high throughput):\nDarren Thomas gives a good answer.  However, one big difference between the Java and Python approaches is that with reference counting in the common case (no circular references) objects are cleaned up immediately rather than at some indeterminate later date.For example, I can write sloppy, non-portable code in CPython such asand the file descriptor for that file I opened will be cleaned up immediately because as soon as the reference to the open file goes away, the file is garbage collected and the file descriptor is freed.  Of course, if I run Jython or IronPython or possibly PyPy, then the garbage collector won't necessarily run until much later; possibly I'll run out of file descriptors first and my program will crash.So you SHOULD be writing code that looks likebut sometimes people like to rely on reference counting to always free up their resources because it can sometimes make your code a little shorter.I'd say that the best garbage collector is the one with the best performance, which currently seems to be the Java-style generational garbage collectors that can run in a separate thread and has all these crazy optimizations, etc.  The differences to how you write your code should be negligible and ideally non-existent.I think the article \"\" from IBM should help explain some of the questions you have.Garbage collection is faster (more time efficient) than reference counting, if you have enough memory. For example, a copying gc traverses the \"live\" objects and copies them to a new space, and can reclaim all the \"dead\" objects in one step by marking a whole memory region. This is very efficient,  you have enough memory. Generational collections use the knowledge that \"most objects die young\"; often only a few percent of objects have to be copied.[This is also the reason why gc can be faster than malloc/free]Reference counting is much more space efficient than garbage collection, since it reclaims memory the very moment it gets unreachable. This is nice when you want to attach finalizers to objects (e.g. to close a file once the File object gets unreachable). A reference counting system can work even when only a few percent of the memory is free. But the management cost of having to increment and decrement counters upon each pointer assignment cost a lot of time, and some kind of garbage collection is still needed to reclaim cycles.So the trade-off is clear: if you have to work in a memory-constrained environment, or if you need precise finalizers, use reference counting. If you have enough memory and need the speed, use garbage collection.One big disadvantage of Java's tracing GC is that from time to time it will  \"stop the world\" and freeze the application for a relatively long time to do a full GC. If the heap is big and the the object tree complex, it will freeze for a few seconds. Also each full GC visits the whole object tree over and over again, something that is probably quite inefficient. Another drawback of the way Java does GC is that you have to tell the jvm what heap size you want (if the default is not good enough); the JVM derives from that value several thresholds that will trigger the GC process when there is too much garbage stacking up in the heap.I presume that this is actually the main cause of the jerky feeling of Android (based on Java), even on the most expensive cellphones, in comparison with the smoothness of iOS (based on ObjectiveC, and using RC). I'd love to see a jvm option to enable RC memory management, and maybe keeping GC only to run as a last resort when there is no more memory left. The latest Sun Java VM actually have multiple GC algorithms which you can tweak.  The Java VM specifications intentionally omitted specifying actual GC behaviour to allow different (and multiple) GC algorithms for different VMs.For example, for all the people who dislike the \"stop-the-world\" approach of the default Sun Java VM GC behaviour, there are VM such as  which allows real-time application to run on Java.Since the Java VM spec is publicly available, there is (theoretically) nothing stopping anyone from implementing a Java VM that uses CPython's GC algorithm.Reference counting is particularly difficult to do efficiently in a multi-threaded environment. I don't know how you'd even start to do it without getting into hardware assisted transactions or similar (currently) unusual atomic instructions.Reference counting is easy to implement. JVMs have had a lot of money sunk into competing implementations, so it shouldn't be surprising that they implement very good solutions to very difficult problems. However, it's becoming increasingly easy to target your favourite language at the JVM.Late in the game, but I think one significant rationale for RC in python is its simplicity. See this , for example.(I could not find a link outside google cache, the email date from 13th october 2005 on python list).
Python

I really don't understand where are  and  used in Python. I mean, I get that  returns the string representation of an object. But why would I need that? In what use case scenario? Also, I read about the usage of But what I don't understand is, where would I use them? Use  if you have a class, and you'll want an informative/informal output, whenever you use this object as part of string. E.g. you can define  methods for Django models, which then gets rendered in the Django administration interface. Instead of something like  you'll get like first and last name of a person, the name and date of an event, etc. and  are similar, in fact sometimes equal (Example from  class in  from the standard library):The one place where you use them both a lot is in an interactive session. If you print an object then its  method will get called, whereas if you just use an object by itself then its  is shown:The  is intended to be as human-readable as possible, whereas the  should aim to be something that could be used to recreate the object, although it often won't be exactly how it was created, as in this case.It's also not unusual for both  and  to return the same value (certainly for built-in types).Grasshopper, when in doubt  and . In them you will find that __repr__() should: 
Python

I am using python to work out how many children would be born in 5 years if a child was born every 7 seconds. The problem is on my last line. How do I get a variable to work when I'm printing text either side of it? Here is my code:Use  to separate strings and variables while printing: in print statement separtes the items by a single space:or better use :String formatting is much more powerful and allows you to do some other things as well, like : padding, fill, alignment,width, set precision etcDemo:two moreWhen adding strings, they concatenate. Also the  (Python 2.6 and newer) method of strings is probably the standard way:This  method can be used with lists as wellor dictionariesYou can either use a formatstring:or in this simple case:On a current python version you have to use parenthesis, like so :print (\"If there was a birth every 7 seconds\", X)I copied and pasted your script into a .py file. I ran it as-is with Python 2.7.10 and received the same syntax error. I also tried the script in Python 3.5 and received the following output:Then, I modified the last line where it prints the number of births as follows:The output was (Python 2.7.10):I hope this helps.If you want to work with python 3, it's very simple: You can use  to do this:or you can give  multiple arguments, and it will automatically separate them by a space:You would first make a variable: for example: D = 1. Then Do This but replace the string with whatever you want:
Python

I am trying to do this:But that's not right...the documentation is vague...how do you do this in Jinja2?As of version 2.6, Jinja2's built-in sort filter allows you to specify an attribute to sort by:See Usually we sort the list before giving it to Jinja2.  There's no way to specify a key in Jinja's  filter.However, you can always try .  That's the syntax.  You don't get to provide any sort of key information for the sorting.You can also try and write a custom filter for this.  Seems silly when you can sort before giving the data to Jinja2.If  is a list of objects, then you can define the various comparison methods (, , etc.) for the class of those objects.If  is a list of tuples or lists, the rating must be first.  Or you'll have to do the sorting outside Jinja2.If  is a list of dictionaries, then you can use , which does accept a key specification for the sorting.  Read this:  for an example.If you want to sort in ascending orderIf you want to sort in descending order
Python

I've got a Python list of dictionaries, as follows:I'd like to check whether a dictionary with a particular key/value already exists in the list, as follows:Here's one way to do it:The part in parentheses is a generator expression that returns  for each dictionary that has the key-value pair you are looking for, otherwise .If the key could also be missing the above code can give you a . You can fix this by using  and providing a default value.Perhaps a function along these lines is what you're after:Maybe this helps:
Python

I'm trying to install Pillow on Ubuntu 14.04 using this command:but the installation fails with this error:The problem was that the package  was not installed. To solve the problem you should do this:Make sure Python-development packages are installed, if not then install it using the following commands : After installing the development packages install the following :You have to install the missing dependencies and libraries that Pillow requires for it to work. Find the dependencies  This are the current dependancies/libraries for Ubuntu 14.04 for Pilllow 3.0.0+. Install them by running the command belowThere may be a problem where pip is relying on a cached version of the dependencies, and clearing the cache can sometimes solve the problem.  Just typeSource: You need to follow this tutorial .If you had installed, just uninstall and reinstall again:
Python

I would like to wipe out all data for a specific kind in Google App Engine. What is the\nbest way to do this?\nI wrote a delete script (hack), but since there is so much data is\ntimeout's out after a few hundred records. The  from Google is that you have to delete in chunks spread over multiple requests. You can use AJAX, , or request your URL from a script until there are no entities left.I am currently deleting the entities by their key, and it seems to be faster.from the terminal, I run curl -N http://...You can now use the Datastore Admin for that: If I were a paranoid person, I would say Google App Engine (GAE) has not made it easy for us to remove data if we want to. I am going to skip discussion on index sizes and how they translate a 6 GB of data to 35 GB of storage (being billed for). That's another story, but they do have ways to work around that - limit number of properties to create index on (automatically generated indexes) et cetera.The reason I decided to write this post is that I need to \"nuke\" all my Kinds in a sandbox. I read about it and finally came up with this code:I have over 6 million records. That's a lot. I have no idea what the cost will be to delete the records (maybe more economical not to delete them). Another alternative would be to request a deletion for the entire application (sandbox). But that's not realistic in most cases.I decided to go with smaller groups of records (in easy query). I know I could go for 500 entities, but then I started receiving very high rates of failure (re delete function).Try using  then you dont even have to deploy any special codePresumably your hack was something like this:As you say, if there's sufficient data, you're going to hit the request timeout before it gets through all the records. You'd have to re-invoke this request multiple times from outside to ensure all the data was erased; easy enough to do, but hardly ideal.The admin console doesn't seem to offer any help, as (from my own experience with it), it seems to only allow entities of a given type to be listed and then deleted on a page-by-page basis.When testing, I've had to purge my database on startup to get rid of existing data.I would infer from this that Google operates on the principle that disk is cheap, and so data is typically orphaned (indexes to redundant data replaced), rather than deleted. Given there's a fixed amount of data available to each app at the moment (0.5 GB), that's not much help for non-Google App Engine users.I've tried db.delete(results) and App Engine Console, and none of them seems to be working for me. Manually removing entries from Data Viewer (increased limit up to 200) didn't work either since I have uploaded more than 10000 entries. I ended writing this script The trick was to include redirect in html instead of using self.redirect. I'm ready to wait overnight to get rid of all the data in my table. Hopefully, GAE team will make it easier to drop tables in the future.  The fastest and efficient way to handle bulk delete on Datastore is by using the new  announced on the latest .If your language of choice is , you just have to register your mapper in a  file  and define a function like this:On  you should have a look to  that suggests a function like this:One tip. I suggest you get to know the  for these types of uses (bulk deleting, modifying, etc.).  But, even with the remote api, batch size can be limited to a few hundred at a time.Unfortunately, there's no way to easily do a bulk delete. Your best bet is to write a script that deletes a reasonable number of entries per invocation, and then call it repeatedly - for example, by having your delete script return a 302 redirect whenever there's more data to delete, then fetching it with \"wget --max-redirect=10000\" (or some other large number).With django, setup url: Setup viewThen run in powershell:If you are using Java/JPA you can do something like this:Java/JDO info can be found here: Yes you can:\nGo to Datastore Admin, and then select the Entitiy type you want to delete and click Delete.\nMapreduce will take care of deleting!You can use the task queues to delete chunks of say 100 objects.\nDeleting objects in GAE shows how limited the Admin capabilities are in GAE. You have to work with batches on 1000 entities or less. You can use the bulkloader tool that works with csv's but the documentation does not cover java.\nI am using GAE Java and my strategy for deletions involves having 2 servlets, one for doing the actually delete and another to load the task queues. When i want to do a delete, I run the queue loading servlet, it loads the queues and then GAE goes to work executing all the tasks in the queue.How to do it:\nCreate a servlet that deletes a small number of objects.\nAdd the servlet to your task queues.\nGo home or work on something else ;)\nCheck the datastore every so often ...I have a datastore with about 5000 objects that i purge every week and it takes about 6 hours to clean out, so i run the task on Friday night.\nI use the same technique to bulk load my data which happens to be about 5000 objects, with about a dozen properties. This worked for me:Thank you all guys, I got what I need. :D\nThis may be useful if you have lots db models to delete, you can dispatch it in your terminal. And also, you can manage the delete list in DB_MODEL_LIST yourself.\nDelete DB_1:Delete All DB:Here is the bulkdel.py file:And here is the modified version of alexandre fiori's code.And of course, you should map the link to model in a file(like main.py in GAE), ;)\nIn case some guys like me need it in detail, here is part of main.py:On a , one can cd to his app's directory then run it like this:Doing so will start the app and clear the datastore.  If you already have another instance running, the app won't be able to bind to the needed IP and therefore fail to start...and to clear your datastore. In javascript, the following will delete all the entries for on page:given that you are on the admin-page (.../_ah/admin) with the entities you want to delete.
Python

At the moment, I'm doing stuff like the following, which is getting tedious:I'm guessing there is some more accepted way of handling this stuff?What I'm looking for is having a function execute once, on demand. For example, at the press of a certain button. It is an interactive app which has a lot of user controlled switches. Having a junk variable for every switch, just for keeping track of whether it has been run or not, seemed kind of inefficient.I would use a decorator on the function to handle keeping track of how many times it runs.Now  will only run once. Other calls to it will return . Just add an  clause to the  if you want it to return something else. From your example, it doesn't need to return anything ever.If you don't control the creation of the function, or the function needs to be used normally in other contexts, you can just apply the decorator manually as well.This will leave  available for other uses.Finally, if you need to only run it once twice, then you can just doAnother option is to set the   for your function to be a code object for a function that does nothing. This should be done at the end of your function body.For example:Here  replaces your function's executable code with the code for lambda:None, so all subsequent calls to  will do nothing.This technique is less flexible than the decorator approach suggested in the , but may be more concise if you only have one function you want to run once. Run the function before the loop. Example:This is the obvious solution. If there's more than meets the eye, the solution may be a bit more complicated.I'm assuming this is an action that you want to be performed at most one time, if some conditions are met. Since you won't always perform the action, you can't do it unconditionally outside the loop. Something like lazily retrieving some data (and caching it) if you get a request, but not retrieving it otherwise.There are many ways to do what you want; however, do note that it is quite possible that \u2014as described in the question\u2014 you don't have to call the function inside the loop.If you insist in having the function call inside the loop, you can also do:I've thought of another, very effective way to do this that doesn't require decorator function or classes. Instead it just uses a mutable keyword argument, which ought to work in most versions of Python. Most of the time these are something to be avoided since normally you wouldn't want a default argument value to be able to change from call-to-call -- but that ability can be leveraged and used as cheap storage mechanism. Here's how it would work:This could be simplified a little further by doing  and using an iterator (which were introduced in Python 2.2.):Here's an answer that doesn't involve reassignment of functions, yet still prevents the need for that ugly \"is first\" check. is supported by Python 2.5 and above.Output:Assuming there is some reason why  can't be called before the loopHere's an explicit way to code this up, where the state of which functions have been called is kept locally (so global state is avoided). I don't much like the non-explicit forms suggested in other answers: it's too surprising to see f() and for this not to mean that f() gets called.This works by using dict.pop which looks up a key in a dict, removes the key from the dict, and takes a default value to use in case the key isn't found.Why is this any different from your code?If I understand the updated question correctly, something like this should workOne object-oriented approach and make your function a class, aka as a \"functor\", whose instances automatically keep track of whether they've been run or not when each instance is created. Since your updated question indicates you may need many of them, I've updated my answer to deal with that by using a  pattern. This is a bit unusual, and iy may have been down-voted for that reason (although we'll never know for sure because they never left a comment). It could also be done with a metaclass, but it's not much simpler.Output:Note: You could make a function/class able to do stuff again by adding a  method to its subclass that reset the shared  attribute. It's also possible to pass regular and keyword arguments to the  method when the functor is created and the method is called, if desired.And, yes, it would be applicable given the information you added to your question.If the condition check needs to happen only once you are in the loop, having a flag signaling that you have already run the function helps. In this case you used a counter, a boolean variable would work just as fine.I'm not sure that I understood your problem, but I think you can divide loop. On the part of the function and the part without it and save the two loops.
Python

I want to return status code  from a Django view. It is in response to an automatic POST which updates a database and I just need to indicate the update was successful (without redirecting the client).There are subclasses of  to handle most other codes but not 204.What is the simplest way to do this?Either what Steve Mayne answered, or build your own by subclassing HttpResponse:When using , there is a  keyword argument.(Note that in the case of status 204 there shouldn't be a response body, but this method is useful for other status codes.)
Python

i am trying to get the latest django model object but cannot seem to succeed. neithernoris working. please help. See the docs from django:\nYou need to specify a field in latest(). eg. Or if your model\u2019s Meta specifies get_latest_by, you can leave off the  argument to . Django will use the field specified in  by default. is really designed to work with date fields (it probably does work with other total-ordered types too, but not sure). And the only way you can use it without specifying the field name is by setting the  meta attribute, as mentioned .
Python

I have a prefix that I want to add to every route.  Right now I add a constant to the route at every definition.  Is there a way to do this automatically?The answer depends on how you are serving this application.Assuming that you are going to run this application inside of a WSGI container (mod_wsgi, uwsgi, gunicorn, etc); you need to actually  the application as a sub-part of that WSGI container (anything that speaks WSGI will do) and to set your  config value to your prefix:Setting the  config value simply limit Flask's session cookie to that URL prefix.  Everything else will be automatically handled for you by Flask and Werkzeug's excellent WSGI handling capabilities.If you are not sure what the first paragraph means, take a look at this example application with Flask mounted inside of it:If, on the other hand, you will be running your Flask application at the root of its WSGI container and proxying requests to it (for example, if it's being FastCGI'd to, or if nginx is -ing requests for a sub-endpoint to your stand-alone  /  server then you can either:You can put your routes in a blueprint:Then you register the blueprint with the application using a prefix:All you have to do is to write a middleware to make the following changes:Like this:Wrap your app with the middleware, like this:Visit ,You will get the right result: And don't forget to set the cookie domain if you need to.This solution is given by . The  is not for this job, although it looks like to be. It's really confusing.This is more of a python answer than a Flask/werkzeug answer; but it's simple and works.If, like me, you want your application settings (loaded from an  file) to also contain the prefix of your Flask application (thus, not to have the value set during deployment, but during runtime), you can opt for the following:Arguably, this is somewhat hackish and relies on the fact that the Flask route function  a  as a first positional argument.You can use it like this:So, I believe that a valid answer to this is: the prefix should be configured in the actual server application that you use when development is completed. Apache, nginx, etc.However, if you would like this to work during development while running the Flask app in debug, take a look at .I'll copy the code here for posterity:Now, when running the above code as a standalone Flask app,  will display .In a comment on another answer, I expressed that I wished to do something like this:Applying  to my contrived example:
Python

I'm writing a script to check permissions of files in user's directories and if they're not acceptable I'll be warning them, but I want to check permissions of not just the logged in user, but also group and others. How can i do this? It seems to me that .access() in Python can only check the permissions for the user running the script.You're right that , like the underlying  syscall, checks for a specific user (real rather than effective IDs, to help out with suid situations). is the right way to get more general info about a file, including permissions per user, group, and others.  The  attribute of the object that  returns has the permission bits for the file.To help interpret those bits, you may want to use the  module.  Specifically, you'll want the bitmasks defined , and you'll use the  operator (bit-and) to use them to mask out the relevant bits in that  attribute -- for example, if you just need a True/False check on whether a certain file is group-readable, one approach is:Take care: the  call can be somewhat costly, so make sure to extract all info you care about with a single call, rather than keep repeating calls for each bit of interest;-).Use  with flags , , and .: Check out  if you are testing directory permissions on Windows.You can check file permissions via  in conjunction with the  module for interpreting the results. and the associated  for the mode.
Python

I have a tar file which has number of files within it.\nI need to write a python script which will read the contents of the files and gives the count o total characters, including  total number of letters, spaces, newline characters, everything,  without untarring the tar file.you can use getmembers()After that, you can use extractfile() to extract the members as file object. Just an exampleWith the file object \"f\" in the above example, you can use read(), readlines() etc. you need to use the tarfile module. Specifically, you use an instance of the class TarFile to access the file, and then access the names with TarFile.getnames()     If instead you want to read the , then you use this methodAn implementation of the methods mentioned by @stefano-borini\nAccess a tar archives member via file name like so Credits:
Python

If I had two strings,  and , I could get all combinations of them using two for loops:However, I would like to be able to do this using list comprehension. I've tried many ways, but have never managed to get it. Does anyone know how to do this?orif you want tuples.Like in the question,  is the outer loop,  is the inner loop.Essentially, you can have as many independent 'for x in y' clauses as you want in a list comprehension just by sticking one after the other.Since this is essentially a Cartesian product, you can also use . I think it's clearer, especially when you have more input iterables.Try recursion too:Gives you the 8 combinations:
Python

When running python26 under windows OS (64bits).....\nI have got errors like:orI have done the msi installation for python26\nall dlls can be found under C:\\Python26\\Lib\\site-packages\\pywin32_system32After I move/copy pywintypes26.dll and pythoncom26.dll to c:\\Python26\\Lib\\site-packages\\win32 -> Solve the problem!I also hit a problem importing win32api. The post-install script for pywin32 failed, which should copy , , and , among other things.  I ran it by hand and my installation was fixed.I had a similar problem when installing under 64 bit Python 3.4.2. I ran the install executable pywin32\u2011219.win\u2011amd64\u2011py3.4.exe from  . On the site it states clearly: \"Python 3.4 users must manually run  from an elevated command prompt.\" which I did not do first time round; I installed from a normal prompt getting the following feedback:I only read the last sentence and I started to run some code resulting in getting these dll load fails.So, did some research, and started an elevated prompt (how: see \"\") and again ran:And now my code runs happily (as far as this matter is concerned... sigh, so much other stuff to do).Run the installer as Administrator and it works:I always install the Active State Python distro which installs the win32 packages for you and gets it right.There appears to be a . The recommended workaround in the ticket is the same one as proposed by Dave Bremer.I could fix this situation by removing all installed Python3.4 versions (had forgotten to uninstall 3.4.1 before installing 3.4.2), deleting C:\\Python34 and after installing Python 3.4.2 pywin32-219.win32-py34.exe could be installed and called without problems.\nSo, copying around DLLs should NOT be necessary!As suggested above the post install script is not run, this issue can be seen when installing from a wheel (As I encountered)If find you have this issue when installing via wheels, then installing it from here can solve the above issue.If the above didn't fix the problem, you're still missing the  file.  It's either in your  folder, or more likely in your  folder.That fixed it for me after hours of search to no avail, even though it looks like the import still isn't resolved as it should be (PyCharm still gives me the squiggly underline), but it works.
Python

I have code that relies heavily on yaml for cross-language serialization and while working on speeding some stuff up I noticed that yaml was insanely slow compared to other serialization methods (e.g., pickle, json).So what really blows my mind is that json is so much faster that yaml when the output is nearly identical.PyYaml's CSafeDumper and cjson are both written in C so it's not like this is a C vs Python speed issue. I've even added some random data to it to see if cjson is doing any caching, but it's still way faster than PyYaml. I realize that yaml is a superset of json, but how could the yaml serializer be 2 orders of magnitude slower with such simple input?In general, it's not the complexity of the output that determines the speed of parsing, but the complexity of the accepted input. The JSON grammar is . The YAML parsers are , leading to increased overheads.I'm not a YAML parser implementor, so I can't speak specifically to the orders of magnitude without some profiling data and a big corpus of examples. In any case, be sure to test over a large body of inputs before feeling confident in benchmark numbers.  Whoops, misread the question. :-( Serialization can still be blazingly fast despite the large input grammar; however, browsing the source, it looks like PyYAML's Python-level serialization  whereas simplejson encodes builtin Python datatypes directly into text chunks.In applications I've worked on, the type inference between strings to numbers (float/int) is where the largest overhead is for parsing yaml is because strings can be written without quotes.  Because all strings in json are in quotes there is no backtracking when parsing strings.  A great example where this would slow down is the value 0000000000000000000s.  You cannot tell this value is a string until you've read to the end of it.  The other answers are correct but this is a specific detail that I've discovered in practice.Speaking about efficiency, I used YAML for a time and felt attracted by the simplicity that some name/value assignments take on in this language. However, in the process I tripped so and so often about one of YAML\u2019s finesses, subtle variations in the grammar that allow you to write special cases in a more concise style and such. In the end, although YAML\u2019s grammar is almost for certain formally consistent, it has left me with a certain feeling of \u2018vagueness\u2019. I then restricted myself to not touch existing, working YAML code and write everything new in a more roundabout, fail-safe syntax\u2014which made me abandon all of YAML. The upshot is that YAML tries to look like a W3C standard, and produces a small library of hard to read literature concerning its concepts and rules.This, I feel, is by far more intellectual overhead than needed. Look at SGML/XML: developed by IBM in the roaring 60s, standardized by the ISO, known (in a dumbed-down and modified form) as HTML to uncounted millions of people, documented and documented and documented again the world over. Comes up little JSON and slays that dragon. How could JSON become so widely used in so short a time, with just one meager website (and a javascript luminary to back it)? It is in its simplicity, the sheer absence of doubt in its grammar, the ease of learning and using it.XML and YAML are hard for humans, and they are hard for computers. JSON is quite friendly and easy to both humans and computers.A cursory look at python-yaml suggests its design is much more complex than cjson's:More complex designs almost invariably mean slower designs, and this is far more complex than most people will ever need.
Python

Google didn't turn up anything that seemed relevant.I have a bunch of existing, working C++ code, and I'd like to use python to crawl through it and figure out relationships between classes, etc.EDIT: Just wanted to point out: I don't think I need or want to parse every bit of C++; I just need something smart enough to pick up on class, function and member variable declarations, and to skip over function definitions. C++ is notoriously hard to parse. Most people who try to do this properly end up taking apart a compiler. In fact this is (in part) why LLVM started: Apple needed a way they could parse C++ for use in XCode that matched the way the compiler parsed it. That's why there are projects like  which you could combine with a python xml library.Some non-compiler projects that seem to do a pretty good job at parsing C++ are:Not an answer as such, but just to demonstrate how hard parsing C++ correctly actually is. My favorite demo:This is perfectly valid, standard-compliant C++, but the exact meaning of commented line depends on your implementation. If  (typical on 32-bit platforms), it is a declaration of local variable  of type . If the condition doesn't hold, then it is a no-op expression . Adding a constructor for  will actually let you expose the difference via presence/absence of side effects.For many years I've been using , which is a very nice Python wrapper around GCC-XML.  It's a very full featured package that forms the basis of some well used code-generation tools out there such as  which is from the same author.You won't find a drop-in Python library to do this. Parsing C++ is fiddly, and few parsers have been written that aren't part of a compiler. You can find a good summary of the issues .The best bet might be , as its C++ support is . Though this is not a Python solution, it sounds as though it would be amenable to re-use within a Python wrapper, given the emphasis on encapsulation and good design in its development. is a complete and functional parser for ANSI C.\nPerhaps you can extend it to c++ :-)If you've formatted your comments in a compatible way,  does a fantastic job. It'll even draw inheritance diagrams if you've got  installed.For example, running DOxygen over the following:Will turn all those comments into entries in .html files. With more complicated designs, the result is even more beneficial - often much easier than trying to browse through the source. shows a C++ grammar written in Antlr, and you  from it.There also seems to be someone who was working on a C++ parser in pyparsing, but I was not able to find out who or its current status.There is no (free) good library to parse C++ in  language.\nYour best choices are probably  g++ plugin, , or .The pyparsing wiki shows this example - all it does is parse struct declarations, so this might give you just a glimpse at the magnitude of the problem.I suggest you (or even better, your employer) shell out $200 and buy .  This software is amazingly powerful for the price, and includes pretty good code reverse engineering features.  You will spend far more than this in your own time to only get about 2% of the job done.  In this case, \"buys\" wins over \"make\". uses  for code generation. It's possible that cpptypes does also.  Even if it doesn't, you could use gcc-xml to generate XML from your C++ file, then parse the xml with one of the built-in or third-party Python XML parsers.Here's a SourceForge project that claims to parse c++ headers. As the other commenters have pointed out, there's no general solution, but you this sounds like it will do enough for your needs. (I just ran across it for a similar need and haven't tried it myself yet.)The Clang project provides libraries for just parsing C++ code.Either with Clang and GCC you can generate an XML representation of the codeIf you prefer a more Pythonian solution you could also search for a C++ yacc grammar and use py-ply (Yacc for Python), but that seems the solution that needs more workI would keep an eye on the  as it seems like plugins are the way to go. Also the  seems like it has a nice implementation.
Python

How do I convert  to ?Are you trying to represent it with only one digit:or actually round off the other decimal places?or even round strictly down?Or use the builtin round:
Python

Can anyone recommend a Socket.IO client library for Python?\nI've had a look around, but the only ones I can find are either server implementations, or depend on a framework such as Twisted.I need a client library that has no dependencies on other frameworks.Simply using one of the many connection types isn't sufficient, as the python client will need to work with multiple socketio servers, many of which won't support websockets, for example.Archie1986's answer was good but has become outdated with socketio updates (more specifically, its protocol : )... as far as i can tell, you need to perform the handshake manually before you can ask for a transport (e.g., websockets) connection... note that the code below is incomplete and insecure... for one, it ignores the list of supported transports returned in the handshake response and always tries to get a websocket... also it assumes that the handshake always succeeds... nevertheless, it's a good place to startyou might also want to read up on python-websockets: First of all, I'm not sure why some of your Socket.IO servers won't support websockets...the intent of Socket.IO is to make front-end browser development of web apps easier by providing an abstracted interface to real-time data streams being served up by the Socket.IO server. Perhaps Socket.IO is not what you should be using for your application? That aside, let me try to answer your question...At this point in time, there aren't any Socket.IO client libraries for Python (gevent-socketio is not a Socket.IO  library for Python...it is a Socket.IO  library for Python). For now, you are going to have to piece some original code together in order to interface with Socket.IO directly as a client while accepting various connection types.I know you are looking for a cure-all that works across various connection types (WebSocket, long-polling, etc.), but since a library such as this does not exist as of yet, I can at least give you some guidance on using the WebSocket connection type based on my experience.For the WebSocket connection type, create a WebSocket client in Python. From the command line install this Python WebSocket Client package  with pip so that it is on your python path like so:Once you've done that try the following, replacing  and  with the appropriate location of your Socket.IO server: At this point you have a medium of interfacing with a Socket.IO server directly from Python. To send messages to the Socket.IO server simply send a message through this WebSocket connection. In order for the Socket.IO server to properly interpret incoming messages through this WebSocket from your Python Socket.IO client, you need to adhere to the Socket.IO protocol and encode any strings or dictionaries you might send through the WebSocket connection. For example, after you've accomplished everything above do the following:The  library supports event callbacks and channels thanks to the work of contributors and is available on  under the MIT license.The  library with the popular asynchronous  is also one of the options available for python.Wrote one: . It only supports websockets so it may have only marginal utility for you.Did you have a look at ?Hope it helps.
Python

I'm trying to write a fabric script that does a ; however, if there is nothing to commit, git exits with a status of . The deploy script takes that as unsuccessful, and quits. I do want to detect  failures-to-commit, so I can't just give fabric a blanket ignore for  failures. How can I allow empty-commit failures to be ignored so that deploy can continue, but still catch errors caused when a real commit fails?Catch this condition beforehand by checking the exit code of git diff?For example (in shell):From the  man page:This causes fabric to ignore the failure. Has the advantage of not creating empty commits.You can wrap it in a additional layer of  to totally suppress output, otherwise you'll get a note in the fabric output that the commit failed (but the fabfile continues to execute).  try/catch baby!
Python

Suppose I have the following code in a Python unit test:Is there an easy way to assert that a particular method (in my case ) was called during the second line of the test? e.g. is there something like this:I use  for this:For your case, it could look like this:Mock supports quite a few useful features, including ways to patch an object or module, as well as checking that the right thing was called, etc etc.  (Buyer beware!)If you mistype  (to  or ) your test may still run, as Mock will think this is a mocked function and happily go along, unless you use . For more info read .I'm not aware of anything built-in.  It's pretty simple to implement:This requires that the object itself won't modify self.b, which is almost always true.Yes if you are using Python 3.3+. You can use the built-in  to assert method called. Here is a quick example in your case:Yes, I can give you the outline but my Python is a bit rusty and I'm too busy to explain in detail.Basically, you need to put a proxy in the method that will call the original, eg:This  about callable may help you understand the above.Although the answer was accepted, due to the interesting discussion with Glenn and having a few minutes free, I wanted to enlarge on my answer:You can mock out , either manually or using a testing framework like . Manually, you'd do it using something like this:Using pymox, you'd do it like this:
Python

How do I serialize a Python dictionary into a string, and then back to a dictionary? The dictionary will have lists and other dictionaries inside it.It depends on what you're wanting to use it for. If you're just trying to save it, you should use  (or , which is faster, if using CPython as you probably are).However, if you want it to be readable, you could use or . and  are very limited in what they will support.  can be used for objects (if it doesn't work automatically, the class can define  to specify precisely how it should be pickled).Use Python's  module, or  if you don't have python 2.6 or higher. you fully trust the string and don't care about  then this is very simple solution:If you're more safety conscious then  is a better bet.Pickle is great but I think it's worth mentioning  from the  module for an even lighter weight solution if you're only serializing basic python types. It's basically a \"safe\" version of the notorious  function that only allows evaluation of basic python types as opposed to any valid python code.Example:One benefit is that the serialized data is just python code, so it's very human friendly. Compare it to what you would get with :The downside is that as soon as the the data includes a type that is not supported by  you'll have to transition to something else like pickling.While not strictly serialization, json may be reasonable approach here. That will handled nested dicts and lists, and data as long as your data is \"simple\": strings, and basic numeric types.  should also be mentioned here. It is both human readable and can serialize any python object.\npyyaml is hosted here:\n One thing  cannot do is  indexed with numerals. The following snippetwill throw Because keys are converted to strings.  preserves the numeric type and the unpacked  can be used right away.If you are trying to only serialize then pprint may also be a good option. It requires the object to be serialized and a file stream.Here's some code:I am not sure if we can deserialize easily. I was using json to serialize and deserialze earlier which works correctly in most cases.However, in one particular case, there were some errors writing non-unicode data to json.
Python

How can I add, subtract, and compare binary numbers in Python without converting to decimal?You can convert between a string representation of the binary using bin() and int()I think you're confused about what binary is.  Binary and decimal are just different representations of a number - e.g. 101 base 2 and 5 base 10 are the same number.  The operations add, subtract, and compare operate on numbers - 101 base 2 == 5 base 10 and addition is the same logical operation no matter what base you're working in.  The fact that your python interpreter may store things as binary internally doesn't affect how you work with it - if you have an integer type, just use +, -, etc.If you have strings of binary digits, you'll have to either write your own implementation or convert them using the int(binaryString, 2) function.If you're talking about bitwise operators, then you're after:Otherwise, binary numbers work exactly the same as decimal numbers, because numbers are numbers, no matter how you look at them. The only difference between decimal and binary is how we represent that data when we are looking at it.Binary, decimal, hexadecimal... the base only matters when reading or outputting numbers, adding binary numbers is just the same as adding decimal number : it is just a matter of representation.Not sure if helpful, but I leave my solution here:I think you're confused about what binary is. Binary and decimal are just different representations of a number - e.g. 101 base 2 and 5 base 10 are the same number. The operations add, subtract, and compare operate on numbers - 101 base 2 == 5 base 10 and addition is the same logical operation no matter what base you're working in.
Python

So I recently stumbled upon this great library for handling HTTP requests in Python; found here .I love working with it, but I can't figure out how to add headers to my get requests. Help?According to the , the headers can all be passed in using requests.get:Seems pretty straightforward, according to the  on the page you linked (emphasis mine).
Python

Suppose I have a list of tuples and I want to convert to multiple lists.For example, the list of tuples is Is there any built-in function in Python that convert it to:This can be a simple program. But I am just curious about the existence of such built-in function in Python.The built-in function  will almost do what you want:The only difference is that you get tuples instead of lists.  You can convert them to lists usingFrom the :Specific example:Or, if you really want lists:Use:Adding to Claudiu's and Claudiu's answer and since map needs to be imported from itertools in python 3, you also use a list comprehension like:
Python

What is the equivalent of this SQL statement in django?How do I implement this in django? I triedBut that did not work. How do i implement this? Use  or :contains and icontains mentioned by falsetrue make queries like  Along with them, you might need these ones with similar behavior:\n, , , making or  Case insensitive search for string in a field.
Python

Requirements:Here is my code:Other things I tried include the following code ... but this is waaaaay slower.Here is a schematic of how this is called:I tried a few different things, with timing.And this is how I timed it:So it looks like regular old Python lists are pretty good ;)np.append() copy all the data in the array every time, but list grow the capacity by a factor (1.125). list is fast, but memory usage is larger than array. You can use array module of the python standard library if you care about the memory.Here is a discussion about this topic:  Using the class declarations in Owen's post, here is a revised timing with some effect of the finalize.In short, I find class C to provide an implementation that is over 60x faster than the method in the original post. (apologies for the wall of text)The file I used:Now, the resulting timings:Class A is destroyed by the updates, class B is destroyed by the finalizes. Class C is robust in the face of both of them.there is a big performance difference in the function that you use for finalization. Consider the following code:Using concatenate seems to be twice as fast as the first version and more than 10 times faster than the second version.If you want improve performance with list operations, have a look to blist library. It is a optimized implementation of python list and other structures.I didn't benchmark it yet but the results in their page seem promising.
Python

I have a module foo, containing util.py and bar.py.I want to import it in IDLE or python session. How do I go about this?I could find no documentation on how to import modules not in the current directory or the default python PATH.\nAfter trying ,\nand  The closest I could get wasWhich gave me Permission denied on windows 7.One way is to simply amend your :Note that this requires foo to be a python package, i.e. contain a  file. If you don't want to modify , you can  or . Beware that this means that other directories or  files in that directory may be loaded inadvertently.Therefore, you may want to use  instead. It needs the filename, not a directory (to a file which the current user is allowed to read):You could customize the module search path using the  environment variable, or manually modify the  directory list.See  documentation on python.org.Give this a tryFollowing phihag's tip, I have this solution. Just give the path of a source file to  and it will load it. You must also provide a name, so you can import this module using this name. I prefer to do it this way because it's more explicit:Another (less explicit) way is this: the method is rewritten to make it clearer.
Python

I'm trying to get started with Sphinx and seem to have relentless problems.Command: I answer all the questions and everything works fine.Command: Everything looks normal. Result:  Command: It seems to work.  I was able to open the index.html file and see a \"shell\" of what I'm wanting.When I try and put my actual source code as the  folder I run into problems.Command: Result:I am a complete newbie to Sphinx and relatively new to this kind of documentation.  Can anyone offer some suggestions?Edit:I'd like to be able to use a Makefile to handle this.  As of now I have two folders in my project.I need  to generate the HTML for  and all other modules I'm going to have.Autodoc can't find your modules, because they are not in . You have to include the path to your modules in in the  in your .\nLook at the top of your  (just after the import of ), there is a  statement, which you can adapt.By the way: you can use the  created by Sphinx to create your documentation.\nJust callto see the options.If something went wrong before try:before running .in just add the path to your project folder.I think I did this the first time I tried to add a file to the toctree.  I think it was because I left out the blank line between the :maxdepth line and the file name.Above is my index.rst file.  stuff.rst resides in the same directory as it.Sphinx is not very  compatible, running    both work in my interpreter, but not in sphinx.I tried checking out the master branch of sphinx, changed my interpreter to python3.4 in the  and got errors on modules that were removed in the 3.x series. You can see my issue report here:You can use  and noweb formatting to generate rst documents that include the output of the code embedded in them. Basically, you write your rst file, with python code embedded in marked chunks like this:and Pweave will execute those chunks, and replace them with their output in a resulting rst file, which you can then use with sphinx. See the  for more details of how it looks.I tried to use autodoc to document my sphinx code, but it would skip over one of my files because I didn't make a class within that file. Here's what the file originally looked something like this:This file would never successfully get documented by sphinx. To get it to be documented, I had to do the following:So, it seems like Sphinx requires you to wrap all your files up in a class to get them documented. hope that helps, cause I spent hours trying to figure out why Sphinx wasn't documenting
Python

I'm trying to use Test-Driven Development with the  module.\npytest will not  to the console when I write .I use  to run it...The  seems to say that it should work by default: But:Nothing gets printed to my standard output console (just the normal progress and how many many tests passed/failed).And the script that I'm testing contains print:In  module, everything gets printed by default, which is exactly what I need. However, I wish to use  for other reasons. It seems like such basic functionality that perhaps I'm missing it!?By default,  captures the result of standard out so that it can control how it prints it out. If it didn't do this, it would spew out a lot of text without the context of what test printed that text.However, if a test fails, it will include a section in the resulting report that shows what was printed to standard out in that particular test.For example,Results in the following output:Note the  section.If you would like to see  statements as they are executed, you can pass the  flag to . However, note that this can sometimes be difficult to parse.Using  option will print output of all functions, which may be too much. If you need particular output, the doc page you mentioned offers few suggestions:That is rather hackish way to do stuff, but may be it is the stuff you need: after all, TDD means you mess with stuff and leave it clean and silent when it's ready :-).I needed to print important warning about skipped tests exactly when  muted literally . I didn't want to fail a test to send a signal, so I did a hack as follow:The  module allows me to print stuff   released the output streams. The output looks as follow:Message is printed even when  is in silent mode, and is  printed if you run stuff with , so everything is tested nicely already.
Python

I need to write, or find, a script to create a Debian package, using python-support, from a Python package. The Python package will be pure Python with no C extensions.The Python package for testing purposes will just be a directory with an empty  file and a single Python module, .The packaging script  use python-support to provide the correct bytecode for possible multiple installations of Python on a target platform, i.e. v2.5 and v2.6 on Ubuntu Jaunty.Most advice I find while googling are just examples of nasty hacks that don't even use python-support or python-central.  I have spent hours researching this, and the best I can come up with is to hack around the script from an existing open source project, but I don't know which bits are required for what I'm doing.Has anyone here made a Debian package out of a Python package in a reasonably non-hacky way?I'm starting to think that it will take me more than a week to go from no knowledge of Debian packaging and python-support to getting a working script.  How long has it taken others?I would take the sources of an existing Debian package, and replace the actual package in it with your package. To find a list of packages that depend on python-support, doPick a package that is , so that it is a pure-Python package. Going through this list, I found that e.g. python-flup might be a good starting point.\nTo get the source of one such package, doTo build it, doWhen editing it, expect that you only need the files in the  folder; replace all references to flup with your own package name.Once you get started, it should take you a day to complete.I think what you want is :Most of the answers posted here are outdated, fortunately a great Debian wiki post has been made recently, which explains the current best practices and describes how to build Debian packages for Python modules and applications.The right way of building a deb package is using  but sometimes it is a little bit complicated. Instead you can use  and it will create your Debian package.These are the basics for creating a Debian package with  with any binary or with any kind of script that runs automatically without needing manual compilation (Python, Bash, Pearl, Ruby):The scripts placed at  are directly called from the terminal, note that I didn't add an extension to the script. Also you can notice that the structure of the deb package will be the structure of the program once it's installed. So if you follow this logic if your program has a single file, you can directly place it under , but if you have multiple files, you should place them under  and place only one file under  that will call your scripts from Here is an example of the  file. You only need to copy-paste it in to an empty file called \"control\" and put it in the DEBIAN folderFirst off, there are plenty of Python packages already in Debian; you can download the source (including all the packaging) for any of them either using  or by visiting .You may find the following resources of use:
Python

I have a path (including directory and file name).\nI need to test if the file-name is a valid, e.g. if the file-system will allow me to create a file with such a name.\nThe file-name  in it.It's safe to assume the directory segment of the path is valid and accessible ().I very much do not want to have to escape anything unless I  to. I'd post some of the example characters I am dealing with, but apparently they get automatically removed by the stack-exchange system. Anyways, I want to keep standard unicode entities like , and only escape things which are invalid in a filename.Here is the catch.  I need to keep that file if it does exist, and not create a file if it does not.Basically I want to check if I  write to a path  (and the automatic file creation/file clobbering that typically entails).As such:Is not acceptable, because it will overwrite the existent file, which I do not want to touch (if it's there), or create said file if it's not.I know I can do:But that will  the file at the , which I would then have to .In the end, it seems like it's spending 6 or 7 lines to do something that should be as simple as  or similar.As an aside, I need this to run on (at least) Windows and MacOS, so I'd like to avoid platform-specific stuff.``Call the  function defined below.Strictly Python 3. That's just how we roll.The question of \"How do I test pathname validity and, for valid pathnames, the existence or writability of those paths?\" is clearly two separate questions. Both are interesting, and neither have received a genuinely satisfactory answer here... or, well,  that I could grep.'s  probably hews the closest, but has the remarkable disadvantages of:We're gonna fix all that.Before hurling our fragile meat suits into the python-riddled moshpits of pain, we should probably define what we mean by \"pathname validity.\" What defines validity, exactly?By \"pathname validity,\" we mean the  of a pathname with respect to the  of the current system \u2013 regardless of whether that path or parent directories thereof physically exist. A pathname is syntactically correct under this definition if it complies with all syntactic requirements of the root filesystem.By \"root filesystem,\" we mean:The meaning of \"syntactic correctness,\" in turn, depends on the type of root filesystem. For  (and most but  all POSIX-compatible) filesystems, a pathname is syntactically correct if and only if that pathname:Syntactic correctness. Root filesystem. That's it.Validating pathnames in Python is surprisingly non-intuitive. I'm in firm agreement with  here: the official  package should provide an out-of-the-box solution for this. For unknown (and probably uncompelling) reasons, it doesn't. Fortunately, unrolling your own ad-hoc solution isn't  gut-wrenching... It's hairy; it's nasty; it probably chortles as it burbles and giggles as it glows. But what you gonna do? We'll soon descend into the radioactive abyss of low-level code. But first, let's talk high-level shop. The standard  and  functions raise the following exceptions when passed invalid pathnames:Crucially, this implies that  The  and  functions raise generic  exceptions when passed pathnames residing in non-existing directories, regardless of whether those pathnames are invalid or not. Directory existence takes precedence over pathname invalidity.Does this mean that pathnames residing in non-existing directories are  validatable? Yes \u2013 unless we modify those pathnames to reside in existing directories. Is that even safely feasible, however? Shouldn't modifying a pathname prevent us from validating the original pathname?To answer this question, recall from above that syntactically correct pathnames on the  filesystem contain no path components  containing null bytes or  over 255 bytes in length. Hence, an  pathname is valid if and only if all path components in that pathname are valid. This is true of   of interest.Does that pedantic insight actually help us? Yes. It reduces the larger problem of validating the full pathname in one fell swoop to the smaller problem of only validating all path components in that pathname. Any arbitrary pathname is validatable (regardless of whether that pathname resides in an existing directory or not) in a cross-platform manner by following the following algorithm:Is there a directory guaranteed to exist? Yes, but typically only one: the topmost directory of the root filesystem (as defined above).Passing pathnames residing in any other directory (and hence not guaranteed to exist) to  or  invites race conditions, even if that directory was previously tested to exist. Why? Because external processes cannot be prevented from concurrently removing that directory  that test has been performed but  that pathname is passed to  or . Unleash the dogs of mind-fellating insanity!There exists a substantial side benefit to the above approach as well:  (Isn't  nice?) Specifically:The above approach obviates this by only validating the path components of a pathname against the root directory of the root filesystem. (If even  stale, slow, or inaccessible, you've got larger problems than pathname validation.)Lost?  Let's begin. (Python 3 assumed. See \"What Is Fragile Hope for 300, ?\") Don't squint at that code. ()Testing the existence or creatability of possibly invalid pathnames is, given the above solution, mostly trivial. The little key here is to call the previously defined function  testing the passed path: and  Except not quite.There exists a caveat. Of course there does.As the official  admits:To no one's surprise, Windows is the usual suspect here. Thanks to extensive use of Access Control Lists (ACL) on NTFS filesystems, the simplistic POSIX permission-bit model maps poorly to the underlying Windows reality. While this (arguably) isn't Python's fault, it might nonetheless be of concern for Windows-compatible applications.If this is you, a more robust alternative is wanted. If the passed path does  exist, we instead attempt to create a temporary file guaranteed to be immediately deleted in the parent directory of that path \u2013 a more portable (if expensive) test of creatability:Note, however, that even  may not be enough.Thanks to User Access Control (UAC), the ever-inimicable Windows Vista and all subsequent iterations thereof  about permissions pertaining to system directories. When non-Administrator users attempt to create files in either the canonical  or  directories, UAC superficially permits the user to do so while  isolating all created files into a \"Virtual Store\" in that user's profile. (Who could have possibly imagined that deceiving users would have harmful long-term consequences?)This is crazy. This is Windows.Dare we? It's time to test-drive the above tests.Since NULL is the only character prohibited in pathnames on UNIX-oriented filesystems, let's leverage that to demonstrate the cold, hard truth \u2013 ignoring non-ignorable Windows shenanigans, which frankly bore and anger me in equal measure:Beyond sanity. Beyond pain. You will find Python portability concerns.Note that  can fail for more reasons than just  so you might have to do finer tests like testing if the containing directory exists and so on.After my discussion with the OP it turned out, that the main problem seems to be, that the file name might contain characters that are not allowed by the filesystem. Of course they need to be removed but the OP wants to maintain as much human readablitiy as the filesystem allows. Sadly I do not know of any good solution for this.\nHowever  takes a closer look at detecting the problem.will open the file or give an error if it doesn't exist. If there's an error, then you can try to write to the path, if you can't then you get a second errorAlso have a look  about permissions on windowstry  this will check for the path and return  if exists and  if not.
Python

I can't seem to get code coverage with Nose to work, despite having the plugin installed.Any ideas on how to fix this?Have you tried ? The coverage plugin depends on separate coverage module, which is not a nose's dependency, so needs to be installed manually.
Python

How do I do I set the syntax highlighting in Vim 7 for python?I would like to set my own colorschemes, and syntax highlighting for a type of code file.The command to enable syntax highlighting in vim is , if you want it to be active everytime you launch vim, just add a line containing  in your .vimrc file.Put the line  in your . on how to setup syntax highlighting in Python for Ubuntu 12.10.  What you see is what you get:There are hundreds of fashionable color schemes here: Pick one that you like.  Then download the  and  files and put them in the right spot as defined here:   Set the appropriate commands in the ~/.vimrc and logout login.Learn to edit the code that causes vim syntax highlighting to work.  Make it better than it ever was.
Python

I want to do something like the following:but this actually tries to run , which is not what I want to do.Is there a general way to turn variables into strings? Something like the following:IPython expands variables with , bash-style.  This is true for , not just .So you would do:myscript.py contains:Via Python's fancy string formatting, you can even put expressions inside :Use  to get a reference to the current , then call the  method: See  \u2014 that's a much better way to do it.It seems this is impossible with the built-in  magic function. Your question led me down a rabbit hole, though, and I wanted to see how easy it would be to do something similar. At the end, it seems somewhat pointless to go to all this effort to create another magic function that just uses . Maybe this will be of some use to someone, somewhere.Using this pair of classes, (and given a python script ) it's possible to create and use a \"macro\" variable with the newly created \"my_run\" magic function like so:Yes, this is a huge and probably wasteful hack. In that vein, I wonder if there's a way to have the name bound to the Macro object be used as the macro's actual name. Will look into that.
Python

I'm just trying to time a piece of code. The pseudocode looks like:How does this look in Python?More specifically, how do I get the number of ticks since midnight (or however Python organizes that timing)?In the  module, there are two timing functions:  and .  gives you \"wall\" time, if this is what you care about.However, the python  say that  should be used for benchmarking. Note that  behaves different in separate systems:Apart from all that, the  module has the  class that is supposed to use what's best for benchmarking from the available functionality.\u00b9 unless threading gets in the way\u2026\u00b2 Python \u22653.3: there are .  is being used by the  module.What you need is  function from  module:You can use  module for more options though.Here's a solution that I started using recently:You use it like this (You need at least Python 2.5):When your code finishes, Timer automatically prints out the run time.  Sweet!  If I'm trying to quickly bench something in the Python Interpreter, this is the easiest way to go.  And here's a sample implementation of 'now' and 'format_delta', though feel free to use your preferred timing and formatting method.Please let me know if you have a preferred formatting method, or if there's an easier way to do all of this!The  in python gives you access to the clock() function, which returns time in seconds as a floating point.Different systems will have different accuracy based on their internal clock setup (ticks per second) but it's generally at least under 20milliseconds, and in some cases better than a few microseconds.-AdamFrom midnight:If you have many statements you want to time, you could use something like this:Then your code could look like:That way you don't need to type  before each block and  after it, while still keeping control over formatting (though you could easily put that in  too).It's a minimal gain, but I think it's kind of convenient.
Python

I am looking for something similar to 'clear' in Matlab: A command/function which removes all variables from the workspace, releasing them from system memory. Is there such a thing in Python?EDIT: I want to write a script which at some point clears all the variables.The following sequence of commands does remove  name from the current module:I doubt you actually DO want to do this, because \"every name\" includes all built-ins, so there's not much you can do after such a total wipe-out.  Remember, in Python there is really no such thing as a \"variable\" -- there are , of many kinds (including modules, functions, class, numbers, strings, ...), and there are , bound to objects; what the sequence does is remove every name from a module (the corresponding objects go away if and only if every reference to them has just been removed).Maybe you want to be more selective, but it's hard to guess exactly what you mean unless you want to be more specific.  But, just to give an example:This sequence leaves alone names that are private or magical, including the  special name which houses all built-in names.  So, built-ins still work -- for example:As you see, name  (the control variable in that ) also happens to stick around (as it's re-bound in the  clause every time through), so it might be better to name that control variable , for example, to clearly show \"it's special\" (plus, in the interactive interpreter, name  is re-bound anyway after every complete expression entered at the prompt, to the value of that expression, so it won't stick around for long;-).Anyway, once you have determined exactly what it  you want to do, it's not hard to define a function for the purpose and put it in your start-up file (if you want it only in interactive sessions) or site-customize file (if you want it in every script).No, you are best off restarting the interpreter is an excellent replacement for the bundled interpreter and has the  command which usually worksWrite a function. Once you leave it all names inside disappear. It is very pointless to do this yourself in any kind of way.The concept is called  and it's so good, it made it into the :This is a modified version of Alex's answer.\nWe can save the state of a module's namespace and restore it by using the following 2 methods...You can also add a line \"clear = restoreContext\" before calling saveContext() and clear() will work like matlab's clear.
Python

I am trying to use Python to login to a website and gather information from several webpages and I get the following error:I used  and it works, but it seems unintelligent and unreliable, is there any other way to dodge this error?Here's my code:Receiving a status 429 is , it is the other server \"kindly\" asking you to please stop spamming requests. Obviously, your rate of requests has been too high and the server is not willing to accept this.You should not seek to \"dodge\" this, or even try to circumvent server security settings by trying to spoof your IP, you should simply respect the server's answer by not sending too many requests.If everything is set up properly, you will also have received a \"Retry-after\" header along with the 429 response. This header specifies the number of seconds you should wait before making another call. The proper way to deal with this \"problem\" is to read this header and to sleep your process for that many seconds.You can find more information on status 429 here: Another workaround would be to spoof your IP using some sort of Public  VPN or Tor network. This would be assuming the rate-limiting on the server at IP level.There is a brief blog post demonstrating a way to use tor along with urllib2:Writing this piece of code fixed my problem:
Python

I am trying to install MySQLdb package. I found the source code .I did the following:As the result I got the following:Does anybody knows how to solve this problem?\nBy the way, if I am able to do the described step, I will need to do the following:And I have no system-administrator-rights. Do I still have a chance to install MySQLdb?Thank you.If MySQLdb's now distributed in a way that requires , your choices are either to download the latter (e.g. from ) or refactor MySQLdb's setup.py to bypass  (maybe just importing  and  from plain  instead might work, but you may also need to edit some of the  files in the same directory).Depending on how your site's Python installation is configured, installing extensions for your own individual use without requiring sysadm rights may be hard, but it's never truly impossible if you have shell access. You'll need to tweak your Python's sys.path to start with a directory of your own that's your personal equivalent of the system-wide site pacages directory, e.g. by setting  persistently in your own environment, and then manually place in said personal directory what normal installs would normally place in site-packages (and/or subdirectories thereof).After trying many suggestions, simply using  worked for me.More info: \nI resolved this issue on centos5.4 by running the following command to install setuptoolsyum install python-setuptoolsI hope that helps.This was sort of tricky for me too, I did the following which worked pretty well.Not sure if you'll need to use sudo if you're just installing it for you current user. You'd definitely need it to install it for all users.@main:and it will be installed (MySQLdb).For Python 2.7, one can easily install using this Also, you can see the build dependencies in the file setup.cfgI am experiencing the same problem right now. According to  you need to have a C Compiler or GCC. I'll try to fix the problem by installing C compiler. I'll inform you if it works (we'll I guess you don't need it anymore, but I'll post the result anyway) :)well installing C compiler or GCC didn't work but I found a way to successfully install mysqldb package kindly follow Mike schrieb's (Thanks to him) instructions  . In my case, I used setuptools-0.6c11-py2.7.egg and setuptools-0.6c11 . Then download the executable file  then install that file. hope it helps :)When you need to install modules in Linux/Unix and you lack sudo / admin rights, one simple way around it is to use the user scheme installation, basically run \"python setup.py install --user\" from the command line in the folder of the module / library to be installed(see  for further details)
Python

This code bit produces error: Can anyone tell me how to get this series of date time strings into a DataFrame as  objects?Use pandas.to_datetime(pd.Series(..)). It's concise and much faster than above code.
Python

I need to store some data in a Django model. These data are not equal to all instances of the model.At first I thought about subclassing the model, but I\u2019m trying to keep the application flexible. If I use subclasses, I\u2019ll need to create a whole class each time I need a new kind of object, and that\u2019s no good. I\u2019ll also end up with a lot of subclasses only to store a pair of extra fields.I really feel that a dictionary would be the best approach, but there\u2019s nothing in the Django documentation about storing a dictionary in a Django model (or I can\u2019t find it).Any clues?If it's really dictionary like arbitrary data you're looking for you can probably use a two-level setup with one model that's a container and another model that's key-value pairs. You'd create an instance of the container, create each of the key-value instances, and associate the set of key-value instances with the container instance. Something like:It's not pretty, but it'll let you access/search the innards of the dictionary using the DB whereas a pickle/serialize solution will not.If you don't need to query by any of this extra data, then you can store it as a serialized dictionary.   Use  to turn the dictionary into a string, and  to turn the string back into a dictionary.  Take care with eval that there's no user data in the dictionary, or use a safe_eval implementation.As Ned answered, you won't be able to query \"some data\" if you use the dictionary approach.If you still need to store dictionaries then the best approach, by far, is the PickleField class documented in Marty Alchin's new book .  This method uses Python class properties to pickle/unpickle a python object, only on demand, that is stored in a model field.The basics of this approach is to use django's  method to dynamically add a new field to your model and uses getattr/setattr to do the serializing on demand.One of the few online examples I could find that is similar is this definition of a .I came to this post by google's 4rth result to \"django store object\"A little bit late, but  looks like good solution to me.Example from doc:To use, just define a field in your model:and assign whatever you like (as long as it's picklable) to the field:Another clean and fast solution can be found here: For convenience I copied the simple instructions.I'm not sure exactly sure of the nature of the problem you're trying to solve, but it sounds curiously similar to .Expandos allow you to specify and store additional fields on an database-backed object instance at runtime. To quote from the docs:Google App Engine currently supports both Python and the Django framework. Might be worth looking into if this is the best way to express your models.Traditional relational database models don't have this kind of column-addition flexibility. If your datatypes are simple enough you could break from traditional RDBMS philosophy and hack values into a single column via serialization as  proposes; however, if you  to use an RDBMS, Django model inheritance is probably the way to go. Notably, it will create  relation for each level of derivation.Being \"not equal to all instances of the model\" sounds to me like a good match for a \"Schema-free database\".  is the poster child for that approach and you might consider that. In a project I moved several tables which never played very nice with the Django ORM over to CouchDB and I'm quite happy with that. I use  without any of the Django-specific CouchDB modules. A description of the data model can be found . The movement from five \"models\" in Django to 3 \"models\" in Django and one CouchDB \"database\" actually slightly reduced the total lines of code in my application.Think it over, and find the commonalities of each data set... then define your model.  It may require the use of subclasses or not.  Foreign keys representing commonalities aren't to be avoided, but encouraged when they make sense.Stuffing random data into a SQL table is not smart, unless it's truly non-relational data.  If that's the case, define your problem and we may be able to help.Django-Geo includes a \"DictionaryField\" you might find helpful:In general, if you don't need to query across the data use a denormalized approach to avoid extra queries. User settings are a pretty good example!I agree that you need to refrain stuffing otherwise structured data into a single column. But if you must do that, Django has an  build-in.There's also  at Django snipplets.If you are using Postgres, you can use an hstore field: .
Python

what's the meaning of  in the following statement?I think I've heard of , , and  but never heard of this.Background:In Python, there are two builtin functions for turning an object into a string:  vs. .  is supposed to be a friendly, human readable string.  is supposed to include detailed information about an object's contents (sometimes, they'll return the same thing, such as for integers). By convention, if there's a Python expression that will eval to another object that's ==,  will return such an expression e.g.If returning an expression doesn't make sense for an object,  should return a string that's surrounded by < and > symbols e.g. .To answer your original question: <-> \n <-> In addition:You can control the way an instance of your own classes convert to strings by implementing  and  methods.It calls  on the object and inserts the resulting string.It prints the replacement as a string with .Adding to the replies given above, '%r' can be useful in a scenario where you have a list with heterogeneous data type.\nLet's say, we have a list = [1, 'apple' , 2 , 'r','banana']\nObviously in this case using '%d' or '%s' would cause an error. Instead, we can use '%r' to print all these values.See  in the docs. Notice that %s and %d etc, might work differently to how you expect if you are used to the way they work in another language such as C.In particular, %s also works well for ints and floats unless you have special formatting requirements where %d or %f will give you more control.
Python

How to test if a module has been imported in python?for example I need the basics:alsoThanks!Rgs.Thanks for all of your comments:\nthe code been pasted here.\nIf you want to optimize by not importing things twice, save yourself the hassle because Python already takes care of this.If you  this to avoid  or something: Fix your sloppy coding - make sure you don't need this, i.e. define (import) everything before you ever use it (in the case if imports: once, at startup, at module level).In case you do have a good reason:  is a dictionary containing all modules already imported somewhere. But it only contains modules, and because of the way  works (import the whole module as usual, extract the things you import from it),  would only add  to  (if it wasn't already imported on startup).  adds  as you probably expect.I feel the answer that has been accepted is not fully correct.Python  when importing the same module multiple times. Python , sure, but that doesn't mean it won't slow down your script. As you will see from the URL below, there is  overhead when importing a module multiple times. For example, in a situation where you may not need a certain module except under a particular condition, if that module is large or has a high overhead then there is reason to import only on condition. That does not explicitly mean you are a sloppy coder either.this is my solution of changing code at runtime!
Python

How can I export a list of DataFrames into one Excel spreadsheet?\nThe docs for  state:Following this, I thought I could write a function which saves a list of DataFrames to one spreadsheet as follows:However (with a list of two small DataFrames, each of which can save  individually), an exception is raised :Presumably I am not calling  correctly, how should I be in order to do this?You should be using pandas own  class:Then the  function works as expected:
Python

I have two Django models which inherit from a base class:Request has two foreign keys to the built-in User model.For some reason I'm getting the errorEverything I've read says that setting the  should prevent the clash, but I'm still getting the same error. Can anyone think of why this would be happening? Thanks!The related_name would ensure that the fields were not conflicting with each other, but you have two models, each of which has both of those fields. You need to put the name of the concrete model in each one, which you can do with some special : for related name in Django 1.9
Python

There is form with two . But when i'm sending it, second submit causes error.::First submit(add) works well, but second(remove)...:How can i fix this error?:It was pretty simple:\nrequest.form returns ImmutableMultiDict:As @Blubber points out, the issue is that Flask raises an HTTP error when it fails to find a key in the  and  dictionaries.  What Flask assumes by default is that if you are asking for a particular key  then something got left out of the request and the entire request is invalid.There are two other good ways to deal with your situation:You can start by posting the actual exception that is being thrown instead of that more or less useless output from your webserver. Anyway, my guess is you should be checking whether or not the 'add' and 'remove' keys are in the request.form dict, i.e.:When you click  it doesn't fail because the first condition is met, and hence the second is never checked. But if the  button is clicked, that first condition will thrown a  exception because the request.form dict doesn't contain a key named .
Python

Is there a way to make Python's optparse print the default value of an option or flag when showing the help with --help?Try using the  string placeholder:And if you need programmatic access to the default values, you can get to them via the  attribute of the parser (it's a dict)And if you want to add default values automatically to all options that you have specified, you can do the following:The comments to your question already indicate there's another way to parse arguments called . It's been introduced in Python 3.2. It actually deprecates  but is used similarly. comes with different formatting classes and for instance  will also print the default values without you having to manipulate the help string manually.An example from the python docs:see Add  to your parserfrom documentation:
Python

There are many questions related to Stackless Python. But none answering this my question, I think (correct me if wrong - please!). There's some buzz about it all the time so I curious to know. What would I use Stackless for? How is it better than CPython?Yes it has green threads (stackless) that allow quickly create many lightweight threads as long as no operations are blocking (something like Ruby's threads?). What is this great for? What other features it has I want to use over CPython?It allows you to work with massive amounts of concurrency. Nobody sane would create one hundred thousand system threads, but you can do this using stackless.This article tests doing just that, creating one hundred thousand tasklets in both Python and Google Go (a new programming language): Surprisingly, even if Google Go is compiled to native code, and they tout their co-routines implementation, Python still wins.Stackless would be good for implementing a map/reduce algorithm, where you can have a very large number of reducers depending on your input data.Stackless Python's main benefit is the support for very lightweight coroutines. CPython doesn't support coroutines natively (although I expect someone to post a generator-based hack in the comments) so Stackless is a clear improvement on CPython when you have a problem that benefits from coroutines. I think the main area where they excel are when you have many concurrent tasks running within your program. Examples might be game entities that run a looping script for their AI, or a web server that is servicing many clients with pages that are slow to create.You still have many of the typical problems with concurrency correctness however regarding shared data, but the deterministic task switching makes it easier to write safe code since you know exactly where control will be transferred and therefore know the exact points at which the shared state must be up to date.Thirler already mentioned that stackless was used in Eve Online. Keep in mind, that:(got this citation from )At PyCon 2009 there was given , describing why and how Stackless is used at CCP Games.Also, there is a very good , which describes why stackless is a good solution for Your applications. (it may be somewhat old, but I think that it is worth reading).EVEOnline is largely programmed in Stackless Python. They have several dev blogs on the use of it. It seems it is very useful for high performance computing.While I've not used Stackless itself, I have used Greenlet for implementing highly-concurrent network applications.  Some of the use cases Linden Lab has put it towards are: high-performance smart proxies, a fast system for distributing commands over huge numbers of machines, and an application that does a ton of database writes and reads (at a ratio of about 1:2, which is very write-heavy, so it's spending most of its time waiting for the database to return), and a web-crawler-type-thing for internal web data.  Basically any app that's expecting to have to do a lot of network I/O will benefit from being able to create a bajillion lightweight threads.  10,000 connected clients doesn't seem like a huge deal to me.Stackless or Greenlet aren't really a complete solution, though.  They are very low-level and you're going to have to do a lot of monkeywork to build an application with them that uses them to their fullest.  I know this because I maintain a library that provides a networking and scheduling layer on top of Greenlet, specifically because writing apps is so much easier with it.  There are a bunch of these now; I maintain Eventlet, but also there is Concurrence, Chiral, and probably a few more that I don't know about.  If the sort of app you want to write sounds like what I wrote about, consider one of these libraries.  The choice of Stackless vs Greenlet is somewhat less important than deciding what library best suits the needs of what you want to do.The basic usefulness for green threads, the way I see it, is to implement a system in which you have a large amount of objects that do high latency operations. A concrete example would be communicating with other machines:Threads let you write the above code naturally, but if the number of objects is large enough, threads just cannot perform adequately. But you can use green threads even for in really large amounts. The  above could switch out to some scheduler where other work is waiting and return later. You get all the benefits of being able to call \"blocking\" functions  without using threads.This is obviously very useful for any kind of distributed computing if you want to write code in a straightforward way.It is also interesting for multiple cores to mitigate waiting for locks:The  function would basically attempt to acquire the lock and just switch out to a main scheduler if it fails due to other cores using the object. Again, green threads are being used to mitigate blocking, allowing code to be written naturally and still perform well.
Python

I switched from Perl to Python about a year ago and haven't looked back.  There is only  idiom that I've ever found I can do more easily in Perl than in Python:The corresponding Python code is not so elegant since the if statements keep getting nested:Does anyone have an elegant way to reproduce this pattern in Python?  I've seen anonymous function dispatch tables used, but those seem kind of unwieldy to me for a small number of regular expressions...With thanks to :Using named groups and a dispatch table:With a little bit of introspection you can auto-generate the regexp and the dispatch table.Yeah, it's kind of annoying.  Perhaps this will work for your case.   Brian correctly pointed out that my first attempt did not work.  Unfortunately, this attempt is longer.For example:I'd suggest this, as it uses the least regex to accomplish your goal.  It is still functional code, but no worse then your old Perl.Alternatively, something not using regular expressions at all:Whether that is suitable depends on your actual problem. Don't forget, regular expressions aren't the swiss army knife that they are in Perl; Python has different constructs for doing string manipulation.To speed it up, one could turn all regexes into one internally and create the dispatcher on the fly. Ideally, this would be turned into a class then.Here's the way I solved this issue:Not nearly as clean as the original pattern.  However, it is simple, straightforward and doesn't require extra modules or that you change the original regexs.how about using a dictionary?however, you must ensure there are no duplicate match_objects dictionary keys ( mo_foo, mo_bar, ... ), best by giving each regular expression its own name and naming the match_objects keys accordingly, otherwise match_objects.setdefault() method would return existing match object instead of creating new match object by running re_xxx.search( text ).Expanding on the solution by Pat Notz a bit, I found it even the more elegant to:\n\u00a0 - name the methods the same as  provides (e.g.  vs. ) and\n\u00a0\u00a0- implement the necessary methods like  on the holder object itself:So instead of e.g. this:One does just this:Looks very natural in the end, does not need too many code changes and avoids the problems with global state like some other solutions.My solution would be:
Python

Ok this is one of those trickier than it sounds questions so I'm turning to stack overflow because I can't think of a good answer. Here is what I want: I need Python to generate a simple a list of numbers from 0 to 1,000,000,000 in random order to be used for serial numbers (using a random number so that you can't tell how many have been assigned or do timing attacks as easily, i.e. guessing the next one that will come up). These numbers are stored in a database table (indexed) along with the information linked to them. The program generating them doesn't run forever so it can't rely on internal state.No big deal right? Just generate a list of numbers, shove them into an array and use Python \"random.shuffle(big_number_array)\" and we're done. Problem is I'd like to avoid having to store a list of numbers (and thus read the file, pop one off the top, save the file and close it). I'd rather generate them on the fly. Problem is that the solutions I can think of have problems:1) Generate a random number and then check if it has already been used. If it has been used generate a new number, check, repeat as needed until I find an unused one. Problem here is that I may get unlucky and generate a lot of used numbers before getting one that is unused. Possible fix: use a very large pool of numbers to reduce the chances of this (but then I end up with silly long numbers).2) Generate a random number and then check if it has already been used. If it has been used add or subtract one from the number and check again, keep repeating until I hit an unused number. Problem is this is no longer a random number as I have introduced bias (eventually I will get clumps of numbers and you'd be able to predict the next number with a better chance of success).3) Generate a random number and then check if it has already been used. If it has been used add or subtract another randomly generated random number and check again, problem is we're back to simply generating random numbers and checking as in solution 1.4) Suck it up and generate the random list and save it, have a daemon put them into a Queue so there are numbers available (and avoid constantly opening and closing a file, batching it instead). 5) Generate much larger random numbers and hash them (i.e. using MD5) to get a smaller numeric value, we should rarely get collisions, but I end up with larger than needed numbers again.6) Prepend or append time based information to the random number (i.e. unix timestamp) to reduce chances of a collision, again I get larger numbers than I need.Anyone have any clever ideas that will reduce the chances of a \"collision\" (i.e. generating a random number that is already taken) but will also allow me to keep the number \"small\" (i.e. less than a billion (or a thousand million for your europeans =)).Answer and why I accepted it:So I will simply go with 1, and hope it's not an issue, however if it is I will go with the deterministic solution of generating all the numbers and storing them so that there is a guarentee of getting a new random number, and I can use \"small\" numbers (i.e. 9 digits instead of an MD5/etc.). This is a neat problem, and I've been thinking about it for a while (with solutions similar to ), but in the end, here's what I think:Use your point 1) and stop worrying.Assuming real randomness, the probability that a random number has already been chosen before is the count of previously chosen numbers divided by the size of your pool, i.e. the maximal number.If you say you only need a billion numbers, i.e. nine digits: Treat yourself to 3 more digits, so you have 12-digit serial numbers (that's three groups of four digits \u2013 nice and readable).Even when you're close to having chosen a billion numbers previously, the probability that your new number is already taken is still only 0,1%.Do step 1 and draw again. You can still check for an \"infinite\" loop, say don't try more than 1000 times or so, and then fallback to adding 1 (or something else).You'll win the lottery before that fallback ever gets used.You could use  to encrypt a counter. Your counter just goes from 0 upwards, and the encryption uses a key of your choice to turn it into a seemingly random value of whatever radix and width you want.Block ciphers normally have a fixed block size of e.g. 64 or 128 bits. But Format-Preserving Encryption allows you to take a standard cipher like AES and make a smaller-width cipher, of whatever radix and width you want (e.g. radix 10, width 9 for the parameters of the question), with an algorithm which is still cryptographically robust.It is guaranteed to never have collisions (because cryptographic algorithms create a 1:1 mapping). It is also reversible (a 2-way mapping), so you can take the resulting number and get back to the counter value you started with. is one proposed standard method to achieve this.I've experimented with some basic Python code for AES-FFX-- (but note that it doesn't fully comply with the AES-FFX specification). It can e.g. encrypt a counter to a random-looking 7-digit decimal number. E.g.:For another example in Python, using another non-AES-FFX (I think) method, see  which does FPE using a Feistel cipher. It generates numbers from 0 to 2^32-1.With some modular arithmic and prime numbers, you can create all numbers between 0 and a big prime, out of order. If they don't have to be random, but just not obviously linear (1, 2, 3, 4, ...), then here's a simple algorithm:Pick two prime numbers.  One of them will be the largest number you can generate, so it should be around one billion.  The other should be fairly large.Just store the previous serial each time so you know where you left off.  I can't prove mathmatically that this works (been too long since those particular classes), but it's demonstrably correct with smaller primes:You could also prove it empirically with 9-digit primes, it'd just take a bit more work (or a lot more memory).This does mean that given a few serial numbers, it'd be possible to figure out what your values are--but with only nine digits, it's not likely that you're going for unguessable numbers anyway.If you don't need something cryptographically secure, but just \"sufficiently obfuscated\"...You could try operations in , e.g. GF(2), to map a simple incrementing counter  to a seemingly random serial number :Many of these operations have an inverse, which means, given your serial number, you can calculate the original counter value from which it was derived.As for finding a library for Galois Field for Python... good question. If you don't need speed (which you wouldn't for this) then you could make your own. I haven't tried these:Pick a suitable 32\u00d732 invertible matrix in GF(2), and multiply a 32-bit input counter by it. This is conceptually related to LFSR, as described in .A related possibility is to use a  calculation. Based on the remainder of long-division with an irreducible polynomial in GF(2). Python code is readily available for CRCs (, ), although you might want to pick a different irreducible polynomial than is normally used, for your purposes. I'm a little fuzzy on the theory, but I think a 32-bit CRC should generate a unique value for every possible combination of 4-byte inputs. Check this. It's quite easy to experimentally check this, by feeding the output back into the input, and checking that it produces a complete cycle of length 2-1 (zero just maps to zero). You may need to get rid of any initial/final XORs in the CRC algorithm for this check to work.I think you are overestimating the problems with approach 1). Unless you have hard-realtime requirements just checking by random choice terminates rather fast. The probability of needing more than a number of iterations decays exponentially. With 100M numbers outputted (10% fillfactor) you'll have one in billion chance of requiring more than 9 iterations. Even with 50% of numbers taken you'll on average need 2 iterations and have one in a billion chance of requiring more than 30 checks. Or even the extreme case where 99% of the numbers are already taken might still be reasonable - you'll average a 100 iterations and have 1 in a billion change of requiring 2062 iterationsThe standard Linear Congruential random number generator's seed sequence CANNOT repeat until the full set of numbers from the starting seed value have been generated.  Then it MUST repeat precisely.  The internal seed is often large (48 or 64 bits).  The generated numbers are smaller (32 bits usually) because the entire set of bits are not random.  If you follow the seed values they will form a distinct non-repeating sequence.  The question is essentially one of locating a good seed that generates \"enough\" numbers.  You can pick a seed, and generate numbers until you get back to the starting seed.  That's the length of the sequence.  It may be millions or billions of numbers.There are some guidelines in Knuth for picking suitable seeds that will generate very long sequences of unique numbers.You can run 1) without running into the problem of too many wrong random numbers if you just decrease the random interval by one each time.For this method to work, you will need to save the numbers already given (which you want to do anyway) and also save the quantity of numbers taken.It is pretty obvious that, after having collected 10 numbers, your pool of possible random numbers will have been decreased by 10. Therefore, you must not choose a number between 1 and 1.000.000 but between 1 an 999.990. Of course this number is not the real number but only an index (unless the 10 numbers collected have been 999.991, 999.992, \u2026); you\u2019d have to count now from 1 omitting all the numbers already collected.Of course, your algorithm should be smarter than just counting from 1 to 1.000.000 but I hope you understand the method.I don\u2019t like drawing random numbers until I get one which fits either. It just feels wrong.My solution , i think you should extend matrix for 1,000,000,000 variations and have fun.I'd rethink the problem itself... You don't seem to be doing anything sequential with the numbers... and you've got an index on the column which has them. Do they actually  to be ?Consider a sha hash... you don't actually need the entire thing. Do what git or other url shortening services do, and take first 3/4/5 characters of the hash. Given that each character now has 36 possible values instead of 10, you have 2,176,782,336 combinations instead of 999,999 combinations (for six digits). Combine that with a quick check on whether the combination exists (a pure index query) and a seed like a timestamp + random number and it should do for almost any situation.  Do you need this to be cryptographically secure or just hard to guess?  How bad are collisions? Because if it needs to be cryptographically strong and have zero collisions, it is, sadly, impossible.I started trying to write an explanation of the approach used below, but just implementing it was easier and more accurate.  This approach has the odd behavior that it gets faster the more numbers you've generated.  But it works, and it doesn't require you to generate all the numbers in advance.  As a simple optimization, you could easily make this class use a probabilistic algorithm (generate a random number, and if it's not in the set of used numbers add it to the set and return it) at first, keep track of the collision rate, and switch over to the deterministic approach used here once the collision rate gets bad.If it is enough for you that a casual observer can't guess the next value, you can use things like a  or even a simple  to generate the values and keep the state in the database in case you need more values. If you use these right, the values won't repeat until the end of the universe. You'll find more ideas in the .If you think there might be someone who would have a serious interest to guess the next values, you can use a database sequence to count the values you generate and encrypt them with an encryption algorithm or another cryptographically strong perfect has function. However you need to take care that the encryption algorithm isn't easily breakable if one can get hold of a sequence of successive numbers you generated - a simple , for instance, won't do it because of the .Bit late answer, but I haven't seen this suggested anywhere.Why not use the  module to create To generate a list of totally random numbers within a defined threshold, as follows:I bumped into the same problem and opened a  before getting to this one.  is a random sample generator of indexes (i.e. non-repeating numbers) in the interval , called . Here are some usage examples:or generates non-repeating random integers, storage need is limited to picked numbers, and the time needed to pick  numbers should be (as some tests confirm) , regardelss of .Here is the code of :You are stating that you store the numbers in a database.Wouldn't it then be easier to store all the numbers there, and ask the database for a random unused number?\nMost databases support such a request.ExamplesMySQL:PostgreSQL:
Python

Without subclassing dict, what would a class need to be considered a mapping so that it can be passed to a method with **At least to the point where it throws errors of missing functionality of mapping, so I can begin implementing.I reviewed emulating container types but simply defining magic methods has no effect, and using ABCMeta to override and register it as a dict validates assertions as subclass, but fails isinstance(o, dict). Ideally, I dont even want to use ABCMeta.The  and  methods will suffice:If you're trying to create a Mapping \u2014 not just satisfy the requirements for passing to a function \u2014 then you really should inherit from .  As described in the , you need to implement just:The Mixin will implement everything else for you:  , , , , , , and .
Python

I use Python a lot, and I am just quickly learning JavaScript right now (or should I say re-learning). So, I wanted to ask, what is the equivalent of  and  in JavaScript?The closest idiom for  would betaking advantage of the fact that  is the number of arguments given in the function definition.You could package this up in a little helper routine likeand then doIf you're in the mood for syntactic sugar, write a function which transforms one function into another one which is called with required and optional arguments, and passes the required arguments along, with any additional optional arguments as an array in final position:Use this as follows:Then again, you could just skip all this mumbo jumbo if you are willing to ask the caller to pass the optional arguments as an array to start with:There is really no analogous solution for , since JS has no keyword arguments. Instead, just ask the caller to pass the optional arguments in as an object:For completeness, let me add that ES6 solves this problem with the rest parameter feature. See .I found a good solution here:\nBasically, use  instead of . apply takes an array as the 2nd arg and 'splats' it for you.ES6 adds a spread operator to JavaScript.  already have it implemented. The following code was tested on Firefox 35.The nearest equivalent is the .ECMAScript 6 will have  which do the same thing as the splat operator.
Python

Say I have a string that looks like this:You'll notice a lot of locations in the string where there is an ampersand, followed by a character (such as \"&y\" and \"&c\").  I need to replace these characters with an appropriate value that I have in a dictionary, like so:What is the fastest way to do this?  I could manually find all the ampersands, then loop through the dictionary to change them, but that seems slow.  Doing a bunch of regex replaces seems slow as well (I will have a dictionary of about 30-40 pairs in my actual code).Any suggestions are appreciated, thanks.As has been pointed out in comments throught this question, my dictionary is defined before runtime, and will never change during the course of the applications life cycle.  It is a list of ANSI escape sequences, and will have about 40 items in it.  My average string length to compare against will be about 500 characters, but there will be ones that are up to 5000 characters (although, these will be rare).  I am also using Python 2.6 currently.\nI accepted Tor Valamos answer as the correct one, as it not only gave a valid solution (although it wasn't the  solution), but took all others into account and did a tremendous amount of work to compare all of them.  That answer is one of the best, most helpful answers I have ever come across on StackOverflow.  Kudos to you.I took the liberty of comparing a few solutions:Results in Python 2.6Both claudiu's and andrew's solutions kept going into 0, so I had to increase it to 10 000 runs.I ran it in  (because of unicode) with replacements of chars from 39 to 1024 (38 is ampersand, so I didn't wanna include it). String length up to 10.000 including about 980 replacements with variable random inserts of length 0-20. The unicode values from 39 to 1024 causes characters of both 1 and 2 bytes length, which could affect some solutions.Results:(** Note that gnibbler's code uses a different dict, where keys don't have the '&' included. Andrew's code also uses this alternate dict, but it didn't make much of a difference, maybe just 0.01x speedup.)Try this, making use of regular expression substitution, and standard string formatting:The re.sub() call replaces all sequences of ampersand followed by single letter with the pattern %(..)s containing the same pattern.The % formatting takes advantage of a feature of string formatting that can take a dictionary to specify the substitution, rather than the more commonly occurring positional arguments.An alternative can do this directly in the re.sub, using a callback:This time I'm using a closure to reference the dictionary from inside the callback function.  This approach could give you a little more flexibility.  For example, you could use something like  to avoid raising exceptions if you had strings with unrecognized code sequences.(By the way, both \"dict\" and \"str\" are builtin functions, and you'll get into trouble if you use those names in your own code much.  Just in case you didn't know that.  They're fine for a question like this of course.)  I decided to check Tor's test code, and concluded that it's nowhere near representative, and in fact buggy.  The string generated doesn't even have ampersands in it (!).  The revised code below generates a representative dictionary and string, similar to the OP's example inputs.I also wanted to verify that each algorithm's output was the same.  Below is a revised test program, with only Tor's, mine, and Claudiu's code -- because the others were breaking on the sample input.  (I think they're all brittle unless the dictionary maps basically  possible ampersand sequences, which Tor's test code was doing.) This one properly seeds the random number generator so each run is the same.  Finally, I added a minor variation using a generator which avoids some function call overhead, for a minor performance improvement.I forgot to include benchmark results before:Also, snippets of the inputs and correct output:Comparing with what I saw from Tor's test code output:If you really want to dig into the topic take a look at this: The obvious solution by iterating over the dictionary and replacing each element in the string takes  time, where n is the size of the dictionary, m is the length of the string.Whereas the Aho-Corasick-Algorithm finds all entries of the dictionary in  where f is the number of found elements.If the number of keys in the list is large, and the number of the occurences in the string is low (and mostly zero), then you could iterate over the occurences of the ampersands in the string, and use the dictionary keyed by the first character of the substrings. I don't code often in python so the style might be a bit off, but here is my take at it:Of course there is a question what happens when there is an ampersand that is coming from the string itself, you would need to escape it in some way before feeding through this process, and then unescape after this process. Of course, as is pretty much usual with the performance issues, timing the various approaches on your typical (and also worst-case) dataset and comparing them is a good thing to do.EDIT: place it into a separate function to work with arbitrary dictionary:EDIT2: get rid of an unneeded concatenation, seems to still be a bit faster than the previous on many iterations.Here is the C Extensions Approach for pythonPython codes I have testedResultsIts suppose to able to run at , and \nOnly took  for  string in My Mobile Celeron 1.6 GHz PCIt will also skip unknown characters as is, for example  will return as isLet me know If you have any problem with compiling, bugs, etc... seems like it does what you want - multiple string replace at once using RegExps. Here is the relevant code:A general solution for defining replacement rules is to use regex substitution using a function to provide the map (see ).This is particularly nice for non-trivial substitutions (e.g anything requiring mathmatical operations to create the substitute).Here is a version using split/joinIn case there are ampersands with invalid codes you can use this to preserve themPeter Hansen pointed out that this fails when there is double ampersand. In that case use this versionNot sure about the speed of this solution either, but you could just loop through your dictionary and repeatedly call the built-in   This might perform decently well if the original string isn't too long, but it would obviously suffer as the string got longer.The problem with doing this mass replace in Python is immutability of the strings: every time you will replace one item in the string then entire new string will be reallocated again and again from the heap.So if you want the fastest solution you either need to use mutable container (e.g. list), or write this machinery in the plain C (or better in Pyrex or Cython). In any case I'd suggest to write simple parser based on simple finite-state machine, and feed symbols of your string one by one.Suggested solutions based on regexps working in similar way, because regexp working using fsm behind the scene.Since someone mentioned using a simple parser, I thought I'd cook one up using pyparsing.  By using pyparsing's transformString method, pyparsing internally scans through the source string, and builds a list of the matching text and intervening text.  When all is done, transformString then ''.join's this list, so there is no performance problem in building up strings by increments.  (The parse action defined for ANSIreplacer does the conversion from the matched &_ characters to the desired escape sequence, and replaces the matched text with the output of the parse action.  Since only matching sequences will satisfy the parser expression, there is no need for the parse action to handle undefined &_ sequences.) The FollowedBy('&') is not strictly necessary, but it shortcuts the parsing process by verifying that the parser is actually positioned at an ampersand before doing the more expensive checking of all of the markup options.Prints:This will certainly not win any performance contests, but if your markup starts to get more complicated, then having a parser foundation will make it easier to extend.try thistr.replace(\"&y\",dict[\"&y\"])tr.replace(\"&c\",dict[\"&c\"])tr.replace(\"&b\",dict[\"&b\"])tr.replace(\"&Y\",dict[\"&Y\"])tr.replace(\"&u\",dict[\"&u\"])
Python

I would like to use my samsung chromebook to develop for app engine using python, unfortunately now it is not possible as I only have browser there.There are online IDE's like  but they are not good enough yet.So in this regards I have 3 questions:Just enable , and you will get the access to the .You can also use  to install a chroot jail and then you are free to apt-get install any library that's compiles to armv7.I have a Samsung Chromebook and I have installed the GAE python sdk , emacs and clozure common lisp for development.Its super easy to set this up:I have blogged about my experience Let me try and answer each of your 3 questions:You can read a blog post I wrote in the past about 'developers and chromebook' - Good luck!Here is a guide for the new Samsung Chromebook that was introduced in October 2012 with flash memory. It will detail how to install Ubuntu onto an SSD drive to allow for dual boot without needing to modify the internal ChromeOS. To boot into Ubuntu after install you type Ctrl-U.     link:\nThese days, you can easily set up  on a VM with any of a number of cloud service providers. EC2 has been done a bunch of times and is well documented, but pretty much any service that you can run a full Linux VM on should work.It works like a regular webapp. Your code runs on the server, so you can't program your Chomebook, just the VM, but that's better in a lot of circumstances.It's one popular option, even with people who have IPython installed locally, just because Cloud, but on Chrome OS, it makes even more sense to look at trying to get something like that set up, even if you use one of the other options to code offline.There are some new information for the new Samsung Chromebook that was introduced in March 2014 with flash memory. It will detail how to install Ubuntu onto an SSD drive to allow for dual boot without needing to modify the internal ChromeOS. To boot into Ubuntu after install you type Ctrl-U. I will post some more info to my blog  just launched a  with native keyboard shortcuts and a bunch of popular starter templates including python, and a google cloud template. You can get the chrome application for free here: Here are some of the features of the app -- the native keyboard shortcuts are hugely helpful since normally the keybindings are overwritten by the browser (for things like new file, close file, find in project, etc...): 
Python

I'm confused as to where I should put my virtualenvs.With my first django project, I created the project with the command, \"django-admin.py startproject djangoproject\".I then cd'd into the djangoproject directory and ran the command, \"virtualenv env\" which created the virtual environment directory at the same level as the inner \"djangoproject\" directory.Is this the wrong place in which to create the virtualenv for this particular project?I'm getting the impression that most people keep all their virtualenvs together in an entirely different directory, e.g. ~/virtualenvs, and then use virtualenvwrapper to switch back and forth between them.Is there a correct way to do this?Many people use the  tool, which keeps all virtualenvs in the same place (the  directory) and allows shortcuts for creating and keeping them there. For example, you might do:and then later:It's probably a bad idea to keep the virtualenv directory in the project itself, since you don't want to distribute it (it might be specific to your computer or operating system). Instead, keep a requirements.txt file using :and distribute that. This will allow others using your project to reinstall all the same requirements into their virtualenv with:This is a major advantage of putting the directory outside of the repository tree, e.g. under  with .Otherwise, if you keep it in the project tree, moving the project location will break the virtualenv.See: There is  but it is known to not be perfect.Another minor advantage: you don't have to  it.If it weren't for that, I'd just leave my virtualenvs gitignored in the project tree itself to keep related stuff close together.This is fine since you you will likely never reuse a given virtualenv across projects.The generally accepted place to put them is the same place that the default installation of virtualenvwrapper puts them: Related: virtualenvwrapper is an excellent tool that provides shorthands for the common virtualenv commands. 
Python

I'm using Python 3.4 on Windows. When I run a script, it complainsSo I tried to install it, but  givesalthough it does show up when I run . I tried to , which installed successfully but that didn't solve the problem.What am I doing wrong?Here are Windows wheel packages built by Chris Golke - Since Qt is a more complicated system with a compiled C++ codebase underlying the python interface it provides you, it can be more complex to build than just a pure python code package, which means it can be hard to install it from source.Make sure you grab the correct Windows wheel file (python version, 32/64 bit), and then use  to install it - e.g:Should properly install if you are running an x64 build of Python 3.5.You can't use pip. You have to download from the Riverbank website and run the installer for your version of python. If there is no install for your version, you will have to install Python for one of the available installers, or build from source (which is rather involved). Other answers and comments have the links. If you install PyQt4 on Windows, files wind up here by default:but it also leaves a file here:If you copy the both the sip.pyd and PyQt4 folder into your virtualenv things will work fine.For example:Then with windows explorer copy from  the file (sip.pyd) and folder (PyQt4) mentioned above to Then back at CLI:The problem with trying to launch a script which calls PyQt4 from within virtualenv is that the virtualenv does not have PyQt4 installed and it doesn't know how to reference the default installation described above. But follow these steps to copy PyQt4 into your virtualenv and things should work great.It looks like you may have to do a bit of manual installation for PyQt4.This might help a bit more, it's a bit more in a tutorial/set-by-step format:Earlier PyQt .exe installers were available directly from the website download page. Now with the release of PyQt4.12 , installers have been deprecated. You can make the libraries work somehow by compiling them but that would mean going to great lengths of trouble. you can use the previous distributions to solve your purpose. The .exe windows installers can be downloaded from :
Python

I am running Mac OSX 10.5.8. I installed matplotlib using macports. I get some examples from the matplotlib gallery like this one, without modification:I run it, get no error, but the picture does not show up. In Linux Ubuntu I get it.Do you know what could be wrong here?ThanksI can verify this on my end as well. To fix, here's what I didAlso, we need to change the default backend to a GUI based one.Edit the file , and add:Also, you can try the following, which may allow you to not need the GTK or Cairo backends.\nEdit  and add:With the port with those variants installed, this works as well, but it doesn't require X11.By the way, the error that I saw was the following:I had the same problem, even I could see how a new application window was created and immediately disappeared. Simple solution - just check if you have after the plotThis is what worked for me. I just changed the import of MatplotlibWhen you try instead of does that save the correct image named  in the current path?just to add a note, The matplotlibrc file was not present on my system and I had to to download a copy from the matplotlib website. Future users may have to do the same.This is what worked for me:References:\n\nI only had python 2.5 and I did not want to install python 2.6 on my mac. So I used different procedure mentioned in the following link to solve this problem:1) Searching where is the directory \"pygtk-2.0.pc\" and locate it. For example mine was located in the following directory: /opt/local/lib/pkgconfig2) Adding the path information to envirement variable. For example:3) Download the configuration information file \"matplotlibrc\" from matplotlib website\n  4) Change backend to MacOSX in the file and save it5) Copy the file to directory .matplotlib\n   You can locate the directory in python by the following command: 
Python

I am using python 2.6.5\nI want to write some japanese characters to a file.\nI am getting this error & I don't know how to change the encoding.you're going to have to 'encode' the unicode string.try this out for a bit of a friendly look at unicode and python: As an alternative, you can use the  module:The  function in 2.6 is very similar to the built-in  function in python3.x (which makes sense since Py3k strings are  Unicode). For future proofing your code in case it is used under Py3k you could do the following.Now your code should work the same in both 2.x and 3.3+.Inserting this at the beginning of my script tends to solve unicode problems.
Python

I have a list of booleans in python. I want to AND (or OR or NOT) them and get the result. The following code works but is not very pythonic.Any suggestions on how to make it more pythonic appreciated.Logical  across all elements in :Logical  across all elements in :If you feel creative, you can also do:keep in mind that those aren't evaluated in short circuit, whilst the built-ins are ;-)another funny way:and yet another:and we could go on all day, but yes, the pythonic way is to use  and  :-)By the way, Python has not tail recursion elimination, so don't try to translate LISP code directly ;-)ANDing and ORing is easy:NOTing is also fairly easy:Of course, how you would use those results might require some interesting applications of DeMorgan's theorem. can do this:As fortran mentioned, all is the most succinct way to do it. But reduce answers the more general question \"How to apply a logical operator to all elements in a python list?\"The idiom for such operations is to use the  function (global in Python 2.X, in module  in Python 3.X) with an appropriate binary operator either taken from the  module or coded explicitly. In your case, it's Here's another solution:ANDing all elements will return True if all elements are True, hence no False in a list.\nORing is similar, but it should return True if at least one True value is present in a list.As the other answers show, there are multiple ways to accomplish this task. Here's another solution that uses functions from the standard library:
Python

In my django app, I have an authentication system. So, If I do not log in and try to access some profile's personal info, I get redirected to a login page. Now, I need to write a test case for this. The responses from the browsers I get is :      How do I write my test ? This what I have so far:what could possibly come next ?Django 1.4:Django 1.7:You could also follow the redirect with:which would mirror the user experience in the browser and make assertions of what you expect to find there, such as:You can check  and see if it matchs with the expected url. Check also that status code is 302. doesn't exist in 1.9. Use this instead:
Python

The first examples that I googled didn't work. This should be trivial, right?Here's the documentation link: 
Python

I am using  and parsing some HTMLs.I'm getting a certain data from each HTML  and adding that data to a certain list.The problem is, some of the HTMLs have different format .So, I was trying to use exception handling and add value  to the list For instance, I have a code like:and some of the links don't have any , so what I want to do is add string  to the list instead.The error appears: What I have done tried is to add some lines like this:But it doesn't work out. It still shows error:What should I do about this? Should I use exception handling? or is there any easier way?Any suggestions? Any help would be really great!Handling the exception is the way to go:Of course you could also check the  of ; but handling the exception is more intuitive.You have two options; either handle the exception or test the length:orUse the first if there  is no second item, the second if there  is no second item.A ternary will suffice. change:tothis is a short hand forTaking reference of ThiefMaster\u2666 sometimes we get an error with value given as '\\n' or null and perform for that required to handle ValueError:Handling the exception is the way to go
Python

Is there a way to do the following preprocessor directives in Python?There's , which is a special value that the compiler does preprocess.  will be replaced with a constant 0 or 1 by the compiler, and the optimizer will remove any  lines before your source is interpreted.I wrote a python preprocessor called pypreprocessor that does exactly what you're describing...Here's an example to accomplish what you're describing.pypreprocessor is capable of a lot more than just on-the-fly preprocessing. To see more use case examples check out the project on Google Code.The way I accomplish the preprocessing is simple. From the example above, the preprocessor imports a pypreprocessor object that's created in the pypreprocessor module. When you call parse() on the preprocessor it self-consumes the file that it is imported into and generates a temp copy of itself that comments out all of the preprocessor code (to avoid the preprocessor from calling itself recursively in an infinite loop) and comments out all of the unused portions.Commenting out the lines is, as opposed to removing them, is necessary to preserve line numbers on error tracebacks if the module throws an exception or crashes. And I've even gone as far as to rewrite the error traceback to report reflect the proper file name of the module that crashed.Then, the generated file containing the postprocessed code is executed on-the-fly.The upside to using this method over just adding a bunch of if statements inline in the code is, there will be no execution time wasted evaluating useless statements because the commented out portions of the code will be excluded from the compiled .pyc files.The downside (and my original reason for creating the module) is that you can't run both python 2x and python 3x in the same file because pythons interpreter runs a full syntax check before executing the code and will reject any version specific code before the preprocessor is allowed to run ::sigh::. My original goal was to be able to develop 2x and 3x code side-by-side in the same file that would create version specific bytecode depending on what it is running on.Either way, the preprocessor module is still very useful for implementing common c-style preprocessing capabilities. As well as, the preprocessor is capable of outputting the postprocessed code to a file for later use if you want.Also, if you want to generate a version that has all of the preprocessor directives as well as any of the #ifdefs that are excluded removed it's as simple as setting a flag in the preprocessor code before calling parse(). This makes removing unwanted code from a version specific source file a one step process (vs crawling through the code and removing if statements manually). I suspect you're gonna hate this answer.  The way you do that in Python isSince python is an interpreter, there's no preprocessing step to be applied, and no particular advantage to having a special syntax.  You can use the preprocessor in Python. Just run your scripts through the cpp (C-Preprocessor) in your bin directory. However I've done this with Lua and the benefits of easy interpretation have outweighed the more complex compilation IMHO.You can just use the normal language constructs:An alternative method is to use a bash script to comment out portions of code which are only relevant to debugging. Below is an example script which comments out lines that have a '#DEBUG' statement in it. It can also remove these comment markers again.
Python

I have a program which interfaces with a radio I am using via a gui I wrote in PyQt.  Obviously one of the main functions of the radio is to transmit data, but to do this continuously, I have to loop the writes, which causes the gui to hang. Since I have never dealt with threading, I tried to get rid of these hangs using  The radio needs to sleep between transmissions, though, so the gui still hangs based on how long these sleeps last.  Is there a simple way to fix this using QThread?  I have looked for tutorials on how to implement multithreading with PyQt, but most of them deal with setting up servers and are much more advanced than I need them to be.  I honestly don't even really need my thread to update anything while it is running, I just need to start it, have it transmit in the background, and stop it.I created a little example that shows 3 different and simple ways of dealing with threads. I hope it will help you find the right approach to your problem.Very nice example from Matt, I fixed the typo and also pyqt4.8 is common now so I removed the dummy class as well and added an example for the dataReady signalAccording to the Qt developers, subclassing QThread is incorrect (see ).  But that article is really hard to understand (plus the title is a bit condescending).  I found a better blog post that gives a more detailed explanation about why you should use one style of threading over another:   In my opinion, you should probably never subclass thread with the intent to overload the run method.  While that does work, you're basically circumventing how Qt wants you to work.  Plus you'll miss out on things like events and proper thread safe signals and slots.  Plus as you'll likely see in the above blog post, the \"correct\" way of threading forces you to write more testable code.Here's a couple of examples of how to take advantage of QThreads in PyQt (I posted a separate answer below that properly uses QRunnable and incorporates signals/slots, that answer is better if you have a lot of async tasks that you need to load balance).Take this answer updated for PyQt5, python 3.4 Use this as a pattern to start a worker that does not take data and return data as they are available to the form.1 - Worker class is made smaller and put in its own file worker.py for easy memorization and independent software reuse.2 - The main.py file is the file that defines the GUI Form class3 - The thread object is not subclassed.4 - Both thread object and the worker object belong to the Form object5 - Steps of the procedure are within the comments.And the main file is:In PyQt there are a lot of options for getting asynchronous behavior.  For things that need event processing (ie. QtNetwork, etc) you should use the QThread example I provided in my other answer on this thread.  But for the vast majority of your threading needs, I think this solution is far superior than the other methods.The advantage of this is that the QThreadPool schedules your QRunnable instances as tasks.  This is similar to the task pattern used in Intel's TBB.  It's not quite as elegant as I like but it does pull off excellent asynchronous behavior.This allows you to utilize most of the threading power of Qt in Python via QRunnable and still take advantage of signals and slots.  I use this same code in several applications, some that make hundreds of asynchronous REST calls, some that open files or list directories, and the best part is using this method, Qt task balances the system resources for me.When exiting the application you'll want to make sure you cancel all of the tasks or the application will hang until every scheduled task has completedBased on the Worker objects methods mentioned in other answers, I decided to see if I could expand on the solution to invoke more threads - in this case the optimal number the machine can run and spin up multiple workers with indeterminate completion times.\nTo do this I still need to subclass QThread - but only to assign a thread number and to 'reimplement' the signals 'finished' and 'started' to include their thread number.I've focused quite a bit on the signals between the main gui, the threads, and the workers.Similarly, others answers have been a pains to point out not parenting the QThread but I don't think this is a real concern.  However, my code also is careful to destroy the QThread objects.However, I wasn't able to parent the worker objects so it seems desirable to send them the deleteLater() signal, either when the thread function is finished or the GUI is destroyed.  I've had my own code hang for not doing this.Another enhancement I felt was necessary was was reimplement the closeEvent of the GUI (QWidget) such that the threads would be instructed to quit and then the GUI would wait until all the threads were finished.   When I played with some of the other answers to this question, I got QThread destroyed errors.Perhaps it will be useful to others. I certainly found it a useful exercise.  Perhaps others will know a better way for a thread to announce it identity.And the worker code below
Python

What would be an  way to check list monotonicity? i.e. that it has monotonically increasing or decreasing values?Examples:This approach is  in the length of the list. If you have large lists of numbers it might be best to use numpy, and if you are:should do the trick.@6502 has the perfect code for lists, I just want to add a general version that works for all sequences:Here is a functional solution using  of complexity :Replace  with the top limit of your values, and  with the bottom limit.  For example, if you are testing a list of digits, you can use  and .I tested its performance against  and its faster.:I timed all of the answers in this question under different conditions, and found that:Here is the code to try it out:If the list was already monotonically increasing (), the fastest to slowest was:If the list was mostly monotonically increasing (), the fastest to slowest was:(Whether or not the starmap or zip was fastest depended on the execution and I couldn't identify a pattern. Starmap appeared to be usually faster)If the list was completely random (), the fastest to slowest was:
Python

I am trying to post a request to log in to a website using the Requests module in Python but its not really working. I'm new to this...so I can't figure out if I should make my Username and Password cookies or some type of HTTP authorization thing I found (??). So now, I think I'm supposed to use \"post\" and cookies....I have a feeling that I'm doing the cookies thing wrong...I don't know.If it doesn't log in correctly, the title of the home page should come out to \"Locationary.com\" and if it does, it should be \"Home Page.\"If you could maybe explain a few things about requests and cookies to me and help me out with this, I would greatly appreciate it. :DThanks....It still didn't really work yet. Okay...so this is what the home page HTML says before you log in:So I think I'm doing it right, but the output is still \"Locationary.com\"2nd EDIT:I want to be able to stay logged in for a long time and whenever I request a page under that domain, I want the content to show up as if I were logged in.Lets call your  variable  instead, like in the  docs:See  below.I know you've found another solution, but for those like me who find this question, looking for the same thing, it can be achieved with requests as follows:Firstly, as Marcus did, check the source of the login form to get three pieces of information - the url that the form posts to, and the name attributes of the username and password fields. In his example, they are inUserName and inUserPass.Once you've got that, you can use a  instance to make a post request to the login url with your login details as a payload. Making requests from a session instance is essentially the same as using requests normally, it simply adds persistence, allowing you to store and use cookies etc.Assuming your login attempt was successful, you can simply use the session instance to make further requests to the site. The cookie that identifies you will be used to authorise the requests.Let me try to make it simple, suppose URL of the site is  and let's suppose you need to sign up by filling username and password, so we go to the login page say  now and view it's source code and search for the action URL it will be in form tag something like now take userinfo.php to make absolute URL which will be '', now run a simple python script I Hope that this helps someone somewhere someday.Find out the name of the inputs used on the websites form for usernames  and passwords  and replace them in the script below. Also replace the url to point at the desired site to log into.The use of  will silence any output from the script when trying to log into sites with unverified SSL certificates. Extra:To run this script from the command line on a UNIX based system place it in a directory, i.e.  and add this directory to your path in  or a similar file used by the terminal.Then create a link to this python scipt inside Close your terminal, start a new one, run 
Python

How can I extract whatever follows the last slash in a URL in Python? For example, these URLs should return the following:I've tried urlparse, but that gives me the full path filename, such as .You don't need fancy things, just see  and you can easily split your url between 'filename' part and the rest:So you can get the part you're interested in simply with:One more (idio(ma)tic) way: should be up to the task:urlparse is fine to use if you want to (say, to get rid of any query string parameters).Output:You cand do like this:Where tail will be your file name. and  are also handy for such things:Output: .Split the url and pop the last element\n
Python

I'm writing a script to import some model objects into the database my django application uses. In the past I've solved this by running  and then . I'm sure there's a better way. I'd like to be able to call a script from anywhere on my HD using , and in the first few lines of that script it would do whatever imports / other operations necessary so that it can access model objects and behave as though it was run using .What do I need to add to my script to achieve this?Based on @Melug's answer, with addition of dynamically setting Python path to address the 'anywhere on my HD' part of the question:You need to setup django environment first:At last import your models, everything goes just like django. you should avoid using  (post by Melug) because it is deprecated. Use the following instead and you will be able to access your modelHere is an example to access and modify your model:Example model:To get models loaded too, I had to combine this with , otherwise I get As an extra, I add this to the  of my django projects, it will automatically discover the app name so it is copy/paste-able:Then I can just do:I think the best way is to create your . Then you can call  from anywhere.Here is the answer for Django versions > 1.4:Upper solutions did not work, but gave me an error:For me solution from  worked out:For Django version 1.9 or later you can use this:so you can use object as same django object:Since at least Django 1.11, your main app includes a wsgi module that does the neccessary setup on import. Assuming  is where your settings.py is, in your script just import:
Python

I have thisIs there a more pythonic (and/or shorter) way of writing this in python?Shortest one should be:Generally this might look a bit confusing, so you should only use it when it is clear what it means. Don't use it for big boolean clauses, since it begins to look ugly fast.This is:EDIT: As per request, the generalized form is:Explanation:  can be anything that evaluates to a Boolean.  It is then treated as an integer since it is used to index the tuple: , , which then selects the right item from the tuple.Well, not being a python guy please take this with a huge grain of salt, but having written (and, with more difficulty, ) a lot of clever code over the years, I find myself with a strong preference now for readable code.  I got the gist of what your original code was doing even though I'm a nobody as a Python guy.  To be sure, you could hide it and maybe impress a Python wonk or two, but why?Or you could use an inline if statement:There's a bit of a writeup on that feature at , and the relevant PEP is .  The inline if statement was introduced in Python 2.5.This one might be a little less pythonic, but you can use and/or in this fashion:This one is used more often in lambda statements than on a line by itself, but the formis similar toI was going to write out a little bit longer explanation, but they covered it better .  They also noted a couple caveats that you probably need to know.Another possibility is to use a dict if you can compute the values outside of the function that accesses them (i.e. the values are static, which also addresses the evaluation issue in scrible's answer's comments).I prefer this and/or the tuple indexing solutions under the general rubric of preferring computation to testing.You can use,but if you are using a python version prior to 2.5,can do the trick also.
Python

I need to write these four s in Python. Notice what it does, is changing between four possible states in a loop:  and back to first.Can anyone suggest me a better/nicer way to write this?When in doubt, apply maths. ;)Magnus' suggestion is undeniably the right answer to your question as posed, but  you want to use a dictionary for problems like this:Even in this case I  argue using a dictionary is better, since it's clear that there are exactly four states and that they repeat, but it's hard to resist the sheer beauty of By the way, the code in your question has a bug in it, and, assuming that the values you test for are the only possible values, is equivalent to:The bug is that you need  for the second and subsequent conditions, otherwise you're continuing to test  and  after changing them. If they're  and , then  and they end up the same at the end! If they start out as  and  then the second and all subsequent conditions will be true, and you again end up with . And so on...Just extending Magnus answer. If you imagine [dx, dy] as a vector, what you're actually doing is a  of 90 degrees (or PI/2).To calculate this, you can use the following transformation:Which in your case translate to:Since  and  we simplify it to:And there you have it!The values you're working with appear to be a unit vector that continuously rotates - in other words, a . , so:Assuming my interpretation of the meaning of the dx,dy values is correct, this gives you extra flexibility in case it turns out later that you want to rotate by some other amount in each step.While I would go with Magnus' answer, here's yet another approach for rotating over a set of values:Note that there should be a  somewhere in the  loop or else it will never end.
Python

 I assume this is a bug in the backend? I am writing some code for processing a fairly large amount of data automatically. The code first of all parses my data files and stores all of the relevant bits. I then have different functions for producing each of the graphs I need (there are about 25 in all). However, I keep running into some kind of memory error and I think it is because Matplotlib / PyPlot are not releasing the memory correctly. Each plotting function ends with a pyplot.close(fig) command and since I just want to save the graphs and not look at them immediately they do  include a pyplot.show(). If I run the plotting functions individually in an interpreter then I don't get any problems. However, if I make a separate function which calls each plotting function in turn then I run into a \"MemoryError: Could not allocate memory for path\". Has anyone came across a problem like this? It would seem to be related to  but pyplot.close() doesn't fix my problem. This is what a typical plot function looks like in my code:If I now run in a terminalThen I don't get any errors. The same is true for all of my plot functions. If I make a new function which does this:Then it runs through about half of the graphs and then I get \"MemoryError: Could not allocate memory for path\".I think the reason it is doing this is because as it goes through all of the different graphs it then runs out of memory probably because it isn't releasing it properly.Why don't you try creating about 3 or so programs each of which do a few graphs instead of one program doing all the graphs:Program 1: Graphs 1-8Program 2: Graphs 9-16Program 3: Graphs 17-25Hope this helps  @FakeDIY : )I run into a very similar problem once. I assume matplotlib keeps references for each plots internally. Given the following code, creating three separate figures:This is counter intuitive, because we redefined  and  several times.\nWith every block, we created a new figure, which can be referenced via . Creating another figure changes the topmost references accessible by . But there must be some internal reference, which allows  to show all figures. Those references seem to be persistent and thus the figures won't be collected by the gc.The workaround I settled with, was changing the data of the plot. In hindsight it was a better approach anyway:Only drawback is you have to keep the Window with the figure open. And without the  the program will just run through
Python

I had my fair chance of getting through the python management of modules, and every time is a challenge: packaging is not what people do every day, and it becomes a burden to learn, and a burden to remember, even when you actually do it, since this happens normally once.I would like to collect here the definitive overview of how import, package management and distribution works in python, so that this question becomes the definitive explanation for all the magic that happens under the hood. Although I understand the broad level of the question, these things are so intertwined that any focused answer will not solve the main problem: understand how all works, what is outdated, what is current, what are just alternatives for the same task, what are the quirks.The list of keywords to refer to is the following, but this is just a sample out of the bunch. There's a lot more and you are welcome to add additional details. Linking to other answers is probably a good idea. As I said, this question is for the high-level overview.For the most part, this is an attempt to look at the packaging/distribution side, not the mechanics of .  Unfortunately, packaging is the place where Python provides way more than one way to do it.  I'm just trying to get the ball rolling, hopefully others will help fill what I miss or point out mistakes.  First of all there's some messy terminology here.  A directory containing an  file is a package.  However, most of what we're talking about here are specific versions of packages published on PyPI, one of it's mirrors, or in a vendor specific package management system like Debian's Apt, Redhat's Yum, Fink, Macports, Homebrew, or ActiveState's pypm.These published packages are what folks are trying to call \"Distributions\" going forward in an attempt to use \"Package\" only as the Python language construct.  You can see some of that usage in  .  Now, your list of keywords relate to several different aspects of the Python Ecosystem:The above are all services that provide a place to publish Python distributions in various formats.  Some, like PyPI mirrors and apt / yum repositories can be run on your local machine or within your companies network but folks typically use the official ones.  Most, if not all provide a tool (or multiple tools in the case of PyPI) to help find and download distributions.Distutils is the standard infrastructure on which Python packages are compiled and built into distributions.  There's a ton of functionality in  but most folks just know:And to some extent that's a most of what you need.  With the prior 9 lines of code you have enough information to install a pure Python package and also the minimal metadata required to publish that package a distribution on PyPI.Setuptools provides the hooks necessary to support the Egg format and all of it's features and foibles.  Distribute is an alternative to Setuptools that adds some features while trying to be mostly backwards compatible.  I believe Distribute is going to be included in Python 3 as the successor to Distutil's .Both Setuptools and Distribute provide a custom version of the  setup command\nthat does useful things like support the Egg format.Distributions are typically provided either as source archives (tarball or zipfile).  The standard way to install a source distribution is by downloading and uncompressing the archive and then running the  file inside.For example, the following will download, build, and install the Pygments syntax highlighting library:Alternatively you can download the Egg file and install it.  Typically this is accomplished by using easy_install or pip: were inspired by Java's Jarfiles and they have quite a few features you should read about A normal python package is just a directory containing an  file and an arbitrary number of additional modules or sub-packages.  Python also has support for finding and loading source code within *.zip files as long as they are included on the  ().The above tools are used to help automate and manage dependencies for a Python project.  Basically they give you tools to describe what distributions your application requires and automate the installation of those specific versions of your dependencies.By default, installing a python distribution is going to drop it into the site-packages directory.  That directory is usually something like .A simple programmatic way to find your site-packages directory:Python's import statement will only find packages that are located in one of the directories included in your .You can inspect and change your path from within Python by accessing:Besides that, you can set the  environment variable like you would any other environment variable on your OS or you could use:To add the above  to site-packages with a *.pth file you'd create a *.pth file.  The name of the file doesn't matter but you should still probably choose something sensible.Let's create :That's it.  Drop that into  on your system or any other directory in your  and  will be added to the path.For packaging question, this should help For import, the old article from Fredrik Lundh  still a very good starting point.I recommend  There's a chapter dedicated to packaging and distribution.I don't think  needs to be explored (Python's namespacing and importing functionality is intuitive IMHO).I use  exclusively now. I haven't run into any issues with it.However, the topic of packaging and distribution is something worth exploring. Instead of giving a lengthy answer, I will say this:I learned how to package and distribute my own \"packages\" by simply copying how Pylons or many other open-source packages do it. I then combined that sort-of template with reading up of the docs to flesh it out even further and have come up with a solid distribution method.When you grok package management and distribution for python (distutils and pypi) it's actually quite powerful. I like it a lot.[edit]I also wanted to add in a bit about virtualenv. USE IT. I create a virtualenv for every project and I always use ; I install all the packages I need for that particular project (even if it's something common amongst them all, like ) inside the virtualev. It keeps everything isolated and it's much easier for me to maintain the grouping in my head (rather than trying to keep track of what's where and for which version of python!)[/edit]
Python

I'm relatively new to the world of TensorFlow, and pretty perplexed by how you'd  read CSV data into a usable example/label tensors in TensorFlow. The example from the  is pretty fragmented and only gets you part of the way to being able to train on CSV data.Here's my code that I've pieced together, based off that CSV tutorial:And here is an brief example from the CSV file I'm loading - pretty basic data - 4 feature columns, and 1 label column:All the code above does is , which, while nice, is pretty darn useless for training.What I'm struggling with here is how you'd actually turn those individual examples, loaded one-by-one, into a training dataset. For example,  I was working on in the Udacity Deep Learning course. I basically want to take the CSV data I'm loading, and plop it into something like  and :I've tried using , like this, but it just inexplicably hangs:So to sum up, here are my questions:\nAs soon as Yaroslav pointed out that I was likely mixing up imperative and graph-construction parts here, it started to become clearer. I was able to pull together the following code, which I think is closer to what would typically done when training a model from CSV (excluding any model training code):I think you are mixing up imperative and graph-construction parts here. The operation  creates a new queue node, and a single node can be used to process the entire dataset. So I think you are hanging because you created a bunch of  queues in your for loop and didn't start queue runners for them. Normal input pipeline usage looks like this:--- end of graph construction, beginning of imperative programming --To be more scalable (to avoid Python GIL), you could generate all of your data using TensorFlow pipeline. However, if performance is not critical, you can hook up a numpy array to an input pipeline by using  Here's an example with some  nodes to see what's going on (messages in  go to stdout when node is run)You should see something like thisThe \"8, 9\" numbers didn't fill up the full batch, so they didn't get produced. Also  are printed to sys.stdout, so they show up in separately in Terminal for me.PS: a minimal of connecting  to a manually initialized queue is in Also, for debugging purposes you might want to set  on your session so that your IPython notebook doesn't hang on empty queue dequeues. I use this helper function for my sessionsScalability Notes:Or you could try this, the code loads the Iris dataset into tensorflow using pandas and numpy and a simple one neuron output is printed in the session. Hope it helps for a basic understanding.... [ I havent added the way of one hot decoding labels].
Python

I know that there is a  but is there, currently or planned, a Microsoft Visual C++ Compiler for Python 3.4 or eve Microsoft Visual C++ Compiler for Python 3.x for that matter?  It would be supremely beneficial if I didn't have to install a different version of visual studio on my entire lab.Unfortunately to be able to use the extension modules provided by others you'll be forced to use the official compiler to compile Python.  These are:Alternatively, you can use MinGw to compile extensions in a way that won't depend on others.See:  or This allows you to have one compiler to build your extensions for both versions of Python, Python 2.x and Python 3.x. suffices to build extensions for Python 3.5. It's free but a 6 GB download (overkill). On my computer it installed vcvarsall at  For Python 3.4 you'd need Visual Studio 2010. I don't think there's any free edition. See For the different python versions:Source: Also refer: 
Python

I am new to celery.I know how to install and run one server but I need to distribute the task to multiple machines.\nMy project uses celery to assign user requests passing to a web framework to different machines and then returns the result.\nI read the documentation but there it doesn't mention how to set up multiple machines.\nWhat am I missing?My understanding is that your app will push requests into a queueing system (e.g. rabbitMQ) and then you can start any number of workers on different machines (with access to the same code as the app which submitted the task). They will pick out tasks from the message queue and then get to work on them. Once they're done, they will update the tombstone database. The upshot of this is that you don't have to do anything special to start multiple workers. Just start them on separate identical (same source tree) machines. The server which has the message queue need not be the same as the one with the workers and needn't be the same as the machines which submit jobs. You just need to put the location of the message queue in your  and all the workers on all the machines can pick up jobs from the queue to perform tasks. The way I deployed it is like this:
Python

Could any one suggest good Python-related podcasts out there, it could be anything about Python or its eco-system (like django, pylons, etc). (several languages there)\n\n\nI didn't think much of Python411 - the episode I downloaded primarily consisted of the host talking about how he was planning on writing a GAE site. as pointed out by Geo is (or possibly was) a good Python podcast. Obviously, as it's focused on Django development there is a lot of Djangoisms discussed however there's also a lot of general Python knowledge shared as well. TWID is currently going through a revamp, keep an eye on  for updates.  (read the blog, listen to the podcast, it is very good) has some Python material, for instance:There has been a few IronPython-related shows on some of the .NET podcasts:
Python

Greetings,I'm trying to write a program in Python which would print a string every time it gets a tap in the microphone. When I say 'tap', I mean a loud sudden noise or something similar.I searched in SO and found this post: I think PyAudio library would fit my needs, but I'm not quite sure how to make my program wait for an audio signal (realtime microphone monitoring), and when I got one how to process it (do I need to use Fourier Transform like it was instructed in the above post)?Thank you in advance for any help you could give me.If you are using LINUX, you can use . \nFor windows, we have  and there is also a library called .I found an example for Linux :If you want a \"tap\" then I think you are interested in amplitude more than frequency. So Fourier transforms probably aren't useful for your particular goal. You probably want to make a running measurement of the short-term (say 10 ms) amplitude of the input, and detect when it suddenly increases by a certain delta. You would need to tune the parameters of:Although I said you're not interested in frequency, you might want to do some filtering first, to filter out especially low and high frequency components. That might help you avoid some \"false positives\". You could do that with an FIR or IIR digital filter; Fourier isn't necessary.
Python

I get an error message when I use this expression:I checked the regex at  and it returns  as expected.  But when I try it in Python I get this error message:Can someone please explain?It seems to be a python bug (that works perfectly in vim).\nThe source of the problem is the (\\s*...)+ bit. Basically , you can't do  which make sense , because you are trying to repeat something which can be null.However  should not be null,  but we know it only because we know what's in \\1. Apparently python doesn't ... that's weird.That is a Python bug between \"*\" and special characters.Instead ofTry:It works, however does not make the same regular expression.This bug seems to have been fixed between 2.7.5 and 2.7.6.
Python

I realize this is a bit of a lazyweb question, but I wanted to see which python library for Twitter people have had good experiences with.I've used  and like its brevity and beauty of interface, but it doesn't seem to be one of the popular ones - it's not even listed on the . There are, however, plenty of others listed:My requirements are fairly simple:Twisted one aside (I'm not using twisted in this case), have you used any of the others, and if so, do you recommend them?[Update] FWIW, I ended up going with  again. The new version supported OAuth nicely, and it's a very clever API, so I stuck to it. should cover the first four requirements. I've used it before, and it's fairly easy to start developing with it. For leveraging Twitter's streaming API, I would recommend . It's a fantastic Python module that grabs tweets in real-time as they are posted. Based on whether you have gardenhose/firehose access to the twitter stream, you'll only get a small fraction of tweets posted. With tweetstream, you can also provide a list of search predicates to filter specific tweets that you are looking for. I used it for a project that involved mining tweets over an 8 hour period and it worked flawlessly. Both of these modules should be available through Python's .EDIT: I don't know what you intend on doing with Python/Twitter but if you do plan on capturing a lot of tweets, keep in mind that Twitter receives myriad tweets in languages besides English. Remember to encode everything properly. Full disclosure: I'm the author of Twython.As such, I'd recommend using mine. It supports OAuth now, and ships with a skeleton Django application to get you up and running in ~5 minutes.It can handle everything you're looking for, sans the Streaming API - I'm of the opinion that something like that should be implemented on a case-by-case basis, as it's generally a fairly custom setup. There's been very little demand for library support for it, either, so I've a hard time dedicating cycles to supporting it.I've used tweepy for playing around and thought it was pretty easy and fun to use. Didn't really look that much into the alternatives however so take my opinion with suitable amount of salt :). 
Python

I am currently working on a project in python, and I would like to make use of the GPU for some calculations. At first glance it seems like there are many tools available; at second glance, I feel like im missing something.Copperhead looks awesome but has not yet been released. It would appear that im limited to writing low-level CUDA or openCL kernels; no thrust, no cudpp. If id like to have something sorted, im going to have to do it myself.That doesnt seem quite right to me. Am I indeed missing something? Or is this GPU-scripting not quite living up to the hype yet?Edit: GPULIB seems like it might be what I need. Documentation is rudimentary, and the python bindings are mentioned only in passing, but im applying for a download link right now. Anyone has experience with that, or links to similar free-for-academic-use GPU libraries? ReEdit: ok, python bindings are infact nonexistant.Edit2: So I guess my best bet is to write something in C/CUDA and call that from python? provides very good integration with CUDA and has several helper interfaces to make writing CUDA code easier than in the straight C api.   is an example from the Wiki which does a 2D FFT without needing any C code at all.I know that this thread is old, but I think I can bring some relevant information that answers to the question asked.Continuum Analytics has a package that contains libraries that resolves the CUDA computing for you. Basically you instrument your code that needs to be parallelized (within a function) with a decorator and you need to import a library. Thus, you don't need any knowledge about CUDA instructions. Information can be found on NVIDIA pageor  you can go directly to the Continuum Analytics' pageThere is a 30 day trial period and a free licence for academics.I use this extensively and accelerates my code between 10 to 50 times.I will publish here some information that I read on redit. It will be useful for people who are coming without a clear idea of what different packages do and how they connect cuda with Python:From:\nThere's a lot of confusion in this thread about what various projects aim to do and how ready they are. There is no \"GPU backend for NumPy\" (much less for any of SciPy's functionality). There are a few ways to write CUDA code inside of Python and some GPU array-like objects which support subsets of NumPy's ndarray methods (but not the rest of NumPy, like linalg, fft, etc..) looks like it might be what you're looking for.  From what I understand, it is very capable of doing some heavy mathematical lifting with the GPU and appears to be actively maintained.Good luck!Have you taken a look at PyGPU? I can recommend  . but for that  you need to download  full version(free for students.) . Another is  .\nIf you are looking for something better and ready to pay for that,you can also take a look at .Write now I am using scikits and quite satisfy so far.
Python

I didn't find a good comparison of jinja2 and Mako. What would you use for what tasks ? I personnaly was satisfied by mako (in a pylons web app context) but am curious to know if jinja2 has some nice features/improvements that mako doesn't ? -or maybe downsides ?-I personally prefer Jinja2's syntax over Mako's. Take this example from the One of the removed construct here is the : . It was quite unfair to place it there since you should actually pass variable inside the context. But Mako still allows you to use plain python code within templates. It shouldn't be used often but when you really need it. It's there just to make your life easier. If you need something in one template but not anywhere else and Passing it to the context is overkill. That's what you really need.There are so many constructs here that I would have to consult the documentation before I could even begin. Which tags begin like  and close with ? Which of those are allowed to close with ? Why is there yet another way to enter the template language when I want to output a variable ()? What's with this  XML where some directives close like tags and have attributes?This is the equivalent example in Jinja2:Jinja2 has filters, which I'm told Mako also has but I've not seen them. Filter functions don't act like regular functions, they take an implicit first parameter of the value being filtered. Thus in Mako you might write:That's horrible. In Jinja2 you would write:In my opinion, the Jinja2 examples are exceedingly more readable. Jinja2's more regular, in that tags begin and end in a predictable way, either with  for processing and control directives, or  for outputting variables.But these are all personal preferences. I don't know of one more substantial reason to pick Jinja2 over Mako or vice-versa. And Pylons is great enough that you can use either! included Jinja2 macros. Although contrived in any case, in my opinion the Jinja2 example is easier to read and understand. Mako's guiding philosophy is \"Python is a great scripting language. Don't reinvent the wheel...your templates can handle it!\" But Jinja2's macros (the entire language, actually) look more like Python that Mako does!Take a look at  example:It is optimized for  (more  and ), well  and .
Python

If I have  how can I build a  out of the ? The only argument  seems to take is the factory function, will I have to initialize and then go through the original  and update the ?:Or given a dictionary : 
Python

I currently use Cython to link C and Python, and get speedup in slow bits of python code. However, I'd like to use goroutines to implement a really slow (and very parallelizable) bit of code, but it must be callable from python. (I've already seen )I'm (sort of) happy to go via C (or Cython) to set up data structures etc if necessary, but avoiding this extra layer would be good from a bug fix/avoidance point of view.What is the simplest way to do this without having to reinvent any wheels?: possible as of Go 1.5 Unfortunately, this is not currently possible. Go can run C code (and that C code can then call back into Go), but the , so the Go runtime can set things up. There is a  package precisely to help you write Python extensions in Go:I've written an extension to setuptools which allows you to write cpython extensions that interface with go: There's a couple example extensions here:The neat thing is these can be installed just like any other  package and support both cpython and pypy. manylinux1 wheels can also be built to provide pre-built wheels via the  tool.The approach is nearly identical to the one in @ColonelPanic's answer but uses some additional tricks to enable python2 + python3 compatibility.
Python

Defining a parameterless exception :When raised, is there any difference between :andWhen trying, I could find none - Is it simply an overloaded syntax?The short answer is that both  and  do the same thing.  This first form auto instantiates your exception.The  says, \" evaluates the first expression as the exception object. It must be either a subclass or an instance of BaseException. If it is a class, the exception instance will be obtained when needed by instantiating the class with no arguments.\"That said, even though the semantics are the same,  the first form is microscopically faster, and the second form is more flexible (because you can pass it arguments if needed).The usual style that most people use in Python (i.e. in the standard library, in popular applications, and in many books) is to use  when there are no arguments.  People only instantiate the exception directly when there some arguments need to be passed.  For example:  .Go look at the raise keyword in the docs \nIt is creating an instance of myException
Python

I'm teaching a python class on Object Oriented Programming and as I'm brushing up on how to explain Classes, I saw an empty class definition:the example then goes on to define a name and other attributes for an object of this class:interesting!I'm wondering if there's a way to dynamically define a function for a class like this? something like:this doesn't work in my python interpreter but is there another way of doing it?A class is more or less a fancy wrapper for a  of attributes to objects. When you instantiate a class you can assign to its attributes, and those will be stored in ; likewise, you can look in  for any attributes you have already written.This means you can do some neat dynamic things like:as well as assigning to a particular instance. (EDIT: added  parameter)Try with :The you'll be able to do:: Thanks  for the note - this works on  and not for Python2, where  appeared to be . But this will work for s, without  (right? Sorry, I know only  (: )You could use AttrDictInstall attrdict from PyPI: It's useful in other situations too - like when you need attribute access to dict keys.You could also use \"named tuples\" from the  standard module. Named tuples work like \"ordinary\" tuples but the elements have names and you can access the elements using the \"dot syntax\". From the :
Python

I'm trying to write a python class which uses a decorator function that needs information of the instance state. This is working as intended, but if I explicitly make the decorator a staticmetod, I get the following error:Why?Here is the code:And if I just remove the line , everything works, but I do not understand why. Shouldn't it need  as a first argument?This is not how  is supposed to be used.   objects are  that return the wrapped object, so they only work when accessed as .  ExampleprintsInside the scope of , you would always get the latter object, which is not callable.I'd strongly recommend to move the dcorator to the module scope -- it does not seem to belong inside the class.  If you want to keep it inside the class, don't make it a , but rather simply  it at the end of the class body -- it's not meant to be used from outside the class in this case.Python classes are created at runtime, after evaluating the contents of the class declaration. The class is evaluated by assigned all declared variables and functions to a special dictionary and using that dictionary to call  (see ).So,is equivalent to:When you annotate a method with @staticmethod, there is some special magic that happens AFTER the class is created with . Inside class declaration scope, the @staticmethod function is just an instance of a staticmethod object, which you can't call. The decorator probably should just be declared above the class definition in the same module OR in a separate \"decorate\" module (depends on how many decorators you have). In general decorators should be declared outside of a class. One notable exception is the property class (see ).  In your case having the decorator inside a class declaration might make sense if you had something like a color class: is returning a  method that isn't decorated by You can return a non-static method to a static_method
Python

I'm writing a small Python script which will periodically pull information from a 3rd party service using a username and password combo. I don't need to create something that is 100% bulletproof (does 100% even exist?), but I would like to involve a good measure of security so at the very least it would take a long time for someone to break it. This script won't have a GUI and will be run periodically by , so entering a password each time it's run to decrypt things won't really work, and I'll have to store the username and password in either an encrypted file or encrypted in a SQLite database, which would be preferable as I'll be using SQLite anyway, and I  need to edit the password at some point. In addition, I'll probably be wrapping the whole program in an EXE, as it's exclusively for Windows at this point. How can I securely store the username and password combo to be used periodically via a  job?I recommend a strategy similar to .  If you can't use ssh-agent directly you could implement something like it, so that your password is only kept in RAM.  The cron job could have configured credentials to get the actual password from the agent each time it runs, use it once, and de-reference it immediately using the  statement.The administrator still has to enter the password to start ssh-agent, at boot-time or whatever, but this is a reasonable compromise that avoids having a plain-text password stored anywhere on disk.After looking though the answers to this and related questions, I've put together some code using a few of the suggested methods for encrypting and obscuring secret data. This code is specifically for when the script has to run without user intervention (if the user starts it manually, it's best to have them put in the password and only keep it in memory as the answer to this question suggests). This method isn't super-secure; fundamentally, the script can access the secret info so anyone who has full system access has the script and its associated files and can access them. What this does do id obscures the data from casual inspection and leaves the data files themselves secure if they are examined individually, or together without the script.My motivation for this is a project that polls some of my bank accounts to monitor transactions - I need it to run in the background without me re-entering passwords every minute or two.Just paste this code at the top of your script, change the saltSeed and then use store() retrieve() and require() in your code as needed:The security of this method would be significantly improved if os permissions were set on the secret files to only allow the script itself to read them, and if the script itself was compiled and marked as executable only (not readable). Some of that could be automated, but I haven't bothered. It would probably require setting up a user for the script and running the script as that user (and setting ownership of the script's files to that user).I'd love any suggestions, criticisms or other points of vulnerability that anyone can think of. I'm pretty new to writing crypto code so what I've done could almost certainly be improved.I'm currently researching this topic and the following seems to be the best solution for my needs...maybe it will work for others coming across this question. integrates with the  API on Windows which encrypts data using the users logon credentials.Usage is very simple:Items are encrypted with the users Windows credentials, thus other applications running in your user account would be able to access the password.  To obscure that vulnerability a bit you could encrypt/obfuscate the password in some manner before storing it on the keyring.  Of course, anyone who was targeting your script would just be able to look at the source and figure out how to unencrypt/unobfuscate the password, but you'd at least prevent some application vacuuming up all passwords in the vault and getting yours as well.I think the best you can do is protect the script file and system it's running on.Basically do the following:There's not much point trying to encrypt the password: the person you're trying to hide it from has the Python script, which will have the code to decrypt it.  The fastest way to get the password will be to add a print statement to the Python script just before it uses the password with the third-party service.So store the password as a string in the script, and base64 encode it so that just reading the file isn't enough, then call it a day.operating systems often have support for securing data for the user.  in the case of windows it looks like it's you can call win32 apis from python using as far as i understand, this will store the data so that it can be accessed only from the account used to store it.  if you want to edit the data you can do so by writing code to extract, change and save the value.I used  because I had troubles installing (compiling) other commonly mentioned libraries on my system. (Win7 x64, Python 3.5)My script is running in a physically secure system/room. I encrypt credentials with an \"encrypter script\" to a config file. And then decrypt when I need to use them.\n\"Encrypter script\" is not on the real system, only encrypted config file is. Someone who analyses the code can easily break the encryption by analysing the code, but you can still compile it into an EXE if necessary.
Python

What's the difference between  and  in Python?which yieldsandwhich yieldsThe difference is that when you use , the  is set and the message states that the exception was . If you omit the  then no  is set, but the  may be set as well, and the traceback then shows the context as .Setting the  happens if you used  in an exception handler; if you used  anywhere else no  is set either.If a  is set, a  flag is also set on the exception; when  is set to , the  is ignored when printing a traceback.When raising from a exception handler where you  want to show the context (don't want a  message), then use  to set  to .In other words, Python sets a  on exceptions so you can introspect where an exception was raised, letting you see if another exception was replaced by it. You can also add a  to an exception, making the traceback explicit about the other exception (use different wording), and the context is ignored (but can still be introspected when debugging). Using  lets you suppress the context being printed.See the :Also see the  for details on the context and cause information attached to exceptions.
Python

Since  and  are instances of , the following is valid in Python:I understand why this happens. However, I find this behaviour a bit unexpected and can lead to hard-to-debug bugs. It has certainly bitten me a couple of times.Can anyone think of a legit use of indexing lists with  or ?In the past, some people have used this behaviour to produce a poor-man's :However, with a  having been added to the language in Python 2.5, this is very much frowned upon, for the reasons you state: relying on booleans being a subclass of integers is too 'magical' and unreadable for a maintainer.So, unless you are code-golfing ( producing very compact and obscure code), useinstead, which has the added advantage that the two expressions this selects between are  evaluated; if  is false, the expression before the  is never executed.If you are puzzled why  is a valid index argument: this is simply for  with the fact that  is a subclass of  and in Python it  a numerical type. If you are asking why  is a numerical type in the first place then you have to understand that  wasn't present in old releases of Python and people used s instead.I will add a bit of historic arguments. First of all the addition of  in python is shortly described in Guido van Rossum (aka BDFL) blogpost: . The type was added via .The PEP contains the  rationales used for this decisions. I'll quote some of the portions of the PEP below.:There are often better ways, but Boolean indices do have their uses.  I've used them when I want to convert a boolean result to something more human readable:
Python

I have a class that I'm testing which has as a dependency another class (an instance of which gets passed to the CUT's init method).  I want to mock out this class using the Python Mock library.What I have is something like:Which is fine, but \"methodfromdepclass\" is a parameterized method, and as such I want to create a single mock object where depending on what arguments are passed to methodfromdepclass it returns different values.  The reason I want this parameterized behaviour is I want to create multiple instances of ClassUnderTest that contain different values (the values of which are produced by what gets returned from the mockobj).Kinda what I'm thinking (this of course does not work):How do I achieve this \"ifcalledwith\" kind of semantics?Try A little sweeter:or for multiple arguments:or with a default value:or a combination of both:and merrily on high we go.I've ran into this when I was doing my own testing.  If you don't care about capturing calls to your methodfromdepclass() but just need it to return something, then the following may suffice:Here's a parameterized version:
Python

I have one field in a pandas DataFrame that was imported as string format. \nIt should be a datetime variable.\nHow do I convert it to a datetime column and then filter based on date.Example:Use the  function, specifying a  to match your data.You can use the DataFrame method  to operate on the values in Mycol:works, however it results in a Python warning of \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using  insteadI would guess this is due to some chaining indexing.
Python

I have the following codeI need to set the value of  to  if  is ; and do nothing otherwise. So, here is my code for thatIs there someway I could avoid the  part to make it look cleaner? An equivalent to I tried replacing it with  like this: . All I got was syntax error. Nor I could just omit the  part.ThanksI don't think this is possible in Python, since what you're actually trying to do probably gets expanded to something like this:If you exclude , you'll receive a syntax error since I'm quite sure that the assignment must actually return something.As others have already mentioned, you could do this, but it's bad because you'll probably just end up confusing yourself when reading that piece of code the next time:I'm not a big fan of the  for the exact same reason. I have to actually think twice on what that line is doing.The best way to actually achieve what you want to do is the original version:The reason that's the best verison is because it's very obvious what you want to do, and you won't confuse yourself, or whoever else is going to come in contact with that code later.Also, as a side note,  is valid Ruby code, because Ruby works a bit differently.Use this:In one line:But don\u2019t do that. This style is normally not expected. People prefer the longer form for clarity and consistency.(Equally, camel caps should be avoided. So rather use .)Note that an in-line   without an  part does not exist because there would not be a return value if the predicate were false. However, expressions must have a clearly defined return value in all cases. This is different from usage as in, say, Ruby or Perl.No. I guess you were hoping that something like  would work, but it doesn't. I think the best way is with the  statement as you have written it:you can use one of the following:
Python

I have a few Pandas DataFrames sharing the same value scale, but having different columns and indices. When invoking , I get separate plot images. what I really want is to have them all in the same plot as subplots, but I'm unfortunately failing to come up with a solution to how and would highly appreciate some help. You can manually create the subplots with matplotlib, and then plot the dataframes on a specific subplot using the  keyword. For example for 4 subplots (2x2):Here  is an array which holds the different subplot axes, and you can access one just by indexing .\nIf you want a shared x-axis, then you can provide  to .You can see e.gs. in the  demonstrating joris answer. Also from the documentation, you could also set  and  within the pandas  function:  You could also use  which takes subplot grid parameters such as 221, 222, 223, 224, etc. as described in the post . Nice examples of plot on pandas data frame, including subplots, can be seen in .You can use the familiar Matplotlib style calling a  and , but you simply need to specify the current axis using . An example:etc...Building on @joris response above, if you have already established a reference to the subplot, you can use the reference as well. For example, 
Python

The above python code gives the output quite different from expected. I want to loop over items so that I can skip an item while looping.Please explain.I've been bitten before by (someone else's) \"clever\" code that tries to modify a list while iterating over it.  I resolved that I would never do it under any circumstance.You can use the slice operator  to skip across to every third item in your list.Other points about my example relate to new syntax in . Never alter the container you're looping on, because iterators on that container are not going to be informed of your alterations and, as you've noticed, that's quite likely to produce a very different loop and/or an incorrect one.  In normal cases, looping on a copy of the container helps, but in your case it's clear that you  want that, as the container will be empty after 50 legs of the loop and if you then try popping again you'll get an exception.What's anything BUT clear is, what behavior are you trying to achieve, if any?!  Maybe you can express your desires with a ...?The general rule of thumb is that you don't modify a collection/array/list while iterating over it. Use a secondary list to store the items you want to act upon and execute that logic in a loop after your initial loop.Try this. It avoids mutating a thing you're iterating across, which is generally a code smell.See .Use a while loop that checks for the truthfulness of the array:And it should do it without any errors or funny behaviour.I guess this is what you want:It is quite handy to code when the number of item to be popped is a run time decision.\nBut it runs with very a bad efficiency and the code is hard to maintain.This slice syntax makes a copy of the list and does what you want:
Python

How can I get a  (degree) character into a string?Put this line at the top of your sourceIf your editor uses a different encoding, substitute for utf-8  Then you can include utf-8 characters directly in the sourceThis is the most coder-friendly version of specifying a unicode character:Note: must be a capital N in the  construct to avoid confusion with the '\\n' newline character. The character name inside the curly braces can be any case.It's easier to remember the  of a character than its unicode index. It's also more readable, ergo debugging-friendly. The character substitution happens at compile time: the  file will contain a constant for :BTW, all I did was search \"unicode degree\" on Google. This brings up two results:\n\"Degree sign U+00B0\" and \"Degree Celsius U+2103\", which are actually different:Above answers assume that UTF8 encoding can safely be used - this one is specifically targetted for Windows.The Windows console normaly uses CP850 encoding and  utf-8, so if you try to use a source file utf8-encoded, you get those 2 (incorrect) characters  instead of a degree .Demonstration (using python 2.7 in a windows console):effectively outputs .Fix: just force the correct encoding (or better use unicode):or if you use a source file that explicitely defines an encoding:just use  python will convert it automatically
Python

I'm using something like this in my templateWhen I view the POST data in Firebug or the Django debug, I see it only sends one value.  Am I doing something wrong or misunderstanding a concept?Just FYI, I had to use:because omitting the [] caused a blank list to be returned instead of the correct values. I'm using jQuery to fetch the values of a multiple select element, and jQuery appears to be adding the [] Watch out! getlist method from QueryDict returns an empty list if the key doesn't exist. It does not throw an exception. 
Python

I've just read in  that \"tuples are faster than lists\".Tuple is immutable, and list is mutable, but I don't quite understand why tuple is faster.Anyone did a performance test on this?The reported \"speed of construction\" ratio only holds for  tuples (ones whose items are expressed by literals).  Observe carefully (and repeat on your machine -- you just need to type the commands at a shell/command window!)...:I didn't do the measurements on 3.0 because of course I don't have it around -- it's totally obsolete and there is absolutely no reason to keep it around, since 3.1 is superior to it in every way (Python 2.7, if you can upgrade to it, measures as being almost 20% faster than 2.6 in each task -- and 2.6, as you see, is faster than 3.1 -- so, if you care seriously about performance, Python 2.7 is really the only release you should be going for!).Anyway, the key point here is that, in each Python release, building a list out of constant literals is about the same speed, or slightly slower, than building it out of values referenced by variables; but tuples behave very differently -- building a tuple out of constant literals is typically three times as fast as building it out of values referenced by variables!  You may wonder how this can be, right?-)Answer: a tuple made out of constant literals can easily be identified by the Python compiler as being one, immutable constant literal itself: so it's essentially built just once, when the compiler turns the source into bytecodes, and stashed away in the \"constants table\" of the relevant function or module.  When those bytecodes execute, they just need to recover the pre-built constant tuple -- hey presto!-)This easy optimization cannot be applied to lists, because a list is a mutable object, so it's crucial that, if the same expression such as  executes twice (in a loop -- the  module makes the loop on your behalf;-), a fresh new list object is constructed anew each time -- and that construction (like the construction of a tuple when the compiler cannot trivially identify it as a compile-time constant and immutable object) does take a little while.That being said, tuple construction (when both constructions actually have to\noccur) still is about twice as fast as list construction -- and  discrepancy can be explained by the tuple's sheer simplicity, which other answers have mentioned repeatedly.  But, that simplicity does not account for a speedup of six times or more, as you observe if you only compare the construction of lists and tuples with simple constant literals as their items!_)With the power of the  module, you can often resolve performance related questions yourself:This shows that tuple is negligibly faster than list for iteration. I get similar results for indexing, but for construction, tuple destroys list:So if speed of iteration or indexing are the only factors, there's effectively no difference, but for construction, tuples win.Alex gave a great answer, but I'm going to try to expand on a few things I think worth mentioning. Any performance differences are generally small and implementation specific: so don't bet the farm on them.In CPython, tuples are stored in a single block of memory, so creating a new tuple involves at worst a single call to allocate memory. Lists are allocated in two blocks: the fixed one with all the Python object information and a variable sized block for the data. That's part of the reason why creating a tuple is faster, but it probably also explains the slight difference in indexing speed as there is one fewer pointer to follow.There are also optimisations in CPython to reduce memory allocations: de-allocated list objects are saved on a free list so they can be reused, but allocating a non-empty list still requires a memory allocation for the data. Tuples are saved on 20 free lists for different sized tuples so allocating a small tuple will often not require any memory allocation calls at all.Optimisations like this are helpful in practice, but they may also make it risky to depend too much on the results of 'timeit' and of course are completely different if you move to something like IronPython where memory allocation works quite differently.Essentially because tuple's immutability means that the interpreter can use a leaner, faster data structure for it, compared to list.One area where a list is notably faster is construction from a generator, and in particular, list comprehensions are much faster than the closest tuple equivalent,  with a generator argument:Note in particular that  seems to be a tiny bit faster than , but  is much faster than both of them.
Python

I feel like I should know this, but I haven't been able to figure it out...I want to get the name of a method--which happens to be an integration test--from inside it so it can print out some diagnostic text.  I can, of course, just hard-code the method's name in the string, but I'd like to make the test a little more DRY if possible.The answers involving introspection via  and the like are reasonable.  But there may be another option, depending on your situation:If your integration test is written with the  module, then you could use  within your TestCase.This seems to be the simplest way using module :You could generalise this with:Credit to  which was found via google.This decorator makes the name of the method available inside the function by passing it as a keyword argument.You would use it this way:But maybe you'd want to write what you want directly inside the decorator itself. Then the code is an example of a way to get the function name in a decorator. If you give more details about what you want to do in the function, that requires the name, maybe I can suggest something else.Output:Use \"back = 1\" to find info regarding two levels back down the stack, etc.I think the  module might have what you're looking for. In particular, the  function looks like it will do the job.
Python

So that I am able to work with it within my python scripts?Installing Boto depends on the Operating system. \nFor e.g in Ubuntu you can use the aptitude command:Or you can download the boto code from their site and move into the unzipped directory to run Edit: pip is now by far the preferred way to install packagesswitch to the  directory and type .Best way to install boto in my opinion is to use:This ensures you'll have the boto glacier code. If you already have boto installed in one python version and then install a higher python version, boto is not found by the new version of python. For example, I had python2.7 and then installed python3.5 (keeping both). My script under python3.5 could not find boto. Doing \"\" told me that boto was already installed in .So I didThis allowed my script under python3.5 to find boto.While trying out the command, I encounter the error To resolve this, issue another command to handle the setuptools using curlAfter doing that, the following command will work perfectly.
Python

I basically want a python equivalent of this in Cbut in python I declare an array likebut the problem is I want to assign random slots with values likebut I can't do that with python, since the array is emptyIf by \"array\" you actually mean a Python list, you can useorYou can't do exactly what you want in Python (if I read you correctly).  You need to put values in for each element of the list (or as you called it, array).But, try this:For lists of other types, use something besides 0.   is often a good choice as well.You can use numpy:import numpy as npExample from :also you can extend that with extend method of list.Just declare the list and append each element. For ex:
Python

I just need a python script that copies text to the clipboard.After the script gets executed i need the output of the text to be pasted to another source.\nIs it possible to write a python script that does this job?See .  Example (taken from Pyperclip site):Also, see .  But it appears to have more dependencies.On mac i use this function.It will copy \"hello world\" to the clipboard. Use Tkinter: (Original author: ) seems to be up to the task.GTK3:One more answer to improve on:\n\nand  (Tkinter).Tkinter is nice, because it's either included with Python (Windows) or easy to install (Linux), and thus requires little dependencies for the end user.Here I have a \"full-blown\" example, which copies the arguments or the standard input, to clipboard, and - when not on Windows - waits for the user to close the application:This showcases:I try this clipboard 0.0.4 and it works well.This is an altered version of @Martin Thoma's answer for . I found that the original solution resulted in the process never ending and my terminal hung when I called the script. Changing the script to the following resolved the issue for me.You will probably want to change what clipboardText gets assigned to, in this script it is assigned to the parameter that the script is called with.To use native python directories, use:Then use:to call the function.(also please accept an answer)PyQt5:This is the only way that worked for me using  plus it's the easiest to implement w/ using the standard  suiteShout out to  for the answer (I copied it completely) from I wrote a little wrapper for it that I put in my  profile <3 
Python

How can I use the logging class in python to write to a file? Every time I try to use it, it just prints out the message.An example of using  rather than  Taken from the \"\":And you're good to go.P.S. Make sure to read the  as well.I prefer to use a configuration file. It allows me to switch logging levels, locations, etc without changing code when I go from development to release. I simply package a different config file with the same name, and with the same defined loggers.Here is my code for the log config file
Python

What's the best way to rename photos with a unique filename on the server as they are uploaded, using django? I want to make sure each name is used only once. Are there any pinax apps that can do this, perhaps with GUID?Use uuid. To tie that into your model see  for  FileField upload_to.For example in your models.py define the following function:Then, when defining your FileField/ImageField, specify  as the  value.Prior to Django 1.6.6, 1.5.9, and 1.4.14, the  function would automatically give files a unique name by adding an underscore. So, for example, if you save one file \"test.jpg\" and then another file, \"test.jpg\" to your server, the first will be called test.jpg, and the second will be called test_1.jpg.Alas, that turns out to be a vector for DDOSing a machine, by sending it thousands of zero-byte files to store, each one checking thousands of previous files to see what its name should be.As you'll , the new system appends seven random digits after the underscore to fix this problem.A better way could be using a common class in your helpers.py. This way you could reuse the random file generator across your apps.In your helpers.py:And then in your model just import the helper class:And then use it:Ref: How about concatenating the filename with the date / time the photo was uploaded and then using  to create a message digest? That should give you unique filenames.Alternatively you could re-use  which creates unique filenames and then use the full path to that file as the input to your hash call. That gives you unique constant length strings which you can map to your files.As of the writing of this answer it seems like you no longer need to do anything special to make this happen. If you set up a FileField with a static upload_to property, the Django storage system will automatically manage naming so that if a duplicate filename is uploaded, Django will randomly generate a new unique filename for the duplicate.Works on Django 1.10.
Python

I'm having a hard time trying to use .strip with the following line of code. Thanks for the help.You can use the strip() to remove trailing and leading spaces.Note: the internal spaces are preservedExpand your one liner into multiple lines. Then it becomes easy:
Python

The  function in python, puts the leading characters  in front of the number. Is there anyway to tell it NOT to put them? So  will be .The code isUse this code:it allows you to specify a number of digits too:For Python 2.6 useorYou can simply writeto get the first two characters removed.Old style string formatting:New styleUsing capital letters as format characters yields uppercase hexadecimal are here.
Python

I've searched up and down, but can't find a de-compiler that will work for Python 2.7 .pyc. Does anybody know of one that will work for Python 2.7? ThanksThis sounds like it works: Issue 8 says it supports 2.7: UPDATE (2013-09-03) - As noted in the comments and in other answers, you should look at  or  instead of unpyc.In case anyone is still struggling with this, as I was all morning today, I have found a solution that works for me:Installation instructions:Once the program is installed (note: it will be installed to your system-wide-accessible Python packages, so it should be in your ), you can recover your Python files like so:The decompiler adds some noise mostly in the form of comments, however I've found it to be surprisingly clean and faithful to my original code. You will have to remove a little line of text beginning with +++ near the end of the recovered file to be able to run your code.Decompyle++ (pycdc) appears to work for a range of python versions:  For example:Here is a great tool to decompile pyc files.It was coded by me and supports python 1.0 - 3.3Its based on uncompyle2 and decompyle++Ned Batchelder has posted a  that will unmarshal a .pyc file and disassemble any code objects within, so you'll be able to see the Python bytecode. \nIt looks like with newer versions of Python, you'll need to comment out the lines that set  and print it (but don't comment the line that sets ).Turning that back into Python source would be somewhat more difficult, although theoretically possible. I assume all these programs that work for older versions of Python do that.
Python

All I need is the contents inside the parenthesis.If your problem is really just this simple, you don't need regex:Use :If you want to find all occurences: Building on tkerwin's answer, if you happen to have nested parentheses like in his answer will not work if you need to take everything between the  and the  to get , because find searches from the left of the string, and would stop at the first closing parenthesis.To fix that, you need to use  for the second part of the operation, so it would become 
Python

At work we used to program our Python in a pretty standard OO way.  Lately, a couple guys got on the functional bandwagon. And their code now contains lots more lambdas, maps and reduces.  I understand that functional languages are good for concurrency but does programming Python functionally really help with concurrency?   I am just trying to understand what I get if I start using more of Python's functional features.: I've been taken to task in the comments (in part, it seems, by fanatics of FP in Python, but not exclusively) for not providing more explanations/examples, so, expanding the answer to supply some., even more so  (and ),  most especially , are hardly ever the right tool for the job in Python, which is a strongly multi-paradigm language. main advantage (?) compared to the normal  statement is that it makes an  function, while  gives the function a name -- and for that very dubious advantage you pay an enormous price (the function's body is limited to one expression, the resulting function object is not pickleable, the very lack of a name sometimes makes it much harder to understand a stack trace or otherwise debug a problem -- need I go on?!-).Consider what's probably the single most idiotic idiom you sometimes see used in \"Python\" (Python with \"scare quotes\", because it's obviously  idiomatic Python -- it's a bad transliteration from idiomatic Scheme or the like, just like the more frequent overuse of OOP in Python is a bad transliteration from Java or the like):by assigning the lambda to a name, this approach immediately throws away the above-mentioned \"advantage\" -- and doesn't lose any of the DISadvantages!  For example,  doesn't  its name --  is the useless string  -- good luck understanding a stack trace with a few of these;-).  The proper Python way to achieve the desired semantics in this simple case is, of course:  is the string , as it clearly should be, and the object is pickleable -- the semantics are otherwise identical (in this simple case where the desired functionality fits comfortably in a simple expression --  also makes it trivially easy to refactor if you need to temporarily or permanently insert statements such as  or , of course). is (part of) an expression while  is (part of) a statement -- that's the one bit of syntax sugar that makes people use  sometimes. Many FP enthusiasts (just as many OOP and procedural fans) dislike Python's reasonably strong distinction between expressions and statements (part of a general stance towards ). Me, I think that when you use a language you're best off using it \"with the grain\" -- the way it was  to be used -- rather than fighting against it; so I program Python in a Pythonic way, Scheme in a Schematic (;-) way, Fortran in a Fortesque (?) way, and so on:-).Moving on to  -- one comment claims that  is the best way to compute the product of a list. Oh, really?  Let's see...:so the simple, elementary, trivial loop is about twice as fast (as well as more concise) than the \"best way\" to perform the task?-)  I guess the advantages of speed and conciseness must therefore make the trivial loop the \"bestest\" way, right?-)By further sacrificing compactness and readability...:...we can get  back to the easily obtained performance of the simplest and most obvious, compact, and readable approach (the simple, elementary, trivial loop). This points out another problem with , actually: performance! For sufficiently simple operations, such as multiplication, the overhead of a function call is quite significant compared to the actual operation being performed --  (and  and ) often forces you to insert such a function call where simple loops, list comprehensions, and generator expressions, allow the readability, compactness, and speed of in-line operations.Perhaps even worse than the above-berated \"assign a lambda to a name\" anti-idiom is actually the following anti-idiom, e.g. to sort a list of strings by their lengths:instead of the obvious, readable, compact, speedierHere, the use of  is doing nothing but inserting a level of indirection -- with no good effect whatsoever, and plenty of bad ones.The motivation for using  is often to allow the use of  and  instead of a vastly preferable loop or list comprehension that would let you do plain, normal computations in line; you still pay that \"level of indirection\", of course. It's not Pythonic to have to wonder \"should I use a listcomp or a map here\": just always use listcomps, when both appear applicable and you don't know which one to choose, on the basis of \"there should be one, and preferably only one, obvious way to do something\". You'll often write listcomps that could not be sensibly translated to a map (nested loops,  clauses, etc), while there's no call to  that can't be sensibly rewritten as a listcomp.Perfectly proper functional approaches in Python often include list comprehensions, generator expressions, , higher-order functions, first-order functions in various guises, closures, generators (and occasionally other kinds of iterators)., as a commenter pointed out, does include  and : the difference is that, like all of itertools, these are stream-based (like  and  builtins in Python 3, but differently from those builtins in Python 2).   offers a set of building blocks that compose well with each other, and splendid performance: especially if you find yourself potentially dealing with very long (or even unbounded!-) sequences, you owe it to yourself to become familiar with itertools -- their whole  in the docs makes for good reading, and the  in particular are quite instructive.Writing your own higher-order functions is often useful, especially when they're suitable for use as  (both function decorators, as explained in that part of the docs, and class decorators, introduced in Python 2.6).  Do remember to use  on your function decorators (to keep the metadata of the function getting wrapped)!So, summarizing...: anything you can code with , , and , you can code (more often than not advantageously) with  (named functions) and listcomps -- and usually moving up one notch to generators, generator expressions, or , is even better.   meets the legal definition of \"attractive nuisance\"...: it's  the right tool for the job (that's why it's not a built-in any more in Python 3, at long last!-).FP is important not only for concurrency; in fact, there's virtually no concurrency in the canonical Python implementation (maybe 3.x changes that?).  in any case, FP lends itself well to concurrency because it leads to programs with no or fewer (explicit) states.  states are troublesome for a few reasons.  one is that they make distributing the computation hard(er) (that's the concurrency argument), another, far more important in most cases, is the tendency to inflict bugs.  the biggest source of bugs in contemporary software is  (there's a close relationship between variables and states).  FP may reduce the number of variables in a program: bugs squashed!see how many bugs can you introduce by mixing the variables up in these versions:versus (warning, 's parameter list differs from that of python's ; rationale given later)as you can see, it's a matter of fact that FP gives you fewer opportunities to shoot yourself in the foot with a variables-related bug.also, readability: it may take a bit of training, but  is way easier to read than : you see  (\"ok, it's reducing a sequence to a single value\"),  (\"by multiplication\").  wherease  has the generic form of a  cycle, peppered with variables and assignments.  these  cycles all look the same, so to get an idea of what's going on in , you need to read almost all of it.then there's succintness and flexibility.  you give me  and I tell you I like it, but want something to sum sequences as well.  no problem, you say, and off you go, copy-pasting:what can you do to reduce the duplication?  well,  operators were values, you could do something likeoh wait!  provides operators that  values!  but.. Alex Martelli condemned  already...  looks like if you want to stay within the boundaries he suggests, you're doomed to copy-pasting plumbing code. is the FP version any better?  surely you'd need to copy-paste as well?well, that's just an artifact of the half-assed approach!  abandoning the imperative , you can contract both versions toor even( is the reason for )what about runtime speed?  yes, using FP in a language like Python will incur some overhead.  here i'll just parrot what a few professors have to say about this:I'm not very good at explaining things.  Don't let me muddy the water too much, read the first half of the  John Backus gave on the occasion of receiving the Turing Award in 1977.  Quote:I program in Python everyday, and I have to say that too much 'bandwagoning' toward OO or functional could lead toward missing elegant solutions. I believe that both paradigms have their advantages to certain problems - and I think that's when you know what approach to use. Use a functional approach when it leaves you with a clean, readable, and efficient solution. Same goes for OO.And that's one of the reasons I love Python - the fact that it is multi-paradigm and lets the developer choose how to solve his/her problem.This answer is completely re-worked.  It incorporates a lot of observations from the other answers.As you can see, there is a lot of strong feelings surrounding the use of functional programming constructs in Python.  There are three major groups of ideas here.First, almost everybody but the people who are most wedded to the purest expression of the functional paradigm agree that list and generator comprehensions are better and clearer than using  or .    Your colleagues should be avoiding the use of  and  if you are targeting a version of Python new enough to support list comprehensions.  And you should be avoiding  and  if your version of Python is new enough for generator comprehensions.Secondly, there is a lot of ambivalence in the community as a whole about .  A lot of people are really annoyed by a syntax in addition to  for declaring functions, especially one that involves a keyword like  that has a rather strange name.  And people are also annoyed that these small anonymous functions are missing any of the nice meta-data that describes any other kind of function.  It makes debugging harder.  Lastly the small functions declared by  are often not terribly efficient as they require the overhead of a Python function call each time they are invoked, which is frequently in an inner loop.Lastly, most (meaning > 50%, but most likely not 90%) people think that  is a little strange and obscure.  I myself admit to having  whenever I want to use it, which isn't all that often.  Though when I see it used, the nature of the arguments (i.e. function, list or iterator, scalar) speak for themselves.As for myself, I fall in the camp of people who think the functional style is often very useful.  But balancing that thought is the fact that Python is not at heart a functional language.  And overuse of functional constructs can make programs seem strangely contorted and difficult for people to understand.To understand when and where the functional style is very helpful and improves readability, consider this function in C++:This loop seems very simple and easy to understand.  And in this case it is.  But its seeming simplicity is a trap for the unwary.  Consider this alternate means of writing the loop:Suddenly, the loop control variable no longer varies in an obvious way.  You are reduced to looking through the code and reasoning carefully about what happens with the loop control variable.  Now this example is a bit pathological, but there are real-world examples that are not.  And the problem is with the fact that the idea is repeated assignment to an existing variable.  You can't trust the variable's value is the same throughout the entire body of the loop.This is a long recognized problem, and in Python writing a loop like this is fairly unnatural.  You have to use a while loop, and it just looks wrong.  Instead, in Python you would write something like this:As you can see, the way you talk about the loop control variable in Python is not amenable to fooling with it inside the loop.  This eliminates a lot of the problems with 'clever' loops in other imperative languages.  Unfortunately, it's an idea that's semi-borrowed from functional languages.Even this lends itself to strange fiddling.  For example, this loop:Oops, we again have a loop that is difficult to understand.  It superficially resembles a really simple and obvious loop, and you have to read it carefully to realize that one of the variables used in the loop's computation is being messed with in a way that will effect future runs of the loop.Again, a more functional approach to the rescue:Now by looking at the code we have some strong indication (partly by the fact that the person is using this functional style) that the lists a and b are not modified during the execution of the loop.  One less thing to think about.The last thing to be worried about is c being modified in strange ways.  Perhaps it is a global variable and is being modified by some roundabout function call.  To rescue us from this mental worry, here is a purely function approach:Very concise, and the structure tells us that x is purely an accumulator.  It is a local variable everywhere it appear.  The final result is unambiguously assigned to c.  Now there is much less to worry about.  The structure of the code removes several classes of possible error.That is why people might choose a functional style.  It is concise and clear, at least if you understand what  and  do.  There are large classes of problems that could afflict a program written in a more imperative style that you know won't afflict your functional style program.In the case of factorial, there is a very simple and clear way to write this function in Python in a functional style:The question, which seems to be mostly ignored here: No.  The value FP brings to concurrency is in eliminating state in computation, which is ultimately responsible for the hard-to-grasp nastiness of unintended errors in concurrent computation.  But it depends on the concurrent programming idioms not themselves being stateful, something that doesn't apply to Twisted.  If there are concurrency idioms for Python that leverage stateless programming, I don't know of them.Here's a short summary of positive answers when/why to program functionally.than to use an imperative construct (loop).You should NOT overuse those features - there are many traps, see Alex Martelli's post. I'd subjectively say the most serious danger is that excessive use of those features will destroy readability of your code, which is a core attribute of Python.The standard functions filter(), map() and reduce() are used for various operations on a list and all of the three functions expect two arguments: A function and a listWe could define a separate function and use it as an argument to filter() etc., and its probably a good idea if that function is used several times, or if the function is too complex to be written in a single line. However, if it's needed only once and it's quite simple, it's more convenient to use a lambda construct to generate a (temporary) anonymous function and pass it to filter().This helps in Using these function, would also turn out to be , because the looping on the elements of the list is done in C, which is a little bit faster than looping in python.And object oriented way is forcibly needed when states are to be maintained, apart from abstraction, grouping, etc., If the requirement is pretty simple, I would stick with functional than to Object Oriented programming.Map and Filter have their place in OO programming.  Right next to list comprehensions and generator functions.Reduce less so.  The algorithm for reduce can rapidly suck down more time than it deserves; with a tiny bit of thinking, a manually-written reduce-loop will be more efficient than a reduce which applies a poorly-thought-out looping function to a sequence. Lambda never.  Lambda is useless.  One can make the argument that it actually  something, so it's not completely .   First: Lambda is  not syntactic \"sugar\"; it makes things bigger and uglier.  Second: the one time in 10,000 lines of code that think you need an \"anonymous\" function turns into two times in 20,000 lines of code, which removes the value of anonymity, making it into a maintenance liability.However.The functional style of no-object-state-change programming is still OO in nature.  You just do more object creation and fewer object updates.  Once you start using generator functions, much OO programming drifts in a functional direction.Each state change appears to translate into a generator function that builds a new object in the new state from old object(s).  It's an interesting world view because reasoning about the algorithm is much, much simpler.But that's no call to use reduce or lambda.
Python

How do I find the previous Monday's date, based off of the current date using Python? I thought maybe I could use:  to do it, but I am getting stuck.I basically want to find today's date and Mondays date to construct a date range query in django using: .  Take todays date. Subtract the number of days which already passed this week (this gets you 'last' monday). Add one week.: The above is for 'next monday', but since you were looking for 'last monday' you could useChristopheD's post is close to what you want. I don't have enough rep to make a comment :(Instead of (which actually gives you the next upcoming monday):I would say:If you want the previous week, add the 'weeks=1' parameter.This makes the code more readable since you are subtracting a timedelta. This clears up any confusion caused by adding a timedelta that has negative and positive offsets.I think the easiest way is using  like this:Note: The OP says in the comments, \"\". I take this to mean we are looking for the last Monday that occurred strictly before today. The calculation is a little difficult to get right using only the  module (especially given the above interpretation of \"past Monday\" and if you wish to avoid clunky ). For example, if  is a Monday such as ,returns , which is the same day as  (not the past Monday).The advantage of using the  is that you don't have to do tricky mental calculations nor force the reader to do the same to get the right date.  does it all for you:Note that  is needed to guarantee that  is a different day than .You can use . I tried  and . Comparing these three, I think  is the best one.To get your result, use like this:Github Link : Try it, It can do more!Using timedeltas and datetime module:gives you today's day of the week, counting 0 (monday) to 6 (sunday)(7-d)%7 gives you days until Monday, or leaves you where you are if today is Monday
Python

This works almost fine but the number starts with 0 sometimes:I've found a lot of examples but none of them guarantee that the sequence won't start with .We generate the first digit in the 1 - 9 range, then take the next 3 from the remaining digits:The generated numbers are equiprobable, and we get a valid number in one step.Just loop until you have something you like:This is very similar to the other answers but instead of  or  you could draw a random integer in the range 1000-9999 until you get one that contains only unique digits:As @Claudio pointed out in the comments the range actually only needs to be 1023 - 9876 because the values outside that range contain duplicate digits.Generally  will be much faster than  or  so even if it's more likely one needs to draw multiple times (as pointed out by @karakfa) it's up to 3 times faster than any ,  approach that also needs to  the single digits.I do not know Python well, but something likeA more useful iteration, actually creating a number:After stealing pieces from other solutions, plus applying the tip from @DavidHammen:[Fixed] Shift all four digits on one position is not right. Swap leading zero with fixed position is not right too. But random swap of the leading zero with any of nine positions is correct and gives equal probability:rejection sampling method.  Create a 4 digit random combination from 10 digits and resample if it doesn't match the criteria.noticed that this is essentially the same as @Austin Haskings's You could use full range for 3 numbers, then choose the leading number among the remaining numbers:Another way if the choice needs to be repeated (and if you remain reasonable on the number of digits), is to pre-compute the list of the possible outputs using , filtering out the ones with a leading zero, and building a list of integers from it:That's some computation time, but after than you can call:as many times you want. It's very fast and provides an evenly distributed random.I don't know Python so I will post a pseudo-code-ish solution for this specific problem:It is possible to generalize this idea a little. For example you can create a function that accepts a list (of digits) and a number (desired length of result); the function will return the number and mutate the list by removing used-up digits. Below is a JavaScript implementation of this solution:Here's how I'd do itMore generally, given a generator, you can use the built-ins  and  to take the first element that satisfies some test function.A Pythonic way to write would be to use 2 nested generators and :It's basically a one-liner variant of If you need many random numbers, you could invest some time and memory for preprocessing all the acceptable numbers: and  are used as boundaries because no int lower than 1023 or greater than 9876 can have 4 unique, distince numbers.Then, you'd just need  for a very fast generation:Disclaimer: this is a terrible anti-Python approach, strictly for the benchmarking part (see @DavidHammen's comments around, and )\nThe idea is to generate the sequence numbers of the digits in one step, and then fix any collisions:Now we have d1=0..8, d2=0..8, d3=0..7, d4=0..6, it can be tested via running the snippet with rnd=4535 (4535=9*9*8*7-1, by the way)First, d1 has to be patched upThen d2 has to \"skip\" d1 if necessaryThen the same has to be done with the remaining digits, getting ugly fast:And the final part is the catastrophic one:For longer numbers, it might work faster with bitfields, but I do not see a trivial way.\n(Checking the >= relations once is not enough, because the collision can easily occur after doing an incrementation.\ne.g. d1=1, d2=2, d3=1: d3 collides with d1, but it does not collide with d2 initially. However after \"puching the hole\" at 1, d3 becomes 2 and now it collides with d2. There is no trivial way to spot this collision in advance)As the code stinks as hell, I put a verification step at the endIt is already faster than the other really fast code (the commented verification displayed the original digits preserved after the divmod-s, for debugging purposes. This is not the kind of code which works immediately...). Commenting both verifications makes it even faster.EDIT: about checking this and thatThis is an approach maintaining an 1:1 relation between the minimal set of valid inputs (0...4535) and valid outputs (the 9*9*8*7 possible 4-digit numbers with distinct digits, not-starting-with-0). So a simple loop can and should generate all the numbers, they can be checked one-by-one and they can be collected into a set for example in order to see if they are all distinct resultsPractically:1) It will not print anything in the loop (all results are 4-digit numbers with distinct digits)2) It will print 4536 at the end (all results are distinct)One can add a verification for the first digit (d1), here and now I just assume that\"(something mod 9)+1\" will not be 0.This will allow zeros after the first digit - 
Python

In the function , if a referred variable is not found then it gives an error. How can I check to see if a variable or method exists as part of an object?How about  function before ?It's easier to ask forgiveness than to ask permission.Don't check to see if a method exists.  Don't waste a single line of code on \"checking\"Check if class has such method?orYou can use  instead of You can try using 'inspect' module:How about looking it up in ?Maybe like this, assuming all method is callableIf your method is outside of a class and you don't want to run it and raise an exception if it doesn't exist:I think you should look at the  package. It allows you to 'wrap' some of the things. When you use the  method it also list built in methods, inherited methods and all other attributes making collisions possible, e.g.:The array you get from  contains both  and  and a lot of built in stuff. With  you can do this:This examples still list both methods in the two classes but if you want to limit the inspection to only function in a specific class it requires a bit more work, but it is absolutely possible.
Python

I have a Python script that works perfectly fine on my development PC. Both are Windows\u00a07 with the same Python version (2.7.9). However on the target machine I get a seems to come from pywin32 module.The code uses a third-party library invoked by pywin32:and then fails later on:Now I'm lost why this is working on my PC and not on the target machine. Both have a \"corporate install\" of Windows\u00a07, for example, the same Regional and date-time settings.What is the issue? How might I resolve it?EDIT:See comments. The cause is probably which  runtime is used. I'm still investigating. I now suspect that it matters which runtimes are present at install time of pywin32. Why? Because DependenyWalker on my development PC says that pywin depends on  in my Lotus Notes installation. This tells me it sure isn't \"hard\" linked.I was all wrong...The issue now also happens on my PC.Some further info. The script reads data files and inserts the read\nmeta-data into a database. Only older files seemed to be affected by the\nbug, not new ones (I now think this is assumption is wrong). So the idea was to to the initial load on my Dev PC and then hope the issue will never occur again with new files.In case of the PC were the script will run, the files it reads are on a\nWindows Shared drive (mapped network drive). I don't have access to that\ndrive so I just copied the files into my PC. Now for doing the initial\nload I requested access to said network drive and BOOM. It also does not\nwork from my Dev. machine when reading from the shared drive.The issue does not always happen with the same file. I now think it has nothing to do with a specific file. I also tried it on a 64-bit PC with 64-bit python. There it took longer till the error occurred. In fact a file was successfully read which failed on my PC. I now think it is some kind of memory issue? I believe that it then always fails on the date line because all other lines just return null or an empty string which causes no problem and is entirely possible such a value can be null. But for the date it is a problem and it should not be null and then the error is thrown.EDIT of Update:On my PC it always fails on the same file. Loading that file alone works perfectly fine. I now think it's some kind of counter/number overflow that after reading n files, the issue occurs. It has to do with the amount of files I load per run of the script and not the file itself. Files that fail work when loading them individually.Turns out the issue was in fact trivial and somewhat due to my lack of experience with python and misleading error message. The COM object  is used to open proprietary files in a loop. To solve the issue one must \"clean-up\" the object before next iteration. This is done either by  \nor \n. That completely solves the issue. It has absolutely nothing to do with dates or date formating.  So Peter Brittain was probably right that this file limit was reached.
Python

I had installed Pymacs, rope, ropemode, ropemacs, and when I executed by accident, I couldn't save modified buffers. It first asked me - . If I answered \"yes\", it threw - . If I answered \"no\", it threw:I managed to work around by executing , loading  module, and answering yes to Pymacs helper restart question. The buffer was saved, but then I started to get another error everytime I saved the file:This is my init-file: describes death of Pymacs helper. It tells that I shouldn't close  buffer, because this kills the helper, and should also restart Emacs if helper is killed. This is unacceptable as I have a habit of closing all buffers from time to time and also rarely restart Emacs. I have several related questions now:The easiest solution I can think of is to use  hook to prevent  to be killed.  Like this:It will ask you if you really want to kill  buffer or not.  You can even make it impossible to kill from keybinds by this:I use  to forcefully reload all modules. I have a function similar to  in .Probably you can add  to  (locally in  buffer) for more graceful termination.  But I am not sure.  For the rest of your question, I guess it's better to ask/request in the Pymacs .If you accidentally kill the *Pymacs* buffer or execute  you can recover the process by executing the following command and answering \"yes\" at the prompt.You can modify your init-file function to allow for the restart to be called interactively with . Restarting Pymacs in this manner will avoid the  error.
Python

I'm trying to work out how best to locate the centroid of an arbitrary shape draped over a unit sphere, with the input being ordered (clockwise or anti-cw) vertices for the shape boundary. The density of vertices is irregular along the boundary, so the arc-lengths between them are not generally equal. Because the shapes may be very large (half a hemisphere) it is generally not possible to simply project the vertices to a plane and use planar methods, as detailed on Wikipedia (sorry I'm not allowed more than 2 hyperlinks as a newcomer). A slightly better approach involves the use of planar geometry manipulated in spherical coordinates, but again, with large polygons this method fails, as nicely illustrated . On that same page, 'Cffk' highlighted  which describes a method for calculating the centroid of spherical triangles. I've tried to implement this method, but without success, and I'm hoping someone can spot the problem?I have kept the variable definitions similar to those in the paper to make it easier to compare. The input (data) is a list of longitude/latitude coordinates, converted to [x,y,z] coordinates by the code. For each of the triangles I have arbitrarily fixed one point to be the +z-pole, the other two vertices being composed of a pair of neighboring points along the polygon boundary. The code steps along the boundary (starting at an arbitrary point), using each boundary segment of the polygon as a triangle side in turn. A sub-centroid is determined for each of these individual spherical triangles and they are weighted according to triangle area and added to calculate the total polygon centroid. I don't get any errors when running the code, but the total centroids returned are clearly wrong (I have run some very basic shapes where the centroid location is unambiguous). I haven't found any sensible pattern in the location of the centroids returned...so at the moment I'm not sure what is going wrong, either in the math or code (although, the suspicion is the math).The code below should work copy-paste as is if you would like to try it. If you have matplotlib and numpy installed, it will plot the results (it will ignore plotting if you don't). You just have to put the longitude/latitude data below the code into a text file called example.txt.Thanks in advance for any suggestions or insight.EDIT: Here is a figure that shows a projection of the unit sphere with a polygon and the resulting centroid I calculate from the code. Clearly, the centroid is wrong as the polygon is rather small and convex but yet the centroid falls outside its perimeter.\nEDIT: Here is a highly-similar set of coordinates to those above, but in the original [lon,lat] format I normally use (which is now converted to [x,y,z] by the updated code).EDIT: A couple more examples...with 4 vertices defining a perfect square centered at [1,0,0] I get the expected result:\n\nHowever, from a non-symmetric triangle I get a centroid that is nowhere close...the centroid actually falls on the far side of the sphere (here projected onto the front side as the antipode):\n\nInterestingly, the centroid estimation appears 'stable' in the sense that if I invert the list (go from clockwise to counterclockwise order or vice-versa) the centroid correspondingly inverts exactly.I think this will do it. You should be able to reproduce this result by just copy-pasting the code below.Legend:Here is the longitude and latitude data you can paste into I think a good approximation would be to compute the center of mass using weighted cartesian coordinates and projecting the result onto the sphere (supposing the origin of coordinates is ). Let be  the n points of the polygon. The approximative (cartesian) centroid can be computed by:whereas  is the sum of all weights and whereas  is a polygon point and  is a weight for that point, e.g. whereas  is the length of a vector . \nI.e. a point is weighted with half the length to the previous and half the length to the next polygon point.This centroid  can now projected onto the sphere by:whereas  is the radius of the sphere. To consider orientation of polygon  the result may beTo clarify: the quantity of interest is the projection of the true 3d centroid\n(i.e. 3d center-of-mass, i.e. 3d center-of-area) onto the unit sphere.Since all you care about is the direction from the origin to the 3d centroid,\nyou don't need to bother with areas at all;\nit's easier to just compute the moment (i.e. 3d centroid times area).\nThe moment of the region to the left of a closed path on the unit sphere\nis half the integral of the leftward unit vector as you walk around the path.\nThis follows from a non-obvious application of Stokes' theorem; see  Problem 13-12.In particular, for a spherical polygon, the moment is the half the sum of\n(a x b) / ||a x b|| * (angle between a and b) for each pair of consecutive vertices a,b.\n(That's for the region to the  of the path;\nnegate it for the region to the  of the path.)(And if you really did want the 3d centroid, just compute the area and divide the moment by it.  Comparing areas might also be useful in choosing which of the two regions to call \"the polygon\".)Here's some code; it's really simple:For the example polygon, this gives the answer (unit vector):This is roughly the same as, but more accurate than, the answer computed by @KobeJohn's code, which uses rough tolerances and planar approximations to the sub-centroids:The directions of the two answers are roughly opposite (so I guess KobeJohn's code\ndecided to take the region to the  of the path in this case).
Python

I'm about to embark on some large Python-based App Engine projects, and I think I should check with Stack Overflow's \"wisdom of crowds\" before committing to a unit-testing strategy.  I have an existing unit-testing framework (based on  with custom runners and extensions) that I want to use, so anything \"heavy-weight\"/\"intrusive\" such as , , or   doesn't seem appropriate.  The crucial unit tests in my worldview are extremely lightweight and fast ones, ones that run in an extremely short time, so I can keep running them over and over all the time without breaking my development rhythm (e.g., for a different project, I get 97% or so coverage for a 20K-lines project with several dozens of super-fast tests that take 5-7 seconds, elapsed time, for a typical run, overall -- that's what I consider a decent suite of small, fast unit-tests).  I'll have richer/heavier tests as well of course, all the way to integration tests with selenium or windmill, that's  what I'm asking about;-) -- my focus in this question (and in most of my development endeavors;-) is on the small, lightweight unit-tests that lightly and super-rapidly cover my code, not on the deeper ones.So I think what I need is essentially a set of small, very lightweight simulations of the various key App Engine subsystems -- data store, memcache, request/response objects and calls to webapp handlers, user handling, mail, &c, roughly in this order of priority.  I haven't found exactly what I'm looking for, so it seems to me that I should either rely on , as I've done often in the past, which basically means mocking each subsystem used in a given test and setting up all expectations &c (strong, but lots of work each time, and very sensitive to the tested-code's internals, i.e. very \"white-box\"y), or rolling my own simulation of each subsystem (and doing asserts on the simulated subsystems' states as part of the unit tests). The latters seems feasible, given GAE's Python-side strong \"stubs\" architecture... but I can't believe I need to roll my own, i.e., that nobody's already written such simple-minded simulators!-)  E.g., for the datastore, it looks like what I need is more or less the \"datastore on file\" stub that's already part of the SDK, plus a way to mark it readonly and easy-to-use accessors for assertions about the datastore's state; and so forth, subsystem by subsystem -- each seems to need \"just a bit more\" than what's already in the SDK, \"perched on top\" of the existing \"stubs\" architecture.So, before diving in and spending a day or two of precious development time \"rolling my own\" simulations of GAE subsystems for unit testing purposes, I thought I'd double check with the SO crowd and see what y'all think of this... or, if there's already some existing open source set of such simulators that I can simply reuse (or minimally tweak!-), and which I've just failed to spot in my searching!-): to clarify, if I do roll my own, I do plan to leverage the SDK-supplied stubs where feasible; but for example there's no stub for a datastore that gets initially read in from a file but then not saved at the end, so I need to subclass and tweak the existing one (which also doesn't offer particularly convenient ways to do asserts on its state -- same for the mail service stub, etc). That's what I mean by \"rolling my own\" -- not \"rewriting from scratch\"!-): \"why not GAEUnit\" -- GAEUnit is nice for its own use cases, but running dev_appserver and seeing results in my browser (or even via urllib.urlopen) is definitely not what I'm after -- I want to use a fully automated setup, suitable for running within an existing test-running framework which is based on extending unittest, and no HTTP in the way (said framework defines a \"fast\" test as one that among other thing does no sockets and minimal disk I/O -- we simulate or mock these -- so via gaeunit I could do no better than \"medium\" tests) + no convenient way to prepopulate datastore for each test (and no OO structure to help customize things).You don't need to write your own stubs - the SDK includes them, since they're what it uses to emulate the production APIs. Not all of them are suitable for use in unit-tests, but most are. Check out  for an example of the setup/teardown code you need to make use of the built in stubs. is a nose plugin that support unittests by automatically setting up the development environment and a test datastore for you. Very useful when developing on dev_appserver.I use GAEUnit for my Google App Engine App and I am quite happy with the speed of the tests. The thing that I like about GAEUnit,and I am sure Webtest does it, is that it creates its own version for stubs of everything for testing leaving your \"live\" versions alone for testing.So your datastore that you may be using for development will be left as is when you run your GAETests.I might also add that  has been very useful in my unit tests. It lets you create models in a declarative syntax, which it converts into stored entities that you can load in your tests. This way you have the same data set at the beginning of every test case!, which saves you from having to create data by hand at the start of every test. Here is an example, from the Fixture documentation:\nGiven this model:Your fixture would look like this:Note however, that I ran into the following issues:\n1. , but the included patch does remedy it. \n2. The datastore is not -by default- reset between test cases. So I use this to force a reset for each test case:The   provides easy configuration of stub libraries for local integration tests.Since  there is the build-in .It is Java only right now but I feel like:So does the author of this framework -  and he explicitly tells us about it in his I/O presentation Does anyone have any updates on this topic?
Python

This problem sounds simple at first glance, but turns out to be a lot more complicated than it seems. It's got me stumped for the moment.There are 52c5 = 2,598,960 ways to choose 5 cards from a 52 card deck. However, since suits are interchangeable in poker, many of these are equivalent - the hand 2H 2C 3H 3S 4D is equivalent to 2D 2S 3D 3C 4H - simply swap the suits around. According to , there are 134,459 distinct 5 card hands once you account for possible suit recolorings.The question is, how do we efficiently generate all these possible hands? I don't want to generate all hands, then eliminate duplicates, as I want to apply the problem to larger numbers of cards, and the number of hands to evaluate fast spirals out of control. My current attempts have centered around either generating depth-first, and keeping track of the currently generated cards to determine what suits and ranks are valid for the next card, or breadth-first, generating all possible next cards, then removing duplicates by converting each hand to a 'canonical' version by recoloring. Here's my attempt at a breadth-first solution, in Python:Unfortunately, this generates too many hands:Can anyone suggest a better way to generate just the distinct hands, or point out where I've gone wrong in my attempt?Your overall approach is sound.  I'm pretty sure the problem lies with your  function.  You can try printing out the hands with num_cards set to 3 or 4 and look for equivalencies that you've missed.I found one, but there may be more:For reference, below is my solution (developed prior to looking at your solution).  I used a depth-first search instead of a breadth-first search.  Also, instead of writing a function to transform a hand to canonical form, I wrote a function to check if a hand is canonical.  If it's not canonical, I skip it.  I defined rank = card % 13 and suit = card / 13.  None of those differences are important.It generates the correct number of permutations:Here's a Python solution that makes use of numpy and generates the canonical deals as well as their multiplicity. I use Python's itertools module to create all 24 possible permutations of 4 suits and then to iterate over all 2,598,960 possible 5-card deals. Each deal is permuted and converted to a canonical id in just 5 lines. It's quite fast as the loop only goes through 10 iterations to cover all deals and is only needed to manage the memory requirements. All the heavy lifting is done efficiently in numpy except for the use of . It's a shame this is not supportedly directly in numpy.Your problem sounded interesting, so i simple tried to implements it by just looping over all possible hands in a sorted way. I've not looked at your code in details, but it seems my implementation is quite different from yours. Guess what count of hands my script found: 160537Are you sure, the number on wikipedia is correct?I'm not a poker player, so the details of hand precedence are beyond me.  But it seems like the problem is that you are traversing the space of \"sets of 5 cards\" by generating sets from the deck, when you should be traversing the space of \"distinct poker hands\".The space of distinct hands will require a new grammar.  The important thing is to capture exactly the information that is relevant to hand precedence.  For example, there are only 4 hands that are royal flushes, so those hands can be described as the symbol \"RF\" plus a suit designator, like \"RFC\" for royal flush in clubs.  A 10-high heart flush could be \"FLH10\" (not sure if there are other precedence characteristics of flushes, but I think that's all you need to know).  A hand that is \"2C 2S AH 10C 5D\" would be a longer expression, something like \"PR2 A 10 5\" if I undestand your initial problem statement. Once you have defined the grammar of distinct hands, you can express it as regular expressions and that will tell you how to generate the entire space of distinct hands.  Sounds like fun!You could simply give all hands a canonical ordering of values (A to K), then assign abstract suit letters according to their order of first appearance in that order.Example:  JH 4C QD 9C 3D would convert to 3a 4b 9b Jc Qa.Generation should work best as dynamic programming:Initial input:Step 1: for each rank greater than or equal the highest rank used, set all suits in that rank to 0.  you can get away with only checking higher cards because lower combinations will be checked by the lower starting points.Step 2: Collapse to distinct rowsStep 3: Climb back up determining first suit that match each distinct row, and choose the suits which match the distinct rows (identified by a *)Now showing the repeat for rank 3Step 4: Once there are 5 cells set to 1, increment the total possible suit abstracted hands count by 1 and recurse up.The total number of suit abstracted hands possible is 134,459.  This is the code I wrote to test it out:Hopefully it is broken up enough to be easily understandable.Here is a simple and straightforward algorithm for reducing hands to a canonical one based on suit permutatoins.This is what the algorithm looks like in C++, with some implied Suit and CardSet classes.  Note that the return statement converts the hand by concatenating the bitstrings.Look at . The problem gets even worse when you're considering completing hands given some cards already drawn.The guy behind PokerStove did a great job in this direction, but the source is disclosed.Generating equivalence classes for 5 card hands is not an easy task.\nWhen I need this I usually use the  webpage. At  you can choose which variety of poker game you need, and in the \"Programming tab\" you have an section on \"Unique Suit Patterns\". So just copying that and loading into program might be easier than trying to generate your own.Take a look here:These regard a 5-card hand (and a 7-card hand) as an integer, the sum the individual cards, which is independent of the suit. Exactly what you need.This is part of a scheme for quickly ranking 7- and 5-card hands, written in Objective-C and Java.If you are just interested in hands that result in different hand rankings, there are actually only 7462 distinct hand classes that have to be considered (see ).By creating a table with an example for each class and their accompanying multiplicity you can check all relevant hands weighted with their probability quite fast. That is, assuming that no cards are known and therefore fixed beforehand already.Chances are you really want to generate the number of distinct hands, in the sense of non-equivalent. In that case, according to the wikipedia article there are 7462 possible hands. Here is a python snippet that will enumerate them all. The logic is simple: there is one hand for each 5-set of ranks; in addition, if all the ranks are distinct, another, different kind of hand can be formed by making all the suits match.
Python

Inspired by Why is there no list.clear() method in python? I've found several questions here that say the correct way to do it is one of the following, but no one has said why there isn't just a method for it.While it may go against the \"zen of python\" to have more than one way of doing something, it certainly seems more obvious to me to have a \"list.clear()\" method. It would also fall in line with dicts and sets, both of which have .clear().I came across a few posts to the python-dev and python-ideas concerning this and didn't come to a definitive answer (see  (2006) and  (2009)). Has Guido weighed in on it? Is it just a point of contention that hasn't been resolved yet over the last 4-5 years? list.clear() was added to python in 3.3 - In the threads you linked  of adding that method. When it comes to language design, it's really important to be conservative. See for example the  principle the C# team has. You don't get something as clean as Python by adding features willy-nilly. Just take a look at some of the more cruftier popular scripting languages to see where it takes you.I guess the  method just never did cross the implicit -100 points rule to become something worth adding to the core language. Although given that the methodname is already used for an equivalent purpose and the alternative can be hard to find, it probably isn't all that far from it.While there was no  when this question was asked, 3.3 now has one (as requested in ). Additionally,  methods have been added to  and  to ease switching between lists and other collections (set, dict etc).Full details of the change can be found .I can't answer to the why; but there absolutely should be one, so different types of objects can be cleared with the same interface.An obvious, simple example:This only requires that the object support iteration, and that it support clear().  If lists had a clear() method, this could accept a list or set equally.  Instead, since sets and lists have a different API for deleting their contents, that doesn't work; you end up with an unnecessarily ugly hack, like:As far as I'm concerned, using del obj[:] or obj[:] = [] are just unpleasant, unintuitive hacks to work around the fact that list is missing clear().This is taking \"reducing redundancy\" to a fault, where it damages the  of the language, which is even more important.As to which you should use, I'd recommend del obj[:].  I think it's easier to implement for non-list-like objects.When testing, it is often useful to setup the data forming the domain of the tests in global variables, so that tests can build on one another if necessary/simpler.\nIn such cases, having a method to clear the list would allow you to do it without the need to declare those variables as global within a function (i.e. the tests).\nI know, the tests should not depend on one another...The question should be why  was deemed necessary in the first place. The following works to clear any Python collection that I can think of.
Python

I am doing something like this... automatically commits the changes. But the docs say nothing about closing the connection. Actually I can use  in later statements (which I have tested). Hence it seems that the context manager is NOT closing the connection.Do I have to manually close the connection. What if I leave it open?My conclusions...In answer to the specific question of what happens if you do not close a SQLite database, the answer is quite simple and applies to using SQLite in any programming language.  When the connection is closed explicitly by code or implicitly by program exit then any outstanding transaction is rolled back.  (The rollback is actually done by the next program to open the database.)  If there is no outstanding transaction open then nothing happens.This means you do not need to worry too much about always closing the database before process exit, and that you should pay attention to transactions making sure to start them and commit at appropriate points.You have a valid underlying concern here, however it's also important to understand how sqlite operates too:in terms of , you only need to worry about transactions and not open handles. sqlite only holds a lock on a database inside a transaction(*) or statement execution.however in terms of , e.g. if you plan to remove sqlite file or use so many connections you might run out of file descriptors, you do care about open out-of-transaction connections too.there are two ways a connection is closed: either you call  explicitly after which you still have a handle but can't use it, or you let the connection go out of scope and get garbage-collected.if you , close it explicitly, according to Python's motto \".\"if you are only checking code for side-effects, letting a last variable holding reference to connection go out of scope may be acceptable, but keep in mind that exceptions capture the stack, and thus references in that stack. if you pass exceptions around, connection lifetime may be extended arbitrarily., sqlite uses \"deferred\" transactions by default, that is the transaction only starts when you execute a statement. In the example above, transaction runs from 3 to 4, rather than from 2 to 4.Your version leaves conn in scope after connection usage.EXAMPLE:    For managing a connection to a database I usually do this, doing so, I'm sure that the connection is explicitly closed.
Python

My current setup.py script works okay, but it installs tvnamer.py (the tool) as \"tvnamer.py\" into site-packages or somewhere similar..Can I make setup.py install tvnamer.py as tvnamer, and/or is there a better way of installing command-line applications?Try the  parameter in the setup() call. As described in the , this should do what I think you want.To reproduce here:
Python

i have:the output should be:This works for dictionaries of any length:And as generator-oneliner:In Python 2.7 and 3.x this can and should be written as dict comprehension (thanks, @katrielalex):In case of Python 3.3+, there is a :Also see:Note: the order of 'b' and 'c' doesn't match your output because dicts are unorderedif the dicts can have more than one key/valueFor flat dictionaries you can do this:This is asymmetrical because you need to choose what to do with duplicate keys; in this case,  will overwrite . Exchange them for the other way.EDIT: Ah, sorry, didn't see that.It is possible to do this in a single expression:No credit to me for this last!However, I'd argue that it might be more Pythonic (explicit > implicit, flat > nested ) to do this with a simple  loop. YMMV.Note I added a second key/value pair to the last dictionary to show it works with multiple entries.\nAlso keys from dicts later in the list will overwrite the same key from an earlier dict.You can use  function from  library:dic1 = {'Maria':12, 'Paco':22, 'Jose':23}\ndic2 = {'Patricia':25, 'Marcos':22 'Tomas':36}dic2 = dict(dic1.items() + dic2.items())and this will be the outcome:dic2\n{'Jose': 23, 'Marcos': 22, 'Patricia': 25, 'Tomas': 36, 'Paco': 22, 'Maria': 12}
Python

I'm working with Python and whenever I've had to validate function input, I assumed that the input worked, and then caught errors.In my case, I had a universal  class which I used for a few different things, one of which is addition. It functioned both as a  class and as a , so when I add a scalar to the , it should add that constant to each individual component.  and  addition required component-wise addition.This code is being used for a raytracer so any speed boosts are great.Here's a simplified version of my  class:I'm currently using the  method. Does anybody know of a faster method? Thanks to the answers, I tried and tested the following solution, which checks specifically for a class name before adding the  objects:I ran a speed test with these two blocks of code using , and the results were pretty significant:I haven't tested the  class with  input validation whatsoever (i.e. moving the checking out of the class and into the actual code), but I'd imagine that it's even faster than the  method.: Looking back at this code, this is  an optimal solution.OOP makes this even faster:I upvoted Matt Joiner's answer, but wanted to include some additional observations to make it clear that, along with a couple of other factors, there are  times that matter when choosing between pre-checking conditions (known as LBYL or \"Look Before You Leap\") and just handling exceptions (known as EAFP or \"Easier to Ask Forgiveness than Permission\").Those timings are:The additional factors are:That last point is the one that needs to be addressed first: if there is a potential for a race condition, then you have no choice, you  use exception handling. A classic example is:Since LBYL doesn't rule out the exception is such cases, it offers no real benefit and there's no judgement call to be made: EAFP is the only approach that will handle the race condition correctly.But if there's no race condition, either approach is potentially viable. They offer different trade-offs:That then leads to the following decision criteria:As a rough rule of thumb:*People will vary as to what they consider \"most of the time\" in this context. For me, if I expect the operation to succeed more than half the time, I would just use EAFP as a matter of course, until I had reason to suspect this piece of code was an actual performance bottleneck.In Python, exceptions are often faster due to the reduced number of lookups. However a friend once said (and it should apply to any language), pretend that everytime an exception is caught, there is a small delay. Avoid using exceptions where a delay could be a problem.In the example you've given, I'd go with the exception.
Python

The docs say that calling sys.exit() raises a SystemExit exception which can be caught in outer levels.  I have a situation in which I want to definitively and unquestionably exit from inside a test case, however the unittest module catches SystemExit and prevents the exit.  This is normally great, but the specific situation I am trying to handle is one where our test framework has detected that it is configured to point to a non-test database.  In this case I want to exit and prevent any further tests from being run.  Of course since unittest traps the SystemExit and continues happily on it's way, it is thwarting me.The only option I have thought of so far is using ctypes or something similar to call   exit(3) directly but this seems like a pretty fugly hack for something that should be really simple.You can call  to directly exit, without throwing an exception:This bypasses all of the python shutdown logic, such as the atexit module, and will not run through the exception handling logic that you're trying to avoid in this situation.  The argument is the exit code that will be returned by the process.As Jerub said,  is your answer. But, considering it bypasses  cleanup procedures, including  blocks, closing files, etc, and should really be avoided at all costs, may I present a \"safer-ish\" way of using it?If you problem is  being caught at outer levels (ie, unittest), then  Wrap your main code in a try/except block, catch SystemExit, and call os._exit there,  This way you may call  normally anywhere in the code, let it bubble out to the top level, gracefully closing all files and running all cleanups, and  calling os._exit.You can even choose which exits are the \"emergency\" ones. The code below is an example of such approach:
Python

I have enum and use the variables like , , etc.  When I return one of these variables from a function, can I print their names (such as ) instead of the value they returned?Short answer: no. Long answer: this is possible with some ugly hacks using traceback, inspect and the like, but it's generally probably not recommended for production code. For example see: Perhaps you can use a workaround to translate the value back to a name/representational string. If you post some more sample code and details about what you're wanting this for maybe we can provide more in-depth assistance.There is no such thing as a unique or original variable name\nTo add to , some concepts...Python \"variables\" are simply references to values.  Each value occupies a given memory location (see ) From the above, you may notice that the value \"1\" is present at the memory location 10052552.  It is referred to 569 times in this instance of the interpreter.  Now, see that because yet another name is bound to this value, the reference count went up by one.Based on these facts, it is not realistic/possible to tell what single variable name is pointing to a value.I think the best way to address your issue is to add a mapping and function to your enum reference back to a string name.Please comment if you would like sample code.Just use the text you want to print as the value of the enum, as incomparing strings for identity is almost as efficient in Python as is comparing integer values (this is due to the fact the strings are immutable as have a hash value)Of course there are easier ways to create the enum in the first place:Then, create you enumeration like this:ans access the same way as above:There are two answers to this question:  and .It depends on an implementation of enums. For example:It doesn't matter whether there are 100 names refers to an integer whose name you'd like to find .For the example above  you can inspect '' using :In this case you even don't have to know all enum names. If enums implemented differently then you might need to use a different hack. There will be some solution in most cases e.g., see . But it doesn't matter because..You could store the canonical name as an attribute of the instance, and then assign it to a variable with the same name. This might work:Regardless, it's not a particularly \"Pythonic\" thing to do.On second thought:Since Python does not provide native Enum types, you should not ask for one, but instead use other, more powerful construct to build your program. Otherwise, the next step will invariably be \"Why does Python not have a  statement, and how do I best emulate it?\"Since Enums are often used to define some kind of state, a much better approach is this:\nCreate a base class that define all the abstract properties, attributes and methods belonging to a state. Then, for each state, derive a sub class that implements the specific behavior of this state. You can then pass around these classes (or maybe instances thereof) to handle the state and its behaviour.If you use classes instead of instances (the Python way of a \"singleton\"), you can simply check for any given state (not that it should be necessary) by  (note the  instead of ) with no performance penalty over comparing integer values.And of course, you can define a  attribute and a  method to access and print the state's name.As far as I know, that will require some introspection. You can try using the inspect module.There are a few simple things you may want to try before that:All that said, there aren't standard enumerations in Python. It would help to know how you are creating them.On second thoughts, you can maintain your variables as a dictionary in the enum, keyed by variable name and provide a method of the enumeration to find the right variable and print its name. This solution (keeping a dict) is bad because variable values aren't necessarily unique.: \nThe problem is not trivial, so you may want to use a tried and tested solution. IMHO, you would be better off avoiding the situation if you can.Erlang has a concept called \"atoms\" -- they are similar to string constants or enumerations.  Consider using a string constant as the value of your enum -- the same as the name of the enum.
Python

How can I calculate matrix mean values along a matrix, but to remove  values from calculation? (For R people, think ).Here is my [non-]working example:With NaNs removed, my expected output would be:I think what you want is a masked array: Combining all of the timing dataReturns:If performance matters, you should use  instead:Assuming you've also got SciPy installed:A masked array with the nans filtered out can also be created on the fly:You can always find a workaround in something like:Numpy 2.0's  has a  option which should take care of that.This is built upon the solution suggested by JoshAdel.Define the following function:Example use:Will print out:How about using Pandas to do this:Gives:From numpy 1.8 (released 2013-10-30) onwards,  does precisely what you need:Or you use laxarray, freshly uploaded, which is among other a wrapper for masked arrays.following JoshAdel's protocoll I get:So laxarray is marginally slower (would need to check why, maybe fixable), but much easier to use and allow labelling dimensions with strings. check out: EDIT: I have checked with another module, \"la\", larry, which beats all tests:Impressive !One more speed check for all proposed approaches:So the best is 'bottleneck.nanmean(dat, axis=1)'\n'scipy.stats.nanmean(dat)' is not faster then .
Python

Cannot figure out, where to change EOF in PyCharm.\nMy scripts, started with:Outputs something like this, when I try to run it like executable (chmode +x):What to do and how to be?Set line separator to :The issue is not EOF but EOL. The shell sees a ^M as well as the end of line and thus tries to find  .The usual way of getting into this state is to edit the python file with a MSDOS/Windows editor and then run on Unix. The simplest fix is to run dos2unix on the file or edit the file in an editor that explicitly allows saving with Unix end of lines.You may find the answers here: As a Mac OS X user, I didn't find the command . Alternatively, I use vi/vim:  and then save the file you may want to try Install dos2unix:\nand let it do the magic:\nIf you are using Vim, just enter the following command:For MacOS you can install it via  like this:And next do Similar to Jiangwei Yu's post. On UNIX/Linux, I used vi to edit the Python file. Using vi, you can see the ^M at the end of each line. Find the following line Hit  to get to the end of the lineHit  to remove the ^MTo save the file and quit, type in: This worked for me.you may try to do this:[ to type in ^M, press ctrl+v,ctrl+m ]Just a Question of format beween win and unix:try command: dos2unix fileNameAfter it run again, it should work
Python

I'm aware that with Boto 2 it's possible to open an S3 object as a string with:get_contents_as_string()\nIs there an equivalent function in boto3 ? This isn't in the boto3 documentation. This worked for me:object being an s3 object:  will return bytes. At least for Python 3, if you want to return a string, you have to decode using the right encoding:I had a problem to read/parse the object from S3 because of  using Python 2.7 inside an AWS Lambda.I added json to the example to show it became parsable :)NOTE: My object is all ascii, so I don't need If body contains a io.StringIO, you have to do like below:
Python

I need to setup environment by running 'which abc' command.\nIs there python  equivalent function for 'which' command?\nThis is my code.There is .()See the Twisted implementation: I know this is an older question, but if you happen to be using Python 3.3+ you can use . You can find the documentation . It has the advantage of being in the standard library.An example would be like so:There's not a command to do that, but you can iterate over  and look if the file exists, which is actually what  does.Good luck!You could try something like the following:If you use , then your command will be run through the system shell, which will automatically find the binary on the path:
Python

A Pandas  contains column named  that contains non-unique  values. \nI can group the lines in this frame using:However, this splits the data by the  values. I would like to group these data by the year stored in the \"date\" column.  shows how to group by year in cases where the time stamp is used as an index, which is not true in my case.How do I achieve this grouping?ecatmur's solution will work fine. This will be better performance on large datasets, though:I'm using pandas 0.16.2. This has better performance on my large dataset:Using the  option and playing around with ,  etc. becomes far easier.This should work:
Python

I just finished installing my  package for Python 2.6, and now when I import it using , a user warning appear will appearIs there a way how to get rid of this?You can change  to not be writeable by group/everyone. I think this works:You can suppress warnings using the :If you just want to flat out ignore warnings, you can use :
Python

Is there a built-in function in Python that would replace (or remove, whatever) the extension of a filename (if it has one) ?Example:In my example:  would become I don't know if it matters, but I need this for a SCons module I'm writing. (So perhaps there is some SCons specific function I can use ?)I'd like something . Doing a simple string replacement of all occurrences of  within the string is obviously not clean. (This would fail if my filename is )Try  it should do what you want.As @jethro said,  is the neat way to do it. But in this case, it's pretty easy to split it yourself, since the extension  the part of the filename coming after the final period:The  tells Python to perform the string splits starting from the right of the string, and the  says to perform at most one split (so that e.g.  -> ). Since  will always return a non-empty array, we may safely index  into it to get the filename minus the extension.Another way to do is to use the  method. For example:I prefer the following one-liner approach using :Example:Expanding on AnaPana's answer, how to  an extension using pathlib (Python >= 3.4):/some/path/somefile.ext\n/some/path/somefileFor Python >= 3.4:
Python

Basically, I'm converting a float to an int, but I don't always have the expected value.Here's the code I'm executing:x = 2.51And here's the result (first value is the result of the operation, second value is int() of the same operation):2.51 and 4.02 are the only values that lead to that strange behaviour on the 2.50 -> 5.00 range. Every other two digits value in that range converts to int without any problem when given the same operations.So, what am I missing that leads to those results? I'm using Python 2.7.2 by the way.The int() function simply truncates the number at the decimal point, giving 250. Use to get 251 as an integer. In general, floating point numbers cannot be represented exactly. One should therefore be careful of round-off errors. As mentioned, this is not a Python-specific problem. It's a recurring problem in all computer languages.Floating-point numbers cannot represent all the numbers.  In particular, 2.51 cannot be represented by a floating-point number, and is represented by a number very close to it:If you use int, which truncates the numbers, you get:Have a look at the  type.Languages that use binary floating point representations (Python is one) cannot represent all fractional values exactly. If the result of your calculation is 250.99999999999 (and it might be), then taking the integer part will result in 250.A canonical article on this topic is .the floating point numbers are inaccurate. in this case, it is 250.99999999999999, which is really close to 251, but int() truncates the decimal part, in this case 250.you should take a look at the Decimal module or maybe if you have to do a lot of calculation at the mpmath library  :),
Python

I am using python MySQL API to connect to Mysql database from python program. I am facing a problem from few days. I am unable to insert records into the database and dont know whats the reason. Here is the way i connect and insert records into the database.Why is it so?Before closing the connection, you should add .
Python

How to convert decimal to hex in the following format (at least two digits, zero-padded, without an 0x prefix)?Input:     Output: Input:        Output: I tried  but it seems that it displays the first example but not the second one. Use the  with a  format.The  part tells  to use at least 2 digits and to use zeros to pad it to length,  means lower-case hexadecimal.The  also gives you  for uppercase hex output, and you can prefix the field width with  to include a  or  prefix (depending on wether you used  or  as the formatter). Just take into account that you need to adjust the field width to allow for those extra 2 characters:I think this is what you want:The first answer is the best, but I have an archaic answer but functional
Python

Can anyone tell me how can I do this?first open a file: I like the accepted answer: it is straightforward and will get the job done. I would also like to offer an alternative implementation:The code I suggest is essentially the same idea as your accepted answer: read a given number of bytes from the file. The difference is that it first reads a good chunk of data (4006 is a good default for X86, but you may want to try 1024, or 8192; any multiple of your page size), and then it yields the characters in that chunk one by one.The code I present may be faster for larger files. Take, for example, . These are my timing results (Mac Book Pro using OS X 10.7.4; so.py is the name I gave to the code I pasted):Now: do not take the buffer size at  as a universal truth; look at the results I get for different sizes (buffer size (bytes) vs wall time (sec)):As you can see, you can start seeing gains earlier on (and my timings are likely very inaccurate); the buffer size is a trade-off between performance and memory. The default of 4096 is just a reasonable choice but, as always, measure first.Python itself can help you with this, in interactive mode:Just:I learned a new idiom for this today while watching Raymond Hettinger's :Just read a single characterYou should try , which is definitely correct and the right thing to do.This will also work:It goes through every line in the the file and every character in every line.To make a supplement, \nif you are reading file that contains a line that is vvvvery huge, which might break your memory, you might consider read them into a buffer then yield the each char 
Python

Is there a way to access a list(or tuple, or other iterable)'s next, or previous element while looping through with for loop?Expressed as a generator function:Usage:One simple way. When dealing with generators where you need some context, I often use the below utility function to give a sliding window view on an iterator:It'll generate a view of the sequence N items at a time, shifting step places over.  eg.When using in lookahead/behind situations where you also need to deal with numbers without having a next or previous value, you may want pad the sequence with an appropriate value such as None.Check out the looper utility from the . It gives you a wrapper object around the loop item that provides properties such as previous, next, first, last etc.Take a look at the  for the looper class, it is quite simple. There are other such loop helpers out there, but I cannot remember any others right now.Example:I know this is old, but why not just use ?If you run this you will see that it grabs previous and next items and doesn't care about repeating items in the list.I don't think there is a straightforward way, especially that an iterable can be a generator (no going back). There's a decent workaround, relying on explicitly passing the index into the loop body:The  function is a builtin.Iterators only have the next() method so you cannot look forwards or backwards, you can only get the next item.enumerate(iterable) can be useful if you are iterating a list or tuple.Immediately previous?  You mean the following, right?If you want  previous items, you can do this with a kind of circular queue of size .If you want the solution to work on iterables, the  has a recipe that does exactly what you want:If you're using Python 2.x, use  instead of Not very pythonic, but gets it done and is simple:TO DO: protect the edges The most simple way is to search the list for the item:Of course, this only works if the list only contains unique items. The other solution is:
Python

I am working with flask in a virtual environment. I was able to install matplotlib with pip, and I can  in a Python session. However, when I import it as I get the following error: I am confused about why it asks me to install Python as framework. Doesn't it already exists? What does it mean to \"install Python as framework\", and how do I install it? This  worked for me. If you already installed matplotlib using pip on your virtual environment, you can just type the following:And then, write  in there. \nIf you need more information, just go to the solution link. I got the same error, and tried 's answer:I run the program, no error, but also no plots, and I tried ,\nit prints out that I haven't got PyQt4 installed.Then I tried another backend: , it works!So maybe we can try difference backends and some may work or install the requeired packages like PyQt4.Here is a sample python snippet that you can try and test matplotlib.I had similar problem when I used pip to install matplotlib. By default, it installed the latest version which was 1.5.0. However, I had another virtual environment with Python 3.4 and matplotlib 1.4.3 and this environment worked fine when I imported matplotlib.pyplot. Therefore, I installed the earlier version of matplotlib using the following:I know this is only a work-around, but it worked for me as a short-term fix.You can fix this issue by using the backend Go to  and open/create  and add the following line  and it should work for you. If you do not want to set a  configuration file, you can circumvent this issue by setting the  backend at runtime right after importing  and before importing :Although most answers seem to point towards patching the  script to use the system python, I was having trouble getting that to work and an easy solution for me - though a little cringey - was to install matplotlib to the global environment and use that instead of a virtualenv instance. You can do this either by creating your virtualenv with the --system-site-packages flag like , or to use the universal flag when pip installing like .A clean and easy solution is to create a kernel that sets  to \u00b4VIRTUAL_ENV` and then uses the system Python executable (instead of the one in the virtualenv).If you want to automate the creation of such a kernel, you can use the  script.
Python

I have a models  and , that are like this:Now I have some  and  objects, and I'd like to get a query that selects all  objects that have less then 2  pointing at them.A is something like a pool thing, and users (the B) join pool. if there's only 1 or 0 joined, the pool shouldn't be displayed at all.Is it possible with such model design? Or should I modify that a bit?Sounds like a job for .If the B count is something you often need as a filtering or ordering criterion, or needs to be displayed on list views, you could consider denormalisation by adding a b_count field to your A model and using signals to update it when a B is added or deleted:Another solution would be to manage a status flag on the A object when you're adding or removing a related B.The question and selected answer are from 2008 and since then this functionality has been integrated into the django framework.  Since this is a top google hit for \"django filter foreign key count\" I'd like to add an easier solution with a recent django version using .In my case I had to take this concept a step further.  My \"B\" object had a boolean field called is_available, and I only wanted to return A objects who had more than 0 B objects with is_available set to True.I'd recommend modifying your design to include some status field on A.The issue is one of \"why?\"  Why does A have < 2 B's and why does A have >= 2 B's.  Is it because user's didn't enter something?  Or is because they tried and their input had errors.  Or is it because the < 2 rule doesn't apply in this case.Using presence or absence of a Foreign Key limits the meaning to -- well -- present or absent.  You don't have any way to represent \"why?\"Also, you have the following optionThis can be pricey because it does fetch all the A's rather than force the database to do the work.Edit: From the comment \"would require me to watch for user join / user leaving the pool events\".You don't \"watch\" anything -- you provide an API which does what you need.  That's the central benefit of the Django model.  Here's one way, with explict methods in the  class.You can also define a special  for this, and replace the default  Manager with your manager that counts references and updates .I assume that joining or leaving the pool may not happen as often as listing (showing) the pools. I also believe that it would be more efficient for the users join/leave actions to update the pool display status. This way, listing & showing the pools would require less time as you would just run a single query for SHOW_STATUS of the pool objects.How about just doing this way?
Python

How do I generate a unique session id in Python?You can use the  like so:A lot has happened in a the last ~5yrs.   has been updated and is now considered a high-entropy source of randomness on modern Linux kernels and distributions.  In the last 6mo we've seen entropy starvation on a Linux 3.19 kernel using Ubuntu, so I don't think this issue is \"resolved\", but it's sufficiently difficult to end up with low-entropy randomness when asking for any amount of randomness from the OS.I hate to say this, but none of the other solutions posted here are correct with regards to being a \"secure session ID.\" Neither  or  are good choices for generating session IDs. Both may generate  results, but random does not mean it is  due to poor . See \"\" by Haldir or . If you still want to use a UUID, then use a UUID that was generated with a good initial random number:or:M2Crypto is best OpenSSL API in Python atm as pyOpenSSL appears to be maintained only to support legacy applications.It can be as simple as creating a random number.  Of course, you'd have to store your session IDs in a database or something and check each one you generate to make sure it's not a duplicate, but odds are it never will be if the numbers are large enough.What's the session for? A web app? You might wanna look at . It is the default module for handling sessions in Pylons.
Python

Suppose code like this:Now I want to call methods start and stop (maybe also others) for each object in the list all. Is there any elegant way for doing this except of writing a bunch of functions likeThe *_all() functions are so simple that for a few methods I'd just write the functions. If you have lots of identical functions, you can write a generic function:Or create a function factory:simple exampleand in python3It seems like there would be a more Pythonic way of doing this, but I haven't found it yet.I use \"map\" sometimes if I'm calling the same function (not a method) on a bunch of objects:This replaces a bunch of code that looks like this:But can also be achieved with a pedestrian \"for\" loop:The downside is that a) you're creating a list as a return value from \"map\" that's just being throw out and b) it might be more confusing that just the simple loop variant.You could also use a list comprehension, but that's a bit abusive as well (once again, creating a throw-away list):For methods, I suppose either of these would work (with the same reservations):orSo, in reality, I think the pedestrian (yet effective) \"for\" loop is probably your best bet.The approachis simple, easy, readable, and concise. This is the main approach Python provides for this operation. You can certainly encapsulate it in a function if that helps something. Defining a special function for this for general use is likely to be less clear than just writing out the for loop.maybe , but since you don't want to make a list, you can write your own...then you can do:by the way, all is a built in function, don't overwrite it ;-)Taking @Ants Aasmas answer one step further, you can create a wrapper that takes any method call and forwards it to all elements of a given list:That class can then be used like this:Which produces the following output:With some work and ingenuity it could probably be enhanced to handle attributes as well (returning a list of attribute values).There is an easier way:
Python

I want to insert the integers 188 and 90 in my MySQL database, but the following code doesn't work:Why doesn't it work? working for me:table in mysql;
Python

How can I extract the date from a string like \"monkey 2010-07-10 love banana\"? Thanks!If the date is given in a fixed form, you can simply use a regular expression to extract the date and \"datetime.datetime.strptime\" to parse the date:Otherwise, if the date is given in an arbitrary form, you can't extract it easily.Using :Invalid dates raise a :It can recognize dates in many formats:Note that it makes a guess if the date is ambiguous:But the way it parses ambiguous dates is customizable:For extracting the date from a string in Python; the best module available is the  module.You can use it in your Python project by following the easy steps given below. if you are expecting a large number of matches; then typecasting to list won't be a recommended way as it will be having a big performance overhead.
Python

For example, the standard division symbol '/' rounds to zero:However, I want it to return 0.04. What do I use?There are three options:which is the same behavior as the C, C++, Java etc, or You can also activate this behavior by passing the argument  to the Python interpreter:The second option will be the default in Python 3.0. If you want to have the old integer division, you have to use the  operator. : added section about , thanks to !Other answers suggest how to get a floating-point value.  While this wlil be close to what you want, it won't be exact:If you actually want a  value, do this:That will give you an object that properly knows that 4 / 100 in  is \"0.04\".  Floating-point numbers are actually in base 2, i.e. binary, not decimal.Make one or both of the terms a floating point number, like so:Alternatively, turn on the feature that will be default in Python 3.0, 'true division', that does what you want. At the top of your module or script, do:You need to tell Python to use floating point values, not integers. You can do that simply by using a decimal point yourself in the inputs:You might want to look at Python's  package, also.  This will provide nice decimal results.Try 4.0/100A simple route 4 / 100.0 or4.0 / 100You cant get a decimal value by dividing one integer with another, you'll allways get an integer that way (result truncated to integer). You need at least one value to be a decimal number.Please consider following example
Python

Every so often on here I see someone's code and what looks to be a 'one-liner', that being a one line statement that performs in the standard way a traditional 'if' statement or 'for' loop works.I've googled around and can't really find what kind of ones you can perform? Can anyone advise and preferably give some examples?For example, could I do this in one line:Or:Well,Is this an improvement? . You could even add more statements to the body of the -clause by separating them with a semicolon. I recommend  that though.I've found that in the majority of cases doing block clauses on one line is a bad idea.It will, again as a generality, reduce the quality of the form of the code.  High quality code form is a key language feature for python.In some cases python will offer ways todo things on one line that are definitely more pythonic. Things such as what Nick D mentioned with the list comprehension: although unless you need a reusable list specifically you may want to consider using a generator insteadnote the biggest difference between the two is that you can't reiterate over a generator, but it is more efficient to use. There is also a built in ternary operator in modern versions of python that allow you to do things likeor Some people may find these more readable and usable than the similar  block.When it comes down to it, it's about code style and what's the standard with the team you're working on.  That's the most important, but in general, i'd advise against one line blocks as the form of the code in python is so very important.More generally, all of the following are valid syntactically:...etc.an example of a language feature that isn't just removing line breaks, although still not convinced this is clearer than the more verbose versionYou can rewrite the above as:Python lets you put the indented clause on the same line if it's only one line:You could do all of that in one line by omitting the  variable:Older versions of Python would only allow a single simple statement after   or similar block introductory statements.I see that one can have multiple simple statements on the same line as any of these.  However, there are various combinations that don't work.  For example we can:... but, on the other hand, we can't:We can:... but we can't:... and so on.In any event all of these are considered to be extremely NON-pythonic.  If you write code like this then experience Pythonistas will probably take a dim view of your skills.It's marginally acceptable to combine multiple statements on a line in some cases.  For example:... or even:... for simple   and even  statements or assigments.In particular if one needs to use a series of  one might use something like:... then you might not irk your colleagues too much.  (However, chains of  like that scream to be refactored into a dispatch table ... a dictionary that might look more like:Dive into python has a bit where he talks about what he calls the , which seems like an effective way to cram complex logic into a single line.Basically, it simulates the ternary operater in c, by giving you a way to test for truth and return a value based on that. For example:This is an example of \"if else\" with actions.
Python

I've a python script that has to launch a shell command for every file in a dir:This works fine for the first file, but after the \"myscript\" command has ended, the execution stops and does not come back to the python script.How can I do? Do I have to  before ?Usage:You can use .  There's a few ways to do it:Or, if you don't care what the external program actually does:The subprocess module has come along way since 2008.  In particular  and  make simple subprocess stuff even easier.  The  family of functions are nice it that they raise an exception if something goes wrong.Any output generated by  will display as though your process produced the output (technically  and your python script share the same stdout).  There are a couple of ways to avoid this.The  functions  the current programm with the new one. When this programm ends so does your process. You probably want .use spawn
Python

How can I convert the result of a ConfigParser.items('section') to a dictionary to format a string like here:This is actually already done for you in .  Example:And then:  My solution to the same problem was downvoted so I'll further illustrate how my answer does the same thing without having to pass the section thru , because  is .Magic happening:So this solution is  wrong, and it actually requires one less step.  Thanks for stopping by!Have you tried?How I did it in just one line.No more than other answers but when it is not the real businesses of your method and you need it just in one place use less lines and take the power of dict compression could be useful. I know this was asked a long time ago and a solution chosen, but the solution selected does not take into account defaults and variable substitution. Since it's the first hit when searching for creating dicts from parsers, thought I'd post my solution which does include default and variable substitutions by using ConfigParser.items().A convenience function to do this might look something like:For an individual section, e.g. \"general\", you can do:
Python

In PHP, a string enclosed in \"double quotes\" will be parsed for variables to replace whereas a string enclosed in 'single quotes' will not. In Python, does this also apply?:Python is one of the few (?) languages where ' and \" have identical functionality. The choice for me usually depends on what is inside. If I'm going to quote a string that has single quotes within it I'll use double quotes and visa versa, to cut down on having to escape characters in the string.Examples:This is documented on the \"String Literals\" page of the python documentation: In some other languages, meta characters are not interpreted if you use single quotes. Take this example in Ruby:In Python, if you want the string to be taken literally, you can use raw strings (a string preceded by the 'r' character):Single and double quoted strings in Python are identical. The only difference is that single-quoted strings can contain unescaped double quote characters, and vice versa. For example:Then again, there are triple-quoted strings, which allow both quote chars and newlines to be unescaped.You can substitute variables in a string using named specifiers and the locals() builtin:The difference between \" and ' string quoting is just in style - except that the one removes the need for escaping the other inside the string content. recommends a consistent rule,  suggests that docstrings use triple double quotes.Widely used however is the practice to prefer double-quotes for natural language strings (including interpolation) - thus anything which is potentially candidate for I18N. And single quotes for technical strings: symbols, chars, paths, command-line options, technical REGEXes, ...(For example, when preparing code for I18N, I run a semi-automatic REGEX converting double quoted strings quickly for using e.g. )The interactive Python interpreter prefers single quotes:This could be confusing to beginners, so I'd stick with single quotes (unless you have different coding standards).There are 3 ways you can qoute strings in python:\n\"string\"\n'string'\n\"\"\"\nstring\nstring\n\"\"\"\nthey all produce the same result.There is no difference in Python, and you can really use it to your advantage when generating XML.  Correct XML syntax requires double-quotes around attribute values, and in many languages, such as Java, this forces you to escape them when creating a string like this:But in Python, you simply use the other quote and make sure to use the matching end quote like this:Pretty nice huh?  You can also use three double quotes to start and end multi-line strings, with the EOL's included like this:Yes. \nThose claiming single and double quotes are identical in Python are simply wrong.Otherwise in the following code, the double-quoted string would not have taken an extra 4.5% longer for Python to process:Output:So if you want fast clean respectable code where you seem to know your stuff, use single quotes for strings whenever practical. You will also expend less energy by skipping the shift key.
Python

I tried running this piece of code:And it prints . I thought Python treats anything with value as . Why is this happening?From :The key phrasing here that I think you are misunderstanding is \"interpreted as false\" or \"interpreted as true\".  This does not mean that any of those values are identical to True or False, or even equal to True or False.The expression  will be treated as true where a Boolean expression is expected (like in an  statement), but the expressions  and  will evaluate to False for the reasons in Ignacio's answer. compares identity. A string will never be identical to a not-string. is equality. But a string will never be equal to either  or .You want neither.
Python

I just want fixed width columns of text but the strings are all padded right, instead of left!!?producesbut we wantThis version uses the  method.Previously there was a statement in the docs about the % operator being removed from the language in the future. This statement has been .You can prefix the size requirement with  to left-justify:on a side note you can make the width variable with Use  instead of  They will be aligned to left..This one worked in my python script:A slightly more readable alternative solution:\n  Note that  uses fixed width characters and doesn't dynamically adjust like the other solutions.
Python

If I have this string:what is the most efficient approach for creating this list:It just so happens that the tokens you want split are already Python tokens, so you can use the built-in  module.  It's almost a one-liner:You can use  from the  module.  Example code:\\DThis looks like a parsing problem, and thus I am compelled to present a solution based on parsing techniques.While it may seem that you want to 'split' this string, I think what you actually want to do is 'tokenize' it. Tokenization or lexxing is the compilation step before parsing. I have amended my original example in an edit to implement a proper recursive decent parser here. This is the easiest way to implement a parser by hand.Implementation of handling of brackets is left as an exercise for the reader. This example will correctly do multiplication before addition.Matches consecutive digits or consecutive non-digits.Each match is returned as a new element in the list.Depending on the usage, you may need to alter the regular expression. Such as if you need to match numbers with a decimal point.This is a parsing problem, so neither regex not split() are the \"good\" solution. Use a parser generator instead.I would look closely at . There have also been some decent articles about pyparsing in the .Regular expressions:You can expand the regular expression to include any other characters you want to split on.Another solution to this would be to avoid writing a calculator like that altogether. Writing an RPN parser is much simpler, and doesn't have any of the ambiguity inherent in writing math with infix notation.This will do the trick. I have encountered this kind of problem before.Why not just use ?  It should do what you're trying to achieve.This doesn't answer the question exactly, but I believe it solves what you're trying to achieve. I would add it as a comment, but I don't have permission to do so yet.I personally would take advantage of Python's maths functionality directly with exec:i'm sure Tim meant if you copy exactly what he has down you only get the  not the .
Python

Python is the language I know the most, and strangely I still don't know why I'm typing \"self\" and not \"this\" like in Java or PHP.I know that Python is older than Java, but I can't figure out where does this come from. Especially since you can use any name instead of \"self\": the program will work fine.So where does this convention come from?Smalltalk-80, released by Xerox in 1980, used .  Objective-C (early 1980s) layers Smalltalk features over C, so it uses  too.  Modula-3 (1988), Python (late 1980s), and Ruby (mid 1990s) also follow this tradition.C++, also dating from the early 1980s, chose  instead of .  Since Java was designed to be familiar to C/C++ developers, it uses  too.Smalltalk uses the metaphor of objects sending messages to each other, so \"self\" just indicates that the object is sending a message to itself.Check the  for user defined classes:It's a choice as good as any other.  You might ask why C++, Java, and C# chose \"this\" just as easily.Smalltalk, which predates Java of course.With respect to python, there is nothing special about . You can use  instead if you wanted:Here's an example:Although you could name it whatever you want,  is the convention for the first argument of a class function. Check out  in the python documentation, which says:As for the convention, it started out in Smalltalk, but is also used in Object Pascal, Python, Ruby, and Objective-C.  has a great explanation.Python follows Smalltalk's footsteps in the aspect - self is used in Smalltalk as well. I guess the  question should be 'why did Bjarne decide to use  in C++'...The primary inspiration was Modula-3, which Guido was introduced to at DEC: -- Guido, I think that since it's explicitly declared it makes more sense seeing an actual argument called \"self\" rather than \"this\". From the grammatical point of view at least, \"self\" is not as context dependent as \"this\".I don't know if I made myself clear enough, but anyway this is just a subjective appreciation. is not a keyword (*). represents by convention the address of the current objectYou can get more info on  .Why not  ? well it is a convention for a name. You can use  for your code if you like it better.(*) This answer has been ported and merged here from a question asking . As the clarification in this first line could be useful for others I keep it here.
Python

I have the following DataFrame:I would like to add a column 'e' which is the sum of column 'a', 'b' and 'd'.Going across forums, I thought something like this would work:But no!I would like to realize the operation having the list of columns  and  as inputs.You can just  and set param  to sum the rows, this will ignore none numeric columns:If you want to just sum specific columns then you can create a list of the columns and remove the ones you are not interested in:If you have a just a few columns to sum, you can write: This creates new column  with the values:For longer lists of columns, EdChum's answer is preferred.
Python

I recently encountered a scenario in which if a set only contained a single element, I wanted to do something with that element.  To get the element, I settled on this approach:But this isn't very satisfying, as it creates an unnecessary list.  It could also be done with iteration, but iteration seems unnatural as well, since there is only a single element.  Am I missing something simple?tuple unpacking works.(By the way, python-dev has explored but rejected the addition of myset.get() to return an arbitrary element from a set. , Guido van Rossum answers  and .)My personal favorite for getting arbitrary element is (when you have an unknown number, but also works if you have just one):: in Python 2.5 and before, you have to use Between making a tuple and making an iterator, it's almost a wash, but iteration wins by a nose...:Not sure why all the answers are using the older syntax  rather than the new one , which seems preferable to me (and also works in Python 3.1).However, unpacking wins hands-down over both:This of course is for single-item sets (where the latter form, as others mentioned, has the advantage of failing fast if the set you \"knew\" had just one item actually had several).  For sets with arbitrary N > 1 items, the tuple slows down, the iter doesn't:So, unpacking for the singleton case, and  for the general case, seem best.I reckon  is great. But if your set  contain more than one element, and you want a not-so-arbitrary element, you might want to use  or . E.g.:or:(Don't use , because that it has unnecessary overhead for this usage.)you can use  which is a bit more efficient, or, you can do something like  I guess constructing an iterator is more efficient than constructing a tuple/list.I suggest:
Python

when i give \nls -l /etc/fonts/conf.d/70-yes-bitmaps.conf so for a symbolic link or soft link, how to find the target file's full(absolute path) in python,If i use it outputs but i need the absolute path not the relative path, so my desired output must be,how to replace the  with the actual full path of the parent directory of the symbolic link or soft link file. returns the canonical path of the specified filename, eliminating any symbolic links encountered in the path.As unutbu says, os.path.realpath(path) should be the right answer, returning the canonical path of the specified filename, resolving any symbolic links to their targets.  But it's broken under Windows.I've created a patch for Python 3.2 to fix this bug, and uploaded it to:It fixes the realpath function in Python32\\Lib\\ntpath.pyI've also put it on my server, here:Unfortunately, the bug is present in Python 2.x, too, and I know of no fix for it there.also joinpath and normpath, depending on whether you're in the current working directory, or you're working with things elsewhere.  might be more direct for you.Update:specifically:
Python

I'm using python2.7's  to read from stdin.I want to let the user change a given default string.Code:Console:The user should be presented with  but can change (backspace) it to something else.The  argument would be the prompt for  and that part shouldn't be changeable by the user.You could do: This way, if user just presses return without entering anything, \"i\" will be assigned \"Jack\". In dheerosaur's answer If user press Enter to select default value in reality it wont be saved as python considers it as '' string so Extending a bit on what dheerosaur.Fyi .. The  of backspace is On platforms with , you can use the method described here: On Windows, you can use the msvcrt module:Note that arrows keys don't work for the windows version, when it's used, nothing will happen.Put this in a file called a.py:Run the program, it stops and presents the user with this:The cursor is at the end, user presses backspace until 'an insecticide' is gone, types something else, then presses enter:Program finishes like this, final answer gets what the user typed: I only add this because you should write a simple function for reuse.  Here is the one I wrote:Try this: The ASCII value of  is .
Python

What's the best way to count the number of occurrences of a given string, including overlap in python? is it the most obvious way:?or is there a better way in python?Well, this  be faster since it does the comparing in C:If you didn't want to load the whole list of matches into memory, which would never be a problem! you could do this if you really wanted:As a function ( makes sure the substring doesn't interfere with the regex):You can also try using the , which supports overlapping matches.Python's  counts non-overlapping substrings:Here are a few ways to count overlapping sequences, I'm sure there are many more :)My answer, to the bob question on the course:This function (another solution!) receive a pattern and a text. Returns a list with all the substring located in the and their positions.Function that takes as input two strings and counts how many times sub occurs in string, including overlaps. To check whether sub is a substring, I used the  operator. Here is my edX MIT \"find bob\"* solution (*find number of \"bob\" occurences in a string named s), which basicaly counts overlapping occurrences of a given substing:For a duplicated  i've decided to count it 3 by 3 and comparing the string e.g.An alternative very close to the accepted answer but using  as the  test instead of including  inside the loop:This avoids  and is a little cleaner in my opinionIf strings are large, you want to use , in summary:If you want to count permutation counts of length 5 (adjust if wanted for different lengths):
Python

By default, when running Flask application using the built-in server (), it monitors its Python files and automatically reloads the app if its code changes:Unfortunately, this seems to work for  files only, and I don't seem to find any way to extend this functionality to other files. Most notably, it would be extremely useful to have Flask restart the app when a  changes. I've lost count on how many times I was fiddling with markup in templates and getting confused by not seeing any changes, only to find out that the app was still using the old version of Jinja template.So, is there a way to have Flask monitor files in  directory, or does it require diving into the framework's source?: I'm using Ubuntu 10.10. Haven't tried that on any other platforms really.After further inquiry, I have discovered that changes in templates indeed  updated in real time, without reloading the app itself. However, this seems to apply only to those templates that are passed to .But it so happens that in my app, I have quite a lot of reusable, parametrized components which I use in Jinja templates. They are implemented as s, reside in dedicated \"modules\" and are ed into actual pages. All nice and DRY... except that those imported templates are apparently never checked for modifications, as they don't pass through  at all.(Curiously, this doesn't happen for templates invoked through . As for , I have no idea as I don't really use them.)So to wrap up, the roots of this phenomenon seems to lie somewhere between Jinja and Flask or Werkzeug. I guess it may warrant a trip to bug tracker for either of those projects :) Meanwhile, I've accepted the 's answer because that's the solution I actually used - and it works like a charm.In my experience, templates don't even need the application to restart to be refreshed, as they should be loaded from disk everytime  is called. Maybe your templates are used differently though.To reload your application when the templates change (or any other file), you can pass the  argument to , a collection of filenames to watch: any change on those files will trigger the reloader.Example:See here: you can use\nTEMPLATES_AUTO_RELOAD = TrueFrom Actually for me TEMPLATES_AUTO_RELOAD = True does not work (0.12 version). I use jinja2 and what i have done:What worked for me is just adding this:()When you are working with  templates, you need to set some parameters. In my case with python3, I solved it with the following code:Using the latest version of Flask on Windows, using the run command and debug set to true; Flask doesn't need to be reset for changes to templates to be brought in to effect. Try Shift+F5 (or Shift plus the reload button) to make sure nothing it being cached.
Python

I have a list in python and I want to convert it to an array to be able to use  function.Use :I wanted a way to do this without using an extra module. First turn list to string, then append to an array:if variable b has a list then you can simply do the below:create a new variable \"a\" as: \n then assign the list to \"a\" as: now \"a\" has all the components of list \"b\" in array.so you have successfully converted list to array.
Python

I have a large amount of data in a collection in mongodb which I need to analyze. How do i import that data to pandas?I am new to pandas and numpy.EDIT:\nThe mongodb collection contains sensor values tagged with date and time. The sensor values are of float datatype. Sample Data: might give you a hand, followings are some codes I'm using: does exactly that, and it's . ()See  which includes a quick tutorial and some timings.You can load your mongodb data to pandas DataFrame using this code. It works for me. Hopefully for you too.export to csv and use \nor JSON and use For dealing with out-of-core (not fitting into RAM) data efficiently (i.e. with parallel execution), you can try : Blaze / Dask / Odo.Blaze (and ) has out-of-the-box functions to deal with MongoDB.A few useful articles to start off:And an article which shows what amazing things are possible with Blaze stack:  (essentially, querying 975 Gb of Reddit comments in seconds).P.S. I'm not affiliated with any of these technologies.Using will consume a lot of memory if the iterator/generator result is largebetter to generate small chunks and concat at the endAs per PEP, simple is better than complicated:  You can include conditions as you would working with regular mongoDB database or even use find_one() to get only one element from the database, etc. and voila!
Python

I don't care if it's JSON, pickle, YAML, or whatever.All other implementations I have seen are not forwards compatible, so if I have a config file, add a new key in the code, then load that config file, it'll just crash.Are there any simple way to do this?There are several ways to do this depending on the file format required.I would use the standard  approach unless there were compelling reasons to use a different format.Write a file like so:The file format is very simple with sections marked out in square brackets:Values can be extracted from the file like so:JSON data can be very complex and has the advantage of being highly portable.Write data to a file:Read data from a file:A basic YAML example is provided . More details can be found on .If you want to use something like an INI file to hold settings, consider using  which loads key value pairs from a text file, and can easily write back to the file. INI file has the format:The file can be loaded and used like this:which outputsAs you can see, you can use a standard data format that is easy to read and write. Methods like getboolean and getint allow you to get the datatype instead of a simple string.Writing configurationresults inSeems not to be used at all for configuration files by the Python community. However, parsing / writing XML is easy and there are plenty of possibilities to do so with Python. One is BeautifulSoup:where the config.xml might look like thisSave and load a dictionary. You will have arbitrary keys, values and arbitrary number of key, values pairs.
Python

The piece of code that I have looks some what like this:Is there a way to make sure (or encourage) that the different processes does not get a copy of glbl_array but shares it. If there is no way to stop the copy I will go with a memmapped array, but my access patterns are not very regular, so I expect memmapped arrays to be slower. The above seemed like the first thing to try. This is on Linux. I just wanted some advice from Stackoverflow and do not want to annoy the sysadmin. Do you think it will help if the the second parameter is a genuine immutable object like .You can use the shared memory stuff from  together with Numpy fairly easily:which prints\nHowever, Linux has copy-on-write semantics on , so even without using , the data will not be copied unless it is written to.The following code works on Win7 and Mac (maybe on linux, but not tested).For those stuck using Windows, which does not support  (unless using CygWin), pv's answer does not work.  Globals are not made available to child processes.Instead, you must pass the shared memory during the initializer of the / as such:(it's not numpy and it's not good code but it illustrates the point  ;-)If you are looking for an option that works efficiently on Windows, and works well for irregular access patterns, branching, and other scenarios where you might need to analyze different matrices based on a combination of a shared-memory matrix and process-local data, the mathDict toolkit in the  package was designed to handle this exact situation.
Python

I have a function asNow I want to write unit test for the above function separately (without calling the view). \nSo how should I call the above in . Is it possible to create request ?See :If you are using django test client () you can access request from response object like this:or if you are using () you can access client instance in any testcase just by typing :Use   to create a dummy request.You mean  right?With Django unittest, you can use the  to make request.See here: @Secator's answer is prefect as it creates a mock object which is really preferred for a really good unittest. But depending on your purpose, it might be easier to just use Django's test tools.You can use django test client for more details\n
Python

I've got a class, located in a separate module, which I can't change.This doesn't change MyClass anywhere else but this file. However if I'll add a method like thisthis will work and foo method will be available everywhere else.How do I replace the class completely?Avoid the  (horrid;-) way to get barenames when what you need most often are  names.  Once you do things the right Pythonic way:This way, you're monkeypatching the  object, which is what you need and will work when that module is used for others.  With the  form, you just don't  the module object (one way to look at the glaring defect of most people's use of ) and so you're obviously worse off;-);The one way in which I recommend using the  statement is to import a module from within a package:so you're still getting the module object and will use qualified names for all the names in that module.I am but an egg . . . . Perhaps it is obvious to not-newbies, but I needed the  idiom.  I had to modify one method of GenerallyHelpfulClass.  This failed:The code ran, but didn't use the behaviors overloaded onto SpeciallyHelpfulClass.This worked:I speculate that the  idiom 'gets the module', as Alex wrote, as it will be picked up by other modules in the package.  Speculating further, the longer dotted reference seems to bring the module into the namespace with the import by long dotted reference, but doesn't change the module used by other namespaces.  Thus changes to the import module would only appear in the name space where they were made.  It's as if there were two copies of the same module, each available under slightly different references.  Its preferable not to change the name of class while replacing, because somehow someone may have referenced them using getattr - which will result in fail like below --> which will fail if you have replaced MyClass by ReplaceClass !
Python

Silly question:\nI have a simple for loop followed by a simple if statement:  and I was wondering if I can write this as a single line somehow.\nSo, yes, I can do this:  but it reads so silly and redundant (\"for airport in airport for airport in airports...\").\nIs there a better way?No, there is no shorter way. Usually, you will even break it into two lines :This is more flexible, easier to read and still don't consume much memory.You could doI'd use a negative guard on the loop. It's readable, and doesn't introduce an extra level of indentation.Mabe this, but it's more or less the same verbose...This is a design philosophy of python.  If it takes you too many words to put it on one line, it should be broken into a few lines to help the person who comes after you.  List and generator expressions are more for transforming iterables in-place -- making more readable forms of  and .Here's an alternative to some of the other filter versions:This has the advantages of being pretty concise and also letting you use dot notation attr('first_class.is_full').You could also put something like that (or a version using a list comprehension) into a utility function like filter_by_attr. Then you could do:I still think e-satis is right to put it in a new variable no matter the method you use, though. It is just clearer that way, especially if the use doesn't exactly match the name of the attribute in question (or the the criteria is more complex).My only note on that would be that if you find yourself using this in several places, perhaps you should make airports a special collection with 'important_airports' being a @property which returns the filtered collection. Or some sort other abstraction to hide away the filtering (like a service call).Using list comprehension (only if airports is a list of objects):
Python

I'm working on something like an online store. I'm making a form in which the customer buys an item, and she can choose how many of these item she would like to buy. But, on every item that she buys she needs to choose what its color would be. So there's a non-constant number of fields: If the customer buys 3 items, she should get 3  boxes for choosing a color, if she buys 7 items, she should get 7 such  boxes.I'll make the HTML form fields appear and disappear using JavaScript. But how do I deal with this on my Django form class? I see that form fields are class attributes, so I don't know how to deal with the fact that some form instance should have 3 color fields and some 7.Any clue?Jacob Kaplan-Moss has an extensive writeup on dynamic form fields:\nEssentially, you add more items to the form's fields member variable during instantiation.Here's another option: how about a ?\nSince your fields are all the same, that's precisely what formsets are used for.The django admin uses s + a bit of javascript to add arbitrary length inlines.you can do it likeand when you create form instance, you just doit's just the basic idea, you can change the code to whatever your want. :D
Python

I want a regular expression to extract the title from a HTML page. Currently I have this:Is there a regular expression to extract just the contents of  so I don't have to remove the tags?thanks!Use   in regexp and  in python to retrieve the captured string ( will return  if it doesn't find the result, so ):Try using capturing groups:Try: You can use any HTML parser like Beautiful Soup for that. Check out Also remember that May I recommend you to Beautiful Soup.  Soup is a very good lib to parse all of your html document.The provided pieces of code do not cope with \nMay I suggestThis returns an empty string by default if the pattern has not been found, or the first match.Don't use regular expressions for HTML parsing in Python.  Use an HTML parser!  (Unless you're going to write a full parser, which would be a of extra work when various HTML, SGML and XML parsers are already in the standard libraries.If your handling \"real world\"  HTML (which is frequently non-conforming to any SGML/XML validator) then use the  package.  It isn't in the standard libraries (yet) but is wide recommended for this purpose.Another option is:  ... which is written for properly structured (standards conformant) HTML.  But it has an option to fallback to using BeautifulSoup as a parser: .
Python

I think that I fully understand this, but I just want to make sure since I keep seeing people say to NEVER EVER test against , , or .  They suggest that routines should raise an error rather than return False or None.  Anyway, I have many situations where I simply want to know if a flag is set or not so my function returns True or False.  There are other situations where I have a function return None if there was no useful result.  From my thinking, neither is problematic so long as I realize that I should never use:and should instead use:since True, False, and None are all singletons and will always evaluate the way I expect when using \"is\" rather than \"==\".  Am I wrong here?Along the same lines, would it be more pythonic to modify the functions that sometimes return None so that they raise an error instead?  Say I have an instance method called \"get_attr()\" that retrieves an attribute from some file.  In the case where it finds that the attribute I requested does not exist is it appropriate to return None?  Would it be better to have them raise an error and catch it later?The advice isn't that you should never  , , or . It's just that you shouldn't use . is silly because  is just a binary operator! It has a return value of either  or , depending on whether its arguments are equal or not. And  will proceed if  is true. So when you write  Python is going to first evaluate , which will become  if  was  and  otherwise, and then proceed if the result of that is true. But if you're expecting  to be either  or , why not just use  directly!Likewise,  can usually be replaced by .There are some circumstances where you might want to use . This is because an  statement condition is \"evaluated in boolean context\" to see if it is \"truthy\" rather than testing exactly against . For example, non-empty strings, lists, and dictionaries are all considered truthy by an if statement, as well as non-zero numeric values, but none of those are equal to . So if you want to test whether an arbitrary value is  the value , not just whether it is truthy, when you would use . But I almost never see a use for that. It's so rare that if you  ever need to write that, it's worth adding a comment so future developers (including possibly yourself) don't just assume the  is superfluous and remove it.Using  instead is actually worse. You should never use  with basic built-in immutable types like booleans (, ), numbers, and strings. The reason is that for these types we care about , not .  tests that values are the same for these types, while  always tests identities.Testing identities rather than values is bad because an implementation could theoretically construct new boolean values rather than go find existing ones, leading to you having two  values that have the same value but are stored in different placed in memory and have different identities. In practice I'm pretty sure  and  are always re-used by the Python interpreter so this won't happen, but that's really an implementation detail. This issue trips people up all the time with strings, because short strings and literal strings that appear directly in the program source are recycled by Python so  always returns . But it's easy to construct the same string 2 different ways and have Python give them different identities. Observe the following: So it turns out that Python's equality on booleans is a little unexpected (at least to me):The rationale for this, as explained in , is that the old behaviour of using integers 1 and 0 to represent True and False was good, but we just wanted more descriptive names for numbers we intended to represent truth values.One way to achieve that would have been to simply have  and  in the builtins; then 1 and True really would be indistinguishable (including by ). But that would also mean a function returning  would show  in the interactive interpreter, so what's been done instead is to create  as a subtype of . The only thing that's different about  is  and ;  instances still have the same data as  instances, and still compare equality the same way, so .So it's wrong to use  when  might have been set by some code that expects that \"True is just another way to spell 1\", because there are lots of ways to construct values that are equal to  but do not have the same identity as it:And it's wrong to use  when  could be an arbitrary Python value and you only want to know whether it is the boolean value . The only certainty we have is that just using  is best when you just want to test \"truthiness\". Thankfully that is usually all that is required, at least in the code I write!A more sure way would be . But that's getting pretty verbose for a pretty obscure case. It also doesn't look very Pythonic by doing explicit type checking... but that really is what you're doing when you're trying to test precisely  rather than truthy; the duck typing way would be to accept truthy values and allow any user-defined class to declare itself to be truthy.If you're dealing with this extremely precise notion of truth where you not only don't consider non-empty collections to be true but also don't consider 1 to be true, then just using  is probably okay, because presumably then you know that  didn't come from code that considers 1 to be true. I don't think there's any pure-python way to come up with another  that lives at a different memory address (although you could probably do it from C), so this shouldn't ever break despite being theoretically the \"wrong\" thing to do.And I used to think booleans were simple!In the case of , however, the idiom is to use . In many circumstances you can use , because  is a \"falsey\" value to an  statement. But it's best to only do this if you're wanting to treat all falsey values (zero-valued numeric types, empty collections, and ) the same way. If you are dealing with a value that is either some possible other value or  to indicate \"no value\" (such as when a function returns  on failure), then it's  better to use  so that you don't accidentally assume the function failed when it just happened to return an empty list, or the number 0.My arguments for using  rather than  for immutable value types would suggest that you should use  rather than . However, in the case of  Python does explicitly guarantee that there is exactly one  in the entire universe, and normal idiomatic Python code uses .Regarding whether to return  or raise an exception, it depends on the context.For something like your  example I would expect it to raise an exception, because I'm going to be calling it like . The normal expectation of the callers is that they'll get the attribute value, and having them get  and assume that was the attribute value is a much worse danger than forgetting to handle the exception when you can actually continue if the attribute can't be found. Plus, returning  to indicate failure means that  is not a valid value for the attribute. This can be a problem in some cases.For an imaginary function like , that we provide a pattern to and it checks several places to see if there's a match, it could return a match if it finds one or  if it doesn't. But alternatively it could return a list of matches; then no match is just the empty list (which is also \"falsey\"; this is one of those situations where I'd just use  to see if I got anything back).So when choosing between exceptions and  to indicate failure, you have to decide whether  is an expected non-failure value, and then look at the expectations of code calling the function. If the \"normal\" expectation is that there will be a valid value returned, and only occasionally will a caller be able to work fine whether or not a valid value is returned, then you should use exceptions to indicate failure. If it will be quite common for there to be no valid value, so callers will be expecting to handle both possibilities, then you can use .Use  or , there is no need for either  or  for that.For checking against None,  and  are recommended. This allows you to distinguish it from False (or things that evaluate to False, like  and ).Whether  should return  would depend on the context. You might have an attribute where the value is None, and you wouldn't be able to do that. I would interpret  as meaning \"unset\", and a  would mean the key does not exist in the file.If checking for truth:for false:for none:for non-none:For  the correct behaviour is  to return  but raise an  error instead - unless your class is something like Concerning whether to raise an exception or return : it depends on the use case.  Either can be pythonic.  Look at python's  class for example,  hooks into  and it raises a  if key is not present.  But  method returns the second argument (which is defaulted to ) if key is not present.    The most important thing to consider is to document that behaviour in the docstring, and make sure that your  method does what it says it does. To address your other questions, use these conventions:Functions that return  or  should probably have a name that makes this obvious to improve code readabilityIn python3 you can \"type-hint\" that:You can directly check that variable contains value or not like  or .In the examples in , I have seen that  or  are being used instead of  or . Also using  is recommended in this document instead of  or . So I think if this is the official Python way, we Python guys should go on this way, too.Regards.In the case of your fictional  function, if the requested attribute always should be available but isn't then throw an error. If the attribute is optional then return .for True, not None:   for false, None:One thing to ensure is that nothing can reassign your variable. If it is not a boolean in the end, relying on truthiness will lead to bugs. The beauty of conditional programming in dynamically typed languages :).The following prints \"\".Now let's change .Now the statement prints \"\" because the string is truthy.This statement, however, correctly outputs \"\".
Python

I'm using flask for my application. I'd like to send an image (dynamically generated by PIL) to client without saving on disk.Any idea how to do this ? First, you can save the image to a  and remove the local file (if you have one):Second, set the temp file to the response (as per ):Here's a version without any temp files and the like (see ):To use in your code simply doIt turns out that flask provides a solution (rtm to myself!):I was also struggling in the same situation. Finally, I have found its solution using a WSGI application, which is an acceptable object for \"make_response\" as its argument.Please replace \"opening image\" operations with appropriate PIL operations.
Python

I want to add a debug print statement test, if I enable  from the command line and if I have the following in the script.I went through the following questions, but couldn't get the answer...You need to combine the wisdom of the  with . Here's an example...Run the help:Running in verbose mode:Running silently:I find both  (for users) and  (for developers) useful.  Here's how I do it with  and :So if  is set, the logging level is set to .  If , logging is set to .  If neither, the lack of  sets the logging level to the default of .Here is a more concise method, that does bounds checking, and will list valid values in help:Usage:Another variant would be to count the number of  and use the count as an index to the a  with the actual levels from :This works for , , , ,  , etc,  If no  then  is selected if more  are provided it will step to  and You can explicity specify a level as an integer after the  flag:if you want to enable logging.DEBUG level for a script you don't want to (or cannot) edit, you can customize your startup:enter the following:then you can just:from Paul Ollis at Here's another take on having argparse count the -v option to increase verbosity up two levels from the default WARNING to INFO (-v) to DEBUG (-vv). This does not map to the constants defined by  but rather calculates the value directly, limiting the input:
Python

I feel like I spend a lot of time writing code in Python, but not enough time creating Pythonic code.  Recently I ran into a funny little problem that I thought might have an easy, idiomatic solution.  Paraphrasing the original, I needed to collect every sequential pair in a list.  For example, given the list , I wanted to compute .I came up with a quick solution at the time that looked like translated Java.  Revisiting the question, the best I could do waswhich has the side effect of tossing out the last number in the case that the length isn't even.Is there a more idiomatic approach that I'm missing, or is this the best I'm going to get?This will do it a bit more neatly:(but it's arguably less readable if you're not familiar with the \"stride\" feature of ranges).Like your code, it discards the last value where you have an odd number of values.The one often-quoted is:I usually copy the  recipe from the  documentation into my code for this.How about using the step feature of :The right thing is probably not to compute lists, but to write an iterator->iterator function. This is more generic -- it works on every iterable, and if you want to \"freeze\" it into a list, you can use the \"list()\" function.I'm surprised the itertools module does not already have a function for that -- perhaps a future revision. Until then, feel free to use the version above :) is a well-built library with many functional programming niceties overlooked in itertools.  solves this (with an option to pad the last entry for lists of odd length)try thisSo,\ngivesIf you don't want to lose elements if their number in list is not even try this:
Python

The first  works and then the second time around it comes up with an error:Does anyone know why this is?@Greg Hewgill: I've already tried that and I get the error:This is the problem:You are redefining what  means.  is the built-in Python name of the string type, and you don't want to change it. Use a different name for the local variable, and remove the  statement.While not in your code, another hard-to-spot error is when the  character is missing in an attempt of string formatting:but it should be:The missing  would result in the same .In my case I had a class that had a method and a string property of the same name, I was trying to call the method but was getting the string property.Another case of this: Messing with the  function of an object where a  call fails non-transparently.In our case, we used a  decorator on the  and passed that object to a .  The  decorator causes the  object to be turned into a string, which then results in the  object is not callable error.I had the same error. In my case wasn`t because of a variable named str. But because i named a function with a str parameter and the variable the same. .I run it in a loop. The first time it run ok. The second time i got this error. Renaming the variable to a name different from the function name fixed this. So I think it\u00b4s because Python once associate a function name in a scope, the second time tries to associate the left part ( same_name =) as a call to the function and detects that the str parameter is not present, so it's missing, then it throws that error.In my case, I had a Class with a method in it. The method did not have 'self' as the first parameter and the error was being thrown when I made a call to the method. Once I added 'self,' to the method's parameter list, it was fine.In my case if I had defined  as a variable and due to same faced . Post that I changed the function name to . Then I stopped the kernel and restarted. Still it didn't work out. Post that I restarted the kernel with option of Restart the Kernel and Clear all outputs. And immediately all codes ran successfully. Thanks for your input.  
Python

Why does this happen? If there are only 5 characters in that string, why is the count function returning one more?Also, is there a more effective way of counting characters in a string? returns how many times an object occurs in a list, so if you count occurrences of  you get 6 because the empty string is at the beginning, end, and in between each letter.Use the  function to find the length of a string.That is because there are six different substrings that are the empty string: Before the 1, between the numbers, and after the 5. If you want to count characters use  instead:How many pieces do you get if you cut a string five times?The same thing is happening here. It counts the empty string after the  also. is what you should use.The most common way is to use . It returns the number of characters in a given string - in this case 5.Count and Len are two very different things. Len simply prints the length of the string (hence the name 'Len'), while Count iterates through the string or list and gives you the number of times an object occurs, which counts the beginning and end of the string as well as in between each letter.It's the same reason why it makes sense for  to return , not .
Python

I made some weird observations that my GridSearches keep failing after a couple of hours and I initially couldn't figure out why. I monitored the memory usage then over time and saw that it it started with a few gigabytes (~6 Gb) and kept increasing until it crashed the node when it reached the max. 128 Gb the hardware can take. \nI was experimenting with random forests for classification of a large number of text documents. For simplicity -- to figure out what's going on -- I went back to naive Bayes.The versions I am using are I found some related discussion on the scikit-issue list on GitHub about this topic:  and\nAnd it sounds like it was already successfully addressed!So, the relevant code that I am using isJust out of curiosity, I later decided to do the grid search the quick & dirty way via nested for loopSo far so good. The grid search runs and writes the results to stdout. However, after some time it exceeds the memory cap of 128 Gb again. Same problem as with the GridSearch in scikit. After some experimentation, I finally found out that in the for loop solves the problem and the memory usage stays constantly at 6.5 Gb over the run time of ~10 hours.Eventually, I got it to work with the above fix, however, I am curious to hear your ideas about what might be causing this issue and your tips & suggestions!RandomForest in 0.15.2 does not support sparse inputs.Upgrade sklearn and try again...hopefully this will allow the multiple copies that end up being made to consume way less memory. (and speed things up)I can't see your exact code, but I faced similar problem nowadays.\nIt is worth a try.\nThe similar memory blow-up easily could happen when we copy values from a mutable array or list like object to an other variable creating a copy of the original one and then we modify the new array or list with append or something similar increasing the size of it and the same time increasing the original object too in the background. So this is an exponential process, so after some time we are out of memory. I was be able to and maybe you can avoid this kind of phenomenon with  the original object at a value passing.I had the similar problem, I blew-up the memory with a similar process, then I managed to stay at 10% memory load.\nNow I see the snippet of the code with pandas DataFrame. There would be such a valuecopy issue easily.I'm not familiar with GridSearch sir, but I'd suggest when memory and huge lists are an issue write a small custom generator. It can be reused for all your items, just use one that takes any list.  If implementing beyond the lower solution here first read this article, best generator article I've found. I typed it all in and went piece by piece, any questions you have after reading it I can try tooDon't need:\nTryThe 'yield' word (anywhere in the declaration) makes this a generator, not a regular function. This runs through and says i equals 0, while True I gotta do stuff, they want me to yield this_list[0], here you go I'll wait for you at  if you need me again. The next time it is called, it picks up and does , and notices it's still in a while loop and gives this_list[1], and records its location ( again...it will wait there until called again). Notice as I feed it the list once and make a generator (x here), it will exhaust your list. Let's see if we can use it in a for:Nope. Let's try to handle that:That works. Now it won't blindly try to return a list element even if it isn't there. From what you said, I can almost guarantee you'll need to be able to seed it (pick up from a certain place, or start freshly from a certain place): is a thing that looks for seed, but seed defaults to None so will usually just start at the logical place, 0, the beginning of the listHow can you use this beast without using (almost) any memory?that looks familiar huh? Now you can process a trillion values one by one, picking important ones to write to disk, and never blowing up your system. Enjoy!
Python

I have been trying to use both the Python implementation (opencv 2.4.11) and the Java implementation (opencv 2.4.10) of OpenCV's MSER algorithm. Interestingly, I've noticed that MSER's detect returns different types of output in Python vs Java. In Python, detect returns a list of lists of points, where each list of points represents a blob detected. In Java, a  is returned, where each row is a single point with an associated diameter representing a blob detected. I would like to reproduce the Python behavior in Java, where blobs are defined by a set of points, not one point. Anyone know what's going on?Python:  Python output:  Java:Java output:A mod on the answers.opencv.org forum provided a bit more information ():You are using two different interfaces to the MSER implementation. Python  gives you a wrapped , which exposes its  to Python as :This gives you the nice list of contours interface you are looking for.In contrast Java uses the  wrapper which calls  which is backed by  and uses the standard FeatureDetector interface: a list of KeyPoints.If you want to access the  in Java (in OpenCV 2.4) you will have to wrap it up in JNI.
Python

My goal is to write an interactive variable viewer for IPython, i.e. which allows one to see, say nested dicts/lists as a tree, and drill down (a bit like the console.log in Javascript).I spent a lot of time trying to extract minimalistic code out of the directview example in IPython but still can't get my head around how it all works. My Python's ok but my jQuery experience is quite limited.So I got to stripping down directview.js to the followingThis works when I load the directview.ipynb. However I am still not clear how to make it completely standalone (i.e. not require the directview.py, and pass another callback than the standard  of ). One of the issues is the  which fails when called in a standalone way.I am lost on several aspects:I appreciate that the authors of the IPython notebook have done an incredible job creating such a beautiful front-end using jQuery/websockets, and that creating developer documentation that allows beginners like me to tweak with it is asking much, but if anyone can lend a hand that would be great!I can answer to your second question.  The fact is when JavaScript calls your callback, it makes it so without specifying the context, i.e. without setting  (Pythonistas call it ).  But it's possible to bound a function to  via , which you saw in:
Python

I'm trying to implement a custom scoring function for RidgeClassifierCV in scikit-learn.  This involves passing a custom scoring function as the  when initializing the  object.  I expected the score_func to take in categorical values as input for  and .  Instead, however, floating point values are passed in as  and .  The size of the y vectors is equal to the number of classes times the number of training examples, rather than simply having a y vector with length equivalent to the number of training examples. Can I somehow force categorical predictions to be passed into the custom scoring function, or do I have to deal with the raw weights?  If I do have to deal directly with the raw weights, is the index of the maximum value in a slice of the vector of outputs equivalent to the predicted class?This is a  that has been fixed.
Python

I'd like to insert a couple small graphics (vector graphics but can be made raster if necessary) into the legend of a maplotlib plot.  There would be one graphic per item in the legend.I know I could manually draw the entire legend using  but that looks tedious, and any small change in the figure would require fixing it by hand.Is there any way to include graphics in the label in a call to  or later in the  call?So, the below is a little hacky, but it can get you most of the way there. Note: you need to replace  with the image you want (otherwise you get Grace Hopper for free!). You can also make the image larger than the default by passing the  parameter. This is the hacky way to fix your aspect ratio on the image. Use the  parameter if your images overlap from one series to the next.Here's what it produces:
Python

This is a follow up to . I have updated the setup and tests, and don't want to change the original question too much.The whole story (including scripts etc) is on Short version: while trying to verify the performance claims made in the 'Graph Database' book I came to the following results (querying a random dataset containing n people, with 50 friends each):\"*\": single run only\"*\": single run onlyUsing 1.9.2 on a 64bit ubuntu  I have setup neo4j.properties with these values:and neo4j-wrapper.conf with:My query to neo4j looks like this (using the REST api):Node_auto_index is in place, obviouslyAnd also there is  with same problem.I'm sorry you can't reproduce the results. However, on a MacBook Air (1.8 GHz i7, 4 GB RAM) with a 2 GB heap, GCR cache, but no warming of caches, and no other tuning, with a similarly sized dataset (1 million users, 50 friends per person), I repeatedly get approx 900 ms using the Traversal Framework on 1.9.2:Cypher is slower, but nowhere near as slow as you suggest: approx 3 seconds:Kind regardsianYes, I believe the REST API is significantly slower than the regular bindings and therein lies your performance problem.
Python

I get different results (test accuracy) every time I run the  example from Keras framework ()\nThe code contains  in the top, before any keras imports. It should prevent it from generating different numbers for every run. What am I missing?  UPDATE: How to repro:  UPDATE2: I'm running it on Windows 8.1 with MinGW/msys, module versions:\ntheano 0.7.0\nnumpy 1.8.1\nscipy 0.14.0c1UPDATE3: I narrowed the problem down a bit. If I run the example with GPU (set theano flag device=gpu0) then I get different test accuracy every time, but if I run it on CPU then everything works as expected. My graphics card: NVIDIA GeForce GT 635)Theano's  talks about the difficulties of seeding random variables and why they seed each graph instance with its own random number generator. They also provide  on how to seed all the random number generators. I finally got reproducible results with my code. It's a combination of answers I saw around the web. The first thing is doing what @alex says:Then you have to solve the issue noted by @user2805751 regarding cuDNN by calling your Keras code with the following additional :And finally, you have to patch your Theano installation as per , which basically consists in:This should get you the same results for the same seed.Note that there might be a slowdown. I saw a running time increase of about 10%.I would like to add something to the previous answers. If you use  and you want to get reproducible results for every run, you have toI agree with the previous comment, but reproducible results sometimes needs the same environment(e.g. installed packages, machine characteristics and so on). So that, I recommend to copy your environment to other place in case to have reproducible results. Try to use one of the next technologies:I have trained and tested  kind of neural networks using Keras. I performed non linear regression on noisy speech data. I used the following code to generate random seed : I get the exact same results of  each time I train and test on the same data. 
Python

I am trying to get Oauth working with the Google API using Python. I have tried different oauth libraries such as ,  and  but I cannot get it to work (including the provided examples).For debugging Oauth I use Google's  and I have studied the  and the With some libraries I am struggling with getting a right signature, with other libraries I am struggling with converting the request token to an authorized token. What would really help me if someone can show me a working example for the Google API using one of the above-mentioned libraries. EDIT: My initial question did not lead to any answers so I have added my code. There are two possible causes of this code not working:\n1) Google does not authorize my request token, but not quite sure how to detect this\n2) THe signature for the access token is invalid but then I would like to know which oauth parameters Google is expecting as I am able to generate a proper signature in the first phase.This is written using oauth2.py and for Django hence the HttpResponseRedirect.I have OAuth working in a python App Engine app:The app is running at:This work for me.Have you tried the official gdata python api ?\nIt ships with an oauth client and hides the complexity of oauth calls.\nThis may be the answer. When calling OAuthGetRequestToken you sign the base_string with your consumer_secret followed by an & (ampersand)When calling OAuthGetAccessToken you sign the base_string with your consumer_secret followed by an & (ampersand) followed by token_secret.You would sign the base_string using (consumer_secret + \"&\") for OAuthGetRequestToken and \nyou would sign the base_string using (consumer_secret + \"&\" + token_secret) for OAuthGetAccessTokenTornado has working code for Google oauth. Check it out here. . I 've used it and worked pretty well out of the box. All you need to do is pluck out the class and carefully put it into a django view. PS: Tornado makes use of async module for the user to return. Since you are using django you need to rely on some get variable to identify that a user has just granted access to your application.IIRC Google oauth is not quite following the standard, you  to specify what service you're requesting for (look at the examples provided in the google docs) in the request as an additional parameter, or it won't work.
Python

I am trying to work on a script that manipulates another script in Python, the script to be modified has structure like:I use  to locate the  line number, and I use some code to change the original file with new description string base on the line number. So far so good.Now the only issue is  occasionally is a multi-line string, e.g.orand I only have the line number of the first line, not the following lines. So my one-line replacer would doand the code is broken. I figured that if I know both the lineno of start and end/number of lines of  assignment I could repair my code to handle such situation. How do I get such information with Python standard library?I looked at the other answers; it appears people are doing backflips to get around the problems of computing line numbers, when your real problem is one of modifying the code.   That suggests the baseline machinery is not helping you the way you really need.If you use a , you could avoid a lot of this nonsense.A good PTS will parse your source code to an AST, and then let you apply source-level rewrite rules to modify the AST, and will finally convert the modified AST back into source text.   Generically PTSes accept transformation rules of essentially this form:[A parser that builds an AST is NOT a PTS.  They don't allow rules like this; you can write ad hoc code to hack at the tree, but that's usually pretty awkward.   Not do they do the AST to source text regeneration.](My PTS, see bio, called) DMS is a PTS that could accomplish this.  OP's specific example would be accomplished easily by using the following rewrite rule:The one transformation rule is given an name  to distinguish it from all the other rule we might define.   The rule parameters (e: expression) indicate the pattern will allow an arbitrary expression as defined by the source language.    means the rule maps a statement in the source language, to a statement in the target language; we could use any other syntax category from the Python grammar provided to DMS.  The  used here is a , used to distinguish the syntax of the rule language form the syntax of the subject language.  The second   separates the source pattern  from the target pattern .You'll notice that there is no need to mention line numbers.  The PTS converts the rule surface syntax into corresponding ASTs by actually parsing the patterns with the same parser used to parse the source file.  The ASTs produced for the patterns are used to effect the pattern match/replacement.   Because this is driven from ASTs, the actual layout of the orginal code (spacing, linebreaks, comments) don't affect DMS's ability to match or replace.  Comments aren't a problem for matching because they are attached to tree nodes rather than being tree nodes; they are preserved in the transformed program.  DMS does capture line and precise column information for all tree elements; just not needed to implement transformations. Code layout is also preserved in the output by DMS, using that line/column information. Other PTSes offer generally similar capabilities.As a workaround you can change:to:etc. It is a simple change but indeed ugly code produced.Indeed, the information you need is not stored in the . I don't know the details of what you need, but it looks like you could use the  module from the standard library. The idea is that every logical Python statement is ended by a  token (also it could be a semicolon, but as I understand it is not your case). I tested this approach with such file:And here is what I propose to do:This prints out:This seems to be correct, you could tune this approach depending on what exactly you need.  is more verbose than  but also more flexible. Of course the best approach is to use them both for different parts of your task. I tried this in Python 3.4, but I think it should also work in other versions.My solution takes a different path: When I had to change code in another file I opened the file, found the line and got all the next lines which had a deeper indent than the first and return the line number for the first line which isn't deeper. \nI return None, None if I couldn't find the text I was looking for.\nThis is of course incomplete, but I think it's enough to get you through :)There is a new  library that addresses this well: produces
Python

What is the correct way to work with complex numbers in Cython?I would like to write a pure C loop using a numpy.ndarray of dtype np.complex128. In Cython, the associated C type is defined in \n as so it seems this is just a simple C double complex.However, it's easy to obtain strange behaviors. In particular, with these definitionsthe linecan be compiled by Cython but gcc can not compiled the C code produced (the error is \"testcplx.c:663:25: error: two or more data types in declaration specifiers\" and seems to be due to the line ). This error has already been reported (for example ) but I didn't find any good explanation and/or clean solution.Without inclusion of , there is no error (I guess because the  is then not included).However, there is still a problem since in the html file produced by , the line  is yellow, meaning that it has not been translated into pure C. The corresponding C code is:and the  and  are orange (Python calls).Interestingly, the linedoes not produce any error and is translated into pure C (just ), whereas it is very very similar to the first one.I can avoid the error by using intermediate variables (and it translates into pure C):or simply by casting (but it does not translate into pure C):So what happens? What is the meaning of the compilation error? Is there a clean way to avoid it? Why does the multiplication of a np.complex128_t and np.float64_t seem to involve Python calls?Cython version 0.22 (most recent version in Pypi when the question was asked) and GCC 4.9.2.I created a tiny repository with the example () and a tiny Makefile with 3 targets (, , ) so it is easy to test anything.The simplest way I can find to work around this issue is to simply switch the order of multiplication.If in  I changetoI change from the failing situation to described to one that works correctly.  This scenario is useful as it allows a direct diff of the produced C code.The order of the multiplication changes the translation, meaning that in the failing version the multiplication is attempted via  types, whereas in the working version it is done via  types.  This in turn introduces the typedef line , which is invalid. I am fairly sure this is a cython bug (Update: ).  Although , the response explicitly states (in saying that it is not, in fact, a  bug, but user code error):They conclude that  is a valid type specifier whereas  is not.   has the same type of response - trying to use  on a non fundamental type is outside spec, and the  indicates that  can only be used with ,  and So - we can hack the cython generated C code to test that: replace  with   and verify that it is indeed valid and can make the output code compile.Swapping the multiplication order only highlights the problem that we are told about by the compiler. In the first case, the offending line is the one that says  - it is trying to assign the type   use the keyword  to the type . or  is a valid type, whereas  is not. To see the effect, you can just delete  from that line, or replace it with  or  and the code compiles fine.  The next question is why that line is produced in the first place...This seems to be produced by  in the Cython source code.Why does the order of the multiplication change the code significantly - such that the type  is introduced, and introduced in a way that fails?In the failing instance, the code to implement the multiplication turns  into a  type, does the multiplication on real and imaginary parts and then reassembles the complex number.  In the working version, it does the product directly via the  type using the function I guess this is as simple as the cython code taking its cue for which type to use for the multiplication from the first variable it encounters.  In the first case, it sees a float 64, so produces () C code based on that, whereas in the second, it sees the (double) complex128 type and bases its translation on that.  This explanation is a little hand-wavy and I hope to return to an analysis of it if time allows...A note on this -  that the  for  is , so in this particular case, a fix might consist of modifying  to use  where  is , but this is getting beyond the scope of a SO answer and doesn't present a general solution.Creates this C code from the line `varc128 = varf64 * varc128Creates this C code from the line Which necessitates these extra imports - and the offending line is the one that says  - it is trying to assign the type   the type  to the type 
Python

Assuming we have a polygon coordinates as polygon = [(x1, y1), (x2, y2), ...], the following code displays the polygon:By default it is trying to adjust the aspect ratio so that the polygon (or whatever other diagram) fits inside the window, and automatically changing it so that it fits even after resizing. Which is great in many cases, except when you are trying to estimate visually if the image is distorted. How to fix the aspect ratio to be strictly 1:1? (Not sure if \"aspect ratio\" is the right term here, so in case it is not - I need both X and Y axes to have 1:1 scale, so that (0, 1) on both X and Y takes an exact same amount of screen space. And I need to keep it 1:1 no matter how I resize the window.)Does it help to use:There is, I'm sure, a way to set this directly as part of your plot command, but I don't remember the trick.  To do it after the fact you can use the current axis and set it's aspect ratio with \"set_aspect('equal')\". In your example:I use this all the time and it's from the examples on the matplotlib website.The best thing to use is:As  Saullo Castro said. Because with equal you can't change one axis limit without changing the other so if you want to fit all non squered figures you will have a lot of white space.Better , it works better if you want to modify the axes with  and .
Python

I tried to install python dateutil for my django tastypie but unsuccessful,I downloaded the tar file in c:/python27 and unzipped it,I get the following error msg,This will install  and its dependencies:To get only dateutil:I am not sure if this is different on Windows, but it does not appear you are referencing an actual link (see the  line). Instead, try this:That will (hopefully) get the package you need. Also, see  post for what looks like a similar issue.
Python

Say I have this list:As far as help showed me, there is not a builtin function that returns the last occurrence of a string (like the reverse of ). So basically, how can I find the last occurrence of  in the given list?If you are actually using just single letters like shown in your example, then  would work nicely.  It will return  if 'a' is not in the list.For the general case you could use: It will raise  if  is not in the list.  The slicing here creates a  of the entire list.  That's fine for short lists, but for the case where  is very large, performance can be better with a lazy approach:A one-liner that's like Ignacio's except a little simpler/clearer would beIt seems very clear and Pythonic to me: you're looking for the highest index that contains a matching value. No nexts, lambdas, reverseds or itertools required. Many of the other solutions require iterating over the entire list.  This does not.Edit: In hindsight this seems like unnecessary wizardry.  I'd do something like this instead:I like both  and  answers. However, I think  provides a slightly more readable alternative, lambda notwithstanding. (For Python 3; for Python 2, use  instead of ).This will raise a  exception if the item isn't found; you could catch that and raise a  instead, to make this behave just like .Defined as a function, avoiding the  shortcut:It works for non-chars too. Tested:Use a simple loop:
Python

Is there a way to slice only the first and last item in a list?For example; If this is my list:I  to do this (obviously  is not valid syntax):Some things I have tried:One way:A better way (Doesn't use slicing, but is easier to read):Just thought I'd show how to do this with numpy's fancy indexing:Note that it also supports arbitrary index locations, which the  method would not work for:As DSM points out, you can do something similar with :You can do it like this:What about this?Some people are answering the wrong question, it seems.  You said you want to do:Ie., you want to extract the first and last elements each into separate variables.In this case, the answers by Matthew Adams, pemistahl, and katrielalex are valid.  This is just a compound assignment:But later you state a complication: \"I am splitting it in the same line, and that would have to spend time splitting it twice:\"So in order to avoid two split() calls, you must only operate on the list which results from splitting once.In this case, attempting to do too much in one line is a detriment to clarity and simplicity.  Use a variable to hold the split result:Other responses answered the question of \"how to get a new list, consisting of the first and last elements of a list?\"  They were probably inspired by your title, which mentions slicing, which you actually don't want, according to a careful reading of your question.AFAIK are 3 ways to get a new list with the 0th and last elements of a list:The advantage of the list comprehension approach, is that the set of indices in the tuple can be arbitrary and programmatically generated.Actually, I just figured it out:You can use something like `if you really want to use slicing. The advantage of this is that it cannot give index errors and works with length 1 or 0 lists as well.This isn't a \"slice\", but it is a general solution that doesn't use explicit indexing, and works for the scenario where the sequence in question is anonymous (so you can create and \"slice\" on the same line, without creating twice and indexing twice): You could just inline it as (after  for brevity at time of use):but if you'll be reusing the getter a lot, you can save the work of recreating it (and give it a useful, self-documenting name) by creating it once ahead of time.Thus, for your specific use case, you can replace:with:and  only once without storing the complete  in a persistent name for  checking or double-indexing or the like.Note that  for multiple items returns a , not a , so if you're not just unpacking it to specific names, and need a true , you'd have to wrap the call in the  constructor.Python 3 only answer (that doesn't use slicing or throw away the rest of the , but might be good enough anyway) is use unpacking generalizations to get  and  separate from the middle:The choice of  as the catchall for the \"rest\" of the arguments is arbitrary; they'll be stored in the name  which is often used as a stand-in for \"stuff I don't care about\".Unlike many other solutions, this one will ensure there are at least two elements in the sequence; if there is only one (so  and  would be identical), it will raise an exception ().The answers work for the specific first and last, but some, like myself, may be looking for a solution that can be applied to a more general case in which you can return the top N points from either side of the list (say you have a sorted list and only want the 5 highest or lowest), i came up with the following solution:and an example to return bottom and top 3 numbers from list 1-10:
Python

I was running some dynamic programming code (trying to brute-force disprove the Collatz conjecture =P) and I was using a dict to store the lengths of the chains I had already computed. Obviously, it ran out of memory at some point. Is there any easy way to use some variant of a  which will page parts of itself out to disk when it runs out of room? Obviously it will be slower than an in-memory dict, and it will probably end up eating my hard drive space, but this could apply to other problems that are not so futile.I realized that a disk-based dictionary is pretty much a database, so I manually implemented one using sqlite3, but I didn't do it in any smart way and had it look up every element in the DB one at a time... it was about 300x slower.Is the smartest way to just create my own set of dicts, keeping only one in memory at a time, and paging them out in some efficient manner?Hash-on-disk is generally addressed with Berkeley DB or something similar - several options are listed in the . You can front it with an in-memory cache, but I'd test against native performance first; with operating system caching in place it might come out about the same.The 3rd party  module is also worth taking a look at. It's very similar to shelve in that it is a simple dict-like object, however it can store to various backends (such as file, SVN, and S3), provides optional compression, and is even threadsafe. It's a very handy moduleLast time I was facing a problem like this, I rewrote to use SQLite rather than a dict, and had a massive performance increase. That performance increase was at least partially on account of the database's indexing capabilities; depending on your algorithms, YMMV.A thin wrapper that does SQLite queries in  and  isn't much code to write.The  module may do it; at any rate, it should be simple to test.  Instead of:do:The only catch is that keys to shelves must be strings, so you'll have to replacewith(I'm assuming your keys are just integers, as per your comment to Charles Duffy's post)There's no built-in caching in memory, but your operating system may do that for you anyway.[actually, that's not quite true: you can pass the argument 'writeback=True' on creation.  The intent of this is to make sure storing lists and other mutable things in the shelf works correctly.  But a side-effect is that the whole dictionary is cached in memory.  Since this caused problems for you, it's probably not a good idea :-) ]With a little bit of thought it seems like you could get the  to do what you want.I've read you think shelve is too slow and you tried to hack your own dict using sqlite.Another did this too :It seems pretty efficient (and sebsauvage is a pretty good coder). Maybe you could give it a try ?read answer for this question from GvR ;)\nYou should bring more than one item at a time if there's some heuristic to know which are the most likely items to be retrieved next, and don't forget the indexes like Charles mentions.I did not try it yet but  is promising and has a Python interface.
Python

I'm trying to center a tkinter window. I know I can programatically get the size of the window and the size of the screen and use that to set the geometry, but I'm wondering if there's a simpler way to center the window on the screen.You can try to use the methods  and , which return respectively the width and height (in pixels) of your  instance (window), and with some basic math you can center your window:I am calling  method before retrieving the width and the height of the window in order to ensure that the values returned are accurate.The general approach to centering a window is to calculate the appropriate screen coordinates for the window's top left pixel:  However, this is  sufficient for  centering a tkinter window (on Windows 7 at least);\nbecause the window's width and height returned by  method will not include the outermost frame, with the title and min/max/close buttons.\nIt will also not include a   (with File, Edit, etc.). Fortunately  to find the dimensions of these.Here is the most basic function, which does not consider the aforementioned issue:Alternatives: , First, and foremost, we want to call the window's  method\ndirectly before retrieving any geometry, to ensure that the values returned are accurate.It's important to understand the  used with the  method.\nThe first half is the window's width and height  the outer-frame,\nand the second half is the outer-frame's top left x and y coordinates.There are four methods that will allow us to determine the outer-frame's dimensions.\n will give us the window's top left x coordinate,  the outer-frame.\n will give us the outer-frame's top left x coordinate.\nTheir difference is the outer-frame's width.The difference between  and  will be our title-bar / menu-bar's height.Here is the complete function, in a working example:One way to prevent seeing the window move across the screen is to use\n to make the window fully transparent and then set it to  after the window has been centered. Using  or  later followed by  doesn't seem to work well, for this purpose, on Windows 7. Note that I use  as a trick to activate the window.Tk provides a helper function that can do this as , but I don't believe it has been exposed as a wrapped method in Tkinter. You would center a widget using the following:This function should deal with multiple displays correctly as well. It also has options to center over another widget or relative to the pointer (used for placing popup menus), so that they don't fall off the screen.I use frame and expand option. Very simple. I want some buttons in the middle of screen. Resize window and button stay in the middle. This is my solution.
Python

I tried using , but some numbers were the same. Is there a method/module to create a list unique random numbers?This will return a list of 10 numbers selected from the range 0 to 99, without duplicates.With reference to your specific code example, you probably want to read all the lines from the file  and then select random lines from the saved list in memory. For example:This way, you only need to actually read from the file once, before your loop. It's much more efficient to do this than to seek back to the start of the file and call  again for each loop iteration.Why not create a list of 1..100 and shuffle it with  algorithm?'s works (+1), but it could become problematic with memory if the sample size is small, but the population is huge (eg ). To fix that, I would go with this:If the list of N numbers from 1 to N is randomly generated, then yes, there is a possibility that some numbers may be repeated.If you want a list of numbers from 1 to N in a random order, fill an array with inegeters 1 to N, and then use a .: as @Greg points out: since this is Python, use You can use the  function from the  module like this:Note here that the shuffle method doesn't return any list as one may expect, it only shuffle the list passed by reference.If you need to sample extremely large numbers, you cannot use  because it throws:Also, if  cannot produce the number of items you want due to the range being too smallit throws:This function resolves both problems:Usage with extremely large numbers:Sample result:Usage where the range is smaller than the number of requested items:Sample result:It also works with with negative ranges and steps:Sample results:If you wish to ensure that the numbers being added are unique, you could use a if using 2.7 or greater, or import the sets module if not.As others have mentioned, this means the numbers are not truly random.From the CLI in win xp: In Canada we have the 6/49 Lotto. I just wrap the above code in lotto.bat and run  or just .Because  often repeats a number, I use  with  and then shorten it to a length of 6.Occasionally if a number repeats more than 2 times the resulting list length will be less than 6.EDIT: However,  is the correct way to go.
Python

I'm looking for a clean way to use variables within a Python multiline string. Say I wanted to do the followingIn a way I'm looking to see if there is a Perl like $ to indicate a variable in the Python syntax.If not - what is the cleanest way I can achieve this multiline string with variables.The common way is the  function:You can also pass a dictionary with variables:The closest thing to what you asked (in terms of syntax) are . For example:I should add though that the  function is more common because it's readily available and it does not require an import line.You probably could have answered this one with a little bit of Googling, but here's the code you were looking for. Note that I corrected your syntax on strings.Some reading to learn more about Python string formatting:That what you want:A dictionary can be passed to , each key name will become a variable for each associated value.\nAlso a list can be passed to , the index number of each value will be used as variables in this case.\nBoth solutions above will output the same:I'm will go there\nI will go now\ngreatI think that the answer above forgot the {}:   
Python

I have two numpy arrays that define the x and y axes of a grid.  For example:I'd like to generate the Cartesian product of these arrays to generate:In a way that's not terribly inefficient since I need to do this many times in a loop.  I'm assuming that converting them to a Python list and using  and back to a numpy array is not the most efficient form.See  for a general solution for computing the Cartesian product of N arrays.Another approach that tests a bit faster for me is to use  + : I did a few tests; see the end of this post for a very simple, general solution that performs very well, if not always optimally, for all inputs. Definitions: is a tad faster for small arrays:And a bit faster yet for large arrays:For smaller arrays it's also faster than :But very large arrays, it doesn't do quite as well:Then there's a generalized version that should work on arbitrary-dimensional products. This is as fast or faster than  for all inputs that I tried:It beats both  and  for very large products:Finally, here's a  simplified approach that performs similarly to the above -- sometimes a bit faster, sometimes a bit slower, but never different by more than 50%. (This is based on ideas from ):You can just do normal list comprehension in pythonwhich should give youMore generally, if you have two 2d numpy arrays a and b, and you want to concatenate every row of a to every row of b (A cartesian product of rows, kind of like a join in a database), you can use this method:
Python

can anyone please explain what is wrong with this code?The output I got is:but I expected it to print  instead.When you say  you are stripping the last element. Instead of slicing the string, you can apply  and  on the string object itself like thisSo the whole program becomes like this    Even simpler, with a conditional expression, like thisYou are testing against the string :Note how the last character, the , is not part of the output of the slice.I think you wanted just to test against the last character; use  to slice for just the last element.However, there is no need to slice here; just use  and  directly.You should either useorbut not slice and check startswith/endswith together, otherwise you'll slice off what you're looking for...When you set a string variable, it doesn't save quotes of it, they are a part of its definition.\nso you don't need to use :1
Python

I'm trying to remove an item from a list in python:But it doesn't remove  item. Any ideas?You can't remove items from a list while iterating over it.  It's much easier to build a new list based on the old one:hymloth and sven's answers work, but they do not modify the list (the create a new one). If you need the object modification you need to assign to a slice:However, for large lists in which you need to remove few elements, this is memory consuming, but it runs in O(n). glglgl's answer suffers from O(n\u00b2) complexity, because  is O(n). Depending on the structure of your data, you may prefer noting the indexes of the elements to remove and using the  keywork to remove by index:Now  is also O(n) because you need to copy all elements after index  (a list is a vector), so you'll need to test this against your data. Still this should be faster than using  because you don't pay for the cost of the search step of remove, and the copy step cost is the same in both cases. [edit] Very nice in-place, O(n) version with limited memory requirements, courtesy of . It uses  which was introduced in python 2.7:This stems from the fact that on deletion, the iteration skips one element as it semms only to work on the index.Workaround could be:The already-mentioned list comprehension approach is probably your best bet. But if you absolutely want to do it in-place (for example if  is really large), here's one way:
Python

Python Version 2.7I am looking for documentation  examples on how to extract text from a PDF file using PDFMiner with Python.It looks like PDFMiner updated their API and all the relevant examples I have found contain outdated code(classes and methods have changed).  The libraries I have found that make the task of extracting text from a PDF file easier are using the old PDFMiner syntax so I'm not sure how to do this.As it is, I'm just looking at source-code to see if I can figure it out. Here is a working example of extracting text from a PDF file using the current version of PDFMiner(September 2016) PDFMiner's structure changed recently, so this should work for extracting text from the PDF files. : Still working as of the 1st of February of 2017.terrific answer from DuckPuncher, this is for Python3:
Python

I have a list containing URLs with escaped characters in them. Those characters have been set by  when it recovers the html page:Is there a way to transform them back to their unescaped form in python?P.S.: The URLs are encoded in utf-8And then just decode.And if you are using  you could use:or You can use 
Python

I am using Python to write chunks of text to files in a single operation:If the script is interrupted so a file write does not complete I want to have no file rather than a partially complete file. Can this be done?Write data to a temporary file and when data has been successfully written, rename the file to the correct destination file e.gAccording to doc alsoNote: A simple snippet that implements atomic writing using Python .or even reading and writing to and from the same file:using two simple context managersThere is a simple AtomicFile helper: I\u2019m using this code to atomically replace/write a file:Usage:It\u2019s based on .Since it is very easy to mess up with the details, I recommend using a tiny library for that. The advantage of a library is that it takes care all these nitty-gritty details, and is being  by a community.One such library is  by  which even has proper Windows support:From the README:
Python

I am trying to install and use the Evernote module () . I ran  and it says that the installation worked.I can confirm that the evernote module exists in . However, when I try to run  I get the following error:This is the contents of my :I am having this same problem with other modules installed with . Help?EDIT: I am a super newbie and have not edited that  file. EDIT:  Outputs the following: I seemed to have made progress towards a solution by adding  to my  file. However, now when I run  it tries to import oauth2, which fails with the same error. The ouath2 module is present in the module directory. is the executable for the python that comes with OS X.  is a location for user-installed programs only, possibly from Python.org or Homebrew. So you're mixing different Python installs, and changing the python path is only a partial workaround for different packages being installed for different installations.In order to make sure you use the  associated with a particular python, you can run , or go look at what the  on your path is, or is symlinked to.I figured it out! I added this line:to my  and now I can import modules stored in that directory. Thanks for everyone who  answered.None of this helped me with my similar problem. Instead, I had to fix the newly installed files  to be able to import. This is usually an obvious thing, but not so much when you use  when installing module/packages.I faced similar problem,its related to /usr/local/lib/python2.7/site-packages had no read or write permission for group and other, and they were owned by root. This means that only the root user could access them. Try this:Simply just type in terminal:and type  (whatever you like) or type  (whatever you like)  (whatever you like).
Python

I have made a custom profile model which looks like this:But when I run , I get:I also tried:But it gives the same error. Where I'm wrong and how to fix this?Change this:to this:Exactly in Django 1.5 the  setting , allowing using a custom user model with auth system.If you're writing an app that's intended to work with projects on Django 1.5 through 1.10 and later, this is the proper way to reference user model (which can now be different from ):In case you're writing a reusable app supporting Django 1.4 as well, then you should probably determine what reference to use by checking Django version, perhaps like this:
Python

I'm developing a website (in Django) that uses OpenID to authenticate users. As I'm currently only running on my local machine I can't authenticate using one of the OpenID providers on the web. So I figure I need to run a local OpenID server that simply lets me type in a username and then passes that back to my main app.Does such an OpenID dev server exist? Is this the best way to go about it?The libraries at  ship with examples that are sufficient to run a local test provider.  Look in the examples/djopenid/ directory of the python-openid source distribution.  Running that will give you an instance of .I have no problems testing with . I thought there would be a problem testing on my local machine but it just worked. (I'm using ASP.NET with DotNetOpenId library).The 'realm' and return url must contain the port number like ''.I assume it works OK because the provider does a client side redirect.I'm also looking into this.  I too am working on a Django project that might utilize Open Id.  For references, check out:Hopefully someone here has tackled this issue.I'm using  to authenticate at StackOverflow right now. Generates a standard HTTP auth realm and works perfectly. It should be exactly what you need.You could probably use the django OpenID library to write a provider to test against. Have one that always authenticates and one that always fails.Why not run an OpenID provider from your local machine?If you are a .Net developer there is an OpenID provider library for .Net at . This uses the standard .Net profile provider mechanism and wraps it with an OpenID layer. We are using it to add OpenID to our custom authentication engine.If you are working in another language/platform there are a number of OpenID implementation avalaiable from the OpenID community site .You shouldn't be having trouble developing against your own machine. What error are you getting?An OpenID provider will ask you to give your site (in this case  or similar) access to your identity. If you click ok then it will redirect you that url. I've never had problems with  and I expect that  will work too.If you're having problems developing locally I suggest that the problem you're having is unrelated to the url being localhost, but something else. Without an error message or problem description it's impossible to say more.: It turns out that Yahoo do things differently to other OpenID providers that I've come across and disallow redirections to ip address, sites without a correct tld in their domain name and those that run on ports other than 80 or 443. See  for a post from a Yahoo developer on this subject.  offers a work around, but I would suggest that for development myopenid.com would be far simpler than working around Yahoo, or running your own provider.
Python

I'm trying to learn a little about python scripting in GVim, but I'm having trouble with starting. Elementary things, really.Are there any resources / tutorials concerting python scripting in Vim out there ? Simple examples which show the basic principles, would be welcomed also.Here is all I know of in terms of such docs::help python-vim is a good start. The best vim resource is always at your fingertips and the sooner you get used to referring to it the better you will get at vim overall.I got better at searching vim help with this..also :he vim-script-intro I'd also recommend looking straight at the source of existing plugins that do something similar to what you want to do. That way you cut out the middle man and dont have to deal with blog ads and other distractions.Have you checked out ?  It is an excellent read.vim 7.0 and above can be compiled with the  flag, which gives vim Python support.  This is a (albeit, somewhat extreme) path to getting the language support you want. Refer to the  chapter in .
Python

Look at all those backends!  Do I need to care which backend is in use?  e.g. if I develop and test my stuff using only  backend, and someone else using my code might be using  backend on their system, might my stuff break for them in a way that I won't have noticed - or are all backends required to more or less \"work\" the same way? The backend mainly matters if you're embedding matplotlib in an application, in which case you need to use a backend (GTK, Qt, TkInter, WxWindows) which matches the toolkit you're using to build your application. If you're also using matplotlib in a simple interactive way, you'll also want to use a backend which matches what is available on your machine (GTK if you're running Gnome, Qt if you're running KDE, etc) (although most libs are already installed on most machines)The drawing layer part of the backend (Cairo, Agg...) also matters in terms of functionalities: you can choose it depending on what that layer provides compared to what your application needs (anti aliasing, alpha channel, export formats...). So if you develop and test using TkAgg and other people run with e.g. TkCairo, some things might not work. OTOH, running with QtAgg would certainly work in a very similar way as long as you stick to the matplotlib API and don't reach in the wrapped toolkit layer. 
Python

I recently started learning . I went through the tutorial, read some introductory articles, so far so good.Now I want to use it for Python development. From what I understand, there are two separate Python modes for Emacs: python-mode.el, which is part of the Python project; and python.el, which is part of Emacs 22.I read all information I could find but most of it seems fairly outdated and I'm still confused. The questions:Relevant links:If you are using GNU Emacs 21 or before, or XEmacs, use python-mode.el. The GNU Emacs 22 python.el won't work on them. On GNU Emacs 22, python.el does work, and ties in better with GNU Emacs's own symbol parsing and completion, ElDoc, etc. I use XEmacs myself, so I don't use it, and I have heard people complain that it didn't work very nicely in the past, but there are updates available that fix some of the issues (for instance, on the emacswiki page you link), and you would hope some were integrated upstream by now. If I were the GNU Emacs kind, I would use python.el until I found specific reasons not to.The python-mode.el's single biggest problem as far as I've seen is that it doesn't quite understand triple-quoted strings. It treats them as single-quoted, meaning that a single quote inside a triple-quoted string will throw off the syntax highlighting: it'll think the string has ended there. You may also need to change your auto-mode-alist to turn on python-mode for .py files; I don't remember if that's still the case but my init.el has been setting auto-mode-alist for many years now.As for other addons, nothing I would consider 'essential'. XEmacs's func-menu is sometimes useful, it gives you a little function/class browser menu for the current file. I don't remember if GNU Emacs has anything similar. I have a rst-mode for reStructuredText editing, as that's used in some projects. Tying into whatever VC you use, if any, may be useful to you, but there is builtin support for most and easily downloaded .el files for the others. has a description of how to get Python code completion in Emacs.\n is a way to get Rope to work in emacs.  I haven't had extensive experience with either, but they're worth looking into.Given the number of times I have several open buffers all called , I consider the  library essential for python development.Pyflakes also aids productivity.
Python

I'm making a simple learning simulation, where there are multiple organisms on screen. They're supposed to learn how to eat, using their simple neural networks. They have 4 neurons, and each neuron activates movement in one direction (it's a 2D plane viewed from the bird's perspective, so there are only four directions, thus, four outputs are required). Their only input are four \"eyes\". Only one eye can be active at the time, and it basically serves as a pointer to the nearest object (either a green food block, or another organism).Thus, the network can be imagined like this:\nAnd an organism looks like this (both in theory and the actual simulation, where they really are red blocks with their eyes around them):And this is how it all looks (this is an old version, where eyes still didn't work, but it's similar):Now that I have described my general idea, let me get to the heart of the problem...But, there is a big problem. I think that this isn't a good approach, because they don't actually learn anything! Only those that had their initial weights randomly set to be beneficial will get a chance of eating something, and then only them will have their weights strengthened! What about those that had their connections set up badly? They'll just die, not learn.How do I avoid this? The only solution that comes to mind is to randomly increase/decrease the weights, so that eventually, someone will get the right configuration, and eat something by chance. But I find this solution to be very crude and ugly. Do you have any ideas?\nThank you for your answers! Every single one of them was very useful, some were just more relevant. I have decided to use the following approach:This is similar to issues with trying to find a , where it's easy to get stuck in a local minimum.  Consider trying to find the global minimum for the profile below: you place the ball in different places and follow it as it rolls down the hill to the minimum, but depending on where you place it, you may get stuck in a local dip.  The general solutions to this are to fluctuate the parameters (, weights, in this case) more vigorously (and usually reduce the size of the fluctuations as you progress the simulation -- like in simulated annealing), or just realize that a bunch of the starting points aren't going to go anywhere interesting.As mentioned by Mika Fischer, this sounds similar to artificial life problems, so that's one avenue you could look at.It also sounds a bit like you're trying to reinvent . I would recommend reading through , which is freely available in HTML form at that website, or purchasable in dead tree format. Example code and solutions are also provided on that page. Use of neural networks (and other function approximators) and planning techniques is discussed later in the book, so don't get discouraged if the initial stuff seems too basic or non-applicable to your problem.How do you want it to learn? You don't like the fact that randomly seeded organisms either die off or prosper, but the only time you provide feedback into your organism is if they randomly get food. Let's model this as hot and cold. Currently, everything feeds back \"cold\" except when the organism is right on top of food. So the only opportunity to learn is accidentally running over food. You can tighten this loop to provide more continuous feedback if you desire. Feedback warmer if there is movement toward food, cold if moving away.Now, the downside of this is that there is no input for anything else. You've only got a food-seeker learning technique. If you want your organisms to find a balance between hunger and something else (say, overcrowding avoidance, mating, etc), the whole mechanism probably needs to be re-thought.There are several algorithms that can be used to optimize the weights in a neural network, the most common of which is the . From reading your question I gather that you are trying to build neural network bots that will search for food. The way to achieve this with backpropogation would be to have an initial learning period, where the weights are initially randomly set (as you're doing) and gradually refined using the backpropogation algorithm until they reach a performance level you're happy with. At that point you can stop them learning and allow them to frolic freely in flatland. However I think there might be a few issues with your network design. Firstly, if there is only 1 eye active at any time, it would make more sense to have just one input node and keep track of orientation some other way (if I'm understanding that correctly). Simply, if there is only one active eye and four possible actions (forward, back, left, right) then the inputs from the inactive eyes (presumably zero) would have no bearing on the output decision, in fact I suspect the weights for each input to all outputs would converge, essentially duplicating the same function. Moreover, it needlessly increases the complexity of the network and increases the learning time. Secondly, you don't need that many output neurons to represent all possible actions. As you have it described there, your output would be {1,0,0,0} = right, {0,1,0,0} = left and so on. Depending on the type of neuron modeled, this can be done with 2 or even 1 output neuron. If using a binary neuron (each output is either 1 or 0), then do something like {0,0} = back, {1,1} = forward, {1,0} = left, {0,1} = right. Using a sigmoidal function neuron (the output can be a real number from 0..1), you could do {0} = back, {0.33} = left, {0.66} = right, {1} = forward. I can see a bunch of potential problems.First and foremost, I'm not clear about the algorithm that updates your weights.  I like the 1% decrease as a concept-- it looks like you're trying to discount distant memories, which is good in principle-- but the rest probably isn't sufficient.  You need to look at some of the standard update algorithms like backpropagation, but that's just a start, because.......You're only giving your network credit for the last stage of eating the food.  It doesn't seem like there's any direct mechanism for getting your network incrementally closer to the food, or to clumps of food.  Even taking the directionality of the eyes at face value, your eyes are very simple, and there's not much long term memory.Also, if your network diagram is accurate, it's probably not sufficient.  You really want to have a hidden layer (at least one) between the sensors and the actuators, if you use something related to backpropagation.  There are detailed mathematics behind that statement, but it boils down to, \"The hidden layers will allow good solutions of more problems.\"Now, notice that a lot of my comments are talking about the architecture of the network, but only in general terms without saying concretely, \"This will work,\" or \"that will work.\"  That's because I don't know either (although I think Kwatford's suggestion of reinforcement learning is a very good one.)  Sometimes, you can evolve the network parameters as well as the network instances.  One such technique is Neuroevolution of Augmenting Topologies, or \"NEAT\".  Might be worth a look. I think a more complex example of what you're doing is presented by .You can also see the Google Tech Talks presentation from 2007:  However, the fundamental idea is to take an evolutionary approach within your system: use small random mutations combined with genetic cross-over (as the main form of diversification) and select individuals which are \"better\" suited to survive the environment.
Python

I want to change the value of the variable declared outside the loop within a loop. But always changing, it keeps the initial value outside the loop.This renders:So the only (bad) solution  have found so far was this:This renders:But, its is very ugly! Is there another more elegant solution?Try also dictionary-based approach. It seems to be less ugly.This also renders:You could do this to clean up the template codeAnd in the server code useThis could be generalized to the followingAnd in the server code use
Python

I am just wondering how come the code above doesn't really print \"you exited\". What am I doing wrong? if so, may someone point me out the correct way to exit gracefully? (I am not referring to process.terminate or kill)The reason you are not seeing this happen is because you are not communicating with the subprocess.  You are trying to use a local variable (local to the parent process) to signal to the child that it should shutdown.Take a look at the information on .  You need to setup a signal of some sort that can be referenced in both processes.  Once you have this you should be able to flick the switch in the parent process and wait for the child to die.Try the following code:
Python

I'm drawing a legend on an axes object in matplotlib but the default positioning which claims to place it in a smart place doesn't seem to work.  Ideally, I'd like to have the legend be draggable by the user.  How can this be done?Note: This is now built into matplotlibwill work as expectedWell, I found bits and pieces of the solution scattered among mailing lists. I've come up with a nice modular chunk of code that you can drop in and use... here it is:...and in your code...I emailed the Matplotlib-users group and John Hunter was kind enough to add my solution it to SVN HEAD.I hope this is helpful to people working with matplotlib.In newer versions of Matplotlib (v1.0.1), this is built-in.If you are using matplotlib interactively (for example, in IPython's pylab mode).
Python

I have a camera that will be stationary, pointed at an indoors area. People will walk past the camera, within about 5 meters of it. Using , I want to detect individuals walking past - my ideal return is an array of detected individuals, with bounding rectangles.I've looked at several of the built-in samples:Is anyone able to provide guidance or samples for doing this - preferably in ?The latest SVN version of OpenCV contains an (undocumented) implementation of HOG-based pedestrian detection.  It even comes with a pre-trained detector and a python wrapper.  The basic usage is as follows:So instead of tracking, you might just run the detector in each frame and use its output directly.See  for the implementation and  for a more complete python example (both in the OpenCV sources).Nick,What you are looking for is not people detection, but motion detection. If you tell us a lot more about what you are trying to solve/do, we can answer better. \nAnyway, there are many ways to do motion detection depending on what you are going to do with the results. Simplest one would be differencing followed by thresholding while a complex one could be proper background modeling -> foreground subtraction -> morphological ops -> connected component analysis, followed by blob analysis if required. Download the opencv code and look in samples directory. You might see what you are looking for. Also, there is an Oreilly book on OCV.Hope this helps,\nNand    This is clearly a non-trivial task. You'll have to look into scientific publications for inspiration ( is your friend here). Here's a paper about human detection and tracking: This is similar to a project we did as part of a Computer Vision course, and I can tell you right now that it is a hard problem to get right.You could use foreground/background segmentation, find all blobs and then decide that they are a person. The problem is that it will not work very well since people tend to go together, go past each other and so on, so a blob might very well consist of two persons and then you will see that blob splitting and merging as they walk along.You will need some method of discriminating between multiple persons in one blob. This is not a problem I expect anyone being able to answer in a single SO-post.My advice is to dive into the available research and see if you can find anything there. The problem is not unsolvavble considering that there exists products which do this: Autoliv has a product to detect pedestrians using an IR-camera on a car, and I have seen other products which deal with counting customers entering and exiting stores.
Python

I am implementing a command line program which has interface like this:I have gone through the . I can implement  as optional argument using  in . And the  using .From the documentation it seems I can have only one sub-command. But as you can see I have to implement one or more sub-commands. What is the best way to parse such command line arguments useing ?@mgilson has a nice  to this question. But problem with splitting sys.argv myself is that i lose all the nice help message Argparse generates for the user. So i ended up doing this:Now after first parse all chained commands are stored in . I reparse it while it is not empty to get all the chained commands and create separate namespaces for them. And i get nicer usage string that argparse generates.I came up with the same qustion, and it seems i have got a better answer.the solution is we shall not simply nest subparser with anothor subparser, but we can add subparser following with a parser fllowing anothor subparser.Code tell you how: returns a Namespace and a list of unknown strings.  This is similar to the  in the checked answer.produces:An alternative loop would give each subparser its own namespace.  This allows overlap in positionals names.You can always split up the command-line yourself (split  on your command names), and then only pass the portion corresponding to the particular command to  -- You can even use the same  using the namespace keyword if you want.    Grouping the commandline is easy with :You could try .  This is an extension to argparse with explicit support for subcommands.Improving on the answer by @mgilson, I wrote a small parsing method which splits argv into parts and puts values of arguments of commands into hierarchy of namespaces:It behaves properly, providing nice argparse help:For :For :And creates a hierarchy of namespaces containing the argument values:you can use the package optparse
Python

The background:  I'm building a trie to represent a dictionary, using a minimal construction algorithm.  The input list is 4.3M utf-8 strings, sorted lexicographically.  The resulting graph is acyclic and has a maximum depth of 638 nodes.  The first line of my script sets the recursion limit to 1100 via .The problem:  I'd like to be able to serialize my trie to disk, so I can load it into memory without having to rebuild from scratch (roughly 22 minutes).  I have tried both  and , with both the text and binary protocols.  Each time, I get a stack-trace that looks like the following:My data structures are relatively simple:   contains a reference to a start state, and defines some methods.   contains a boolean field, a string field, and a dictionary mapping from label to state.I'm not very familiar with the inner workings of  - does my max recursion depth need to be greater/equal n times the depth of the trie for some n?  Or could this be caused by something else I'm unaware of?Update:  Setting the recursion depth to 3000 didn't help, so this avenue doesn't look promising.Update 2:  You guys were right; I was being short-sighted in assuming that pickle would use a small nesting depth due to default recursion limitations.  10,000 did the trick.From :Although your trie implementation may be simple, it uses recursion and can lead to issues when converting to a persistent data structure.  My recommendation would be continue raising the recursion limit to see if there is an upper bound for the data you are working with and the trie implementation you are using.  Other then that, you can try changing your tree implementation to be \"less recursive\", if possible, or write  that has data persistence built-in (use pickles and  in your implementation).  Hope that helpsPickle does need to recursively walk your trie. If Pickle is using just 5 levels of function calls to do the work your trie of depth 638 will need the level set to more than 3000.Try a much bigger number, the recursion limit is really just there to protect users from having to wait too long if the recursion falls in an infinite hole.Pickle handles cycles ok, so it doesn't matter even if your trie had a cycle in thereDouble-check that your structure is indeed acyclic.You could try bumping up the limit even further. There's a hard maximum that's platform dependent, but trying 50000 would be reasonable.Also try pickling a trivially small version of your trie. If pickle dies even though it's only storing a couple three-letter words, then you know there's some fundamental problem with your trie and not pickle. But if it only happens when you try storing 10k words, then it might be the fault of a platform limitation in pickle.If you use just , you can still segfault if you reach the maximum stack size allowed by the Linux kernel.This value can be increased with  as mentioned at: See also: The default maximum value for me is 8Mb.Tested on Ubuntu 16.10, Python 2.7.12.
Python

Whats a simple code that does parallel processing in python 2.7? All the examples Ive found online are convoluted and include unnecessary codes.how would i do a simple brute force integer factoring program where I can factor 1 integer on each core (4)? my real program probably only needs 2 cores, and need to share information.I know that parallel-python and other libraries exist, but i want to keep the number of libraries used to a minimum, thus I want to use the  and/or  libraries, since they come with pythonA good simple way to start with parallel processing in python is just the pool mapping in mutiprocessing -- its like the usual python maps but individual function calls are spread out over the different number of processes.Factoring is a nice example of this - you can brute-force check all the divisions spreading out over all available tasks:This gives me is the simplest map/reduce implementation that I've found. Also, it's very light on dependencies - it's a single file and does everything with standard library.I agree that using  from  is probably the best route if you want to stay within the standard library.  If you are interested in doing other types of parallel processing, but not learning anything new (i.e. still using the same interface as ), then you could try , which provides several forms of parallel maps and has pretty much the same interface as  does.Also,  has a sister package with the same interface, called , which runs , but provides it with parallel maps that run in MPI and can be run using several schedulers.One other advantage is that  comes with a much better serializer than you can get in standard python, so it's much more capable than  at serializing a range of functions and other things.  And you can do everything from the interpreter.Get the code here: 
Python

When saving a form I am getting this error:\n\"\" needs to have a value for field \"surveythread\" before this many-to-many relationship can be used.Models.py:views.py:forms.pyError Message:Traceback:I'm new to Django and Python. I can post the debug trace or migration file if needed, but I have a feeling it's a simple fix. Obviously the point is I want to save multiple survey thread for each survey result.Thanks!Ok, the code is slightly messy, I'm sure you'll be better off . Seems to me the problem actually is the line:because  object hasn't been written to the database yet, so accessing it's  ManyToMany field can yield problems. If you want to copy the same set of surveys from   to  you should do it iterating over them like this:If this yields the same error, then try to do  first and later copy the items:Your code is likely to remain like this:I can see you have a  to persist the object, so try to accommodate the code to make use of it. If the first version of my answer worked then you'll be fine with the  at the end, if the second is the one who worked, then you'll have to adjust the code a little to stick to the  value.Hope this helps!In this part of the code in , you're setting the  field on the  object to , yet it's not allowed to be  according to your :You have to set  to a  object before you can save it, or allow it to be  in the model.I think you want to change it to say:
Python

There are two (three, but I'm not counting , as its not \"official\") ways to define a persisting object with :I can see that while using the mapper objects, I separate completely the ORM definition from the business logic, while using the declarative syntax, whenever I modify the business logic class, I can edit right there the database class (which ideally should be edited little).What I'm not completely sure, is which approach is more maintainable for a business application?I haven't been able to find a comparative between the two mapping methods, to be able to decide which one is a better fit for my project.I'm leaning towards using the \"normal\" way (i.e. not the declarative extension) as it allows me to \"hide\", and keep out of the business view all the ORM logic, but I'd like to hear compelling arguments for both approaches.\"What I'm not completely sure, is which approach is more maintainable for a business application?\"Can't be answered in general.However, consider this.The Django ORM is strictly declarative -- and people like that.SQLAlchemy does several things, not all of which are relevant to all problems.The fundamental question is \"Do you want to see and touch the SQL?\"If you think that touching the SQL makes things more \"maintainable\", then you have to use explicit mappings.If you think that concealing the SQL makes things more \"maintainable\", then you have to use declarative style.In our team we settled on declarative syntax.Rationale:Regarding \"keeping out ORM from business view\": in reality your  class, defined in a \"normal\" way, gets seriously monkey-patched by SA when  function has its way with it. IMHO, declarative way is more honest because it screams: \"this class is used in ORM scenarios, and may not be treated just as you would treat your simple non-ORM objects\".I've found that using mapper objects are much simpler then declarative syntax if you use  to version your database schema (and this is a must-have for a business application from my point of view). If you are using mapper objects you can simply copy/paste your table declarations to migration versions, and use simple api to modify tables in the database. Declarative syntax makes this harder because you have to filter away all helper functions from your class definitions after copying them to the migration version.Also, it seems to me that complex relations between tables are expressed more clearly with mapper objects syntax, but this may be subjective.
Python

I'm trying to get the post data in flaskI'm sending the data \"personId\" via POST in RESTClient. But i'm not getting the result. \nIs there an error in the code? If so how do I get specific data when the request data is via POST.I'm new to flask, so can anybody give a solution to this?You want to  your  value; printing it to the console won't help in a web application:The parenthesis around  are meaningless noise, btw, they are not needed in Python and are in this case ignored by the parser.I'm assuming you are doing something meaningful with the  value in the view; otherwise using  on the value is a little pointless.You can also use the  to have the value converted for you:Now  will be set to an integer,   if the field is not present in the form or cannot be converted to an integer.
Python

I am starting with multi-threads in python (or at least it is possible that my script creates multiple threads). would this algorithm be the right usage of a Mutex? I haven't tested this code yet and it probably won't even work. I just want processData to run in a thread (one at time) and the main while loop to keep running, even if there is a thread in queue.  Edit: re-reading my code I can see that it is grossly wrong. but hey, that's why I am here asking for help.I don't know why you're using the Window's Mutex instead of Python's.  Using the Python methods, this is pretty simple:But note, because of the architecture of CPython (namely the ) you'll effectively only have one thread running at a time anyway--this is fine if a number of them are I/O bound, although you'll want to release the lock as much as possible so the I/O bound thread doesn't block other threads from running.An alternative, for Python 2.6 and later, is to use Python's  package.  It mirrors the  package, but will create entirely new processes which  run simultaneously.  It's trivial to update your example:This is the solution I came up with: Output:You have to unlock your Mutex at sometime...
Python

I want to remove any brackets from a string. Why doesn't this work properly?I did a time test here, using each method 100000 times in a loop.  The results surprised me.  (The results still surprise me after editing them in response to valid criticism in the comments.)Here's the script:Here are the results:Results on other runs follow a similar pattern.  If speed is not the primary concern, however, I still think  is not the most readable; the other three are more obvious, though slower to varying degrees.Because that's not what  does. It removes leading and trailing characters that are present in the argument, but not those characters in the middle of the string.You could do:or:or maybe use a regex: with table=None works fine.Because  only strips trailing and leading characters, based on what you provided. I suggest: only strips characters from the very front and back of the string.To delete a list of characters, you could use the string's  method:
Python

Is this possible? Doesn't have to be in place, just looking for a way to reverse a tuple so I can iterate on it backwards.There are two idiomatic ways to do this:or Since tuples are immutable, there is no way to reverse a tuple in-place.\nBuilding on @lvc's comment, the iterator returned by  would be equivalent toi.e. it relies on the sequence having a known length to avoid having to actually reverse the tuple.As to which is more efficient, i'd suspect it'd be the  if you are using all of it and the tuple is small, and  when the tuple is large, but performance in python is often surprising so measure it!You can use the  builtin function.If you just want to iterate over the tuple, you can just use the iterator returned by  directly without converting it into a tuple again.Similar to the way you would reverse a list, i.e. s[::-1]and
Python

Let's say I have this number .\nHow do I refer to it as to an unsigned variable?\nSomething like  in C.:then you just need to add  to the negative value.For example, apply this to -1:Assumption #1 means you want -1 to be viewed as a solid string of 1 bits, and assumption #2 means you want 32 of them.Nobody but you can say what your hidden assumptions are, though.  If, for example, you have 1's-complement representations in mind, then you need to apply the  prefix operator instead.  Python integers work hard to give the illusion of using an infinitely wide 2's complement representation (like regular 2's complement, but with an infinite number of \"sign bits\").And to duplicate what the platform C compiler does, you can use the  module:C's  happens to be 4 bytes on the box that ran this sample.To get the value equivalent to your C cast, just bitwise and with the appropriate mask. e.g. if  is 32 bit:or if it is 64 bit:Do be aware though that although that gives you the value you would have in C, it is still a signed value, so any subsequent calculations may give a negative result and you'll have to continue to apply the mask to simulate a 32 or 64 bit calculation.Python doesn't have builtin unsigned types.  You can use mathematical operations to compute a  int representing the value you would get in C, but there is no \"unsigned value\" of a Python int.  The Python int is an abstraction of an integer value, not a direct access to a fixed-byte-size integer.
Python

I am studying python, and although I think I get the whole concept and notion of Python, today I stumbled upon a piece of code that I did not fully understand:Say I have a class that is supposed to define Circles but lacks a body:Since I have not defined any attributes, how can I do this:The weird part is that Python accepts the above statement. I don't understand why Python doesn't raise an . I do understand that via  I just bind variables to objects whenever I want, but shouldn't an attribute  exist in the  class to allow me to do this?: Lots of wonderful information in your answers!  It's a pity I only get to mark one as an answer.A leading principle is that . That is, you never declare \"this class has a method foo\" or \"instances of this class have an attribute bar\", let alone making a statement about the types of objects to be stored there. You simply define a method, attribute, class, etc. and it's added. As JBernardo points out, any  method does the very same thing. It wouldn't make a lot of sense to arbitrarily restrict creation of new attributes to methods with the name . And it's sometimes useful to store a function as  which don't actually have that name (e.g. decorators), and such a restriction would break that.Now, this isn't universally true. Builtin types omit this capability as an optimization. Via , you can also prevent this on user-defined classes. But this is merely a space optimization (no need for a dictionary for every object), not a correctness thing.If you want a safety net, well, too bad. Python does not offer one, and you cannot reasonably add one, and most importantly, it would be shunned by Python programmers who embrace the language (read: almost all of those you want to work with). Testing and discipline, still go a long way to ensuring correctness. Don't use the liberty to make up attributes outside of  , and do automated testing. I very rarely have an  or a logical error due to trickery like this, and of those that happen, almost all are caught by tests.Just to clarify some misunderstandings in the discussions here. This code:And this code:is . There really is no difference. It does exactly the same thing. This difference is that in the first case it's encapsulated and it's clear that the bar attribute is a normal part of Foo-type objects. In the second case it is not clear that this is so.In the first case you can not create a Foo object that doesn't have the bar attribute (well, you probably can, but not easily), in the second case the Foo objects will not have a bar attribute unless you set it.So although the code is programatically equivalent, it's used in different cases.Python lets you store attributes of any name on virtually on any instance. It's possible to block this (either by writing the class in C, like the built-in types, or by using  which allows only certain names).The reason it works is that most instances store their attributes in a dictionary. Yes, a regular Python dictionary like you'd define with . The dictionary is stored in an instance attribute called . In fact, some people say \"classes are just syntactic sugar for dictionaries.\" That is, you can do everything you can do with a class with a dictionary; classes just make it easier.You're used to static languages where you must define all attributes at compile time. In Python, class definitions are , not compiled; classes are objects just like any other; and adding attributes is as easy as adding an item to a dictionary. This is by design.No, python is flexible like that, it does not enforce what attributes you can store on user-defined classes.There is a trick however, using the  on a class definition will prevent you from creating additional attributes not defined in the  sequence:It creates a  data member of .If you had asked it for  it would have thrown an exception:Interestingly, this does not change the class; just that one instance. So:There are two types of attributes in Python -  and .Python gives you flexibility of creating  on the fly. Since an instance data attribute is related to an instance, you can also do that in  method or you can do it after you have created your instance..So, you see that we have created two instance attributes, one inside  and one outside, after instance is created..But a difference is that, the instance attribute created inside  will be set for all the instances, while if created outside, you can have different instance attributes for different isntances..This is unlike Java, where each Instance of a Class have same set of Instance Variables..
Python

This crops up every now and then for me: I have some C# code badly wanting the  function available in Python.I am aware of usingBut this brakes down in functional usages, as when I want to do a Linq  instead of writing the above loop.Is there any builtin? I guess I could always just roll my own with a  or such, but this would be  handy to just .You're looking for the  method:Just to complement everyone's answers, I thought I should add that  is closer to Python 2.x's  because it's an enumerable.If anyone requires specifically a list or an array:orare closer to Python's .Enumerable.Range(0,12);
Python

I have a script which uses the Django ORM features, amongst other external libraries, that I want to run outside of Django (that is, executed from the command-line).Edit: At the moment, I can launch it by navigating to a URL...How do I setup the environment for this?The easiest way to do this is to set up your script as a  subcommand. It's quite easy to do:Put this in a file, in any of your apps under management/commands/yourcommand.py (with empty  files in each) and now you can call your script with .All you need is importable settings and properly set python path. In the most raw form this can be done by setting up appropriate environment variables, like:There are other ways, like calling  and already mentioned  described by James Bennett in . that the suggestions around importing settings and using setup_environ have been deprecated with Django 1.4.  There's a thread on the Django Github describing .There are still some other options out there but many of them seem hackish to me.  My preferred method is often to include the scripted function as an Use  from : In order to do this, you need to:Refer to  and  for more details.I like to add the following command to my projects::Then, I can run custom scripts, e.g:
Python

Is there a way to group boxplots in matplotlib?Assume we have three groups \"A\", \"B\", and \"C\" and for each we want to create a boxplot for both \"apples\" and \"oranges\". If a grouping is not possible directly, we can create all six combinations and place them linearly side by side. What would be to simplest way to visualize the groupings? I'm trying to avoid setting the tick labels to something like \"A + apples\" since my scenario involves much longer names than \"A\".How about using colors to differentiate between \"apples\" and \"oranges\" and spacing to separate \"A\", \"B\" and \"C\"?  Something like this:A simple way would be to use .\nI adapted an example from the :Here is my version. It stores data based on categories.I am short of reputation so I cannot post an image to here.\nYou can run it and see the result. Basically it's very similar to what Molly did.Just to add to the conversation, I have found a more elegant way to change the color of the box plot by iterating over the dictionary of the object itselfCheers!Here's a function I wrote that takes Molly's code and some other code I've found on the internet to make slightly fancier grouped boxplots:You can use the function(s) like this:
Python

I'm developing C extensions from python ad I obtain some segfaults (inevitable during the development...).I'm searching a way to display at which line of code the segfault happens (an idea is like tracing every single line of code), how I can do that?Here's a way to output the filename and line number of every line of Python your code runs:Output:(You'd probably want to write the trace output to a file, of course.)If you are on linux, run python under gdbSegfaults from C extensions are very frequently a result of not incrementing a reference count when you create a new reference to an object. That makes them very hard to track down as the segfault occurs only after the last reference is removed from the object, and even then often only when some other object is being allocated.You don't say how much C extension code you have written so far, but if you're just starting out consider whether you can use either ctypes or . Ctypes may not be flexible enough for your needs, but you should be able to link to just about any C library with Cython and have all the reference counts maintained for you automatically.That isn't always sufficient: if your Python objects and any underlying C objects have different lifetimes you can still get problems, but it does simplify things considerably.There are somewhat undocumented python extensions for gdb.From the Python source grab  (it is not included in a normal install). Put this in Then:As you can see we now have visibility into the Python stack corresponding with the CPython call chain.Some caveats:If you cannot copy  into  then you can add it's location to  like this:This is somewhat poorly documented in the ,  and If you have an older  or just can't get this working there is also a  in the Python source that you can copy to  which add some similar functionality 
Python

When I load a page, there is a link  that I want to append to it the  of its containing page.I have following URL: How can I do that?To capture the QUERY_PARAMS that were part of the request, you reference the dict that contains those parameters () and urlencode them so they are acceptable as part of an href.   returns a string that looks like  which you can put into a link on the page like so:I found that @Michael's answer didn't quite work when you wanted to update an existing query parameter.The following worked for me:If you register a templatetag like follows:you can modify the query string in your template:This will preserve anything already in the query string and just update the keys that you specify.Following on from @Prydie (thank you!) I wanted to do the same, but in Python 3 & Django 1.10, with the addition of being able to strip querystring keys as well as modify them. To that end, I use this:The python 3 bit being  over 
Python

In Python, how to check if a string only contains certain characters?I need to check a string containing only a..z, 0..9, and . (period) and no other character.I could iterate over each character and check the character is a..z or 0..9, or . but that would be slow.I am not clear now how to do it with a regular expression.Is this correct? Can you suggest a simpler regular expression or a more efficient approach.Answer, wrapped up in a function, with annotated interactive session:Note: There is a comparison with using re.match() further down in this answer. Further timings show that match() would win with much longer strings; match() seems to have a much larger overhead than search() when the final answer is True; this is puzzling (perhaps it's the cost of returning a MatchObject instead of None) and may warrant further rummaging.The [previously] accepted answer could use a few improvements:(1) Presentation gives the appearance of being the result of an interactive Python session:but match() doesn't return (2) For use with match(), the  at the start of the pattern is redundant, and appears to be slightly slower than the same pattern without the (3) Should foster the use of raw string automatically unthinkingly for any re pattern(4) The backslash in front of the dot/period is redundant(5)  (6) Here's a simple, pure-Python implementation. It should be used when performance is not critical (included for future Googlers).Regarding performance, iteration will probably be the fastest method. Regexes have to iterate through a state machine, and the set equality solution has to build a temporary set. However, the difference is unlikely to matter much. If performance of this function is very important, write it as a C extension module with a switch statement (which will be compiled to a jump table).Here's a C implementation, which uses if statements due to space constraints. If you absolutely need the tiny bit of extra speed, write out the switch-case. In my tests, it performs very well (2 seconds vs 9 seconds in benchmarks against the regex).Include it in your setup.py:Use as:Simpler approach? A little more Pythonic?It certainly isn't the most efficient, but it's sure readable.Regular expression solution is the fastest pure python solution so farCompared to other solutions:If you want to allow empty strings then change it to:Under request I'm going to return the other part of the answer. But please note that the following accept A-Z range.You can use  Using isalnum is much more efficient than the set solution\n    John gave an example where the above doesn't work. I changed the solution to overcome this special case by using encodeAnd it is still almost 3 times faster than the set solutionIn my opinion using regular expressions is the best to solve this problemThis has already been answered satisfactorily, but for people coming across this after the fact, I have done some profiling of several different methods of accomplishing this. In my case I wanted uppercase hex digits, so modify as necessary to suit your needs.Here are my test implementations:And the tests, in Python 3.4.0 on Mac OS X:which gave the following results:where:The columns we actually care about are cumtime and percall, as that shows us the actual time taken from function entry to exit. As we can see, regex match and search are not massively different. It is faster not to bother compiling the regex if you would have compiled it every time. It is about 7.5% faster to compile once than every time, but only 2.5% faster to compile than to not compile.test_set was twice as slow as re_search and thrice as slow as re_matchtest_not_any was a full order of magnitude slower than test_set: Use re.match or re.search
Python

Currently I am hosting a Django app I developed myself for my clients, but I am now starting to look at selling it to people for them to host themselves.My question is this: How can I package up and sell a Django app, while protecting its code from pirating or theft? Distributing a bunch of .py files doesn't sound like a good idea as the people I sell it to too could just make copies of them and pass them on.I think for the purpose of this problem it would be safe to assume that everyone who buys this would be running the same (LAMP) setup.Don't try and obfuscate or encrypt the code - it will never work.I would suggest selling the Django application \"as a service\" - either host it for them, or sell them the code . Write up a contract that forbids them from redistributing it.That said, if you were determined to obfuscate the code in some way - you can distribute python applications entirely as .pyc (Python compiled byte-code).. It's how Py2App works.It will still be re-distributable,  it will be very difficult to edit the files - so you could add some basic licensing stuff, and not have it foiled by a few s..As I said, I don't think you'll succeed in anti-piracy via encryption or obfuscation etc.. Depending on your clients, a simple contract, and maybe some really basic checks will go a long much further than some complicated decryption system (And make the experience of using your application , instead of )The way I'd go about it is this:This way the user only has to contact the server when the hostname changes and on first install, but you get a small layer of security.  You could change the hostname to something more complex, but there's really no need -- anyone that wants to pirate this will do so, but a simple mechanism like that will keep honest people honest.You could package the whole thing up as an Amazon Machine Instance (AMI), and then have them run your app on .  The nice thing about this solution is that Amazon will , and since you're distributing the entire machine image, you can be certain that all your clients are using the same LAMP stack.  The AMI is an encrypted machine image that is configured however you want it.You can have Amazon bill the client with a one-time fee, usage-based fee, or monthly fee.Of course, this solution requires that your clients host their app at Amazon, and pay the appropriate fees.\"Encrypting\" Python source code (or bytecode, or really bytecode for any language that uses it -- not just Python) is like those little JavaScript things some people put on web pages to try to disable the right-hand mouse button, declaring \"now you can't steal my images!\"The workarounds are trivial, and will not stop a determined person.If you're really serious about selling a piece of Python software, you need to act serious. Pay an attorney to draw up license/contract terms, have people agree to them at the time of purchase, and then just let them have the actual software. This means you'll have to haul people into court if they violate the license/contract terms, but you'd have to do that no matter what (e.g., if somebody breaks your \"encryption\" and starts distributing your software), and having the actual proper form of legal words already set down on paper, with their signature, will be far better for your business in the long term.If you're really  paranoid about people \"stealing\" your software, though, just stick with a hosted model and don't give them access to the server. Plenty of successful businesses are based around that model.You'll never be able to keep the source code from people who really want it. It's best to come to grips with this fact now, and save yourself the headache later.One thing you might want to consider is what FogBugz does.  Simply include a small binary (perhaps a C program) that is compiled for the target platforms and contains the code to validate the license. This way you can keep the honest people honest with minimal headache on your part.May I speak frankly, as a friend? Unless your app is Really Amazing, you may not get many buyers. Why waste the time on lawyers, obfuscation, licensing and whatnot? You stand to gain a better reputation by open-sourcing your code...and maintaining it.Django comes from the open-source end of the spectrum from licensing (and obfuscating). Granted, the MIT license is more common than the GPL; still they are both very far removed from anything like Microsoft's EULA. A lot of Djangophiles will balk at closed source code, simply because that's what Microsoft does.Also, people will trust your code more, since they will be able to read it and verify that it contains no malicious code. Remember, \"obfuscating\" means \"hiding;\" and who will really know exactly what you've hidden?Granted, there's no easy way to monetize open-sourced code. But you could offer your services or even post a campaign on Pledgie.com, for those who are thankful for all your great work.
Python

How can I print the next year if the current year is given in python using the simplest code, possibly in one line using datetime module. Both date and datetime objects have a  attribute, which is a number. Just add 1:If you have the current year in a variable, just add 1 directly, no need to bother with the datetime module:If you have the date in a string, just select the 4 digits that represent the year and pass it to :Year arithmetic is exceedingly simple, make it an integer and just add 1. It doesn't get much simpler than that.If, however, you are working with a whole date, and you need the same date but one year later, use the components to create a new  object with the year incremented by one:or you can use the  function, which returns a copy with the field you specify changed:Note that this can get a little tricky when  is February 29th in a leap year. The absolute, fail-safe correct way to work this one is thus:
Python

I am writing a scraper that downloads all the image files from a HTML page and saves them to a specific folder. all the images are the part of the HTML page.Here is some code to download all the images from the supplied URL, and save them in the specified output folder. You can modify it to your own needs. You can specify the output folder now.Ryan's solution is good, but fails if the image source URLs are absolute URLs or anything that doesn't give a good result when simply concatenated to the main page URL.  urljoin recognizes absolute vs. relative URLs, so replace the loop in the middle with:You have to download the page and parse html document, find your image with regex and download it.. You can use urllib2 for downloading and Beautiful Soup for parsing html file.And this is function for download one image:Use htmllib to extract all img tags (override do_img), then use urllib2 to download all the images.If the request need an authorization refer to this one:
Python

What is the safest way to run queries on mysql, I am aware of the dangers involved with MySQL and SQL injection. However I do not know how I should run my queries to prevent injection on the variables to which other users (webclients)  can manipulate. I used to write my own escape function, but apparently this is \"not-done\". What should I use and how should I use it to query and do inserts safely on a MySQL database through python without risking mysql injection? To avoid injections, use  with  in place of each variable, then pass the value via a list or tuple as the second parameter of . Here is an :Note that this is using a , not  (which would be a direct string substitution, not escaped). :In addition, you don't need the quotes around the position holder () if the parameter is a string.As an expansion of Bruno's answer, your MySQL client library may support any of several different formats for specifying named parameters. From , you could write your queries like:You can see which your client library supports by looking at the  module-level variable:Any of the above options should Do The Right Thing with regards to handling your possibly insecure data. As Bruno pointed out, please don't ever try to insert parameters yourself. The commonly-used client libraries are much better at processing data correctly than we mere mortals will ever be.
Python

If the value is None, I'd like to change it to \"\" (empty string).I start off like this, but I forget:In a more general case, e.g. if you were adding or removing keys, it might not be safe to change the structure of the container you're looping on -- so using  to loop on an independent list copy thereof might be prudent -- but assigning a different value at a given existing index does  incur any problem, so, in Python 2.any, it's better to use .You could create a dict comprehension of just the elements whose values are None, and then update back into the original: - did some performance testsWell, after trying dicts of from 100 to 10,000 items, with varying percentage of None values, the performance of Alex's solution is across-the-board about twice as fast as this solution.Comprehensions are usually faster, and this has the advantage of not editing  during the iteration:
Python

I just updated my Aptana Studio3. When I open my python file it says that it can not find ,  and  and some other methods. but when I run my code, it'll run without any problem. my code completion doesn't work any more. The error for code completion when I use CTRL+SPACE is I don't know where the problem is ?!! I searched but I couldn't find a proper solution. I'm using windows 7. It seems that this is solved on PyDev and the problem is you can't upgrade PyDev on Aptana 3.6.0. Version 3.6.1 takes out the integration with PyDev and lets you upgrade PyDev.\nSo I installed Aptana 3.6.1 through Beta repository and then installed the latest PyDev.Aptana Beta link to add to \"Available Software Sites\" on Aptana:\nUpgrade to Aptana 3.6.1. This will uninstall PyDev.PyDev link to add to \"Available Software Sites\" on Aptana:\nInstall PyDev.And then, \"Port not bound\" will be solved.I did trace the differrence between Aptana 3.4 and 3.5, found a forked process to start pycompletionserver at specific ports:In 3.5, this process is not found at all, the version of pydev also changed.I managed to start the completion server with the same old ports, still Port not bound error occur.-Perhaps Aptana has changed the port numbers....I'm sorry to revert back to 3.4 :-( I've had the same issue for some time now. I originally downgraded to the previous release but have now decided to upgrade to the 3.6.1 beta release and this problem seems to be fixed. Instructions on how to upgrade to 3.6.1 .The PyDev interpreter may not get automatically installed when you upgrade so you'll have to manually install it again. If needed, there are instructions .Using info from idubs11, I was able to get my Aptana 3.6.1(downloaded 2016-03-01) working.  It exhibited the same problem, port not bound.  I was not able to uninstall pydev, until...Now it was in a weird state, no Pydev anymore and now using the beta version.  I then used the pydev.org install site to install pydev and now everything works just fine.I had this issue, even with Windows Firewall disabled. I even tried a clean reinstall (version 3.6) to no avail. In the end I was forced to downgrade to . It's now no longer an issue.I know that the OP asked for help in regards with a Windows OS, however if anyone wants to get this working on OS X 10.9+, then  follow the steps originally suggested by  , which are:, when installing PyDev uncheck  check box in Aptana's  window and make sure that you choose the latest 2.x.x version of PyDev.PyDev 3.x+ needs Java JDK 7+ in order to run, however for the latest versions of OS X any Java JDK 7+ is only available as the 64 bit version. Aptana Studio 3 for OS X seems to be available in 32 bit only, which requires a 32 bit JDK.Another option is to install a 64 bit Eclipse IDE and install Aptana Studio 3.6.1 as a plugin and the latest PyDev separately. I'm running Windows 10, I fixed this issue by running the installer again and picked \"repair\". Fixed this issue for me and did not lose any configuration in the process.Performing a clean Aptana reinstall had fixed this for me.but have you checked the windows firewall? as it tells the IDE? You should try to put an exception for Aptana and it should work .. in fact it seems that the method of python builtin does not read directly from python but from a db, most likely via a socket on a port closed by the firewall ..
Python

I'm really curious about  format string in Python 3.  says  is  and that  is .It also says  will apply , but it doesn't say anything similar about . I think there's no significant difference between them, but I want to be sure. Can anyone clarify these?Some code example:It's still confusing, but let me wrap up with my own (layperson's) words.Is anything wrong here?, and its brethren  and  apply ,  and  respectively  interpolation and formatting. These are called , and are part of the , not the  applied to values when interpolating:Bold emphasis mine. only applies afterwards to the conversion result (or the original object if no conversion had been applied), and only if the  method for the type of object supports that formatting option. Usually, only objects of type  support this formatter; it's there as the default, mostly because the  allows for the existence of a type character and because the older   had a  format. If you tried to apply the  type to an object that doesn't support it, you'd get an exception.Use  (or  or ) when you have an object that is not itself a string and either doesn't support formatting otherwise (not all types do) or would format differently from their ,  or  conversions:Note:  formatting specified by the format spec are the responsibility of the  method; the last line does not apply the alignment operation in the  formatting spec, the  method only used it as literal text in a formatting operation (using a  conversion here).For the converted values, on the other hand, the  method is used and the output is aligned to the right in a 50 character wide field, padded with spaces on the left.You're unlucky you used strings as the value to be formatted. Using pretty much any other object you'd get how these aren't the same.In (as much as I can) layman's terms:I do think, though, that  is probably a confusing name to give this specifier.From the documentation, :So no, it's not the same.For example:If you want to print a float as a string, you need a conversion (float \u2192 string).If you don't use the conversion mark, you will get an error.
Python

I've been looking around the internet for a Java scientific package that is \"similar\" to Scipy.  The only thing I have really found  is  but it seems not to offer plotting and such.  Does anyone know of a good scientific package for Java?I'm looking for similar packages .  Here is a summary of what's shown up there so far:My personal experience is focused primarily in Apache Commons Math where it is certainly working for our needs.We also use JFreechart at work.  That is less of a numerical method / scientific package and much more focused on just getting your values on the screen in some useful form.Your mileage may vary but hopefully this will aid your search.I had really good results with .You can try . It's a very good library, plots graphs and it's free :)\nSomeone also told me about  but i've never used it myself.Have a look at .  It is an open source project based on Eclipse.  It supports all kinds of different user interfaces.  It is easy to use and flexible.Even if it is not exactly what you need, keep reading down the page.  It mentions a lot of other technologies that might be an even closer fit.Both MathEcliipse and  look like incredibly outstanding tools for making powerful mathematics very easy and accessible for users of Java programs.You could also take a look at , which says you can interface it to your favorite plotting libraries.I have used  before and found it very simple to use.  Others must too.  I have found it embedded in some other well known Java projects.It may not be strictly connected to question, but whatever library you'll choose, I recommend using it with . Its state-of-art optimized, really stable and, what is important - usable in real-time apps. Interface has a lot in common with standard Java libraries, and new stuff is designed to be very understandable.You might want to check out  collection of Java numerics packages.If you have a Java library, you can script using anything like Groovy, Scala, Jyphon, JRuby, Javascript, etc. etc.Here is an example to script math in Groovy using SuanShu:For plotting you can use , a really nice open source library.  You'll have to combine it with another library to get all of the functionality you're asking for, though.If you must use the library and no Java equivalent exists, can you import the package from ?
Python

I'm debugging a python script, and I want to watch a variable for a change (much like you can watch a memory adress in gdb).  Is there a way to do this?Here is a really hacky way to do this with . These commands can be put in your  for automatic loading every time you use .This adds two commands,  and  which each take a variable name  as an argument. They will make a shallow copy of the current frame's local variable for  if possible, and keep executing  or  respectively until what that name points to changes.This works in CPython 2.7.2 but relies on some  internals so it will probably break elsewhere.For watching a variable when you are hitting a , you can use the  command. E.g. printing  when hitting breakpoint #1 ().For :you can use  functionality of pdbOnce you hit the breakpoint just type ipdb>  as you can see, each time you type display - it will print all of your watches (expressions). You can use undisplay function to remove certain watch.You can also use  to prettyprint the expression (very useful)A possible solution is to use :Then \"mark\" the object you want to watch with the decorator :Here  will break on any change of the attribute  on any Foo-object.\nOnly invocations of the underlying -method will trigger the breakpoint. This means that  and  will work, but manipulating the -object will not trigger the breakpoint:
Python

I want to test whether an object is an instance of a class, and only this class (no subclasses). I could do it either with:Are there reasons to choose one over another? (performance differences, pitfalls, etc)In other words: a) is there any practical difference between using  and ? b) are class objects always safe for comparison using ? Thanks all for the feedback. I'm still puzzled by whether or not class objects are singletons, my common sense says they are, but it's been really hard to get a confirmation (try googling for \"python\", \"class\" and \"unique\" or \"singleton\").I'd also like to clarify that, for my particular needs, the \"cheaper\" solution that just works is the best, since I'm trying to optimize the most out of a few, specialized classes (almost reaching the point where the sensible thing to do is to drop Python and develop that particular module in C). But the reason behind the question was to understand better the language, since some of its features are a bit too obscure for me to find that information easily. That's why I'm letting the discussion extend a little instead of settling for , so I can hear the opinion of more experienced people. So far it's been very fruitful!I ran a small test to benchmark the performance of the 4 alternatives. The profiler results were:Unsurprisingly,  performed better than  for all cases.  performed better in Python (2% faster) and  performed better in PyPy (6% faster). Interesting to note that  performed better in PyPy than . many people don't seem to understand what I mean with \"a class is a singleton\", so I'll ilustrate with an example:It doesn't matter if there are N objects of type , given an object, only one will be its class, hence it's safe to compare for reference in this case. And since reference comparison will always be cheaper than value comparison, I wanted to know whether or not my assertion above holds. I'm reaching the conclusion that it does, unless someone presents evidence in contrary.For old-style classes, there is a difference:The point of new-style classes was to unify class and type. Technically speaking,  is the only solution that will work both for new and old-style class instances, but it will also throw an exception on old-style class objects themselves. You can call  on any object, but not every object has . Also, you can muck with  in a way you can't muck with .Personally, I usually have an environment with new-style classes only, and as a matter of style prefer to use  as I generally prefer built-in functions when they exist to using magic attributes. For example, I would also prefer  to . should only be used for identity checks, not type checks (there is an exception to the rule where you can and should use  for check against singletons).  Note: I would generally not use  and  for type checks, either.  The preferable way for type checks is .  If you ever have a reason to check if something is not an subclass instance, it smells like a fishy design to me.  When , then   , and you should be avoiding any situations where some part of your code has to work on a  instance but breaks on a  instance. The result of  is equivalent to  in new style classes, and class objects are not safe for comparison using , use  instead. the preferable way here would be .As Michael Hoffman pointed out in his answer, there is a difference here between new and old style classes, so for backwards compatible code you may need to use .For those claiming that  is preferable, consider the following scenario:The OP wants the behavior of , where it will be false even though  is a base class of .I can confirm that  is a singleton. Here is the proof.As you can see both  and  print out the same value in memory even though  and  are at different values in memory. Here is the proof of that.The  method only exists if you used . If you use the classic style class, , than the  method doesn't exist.What this means is to be the most generic you probably want to use  unless you know for a fact instance does exist.
Python

So I have these two problems for a homework assignment and I'm stuck on the second one. For the first one, this works perfectly: However, I'm pretty stumped on the second one. I think I may have to take the Cartesian                       product of the set r with something but I'm just not sure. This gets me somewhat close but I just want the consecutive pairs.Any help is greatly appreciated, thanks.I simplified the test a bit -  instead of I also limited y's range; there is no point in testing for divisors > sqrt(x). So max(x) == 100 implies max(y) == 10. For x <= 10, y must also be < x.Instead of generating pairs of primes and testing them, get one and see if the corresponding higher prime exists.You can get clean and clear solutions by building the appropriate predicates as helper functions.  In other words, use the Python set-builder notation the same way you would write the answer with regular mathematics set-notation.  The whole idea behind set comprehensions is to let us write and reason in code the same way we do mathematics by hand.With an appropriate predicate in hand, problem 1 simplifies to:And problem 2 simplifies to:Note how this code is a direct translation of the problem specification, \"A Prime Pair is a pair of consecutive odd numbers that are both prime.\"P.S. I'm trying to give you the correct problem solving technique without actually giving away the answer to the homework problem.You can generate pairs like this:Then all that is left to do is to get a condition to make them prime, which you have already done in the first example.A different way of doing it: (Although slower for large sets of primes)
Python

I was just pleasantly surprised to came across the documentation of , but noticed that it's gone in Python 3.0, without any clear replacement or explanation.I can't seem to find any discussion on python-dev about how this decision was made - does anyone have any insight inot this decision?I believe the functionality is now built in:
Python

I've recently started using git, and also begun unit testing (using Python's  module). I'd like to run my tests each time I commit, and only commit if they pass.I'm guessing I need to use  in , and I've managed to make it run the tests, but I can't seem to find a way to stop the commit if they tests fail. I'm running the tests with , which in turn is running . It seems like I don't get a different exit condition whether the tests pass or fail, but I may be looking in the wrong place. Is this something uncommon that I want to do here? I would have thought it was a common requirement... Just in case people can't be bothered to read the comments, the problem was that  doesn't exit with non-zero status, whether the test suite is successful or not. To catch it, I did:I would check to make sure that each step of the way, your script returns a non-zero exit code on failure. Check to see if your  returns a non-zero exit code if a test fails. Check to make sure your  command returns a non-zero exit code. And finally, check that your  hook itself returns a non-zero exit code on failure.You can check for a non-zero exit code by adding  to the end of a command; that will print out the exit code if the command failed.The following example works for me (I'm redirecting stderr to  to avoid including too much extraneous output here)::::Note the . This isn't necessary if  is the last command in the hook, as the exit status of the last command will be the exit status of the script. But if you have later checks in your  hook, then you need to make sure you exit with an error; otherwise, a successful command at the end of the hook will cause your script to exit with a status of .Could you parse the result of the python test session and make sure to exit your pre-commit hook with a non-zero status?So if your python script does not return the appropriate status for any reason, you need to determine that status directly from the  hook script.\nThat would ensure the commit does not go forward if the tests failed.\n(or you could call from the hook a python wrapper which would call the tests, and ensure a  according to the test results).Another option, if you don't want to handle manually pre-commit's:\nThere is nice tool to run tests and syntax checks for Python, Ruby and so on: 
Python

The usual check to differentiate between running Python-application on Windows and on other OSes (Linux typically) is to use conditional:But I wonder is it safe to use today when 64-bit Python is more widely used in last years? Does 32 really means 32-bit, or basically it refers to Win32 API?If there is possibility to have one day sys.platform as 'win64' maybe such condition would be more universal?There is also another way to detect Windows I'm aware of:But I really never saw in other code the use of the latter.What is the best way then?: I'd like to avoid using extra libraries if I can. Requiring installing extra library to check that I'm work not in the Windows may be annoying for Linux users.  will be  regardless of the bitness of the underlying Windows system, as you can see in  (from the Python 2.6 source distribution):It's possible to find the  that introduced this on the web, which offers a bit more explanation:Notice that you cannot use either  or  for this on Jython:I think there's a plan in Jython project to change  to report the underlying OS similarly as CPython, but because people are using  to check are they on Jython this change cannot be done overnight. There is, however, already  on Jython 2.5.x:Personally I tend to use  with code that needs to run both on Jython and CPython, and both on Windows and unixy platforms. It's somewhat ugly but works.The caveats for Windows/32 and Windows/64 are the same, so they should use the same value. The only difference would be in e.g.  and . If you need to distinguish between 32 and 64 regardless then  is your best bet.Personally I use  for detecting the underlying platform.For 32-bit,  returns .
Python

Is there an easy way in Python to check whether the value of an optional parameter comes from its default value, or because the user has set it explicitly at the function call?Not really.  The standard way is to use a default value that the user would not be expected to pass, e.g. an  instance:Usually you can just use  as the default value, if it doesn't make sense as a value the user would want to pass.The alternative is to use :However this is overly verbose and makes your function more difficult to use as its documentation will not automatically include the  parameter.The following function decorator, , makes a set of parameter names of all the parameters given explicitly. It adds the result as an extra parameter () to the function. Just do  to check if parameter  is given explicitly.I sometimes use a universally unique string (like a UUID).This way, no user could even guess the default if they tried so I can be very confident that when I see that value for , it was not passed in.I agree with Volatility's comment. But you could check in the following manner:A little freakish approach would be:Which outputs:Now this, as I mentioned, is quite freakish, but it does the job. However this is quite unreadable and similarly to 's  won't be automatically documented.
Python

I'm trying to mock something while testing a Django app using the imaginatively named . I can't seem to quite get it to work, I'm trying to do this:What am I doing wrong?Ah I was confused on where to apply that patch decorator. Fixed:To add onto Kit's answer above, specifying a 3rd argument to patch.object() allows the mocked object/method to be specified, otherwise a default MagicMock object is used.Note that, if you specify the mocking object, then the default MagicMock() is  passed into the patched object -- e.g. no longer:but instead:
Python

The Python docs clearly state that  calls .  However it seems that under many circumstances, the opposite is true.  Where is it documented when or why this happens, and how can I work out for sure whether my object's  or  methods are going to get called.Edit: Just to clarify, I know that  is called in preferecne to , but I'm not clear why  is called in preference to , when the latter is what the docs state will happen.Edit: From Mark Dickinson's answer and comment it would appear that:This explains the behaviour in the examples.   is a subclass of  but doesn't implement its own  so the  of  takes precedence in both cases (ie  calls  as an  because of rule 1).In the  examples,  is called in both instances because  is a subclass of  and so it is called in preference.In the  examples,  implements  and  doesn't so  gets called both times (rule 1).But I still don't understand the very first example with .   is not a subclass on  so AFAICT  should be called, but isn't.You're missing a key exception to the usual behaviour:  when the right-hand operand is an instance of a subclass of the class of the left-hand operand, the special method for the right-hand operand is called first.See the documentation at:and in particular, the following two paragraphs:Actually, in the , it states: is a rich comparison method and, in the case of , is not defined, hence the calling of As I know,  is a so-called \u201crich comparison\u201d method, and is called for comparison operators in preference to  below.  is called if \"rich comparison\" is not defined.So in A == B:\n    If  is defined in A it will be called\n    Else  will be called defined in 'str' so your  function was not called.The same rule is for  and  \"rich comparison\" methods.Is this not documented in the ? Just from a quick look there, it looks like  is ignored when , , etc are defined. I'm understanding that to include the case where  is defined on a parent class.  is already defined so  on its subclasses will be ignored.  etc are not defined so  on its subclasses will be honored.In response to the clarified question: Docs say  will be called first, but it has the option to return  in which case  is called. I'm not sure why you're confident something different is going on here.Which case are you specifically puzzled about? I'm understanding you just to be puzzled about the  and  cases, correct? In either case,  is being called. Since you don't override the  method in TestStrCmp, eventually you're just relying on the base string method and it's saying the objects aren't equal.Without knowing the implementation details of , I don't know whether  will return  and give tsc a chance to handle the equality test. But even if it did, the way you have TestStrCmp defined, you're still going to get a false result.So it's not clear what you're seeing here that's unexpected.Perhaps what's happening is that Python is preferring  to  if it's defined on  of the objects being compared, whereas you were expecting  on the leftmost object to have priority over  on the righthand object. Is that it?
Python

What Kivy tutorials and learning aids exist?   Where is the list for Kivy?This is besides the pong tutorial on their website?As others suggested, the  in the kivy_installation directory are there to help programmers understand how basic tasks can be done using kivy.There is also this  where we encourage people to put there snippets in the  section.You could also look at the  section in the I guess we need to be better at explaining that. There is an effort at a new  that aims at helping to introduce the different parts of the documentation that are otherwise not quite obvious to new comers, suggestions are welcome. You can open a issue on  for documentation, we will be also adding a suggestion section to the documentation.
Python

 to another thread suggests using  instead of . However, when I share axes between subplots, I usually use a syntax like the followingHow can I specify  and  when I use  ?First off, there's an easier workaround for your original problem, as long as you're okay with being slightly imprecise. Just reset the top extent of the subplots to the default  calling :However, to answer your question, you'll need to create the subplots at a slightly lower level to use gridspec.  If you want to replicate the hiding of shared axes like  does, you'll need to do that manually, by using the  argument to  and hiding the duplicated ticks with .As an example:Both Joe's choices gave me some problems: the former, related with direct use of  instead of  and, the latter, with some backends (). But Joe's answer definitely cleared my way toward another compact alternative. This is the result for a problem close to the OP's one:
Python

After googling and searching on here, couldn't figure out what this does.  Maybe I wasn't searching the right stuff but here it is.  Any input in debunking this shorthand is greatly appreciated.The current answers are good, but do not talk about how they are just  to some pattern that we are so used to.Let's start with an example, say we have 10 numbers, and we want a subset of those that are greater than, say, 5.For the above task, the below approaches below are totally identical to one another, and go from most verbose to concise, readable and :where:To understand the syntax in a slightly different manner, look at the Bonus section below.For further information, follow the tutorial all other answers have linked: (Slightly un-pythonic, but putting it here for sake of completeness)The example above can be written as:The general expression above can be written as:It's a  will be a filtered list of  containing the objects with the attribute occupants > 1 can be a , ,  or any other iterableHere is an example to clarifySo foo has 2  objects, but how do we check which ones they are? Lets add a  method to  so it is more informativeThis return a list which contains all the elements in bar which have occupants > 1.The way this should work as far as I can tell is it checks to see if the list \"bar\" is empty (0) or consists of a singleton (1) via x.occupants where x is a defined item within the list bar and may have the characteristic of occupants. So foo gets called, moves through the list and then returns all items that pass the check condition which is x.occupant.In a language like Java, you'd build a class called \"x\" where 'x' objects are then assigned to an array or similar. X would have a Field called \"occupants\" and each index would be checked with the x.occupants method which would return the number that is assigned to occupant. If that method returned greater than 1 (We assume an int here as a partial occupant would be odd.) the foo method (being called on the array or similar in question.) would then return an array or similar as defined in the foo method for this container array or what have you. The elements of the returned array would be the 'x' objects in the first array thingie that fit the criteria of \"Greater than 1\".Python has built-in methods via list comprehension to deal with this in a much more succinct and vastly simplified way. Rather than implementing two full classes and several methods, I write that one line of code.
Python

I've been trying to wrap my head around how sockets work, and I've been trying to pick apart some sample code I found at  for a very simple client socket program. Since this is basic sample code, I assumed it had no errors, but when I try to compile it, I get the following error message. I've googled pretty much every part of this error, and people who've had similar problems seem to have been helped by changing the port number, using 'connect' instead of 'bind,' and a few other things, but none of them applied to my situation. Any help is greatly appreciated, since I'm very new to network programming and fairly new to python.By the way, here is the code in case that link doesn't work for whatever reason.It's trying to connect to the computer it's running on on port 5000, but the connection is being refused. Are you sure you have a server running?If not, you can use  for testing:Some implementations may require you to omit the  flag.Here is the simplest python socket example.Server side:Client Side:Here is a pretty simple socket program. This is about as simple as sockets get.for the client program(CPU 1)You have to replace the 111.111.0.11 in line 4 with the IP number found in the second computers network settings.For the server program(CPU 2)Run the server program and then the client one.It looks like your client is trying to connect to a non-existent server. In a shell window, run:before running your Python code. It will act as a server listening on port 5000 for you to connect to. Then you can play with typing into your Python window and seeing it appear in the other terminal and vice versa.You might be confusing compilation from execution. Python has no compilation step! :) As soon as you type  the program runs and, in your case, tries to connect to an open port 5000, giving an error if no server program is listening there. It sounds like you are familiar with two-step languages, that require compilation to produce an executable \u2014 and thus you are confusing Python's runtime compilaint that \u201cI can't find anyone listening on port 5000!\u201d with a compile-time error. But, in fact, your Python code is fine; you just need to bring up a listener before running it!
Python

I'm using Python 2.7.2 on Ubuntu 11.10. I got this error when importing the bz2 module:I thought the bz2 module is supposed to come with Python 2.7. How can I fix this problem?EDIT: I think I previously installed Python 2.7.2 by compiling from source. Probably at that point I didn't have libbz2-dev and so the bz2 module is not installed. Now, I'm hoping to install Python2.7 throughBut it will say it's already installed. Is there a way to uninstall the previous Python2.7 installation and reinstall?Okay, this is much easier to understand in answer form, so I'll move what I would write in my comment to this answer.Luckily for you, you didn't overwrite the system version of python, as Ubuntu 11.10 comes with 2.7.2 preinstalled.Your python binaries ( and ) are located in , which is a directory where user-specific stuff is usually installed. This is fine, it means your system python is still there.First, just try to run the system python. Type this from the command line:This should print out something like this:If so, means you're fine.So you just have to fix your , which tells the shell where to find commands.  is going to have priority over , so there are some ways to fix this, in order of difficulty/annoyance/altering your system:This will make it so that when you type , it should go back to executing , which is an alias for the system's python 2.7.2.Might not be desirable if you already have stuff in  that should have precedence over , but I'm adding this for completeness.In your shell profile (not sure what Ubuntu's default is, but I'm using , you can do this:This is extreme and the first option I presented should be your first option.Do you really need your own version of Python? If you want isolated python environments you probably really want . You can probably remove yours unless there's a reason not to.It's going to be a little annoying though, but basically:This part is not complete because I forget what else there is.I meet the same problem, here's my solution.The reason of import error is while you are building python, system couldn't find the bz2 headers and skipped building bz2 module.Install them on Ubuntu/Debian:Fedora:and then rebuild pythoncomes from @birryree's answer helps to back to the system's original python.In case, you must be used python2.7, you should run: (Centos 6.4)Maybe it will helps someone:For Ubuntu/Debian:For Fedora:And then recompile the python and install it.I used a symlink between Worked fine for me...matocnhoi's answer works for me in centOSand I used virtualenv, so the command isMake sure you bz2 installed, run . usually is , you need replace that if you install python in a another path.
Python

In numpy/scipy I have an image stored in an array. I can display it, I want to save it using   any borders, axes, labels, titles,... Just pure image, nothing else.I want to avoid packages like  or , they are sometimes problematic (they do not always install well, only basic  for meAssuming : To make a figure without the frame :To make the content fill the whole figure Then draw your image on it :The  parameter changes the pixel size to make sure they fill the figure size specified in . To get a feel of how to play with this sort of things, read through , particularly on the subject of Axes, Axis and Artist.An easier solution seems to be:You can find the bbox of the image inside the axis (using ), and use the  parameter to save only that portion of the image:I learned this trick from Joe Kington .I've tried several options in my case, and the best solution was this:then save your figure with I will suggest heron13 answer with a slight addition borrowed from  to remove the padding left after setting the bbox to tight mode, therefore:I had the same problem while doing some visualization using  where I wanted to extract content of the plot without any other information. So this my approach. unutbu answer also helps me to make to work.
Python

Thanks to some help from people here, I was able to get my code for Tasmanian camels puzzle working. However, it is horribly slow (I think. I'm not sure because this is my first program in python). The example run in the bottom of the code takes a long time to be solved in my machine:Here's the code:That is just for 3 camels each. I wanted to do this for 4 at least. That test case is still running (It's been about 5 minutes now :(). I'll update this if and when it finishes.What should I do to improve this code?(Mostly performance-wise, any other suggestions are welcome also).Thanks.I've been tripped up by this before too.  The bottleneck here is actually .The  statement is so easy to use, you forget that it's linear search, and when you're doing linear searches on lists, it can add up fast.  What you can do is convert closedlist into a  object.  This keeps hashes of its items so the  operator is much more efficient than for lists.  However, lists aren't hashable items, so you will have to change your configurations into tuples instead of lists.If the order of  is crucial to the algorithm, you could use a set for the  operator and keep an parallel list around for your results.I tried a simple implementation of this including aaronasterling's namedtuple trick and it performed in 0.2 sec for your first example and 2.1 sec for your second, but I haven't tried verifying the results for the second longer one.First let me tell you how to find the problem. Then I'll tell you where it is:I haven't even bothered to try to figure out your code. I just ran it and took 3 random-time stack samples. I did that by typing control-C and looking at the resulting stacktrace.One way to look at it is: if a statement appears on X% of random stack traces, then it is on the stack for about X% of the time, so that is what it's responsible for. If you could avoid executing it, that is how much you would save.OK, I took 3 stack samples. Here they are:Notice, in this case the stack samples are all identical. In other words, each one of these three lines is individually responsible for nearly all of the time. So look at them:Clearly line 87 is not one you can avoid executing, and probably not 85 either. That leaves 80, the  call. Now, you can't tell if the problem is in the  operator, the  call, the  call, or in the  call. You could find out if you could split those out onto separate lines.So I hope you pick up from this a quick and easy way to find out where your performance problems are.tkerwin is correct that you should be using a set for closedlist, which speeds things up a lot, but it is still kind of slow for 4 camels on each side. The next problem is that you are allowing a lot of solutions that aren't possible because you are allowing fCamels to go backwards and bCamels to go forward. To fix this, replace the lines,withthen I get solution to the 4 camels on each side problem in like .05 seconds rather than 10 seconds. I also tried 5 camels on each side and it took 0.09 seconds. I also am using a set for closedlist and heapq rather than Queue.You can get an additional speed-up by using your heuristic correctly. Currently, you are using the line(or the heapq version of that) but you should change it toThis doesn't factor in the number of moves that has been needed, but that is okay. With this puzzle (and the screening out of moves that move camels in the wrong direction), you don't need to worry about the number of moves it takes - either a move advances you towards the solution or it will come to a dead end. In other words, all possible solutions require the same number of moves. This one change takes the time to find the solution of the 12 camels on each side case from over 13 seconds (even using the heapq, set for closedlist, and the changes to find the neighbors above) to 0.389 seconds. That's not bad. By the way, a better way to find if you've found the solution is to check if the index of the first fCamel is equal to the length of the formation/2 + 1(using int division) and that the index before that is equal to the gap.Replacing with dropped the times from around 340-600 msecs to  1.89 msecs on the input . It yielded the same output.This obviously wont help with any algorithmic problems but as far as micro-optimizations go, it ain't bad.The code below using less than 1s to solve thiswell, I can't really say quite where your algorithm is running astray, but I just went ahead and made my own.  In the interest of doing the simplest thing that could possibly work, I used a bastardized version of Dijkstra's algorithm, where open nodes are visited in arbitrary order, without consideration of distance.  This means I don't have to come up with a heuristic.My other answer is rather long, so I decided to list this as a separate answer. This problem is really better suited to doing a depth-first search. I made a depth-first search solution and it is much, much faster than the optimized A-star method made with the changes outlined in my other answer (which is much, much faster than the OP code). For instance, here are the results for running both my A-star and my depth-first search methods on the 17 camels per side case.Here's my depth-first method code if you are interested:
Python

I would like to perform a bitwise exclusive or of two strings in python, but xor of strings are not allowed in python. How can I do it ?You can convert the characters to integers and xor those instead:Here's an updated function in case you need a string as a result of the XOR:See it working online: If you want to operate on bytes or words then you'll be better to use Python's array type instead of a string. If you are working with fixed length blocks then you may be able to use H or L format to operate on words rather than bytes, but I just used 'B' for this example:For bytearrays you can directly use XOR:Here is your string XOR'er, presumably for some mild form of encryption:Note that this is an  weak form of encryption.  Watch what happens when given a blank string to encode:the one liner for python3 is : where ,  and the returned value are  instead of  of coursecan't be easier, I love python3 :)(Based on Mark Byers answer.)Do you mean something like this:If the strings are not even of equal length, you can use thisBelow illustrates XORing string s with m, and then again to reverse the process:I've found that the ''.join(chr(ord(a)^ord(b)) for a,b in zip(s,m)) method is pretty slow. Instead, I've been doing this:Based on William McBrine's answer, here is a solution for fixed-length strings which is 9% faster for my use case:
Python

I want to find string similarity between two strings.  page has examples of some of them. Python has an implemnetation of . Is there a better algorithm, (and hopefully a python library), under these contraints.Would something other than Levenshtein distance(or Levenshtein ratio) be a better algorithm for my case?There's a great resource for string similarity metrics at the University of Sheffield. It has a list of various metrics (beyond just Levenshtein) and has open-source implementations of them. Looks like many of them should be easy to adapt into Python.Here's a bit of the list:I realize it's not the same thing, but this is close enough:You can make this as a functionThis snippet will calculate the difflib, Levenshtein, S\u00f8rensen, and Jaccard similarity values for two strings. In the snippet below, I was iterating over a tsv in which the strings of interest occupied columns  and  of the tsv. ( and ):I would use Levenshtein distance, or the so-called Damerau distance (which takes transpositions into account) rather than the difflib stuff for two reasons (1) \"fast enough\" (dynamic programming algo) and \"whoooosh\" (bit-bashing) C code is available and (2) well-understood behaviour e.g. Levenshtein satisfies the triangle inequality and thus can be used in e.g. a Burkhard-Keller tree.Threshold: you should treat as \"positive\" only those cases where distance < (1 - X) * max(len(string1), len(string2)) and adjust X (the similarity factor) to suit yourself. One way of choosing X is to get a sample of matches, calculate X for each, ignore cases where X < say 0.8 or 0.9, then sort the remainder in descending order of X and eye-ball them and insert the correct result and calculate some cost-of-mistakes measure for various levels of X.N.B. Your ape/apple example has distance 2, so X is 0.6 ... I would only use a threshold as low as 0.75 if I were desperately looking for something and had a high false-negative penaltyIs that what you mean?look at I know this isn't the same but you can adjust the ratio to filter out strings that are not similar enough and return the closest match to the string you are looking for.Perhaps you would be more interested in semantic similarity metrics.I realize you said speed is not an issue but if you are processing a lot of the strings for your algorithm the below is very helpful.Its about 20 times faster than difflib.import Levenshtein
Python

how can we XOR hex numbers in python eg. I want to xor 'ABCD' to '12EF'. answer should be B922.i used below code but it is returning garbage valueWhoa. You're really over-complicating it by a very long distance. Try:You seem to be ignoring these handy facts, at least:If you already have the numbers as strings, you can use the  function to convert to numbers, by providing the expected base (16 for hexadecimal numbers):So you can do two conversions, perform the XOR, and then convert back to hex:If the two hex strings are the same length and you want a hex string output then you might try this.If the strings are the same length, then I would go for  of the built-in xor (). Examples - If the strings are not the same length, truncate the longer string to the length of the shorter using a slice here's a better functionFor performance purpose, here's a little code to benchmark these two alternatives:Here are the results :Seems like  is faster then the zip version.
Python

Anyone have any suggestions on how to make randomized colors that are all greenish? Right now I'm generating the colors by this:That mostly works, but I get brownish colors a lot. Simple solution:  instead of rgb (convert it to RGB afterwards if you need this). The difference is the meaning of the tuple: Where RGB means values for Red, Green and Blue, in HSL the H is the color (120 degree or 0.33 meaning green for example) and the S is for saturation and the V for the brightness. So keep the H at a fixed value (or for even more random colors you could randomize it by add/sub a small random number) and randomize the S and the V. See the  article.As others have suggested, generating random colours is much easier in the HSV colour space (or HSL, the difference is pretty irrelevant for this)So, code to generate random \"green'ish\" colours, and (for demonstration purposes) display them as a series of simple coloured HTML span tags:The output (when viewed in a web-browser) should look something along the lines of:: I didn't know about the colorsys module. Instead of the above  function, you could use , which makes the code much shorter (it's not quite a drop-in replacement, as my  function expects the hue to be in degrees instead of 0-1):Check out the  module:Use the HSL or HSV color space. Randomize the hue to be close to green, then choose completely random stuff for the saturation and V (brightness).If you stick with RGB, you basically just need to make sure the G value is greater than the R and B, and try to keep the blue and red values similar so that the hue doesn't go too crazy. Extending from Slaks, maybe something like (I know next to nothing about Python):So in this case you are lucky enough to want variations on a primary color, but for artistic uses like this it is better to specify color wheel coordinates rather than primary color magnitudes.You probably want something from the  module like:The solution with HSx color space is a very good one. However, if you need something extremely simplistic and have no specific requirements about the distribution of the colors (like uniformity), a simplistic RGB-based solution would be just to make sure that G value is greater than both R and BThis will give you \"greenish\" colors. Some of them will be ever so slightly greenish. You can increase the guaranteed degree of greenishness by increasing (absolutely or relatively) the lower bound in the last  call.What you want is to work in terms of  instead of RGB. You could find a range of hue that satisfies \"greenish\" and pick a random hue from it. You could also pick random saturation and lightness but you'll probably want to keep your saturation near 1 and your lightness around 0.5 but you can play with them.Below is some actionscript code to convert HSL to RGB. I haven't touched python in a while or it'd post the python version.I find that greenish is something like 0.47*PI to 0.8*PI.The simplest way to do this is to make sure that the red and blue components are the same, like this: (Forgive my Python)I'd go with with the HSV approach everyone else mentioned. Another approach would be to get a nice high resolution photo which some greenery in it, crop out the non-green parts, and pick random pixels from it using .
Python

I am trying to make a discrete colorbar for a scatterplot in matplotlibI have my x, y data and for each point an integer tag value which I want to be represented with a unique colour, e.g.typically tag will be an integer ranging from 0-20, but the exact range may changeso far I have just used the default settings, e.g.which gives a continuous range of colours. Ideally i would like a set of n discrete colours (n=20 in this example). Even better would be to get a tag value of 0 to produce a gray colour and 1-20 be colourful.I have found some 'cookbook' scripts but they are very complicated and I cannot think they are the right way to solve a seemingly simple problemYou can create a custom discrete colorbar quite easily by using a BoundaryNorm as normalizer for your scatter. The quirky bit (in my method) is making 0 showup as grey. For images i often use the cmap.set_bad() and convert my data to a numpy masked array. That would be much easier to make 0 grey, but i couldnt get this to work with the scatter or the custom cmap. As an alternative you can make your own cmap from scratch, or read-out an existing one and override just some specific entries.I personally think that with 20 different colors its a bit hard to read the specific value, but thats up to you of course.You could follow this :which produces the following image:To set a values above or below the range of the colormap, you'll want to use the  and  methods of the colormap.  If you want to flag a particular value, mask it (i.e. create a masked array), and use the  method.  (Have a look at the documentation for the base colormap class:  )It sounds like you want something like this:The above answers are good, except they don't have proper tick placement on the colorbar. I like having the ticks in the middle of the color so that the number -> color mapping is more clear. You can solve this problem by changing the limits of the matshow call:I think you'd want to look at  to generate your colormap, or if you just need a static colormap I've been working on  that might help.
Python

In Python, How can one subtract two non-unique, unordered lists? Say we have  and  I'd like to do something like  and have  be  or  order doesn't matter to me. This should throw an exception if a does not contain all elements in b. I'm not interested in finding the difference of the sets of elements in a and b, I'm interested in the difference between the actual collections of elements in a and b.I can do this with a for loop, looking up the first element of b in a and then removing the element from b and from a, etc. But this doesn't appeal to me, it would be very inefficient (order of  time) while it should be no problem to do this in  time.Python 2.7 and 3.2 will add the  class which is a dictionary that maps elements to the number of occurrences of the element.  This can be used as a multiset.According to the docs you should be able to do something like this (untested, since I do not have either version installed).:Since you are stuck with 2.5 you could try importing it and define your own version if that fails.  That way you will be sure to get the latest version if it is available, and fall back to a working version if not. You will also benefit from speed improvements if if gets converted to a C implementation in the future.i.e.You can find the current Python source . I know \"for\" is not what you want, but it's simple and clear:Or if members of  might not be in  then use:..as wich wrote, this is wrong - it works only if the items are unique in the lists. And if they are, it's better to useI'm not sure what the objection to a for loop is: there is no multiset in Python so you can't use a builtin container to help you out.Seems to me anything on one line (if possible) will probably be helishly complex to understand.  Go for readability and KISS.  Python is not C :)to use list comprehension:would do the trick. It would change b in the process though. But I agree with jkp and Dyno Fu that using a for loop would be better.Perhaps someone can create a better example that uses list comprehension but still is KISS? Python 2.7+ and 3.0 have  (a.k.a. multiset).  The documentation links to  for Python 2.5:Then you can writeTo prove jkp's point that 'anything on one line will probably be helishly complex to understand', I created a one-liner. Please do not mod me down because I understand this is not a solution that you should actually use. It is just for demonstrational purposes.The idea is to add the values in a one by one, as long as the total times you have added that value does is smaller than the total number of times this value is in a minus the number of times it is in b:The horror! But perhaps someone can improve on it? Is it even bug free?Edit: Seeing Devin Jeanpierre comment about using a dictionary datastructure, I came up with this oneliner:Better, but still unreadable.You can try something like this:You have to define what [1, 2, 3] - [5, 6] should output though, I guess you want [1, 2, 3] thats why I ignore the ValueError.Edit:\nNow I see you wanted an exception if  does not contain all elements, added it instead of passing the ValueError.I attempted to find a more elegant solution, but the best I could do was basically the same thing that Dyno Fu said:Here's a relatively long but efficient and readable solution. It's O(n).You can use the  construct to do this. It looks quite ok, but beware that the  line itself will return a list of s.
Python

The list can be all  or one of it is an re.Match instance.\nWhat one liner check can I do on the returned list to tell me that the contents are all ?will return  if all of the elements of  are Note that  is a lot faster but requires that  be an actual  and not just an iterable.returns  if all items of  are falsy.:  Since match objects are always trucy and  is falsy, this will give the same result as  for the case at hand.  As demonstrated in , using  is by far the faster alternative.Since Match objects are never going to evaluate to false, it's ok and much faster to just use Or a bit weird but:OR:EDITED:
Python

I am reading a code. There is a class in which  method is defined. I figured out that this method is used to destroy an instance of the class. However, I cannot find a place where this method is used. The main reason for that is that I do not know how this method is used, probably not like that: . So, my questions is how to call the  method? Thank you for any help. is a . It is called when an object is  which happens after all references to the object have been deleted. In a  this could be right after you say  or, if  is a local variable, after the function ends. In particular, unless there are circular references, CPython (the standard Python implementation) will garbage collect immediately. However, this is the  of CPython. The only  property of Python garbage collection is that it happens  all references have been deleted, so this might not necessary happen  and . Even more, variables can live for a long time for , e.g. a propagating exception or module introspection can keep variable reference count greater than 0. Also, variable can be a part of  \u2014 CPython with garbage collection turned on breaks most, but not all, such cycles, and even then only periodically.Since you have no guarantee it's executed, one should  put the code that you need to be run into  \u2014 instead, this code belongs to  clause of the  block or to a context manager in a  statement. However, there are  for : e.g. if an object  references  and also keeps a copy of  reference in a global  () then it would be polite for  to also delete the cache entry. that the destructor provides (in violation of the above guideline) a required cleanup, you might want to , since there is nothing special about it as a method: . Obviously, you should you do so only if you know that it doesn't mind to be called twice. Or, as a last resort, you can redefine this method usingI wrote up the answer for another question, though this is a more accurate question for it.  Here is a slightly opinionated answer.Don't use . This is not C++ or a language built for destructors. The  method really should be gone in Python 3.x, though I'm sure someone will find a use case that makes sense. If you need to use , be aware of the basic limitations per :But, on the other hand:And my pesonal reason for not liking the  function.So, find a reason not to use .The  method (note spelling!) is called when your object is finally destroyed.  Technically speaking (in cPython) that is when there are no more references to your object, ie when it goes out of scope.If you want to delete your object and thus call the  method usewhich will delete the object (provided there weren't any other references to it).I suggest you write a small class like thisAnd investigate in the python interpreter, egNote that jython and ironpython have different rules as to exactly when the object is deleted and  is called.  It isn't considered good practice to use  though because of this and the fact that the object and its environment may be in an unknown state when it is called.  It isn't absolutely guaranteed  will be called either - the interpreter can exit in various ways without deleteting all objects.The  method, it will be called when the object is garbage collected.  Note that it isn't necessarily guaranteed to be called though.  The following code by itself won't necessarily do it:The reason being that  just decrements the reference count by one.  If something else has a reference to the object,  won't get called.There are a few caveats to using  though.  Generally, they usually just aren't very useful.  It sounds to me more like you want to use a close method or maybe a .See the .One other thing to note:   methods can inhibit garbage collection if overused.  In particular, a circular reference that has more than one object with a  method won't get garbage collected.  This is because the garbage collector doesn't know which one to call first.  See the documentation on the  for more info.
Python

I have two vectors as Python lists and an angle. E.g.:What is the best/easiest way to get the resulting vector when rotating the v vector around the axis?The rotation should appear to be counter clockwise for an observer to whom the axis vector is pointing. This is called the Take a look at . It provides a  class which has a method . It also provides a helper function  if you don't want to call the method on .Using the :A one-liner, with numpy/scipy functions.We use the following:  computes the taylor series of the exponential:\n\n, so it's time expensive, but readable and secure.\nIt can be a good way if you have few rotations to do but a lot of vectors.I just wanted to mention that if speed is required, wrapping unutbu's code in scipy's weave.inline and passing an already existing matrix as a parameter yields a 20-fold decrease in the running time.The code (in rotation_matrix_test.py):The timing:I made a fairly complete library of 3D mathematics for Python{2,3}. It still does not use Cython, but relies heavily on the efficiency of numpy. You can find it here with pip:Or have a look at my gitweb   and now also on github:  .Once installed, in python you may create the orientation object which can rotate vectors, or be part of transform objects. E.g. the following code snippet composes an orientation that represents a rotation of 1 rad around the axis [1,2,3], applies it to the vector [4,5,6], and prints the result:The output would beThis is more efficient, by a factor of approximately four, as far as I can time it, than the oneliner using scipy posted by B. M. above. However, it requires installation of my math3d package.
Python

When describing a python package in  in  in Python, is there a way to make it so automatically get every directory that has a  in it and include that as a subpackage?ie if the structure is: I want to avoid doing:and instead just do:and have it automatically find things like  and  since they have an init file. thanks.The easiest way (that I know of) is to use  to yield the packages:I would recommend using the find_packages() function available with  such as:and then do Same as dm76 answer, just that I also have tests in my repo, so I use:
Python

null=True\nblank=True\ndefault = 0What's the difference? When do you use what?Direct from :  Do you not understand all this?From :You can use \"\" to set the value that will be used for the field in question should your code not explicitly set it to a value.Use \"\" for form validation purposes - blank=True will allow the field to be set to an empty valueUse \"\" if you would like to store an empty value as \"null\" in the DB.  Often it's preferred, however, to set blank values to an empty string or to 0 as appropriate for a given field.In implementation terms:The 'blank' field corresponds to all forms. Specifies if this value is required in form and corresponding form validation is done.\n'True' allows empty values.The 'null' field corresponds to DB level. It will be set as NULL or NOT NULL at the DB.Hence if leave a field empty in admin with blank=true, NULL is fed into the DB. Now this might throw an error if that particular column in the DB is specified as NOT NULL.Is probably as laymen as it gets.Blank implies that it is NOT NULL and instead has some value that represents \"blank\" for that datatype, which in the case of a string is probably an empty string. For numbers it might be 0.
Python

I'm confused about how  searches for the executable when using .  It works if given absolute paths to the child process, but I'm trying to use relative paths.  I've found that if I set the environment variable PYTHONPATH then I can get imported modules from that path ok, and PYTHONPATH is there in , but it doesn't seem to help with the behaviour of .  I've also tried editing the  file adding PYTHONPATH to , like so and verified that when starting up python , either interactively, with ipython, or by running a script from the command line, that PYTHONPATH is successfully appearing in .  However,   doesn't search there for the executable.   I thought it was supposed to inherit the parents environment, if no  kwarg is specified?  Next I tried giving  explicitly, first by making a copy of  and secondly just by giving , and it still does not find the executable.  Now I'm stumped.  Hopefully an example will help explain my problem more clearly:/dir/subdir1/some_executable\n/dir/subdir2/some_script.pyIf I'm in  and I run  it works, but if I'm in  and I run  even though  is in the , then subprocess will throw .  (filling in details from a comment to make a separate answer)First off, relative paths (paths containing slashes) never get checked in any PATH, no matter what you do.  They are relative to the  only.  If you need to resolve relative paths, you will have to search the PATH manually, or munge the PATH to include the subdirectories and then just use the command name as in my suggestion below.If you want to run a program , use  and go from there to find the absolute path of the program, and then use the absolute path in .Secondly, there is  about how Python deals with bare commands (no slashes).  Basically, on Unix/Mac  uses  when invoked with , which means it looks at the value of   and no amount of changing  will help you fix that.  Also, on Windows with , it pays no attention to PATH at all, and will only look in relative to the current working directory.If you JUST need path evaluation and don't really want to run your command line through a shell, and are on UNIX, I advise using  instead of , as in .  This lets you pass a different PATH to the  process, which will use it to find the program.  It also avoids issues with shell metacharacters and potential security issues with passing arguments through the shell.  Obviously, on Windows (pretty much the only platform without a ) you will need to do something different.You appear to be a little confused about the nature of  and . is an environment variable that tells the OS shell where to search for executables. is an environment variable that tells the Python interpreter where to search for modules to import. It has nothing to do with  finding executable files.Due to the differences in the underlying implementation,  will only search the path by default on non-Windows systems (Windows has some system directories it always searches, but that's distinct from  processing). The only reliable cross-platform way to scan the path is by passing  to the subprocess call, but that has its own issues (as detailed in the )However, it appears your main problem is that you are passing a path fragment to  rather than a simple file name. As soon as you have a directory separator in there, you're going to disable the  search, even on a non-Windows platform (e.g. see the Linux documentation for the ).A relative path in subprocess.Popen acts relative to the current working directory, not the elements of the systems PATH.  If you run  from  than the expected executable location will be , a.k.a .If you would definitely like to use relative paths from a scripts own directory to a particular executable the best option would be to first construct an absolute path from the directory portion of the  global variable.The pythonpath is set to the path from where the python interpreter is executed. So, in second case of your example, the path is set to /dir and not /dir/subdir2\nThat's why you get an error.
Python

I know how to convert a numpy array into a tensor object with the function . My problem is that after I apply some preprocessing to this tensors in terms of brightness, contrast, etc, I would like to view the resulting transformations to evaluate and tweak my parameters.How can I convert a tensor into a numpy array so I can show it as an image with PIL?To convert back from tensor to numpy array you can simply run  on the transformed tensor.Any tensor returned by  or  is a NumPy array.Or:Or, equivalently:You need to: Code:This worked for me. You can try it in a ipython notebook. Just don't forget to add the following line:Maybe you can try\uff0cthis method:
Python

I'm fairly new when it comes to programming, and have started out learning python.What I want to do is to recolour sprites for a game, and I am given the original colours,\nfollowed by what they are to be turned into. Each sprite has between 20 and 60 angles, so\nlooping through each one in the folder for each colour is probably the way to go for me.\nMy code goes thusly;But I keep getting an error on the pathname, and on pix being a string value (They're all pictures)Any help appreciated. returns a list of file names. Thus,  is a string. You need to open the file before iterating on it, I guess.Also, be careful with backslashes in strings. They are mostly used for special escape sequences, so you need to escape them by doubling them. You could use the constant  to be more portable, or even use  :iterates over the letters of the filename. So that's certainly not what you want. You'll probably want to replace that line by:(assuming Python 2.6) and indent the rest of the loop accordingly. However, I'm not sure that the new  loop does what you want unless by  you mean a line of text in the current file. If the files are binary picture files, you'll first need to read their contents correcty - not enough info in your post to guess what's right here. The path is wrong because the backslashes need to be doubled up - backslash is an escape for special characters. does not return open files, it returns filenames. You need to open the file using the filename.
Python

I love how beautiful python looks/feels and I'm hoping this can be cleaner (readability is awesome).What's a clean way to accept an optional keyword argument when overriding a subclassed  where the optional  has to be used  the  call? I have a django form where I'd like to accept an optional user argument, but if I define it as one of the arguments , then the usual form call  assumes the positional argument refers to the keyword argument .Code speaks better than (my) words:I can make this the cleanest by looking into the actual  class to see what arguments it's looking for, but one of the greatest things about subclassing anything in python is collecting all  and  and passing it into whatever you subclassed. Also this doesn't hold up to any changes in the source.But unfortunately I have:Thanks for any input!I usually just do essentially what you're doing here. However, you can shorten/clean up your code by supplying a default argument to :
Python

Without going through with the installation, I want to quickly see all the packages that  would install.The closest you can get with pip directly is by using the  argument:For example, this is the output when installing celery:Admittedly, this does leave some cruft around in the form of temporary files, but it does accomplish the goal. If you're doing this with virtualenv (which you should be), the cleanup is as easy as removing the  directory.The accepted answer is no longer relevant for more current versions of pip and does not give an immediate answer without perusing multiple comments so I am providing an updated answer.This was tested with pip versions  and .To get the output without cluttering your current directory on Linux use tells pip the directory that download should put files in.Better, just use this script with the argument being the package name to get only the dependencies as output:Also available .If and only if the package is install, you can use . Look for the  filed at the end of the output.  Clearly, this breaks your requirement but might be useful nonetheless.For example:The command  should be used, as mentioned in comments by @radtek, since as of 7.0.0 (2015-05-21), --no-install is  from . This will download the dependencies needed into .
Python

When I call  it will generate  but there are times where I'd like it to generate  instead. I can't find in the documentation where I would specify this. Do I just need to do ? takes an  keyword argument that will return an absolute (rather than relative) URL.  I believe you will need to set a  config key with your root domain to make it work correctly.
Python

I have a very large dataset were I want to replace strings with numbers. I would like to operate on the dataset without typing a mapping function for each key (column) in the dataset. (similar to the fillna method, but replace specific string with assosiated value).\nIs there anyway to do this?Here is an example of my datasetThe desired result:very bad=1, bad=2, poor=3, good=4, very good=5//JonasUse 
Python

In Python 2, we could reassign  and  (but not ), but all three (, , and ) were considered builtin variables.  However, in Py3k all three were changed into keywords as per .From my own speculation, I could only guess that it was to prevent shenanigans like  which derive from the old  prank.  However, in Python 2.7.5, and perhaps before, statements such as  which reassigned  raised .Semantically, I don't believe , , and  are keywords, since they are at last semantically literals, which is what Java has done.  I checked PEP 0 (the index) and I couldn't find a PEP explaining why they were changed.Are there performance benefits or other reasons for making them keywords as opposed to literals or special-casing them like  in python2?Possibly because Python 2.6 not only allowed  but also allowed you to say funny things like:which would reset  to  for the entire process.  It can lead to really funny things happening:: As pointed out by , the  also states the following under :For two reasons, mainly:This was discussed some months ago on python-dev. \nHaving tons of links to the definition of True would be annoying, contrary to links to e.g. the nonlocal or with statements doc.And things I conclude why True and False will make things \"even finer\".
Python

I'd like to generate video using  feature.I've followed instructions found  and .And I now have the following process to build my  function:Fire a  instance and run this as root on it:I scp the resulting tarball to my laptop. And then run this script to build a zip archive. script is at the moment only a test to see if the stack is ok:Then I upload the resulting archive to S3 to be the source of my  function.\nWhen I test the function I get the following :I cant understand why python does not found the core directory that is present in the folder structure.EDIT:Following @jarmod advice I've reduced the function to:I now have the following error:I was also following your first link and managed to import  and  in a Lambda function this way (on Windows):With this, I could import numpy and pandas. I'm not familiar with moviepy, but scipy might already be tricky as Lambda has a  for unzipped deployment package size at 262 144 000 bytes. I'm afraid numpy and scipy together are already over that.With the help of all posts in this thread here is a solution for the records:To get this to work you'll need to:You can also download the  .The posts here help me to find a way to statically compile NumPy with libraries files that can be included in the AWS Lambda Deployment package. This solution does not depend on LD_LIBRARY_PATH value as in @rouk1 solution.The compiled NumPy library can be downloaded from Here are the steps to custom compile NumPyPrepare a fresh AWS EC instance with AWS Linux.Install compiler dependenciesInstall NumPy dependencies Create /var/task/lib to contain the runtime libraries/var/task is the root directory where your code will reside in AWS Lambda thus we need to statically link the required library files in a well known folder which in this case /var/task/libCopy the following library files to the /var/task/libGet the latest numpy source code from Go to the numpy source code folder e.g numpy-1.10.4\nCreate a site.cfg file with the following entries-lgfortran -lquadmath flags are required to statically link gfortran and quadmath libraries with files defined in runtime_library_dirsBuild NumPyInstall NumPyCheck whether the libraries are linked to the files in /var/task/libYou should seeAnother, very simple method that's possible these days is to build using the awesome docker containers that LambCI made to mimic Lambda: The  container resembles AWS Lambda with the addition of a mostly-complete build environment. To start a shell session in it:Inside the session:Or, with virtualenv:Later on you can use the main lambci/lambda container to test your build.I like @Vito Limandibhrata's answer but I think it's not enough to build numpy with runtime_library_dirs in numpy==1.11.1. If anybody think site-cfg is ignored, do the following:*.a files under atlas-sse3 are needed to build numpy. Also, you might need to run the following:to check numpy configuration. If it requires something more, you will see the following message:then site-cfg is going to be ignored.Tip: If pip is used to build numpy with runtime_library_dirs, you would better create  and add the following:then numpy recognizes .numpy-site.cfg file. It's quite simple and easy way.As of 2017, NumPy and SciPy have wheels that work on Lambda (the packages include precompiled  and ).\nAs far as I know, MoviePy is a pure Python module, so basically you could do:Then copy your handler into the  directory and zip it. Except, that you'll most likely exceed the 50/250 MB size limits. There are a couple of things that can help:Here's an example  that automates the above points.
Python

In the 2nd case below, Python tries to look for a local variable. When it doesn't find one, why can't it look in the outer scope like it does for the 1st case? This looks for x in the local scope, then outer scope:This gives  error:I am not allowed to modify the signature of function f2() so I can not pass and return values of x. However, I do need a way to modify x. Is there a way to explicitly tell Python to look for a variable name in the outer scope (something similar to the  keyword)?Python version: 2.7Workaround is to use a mutable object and update members of that object. Name binding is tricky in Python, sometimes.In Python 3.x this is possible:The problem and a solution to it, for Python 2.x as well, are given in  post. Additionally, please read  for more information on this subject.
Python

I've been searching for the accurate answer to this question for a couple of days now but haven't got anything good. I'm not a complete beginner in programming, but not yet even on the intermediate level.When I'm in the shell of Python, I type:  and I can see all the names of all the objects in the current scope (main block), there are 6 of them:Then, when I'm declaring a variable, for example , it automatically adds to that lists of objects under built-in module , and when I type  again, it shows now:The same goes for functions, classes and so on.  How do I delete all those new objects without erasing the standard 6 which where available at the beginning?I've read here about \"memory cleaning\", \"cleaning of the console\", which erases all the text from the command prompt window:  But all this has nothing to do with what I'm trying to achieve, it doesn't clean out all used objects.You can delete individual names with :or you can remove them from the  object:This is just an example loop; it defensively only deletes names that do not start with an underscore, making a (not unreasoned) assumption that you only used names without an underscore at the start in your interpreter. You could use a hard-coded list of names to keep instead (whitelisting) if you really wanted to be thorough. There is no built-in function to do the clearing for you, other than just exit and restart the interpreter.Modules you've imported () are going to remain imported because they are referenced by ; subsequent imports will reuse the already imported module object. You just won't have a reference to them in your current global namespace.Yes. There is a simple way to remove everything in iPython. \nIn iPython console, just type:Then system will ask you to confirm. Press y.\nIf you don't want to see this prompt, simply type:This should work..Actually python will reclaim the memory which is not in use anymore.This is called  which is automatic process in python. But still if you want to do it then you can delete it by . You can also do it by assigning the variable to  The only way to truly reclaim memory from unreferenced Python objects is via the garbage collector. The del keyword simply unbinds a name from an object, but the object still needs to be garbage collected. You can force garbage collector to run using the gc module, but this is almost certainly a premature optimization but it has its own risks. Using  has no real effect, since those names would have been deleted as they went out of scope anyway.
Python

I've two pandas data frames which have some rows in common.Suppose dataframe2 is a subset of dataframe1.One method would be to store the result of an inner merge form both dfs, then we can simply select the rows when one column's values are not in this common:Another method as you've found is to use  which will produce  rows which you can drop:However if df2 does not start rows in the same manner then this won't work:will produce the entire df:Suppose you have two dataframes, df_1 and df_2 having multiple fields(column_names) and you want to find the only those entries in df_1 that are not in df_2 on the basis of some fields(e.g. fields_x, fields_y), follow the following steps.Step1.Add a column key1 and key2 to df_1 and df_2 respectively.Step2.Merge the dataframes as shown below. field_x and field_y are our desired columns.Step3.Select only those rows from df_1 where key1 is not equal to key2.Step4.Drop key1 and key2.This method will solve your problem and works fast even with big data sets. I have tried it for dataframes with more than 1,000,000 rows.As already hinted at, isin requires columns and indices to be the same for a match. If match should only be on row contents, one way to get the mask for filtering the rows present is to convert the rows to a (Multi)Index:If index should be taken into account, set_index has keyword argument append to append columns to existing index. If columns do not line up, list(df.columns) can be replaced with column specifications to align the data.could alternatively be used to create the indices, though I doubt this is more efficient.you can do it using  method:Explanation:a bit late, but it might be worth checking the \"indicator\" parameter of pd.merge.See this other question for an example:\nAssuming that the indexes are consistent in the dataframes (not taking into account the actual col values):My way of doing this involves adding a new column that is unique to one dataframe and using this to choose whether to keep an entryThis makes it so every entry in df1 has a code - 0 if it is unique to df1, 1 if it is in both dataFrames. You then use this to restrict to what you want
Python

The python documentation frequently speaks of \"containers\".  :But I can't find any official definition of containers, neither a list of them.For Python 2.7.3:( returns ) ( returns ):Tell me which other builtin types you have checked for   and I'll add them to the list.Containers are any object that holds an arbitrary number of other objects.  Generally, containers provide a way to access the contained objects and to iterate over them.Examples of containers include , , , ; these are the .  More container types are available in the  module.Strictly speaking, the  abstract base class ( in Python2) holds for any type that supports the  operator via the  magic method; so if you can write  then  is  a container, but not always: an important point of difference between  and general  is that when iterated over, containers will return existing objects that they hold a reference to, while generators and e.g.  objects will create a new object each time.  This has implications for garbage collection and deep object traversal (e.g.  and serialisation).As an example,  supports the  operator, but it is certainly  a container!The intent of the  abstract base class in only considering the  magic method and not other ways of supporting the  operator is that a true container should be able to test for containment in a single operation and without observably changing internal state.  Since  defines  as an abstract method, you are guaranteed that if  then  supports the  operator.In practice, then, all containers will have the  magic method. However, when testing whether an object is a container you should use  for clarity and for forward compatibility should the  subclass check ever be changed.According to , the most general definition of a container is simply an object that implements .  In general, Python concepts like \"container\" or \"sequence\" are not defined abstractly; they are \"duck-typed\" by their behavior.  That is, a container is something that you can use the  operator on.The Python builtin container types are tuple, list, dict, set, frozenset and str and unicode (or bytes and str in Python 3), as well as a couple other constructs that are technically types but are not commonly used outside of specific contexts (e.g., buffer objects and xrange objects).  Additional container types are provided in the  module.Container are all python objects that contain other object like  or . The  type is an ABC, it behave like an interface. A Container is a class that implements the  method.Here is the 
Python

I went through the  in the  documentation, but it wasn't clear to me how I can make a plot that fills the area between two specific vertical lines.For example, say I want to create a plot between  and  (for the full  range of the plot). Should I use ,  or ? Can I use the  condition for this?It sounds like you want , rather than one of the fill between functions. The differences is that  (and ) will fill up the entire y (or x) extent of the plot regardless of how you zoom.For example, let's use  to highlight the x-region between 8 and 14:You could use  to do this, but the extents (both x and y) of the rectangle would be in .  With , the y-extents of the rectangle default to 0 and 1 and are in  (in other words, percentages of the height of the plot).  To illustrate this, let's make the rectangle extend from 10% to 90% of the height (instead of taking up the full extent).  Try zooming or panning, and notice that the y-extents say fixed in display space, while the x-extents move with the zoom/pan:
Python

Where should utility functions live in Django? Functions like custom encrypting/decrypting a number, sending tweets, sending email, verifying object ownership, custom input validation, etc. Repetitive and custom stuff that I use in a number of places in my app. I'm definitely breaking DRY right now.I saw some demos where functions were defined in models.py, although that didn't seem conceptually right to me. Should they go in a \"utilities\" app that gets imported into my project? If so, where do they go in the utilities app? The models.py file there?Thanks for helping this n00b out. Let me be even more specific. Say I need a function \"light_encrypt(number)\" which takes the param \"number\", multiplies it by 7, adds 10 and returns the result, and another function \"light_decrypt(encr_number) which takes the param \"encr_number\", subtracts 10, divides by 7 and returns the results. Where in my Django tree would I put this? This is not middleware, right? As Felix suggests, do I create a python package and import it into the view where I need these functions?Different  but same answer:OK, after reading the comments and answer here I've decided to create a directory called \"common/util/\" inside my project directory. Within that I have a file \"__ init__.py\" where I have my little helper functions. I guess if the file gets too big, I'll then split out the functions into individual .py files in common. So now, my project structure looks like this. Please correct if I'm making any poor choices, I'm early enough in development that I can fix it now while it is still easy to do so!Here is another way to do it:If the utility functions can be a stand-alone module\nand you are using a virtualenv environment for your django app\nthen you can bundle the functionality as a package and install it in your virtualenv.This makes it easy to import where ever you need it in your django app.
Python

An Android/Iphone app will be accessing application data from the server. \n[Django-Python]How can I secure the communication with the mobile app ? : Secure enough for sensitive information like passwords, there shall be no direct way of decryption except brute-forcing. :: :So, how can/should I move forward on this ?\nShould I implement casual approach :Conclusion was to use AES, since if I can keep the key secure then I am as good as SSL.\nPlus I can keep changing the key over-time for better security.\nContribute if you think there is a better way, do read the entire post before posting.You're working on bad information. SSL can absolutely authenticate the client, it's just not something that is done for the bulk of SSL as the protocol is (or, atleast was) typically used to protect e-commerce sites where authentication of the server was important but doing so with the client was not important and/or not feasible. What you want to do is employ mutually-authenticated SSL, so that your server will only accept incoming connections from your app and your app will only communicate with your server.Here's the high-level approach. Create a self-signed server SSL certificate and deploy on your web server. If you're using Android, you can use the keytool included with the Android SDK for this purpose; if you're using another app platform like iOS, similar tools exist for them as well. Then create a self-signed client and deploy that within your application in a custom keystore included in your application as a resource (keytool will generate this as well). Configure the server to require client-side SSL authentication and to only accept the client certificate you generated. Configure the client to use that client-side certificate to identify itself and only accept the one server-side certificate you installed on your server for that part of it.If someone/something other than your app attempts to connect to your server, the SSL connection will not be created, as the server will reject incoming SSL connections that do not present the client certificate that you have included in your app.A step-by-step for this is a much longer answer than is warranted here. I would suggest doing this in stages as there are resources on the web about how to deal with self-signed SSL certificate in both Android and iOS, both server and client side. There is also a complete walk-through in my book, , published by O'Reilly.SSL does have two way authentication as already mentioned by the other commenters. \nBut, I do not think you even should try to authenticate the client, aka the app. You only authenticate the user (resource owner in Oauth terms) not the agent or client.It is a fact that mobile apps cannot hold any secrets. So never put certificates/ passwords on the device. Typical bad example would be to save the username and password in some system keystore, such as IOS keychain. If the app user does not set password on the phone, the entire keystore is saved in plain text and anyone can dump all information. Embed a certificate in the app is almost equally bad as unlike a server, mobile phone is not locked in a computer room. People do lose them.On that basis, you need a token based solution, so that the app does not need to hold secrets. You pass on the secrets (user login credentials) and clear them out from memory immediately. You only need to hold the token, which will be short lived (expires in 30 mins etc.)Oauth 2.0 Implicit flow is designed to solve this problem. However, its a far from perfect. And there are some fundamental issues with the Oauth 2.0 spec.  Especially, implementing this flow requires the app to use UIWebView (embeded browser), which itself can be insecure and bad user experience.  So this pretty much eliminates all redirection based flows.  The only well known app that uses OAuth 2 redirection flow is facebook, and its done badly. OAuth 2.0 Resource Owner flow is one option.   With this flow, your entire systems security level can be as high as B2C solution -- browser based online banking solution as an example. This means anyone with the username password will be able to access the resources on the server -- the same level of security for a browser based solution.However, you still need to be careful, as mentioned before, the OAuth 2 spec has some fundamental issues -- in this case, you cannot follow its spec to implement the token refresh logic -- that typically involves using a never-expire refreshing token-- which can be seen as Google's OAuth 2 implementation. That token then becomes a secret itself -- defeats the purpose of using OAuth. One workaround is to auto-renew the token based on last activity. Anyway, mobile app security is not a new topic at all but sadly we still do not have any standard tools/mechinisms to solve those unique challenges. Thats why banks pay millions to do their mobile banking solution and yet they still fail() \n;-)Use client authentication with SSL or just layer your own client authentication (username/password, token, etc) on top of server-authentication SSL. (Edit: Moving the comment here, since it won't fit as a comment)To elaborate a bit, any authentication info needs to be stored or entered in the app. If you have people enter the password each time, you don't need to save it, but that's clearly inconvenient. You can encrypt it with a device-specific key, so it's not visible on rooted devices. With a private key, you need to either protect it with a user entered password (see above) or have it protected by the system. That is only available since Android 4.0 (ICS) with the public API to the system keystore, the  class. In this case, the user needs to unlock (using pattern/password or PIN) the phone to access the keystore.
Python

\nLast year I made some C++ code to compute posterior probabilities for a particular type of model (described by a Bayesian network). The model worked pretty well and some other people started to use my software. Now I want to improve my model. Since I'm already coding slightly different inference algorithms for the new model, I decided to use python because runtime wasn't critically important and python may let me make more elegant and manageable code.Usually in this situation I'd search for an existing Bayesian network package in python, but the inference algorithms I'm using are my own, and I also thought this would be a great opportunity to learn more about good design in python.I've already found a great python module for network graphs (networkx), which allows you to attach a dictionary to each node and to each edge. Essentially, this would let me give nodes and edges properties. For a particular network and it's observed data, I need to write a function that computes the likelihood of the unassigned variables in the model. For instance, in the classic \"Asia\" network (), with the states of \"XRay Result\" and \"Dyspnea\" known, I need to write a function to compute the likelihood that the other variables have certain values (according to some model). \nI'm going to try a handful of models, and in the future it's possible I'll want to try another model after that. For instance, one model might look exactly like the Asia network. In another model, a directed edge might be added from \"Visit to Asia\" to \"Has Lung Cancer.\" Another model might use the original directed graph, but the probability model for the \"Dyspnea\" node given the \"Tuberculosis or Cancer\" and \"Has Bronchitis\" nodes might be different. All of these models will compute the likelihood in a different way.All the models will have substantial overlap; for instance, multiple edges going into an \"Or\" node will always make a \"0\" if all inputs are \"0\" and a \"1\" otherwise. But some models will have nodes that take on integer values in some range, while others will be boolean. In the past I've struggled with how to program things like this. I'm not going to lie; there's been a fair amount of copied and pasted code and sometimes I've needed to propagate changes in a single method to multiple files. This time I  want to spend the time to do this the right way.Some options:Thanks a lot for your help.\nObject oriented ideas help a lot here (each node has a designated set of predecessor nodes of a certain node subtype, and each node has a likelihood function that computes its likelihood of different outcome states given the states of the predecessor nodes, etc.). OOP FTW!I've been working on this kind of thing in my spare time for quite a while.  I think I'm on my third or fourth version of this same problem right now.  I'm actually getting ready to release another version of Fathom (https://github.com/davidrichards/fathom/wiki) with dynamic bayesian models included and a different persistence layer.As I've tried to make my answer clear, it's gotten quite long.  I apologize for that.  Here's how I've been attacking the problem, which seems to answer some of your questions (somewhat indirectly):I've started with Judea Pearl's breakdown of belief propagation in a Bayesian Network. That is, it's a graph with prior odds (causal support) coming from parents and likelihoods (diagnostic support) coming from children.  In this way, the basic class is just a BeliefNode, much like what you described with an extra node between BeliefNodes, a LinkMatrix.  In this way, I explicitly choose the type of likelihood I'm using by the type of LinkMatrix I use.  It makes it easier to explain what the belief network is doing afterwards as well as keeps the computation simpler.Any subclassing or changes that I'd make to the basic BeliefNode would be for binning continuous variables, rather than changing propagation rules or node associations.I've decided on keeping all data inside the BeliefNode, and only fixed data in the LinkedMatrix.  This has to do with ensuring that I maintain clean belief updates with minimal network activity.  This means that my BeliefNode stores:The LinkMatrix can be constructed with a number of different algorithms, depending on the nature of the relationship between the nodes.  All of the models that you're describing would just be different classes that you'd employ.  Probably the easiest thing to do is default to an or-gate, and then choose other ways to handle the LinkMatrix if we have a special relationship between the nodes.  I use MongoDB for persistence and caching.  I access this data inside of an evented model for speed and asynchronous access.  This makes the network fairly performant while also having the opportunity to be very large if it needs to be.  Also, since I'm using Mongo in this way, I can easily create a new context for the same knowledge base.  So, for example, if I have a diagnostic tree, some of the diagnostic support for a diagnosis will come from a patient's symptoms and tests.  What I do is create a context for that patient and then propagate my beliefs based on the evidence from that particular patient.  Likewise, if a doctor said that a patient was likely experiencing two or more diseases, then I could change some of my link matrices to propagate the belief updates differently.If you don't want to use something like Mongo for your system, but you are planning on having more than one consumer working on the knowledge base, you will need to adopt some sort of caching system to make sure that you are working on freshly-updated nodes at all times.My work is open source, so you can follow along if you'd like.  It's all Ruby, so it would be similar to your Python, but not necessarily a drop-in replacement.  One thing that I like about my design is that all of the information needed for humans to interpret the results can be found in the nodes themselves, rather than in the code.  This can be done in the qualitative descriptions, or in the structure of the network.So, here are some important differences I have with your design:One big caveat: some of what I'm talking about hasn't been released yet.  I worked on the stuff I am talking about until about 2:00 this morning, so it's definitely current and definitely getting regular attention from me, but isn't all available to the public just yet.  Since this is a passion of mine, I'd be happy to answer any questions or work together on a project if you'd like.The  solves a similar problem: you describe your problem in terms of constraints on finite domain variables, constraint propagators and distributors, cost functions. When no more inference is possible but there are still unbound variables, it uses your cost functions to split the problem space on the unbound variable that most likely reduces search costs: that is, if X is between [a,c] is such a variable, and c (a < b < c) is the point most likely to reduce search cost, you end up with two problem instances where X is between [a,b] and, in the other instance, X is between [b,c]. Mozart does this rather elegantly since it reifies variable binding as a first class object (this is very useful, since Mozart is pervasively concurrent and distributed, to move a problem space to a different node). In its implementation, I suspect that it employs a copy-on-write strategy.You can surely implement a copy-on-write scheme in a graph-based library (tip: numpy uses various strategies to minimize copying; if you base your graph representation on it, you may get copy-on-write semantics for free) and reach your goals.I'm not too familiar with Bayesian Networks, so I hope the following is usefull:In the past I had a seemingly similar problem with a Gaussian Process regressor, instead of a\nbayesian classifier.I ended up using inheritance, which worked out nicely. All model-specific paremeters are set with the constructor. The calculate() functions are virtual.\nCascading different methods (e.g. a sum-method which combines an arbitrary number of other methods) also works nicely that way.I think you need to ask a couple questions that influence the design.If most of the time will be spent with existing models and new models will be less common, then inheritance is probably the design I would use.  It makes the documentation easy to structure and the code that uses it will be easy to understand.If the major purpose of the library is to provide a platform for experimenting with different models, then I would take the graph with properties that map to functors for computing things based on parents.  The library would be more complex and graph creation would be more complex, but it would be far more powerful as it would allow you to do hybrid graphs that change the computation functor based on the nodes.Regardless of what final design you work towards, I would start with a simple one class-one implementation design.  Get it passing a set of automated tests, then refactor into the more full design after that is done.  Also, don't forget version control ;-)
Python

I'm trying to understand the relationship between decision_function and predict, which are instance methods of SVC  (). So far I've gathered that decision function returns pairwise scores between classes. I was under the impression that predict chooses the class that maximizes its pairwise score, but I tested this out and got different results. Here's the code I was using to try and understand the relationship between the two. First I generated the pairwise score matrix, and then I printed out the class that has maximal pairwise score which was different than the class predicted by clf.predict.Does anyone know the relationship between these predict and decision_function?I don't fully understand your code, but let's go trough the example of the documentation page you referenced:Now let's apply both the decision function and predict to the samples:The output we get is:And that is easy to interpret: The desion function tells us on which side of the hyperplane generated by the classifier we are (and how far we are away from it). Based on that information, the estimator then label the examples with the corresponding label.When you call , you get the output from each of the pairwise classifiers (n*(n-1)/2 numbers total). See .Each classifier puts in a vote as to what the correct answer is (based on the sign of the output of that classifier);  returns the class with the most votes.For those interested, I'll post a quick example of the  function translated from C++ () to python:There are a lot of input arguments for  and , but note that these are all used internally in by the model when calling . In fact, all of the arguments are accessible to you inside the model after fitting:They probably have a bit complicated mathematical relation. But if you use the  in  classifier, the relation between those two will be more clear! Because then  will give you scores for each class label (not same as SVC) and predict will give the class with the best score. 
Python

There is almost no documentation for it here:\nMaybe someone could, by example, show me how to populate a  in Django?-thanks.Looking at the source for django...Check out that regex validator.  Looks like as long as you give it a list of integers and commas, django won't complain.You can define it just like a charfield basically:And populate it like this:I just happened to have dealt with CommaSeparatedIntegerField in my latest project. I was using MySQL and it seemed like supplying a string of comma separated integer values is very DB friendly e.g. '1,2,3,4,5'. If you want to leave it blank, just pass an empty string.It does act like a CharField, and beaved in a weird way for me.. I ended up with values like \"[1, 2, 3, 4, 5]\" including the brackets in my database! So watch out!
Python

Lets say I have a MultiIndex Series :and I want to apply a function which uses the index of the row:How can I do  for such a function? What is the recommended way to make this kind of operations? I expect to obtain a new Series with the values resulting from this function applied on each row and the same MultiIndex.I don't believe  has access to the index; it treats each row as a numpy object, not a Series, as you can see:To get around this limitation, promote the indexes to columns, apply your function, and recreate a Series with the original index.Other approaches might use , which often gets a little ugly in my opinion, or , which is likely to be slower -- perhaps depending on exactly what  does.Make it a frame, return scalars if you want (so the result is a series)SetupPrinting functionSince you can return anything here, just return the scalars (access the index via the  attribute)You  find it faster to use  rather than  here:Also you can use numpy-style logic/functions to any of the parts:You can access the whole row as argument inside the fucntion if you use DataFrame.apply() instead of Series.apply(). 
Python

I'm confused about the rules Pandas uses when deciding that a selection from a dataframe is a copy of the original dataframe, or a view on the original.If I have, for example,I understand that a  returns a copy so that something likewill have no effect on the original dataframe, . I also understand that scalar or named slices return a view, so that assignments to these, such as or will change . But I'm lost when it comes to more complicated cases. For example, changes , butdoes not.Is there a simple rule that Pandas is using that I'm just missing? What's going on in these specific cases; and in particular, how do I change all values (or a subset of values) in a dataframe that satisfy a particular query (as I'm attempting to do in the last example above)?Note: This is not the same as ; and I have read , but am not enlightened by it. I've also read through the \"Related\" questions on this topic, but I'm still missing the simple rule Pandas is using, and how I'd apply it to \u2014 for example \u2014\u00a0modify the values (or a subset of values) in a dataframe that satisfy a particular query.Here's the rules, subsequent override:Your example of is not guaranteed to work (and thus you shoulld  do this). Instead do:as this is  and will always workThe chained indexing is 2 separate python operations and thus cannot be reliably intercepted by pandas (you will oftentimes get a , but that is not 100% detectable either). The , which you pointed, offer a much more full explanation.
Python

This  of @Dunes states, that due to pipeline-ing there is (almost) no difference between floating-point multiplication and division. However, from my expience with other languages I would expect the division to be slower.My small test looks as follows:For different commands and  I get the following times on my machine:The most interesting part: dividing by  is almost twice as fast as dividing by . One could assume, it is due to some smart optimization, e.g. replacing division by . However the timings of  and  are too far off to support this claim.In general, the division by floats with values  is faster:It gets even more interesting, if we look at :Now,  there is no difference between division by  and by !I tried it out for different numpy versions and different machines. On some machines (e.g. Intel Xeon E5-2620) one can see this effect, but not on some other machines  - and this does not depend on the numpy version.With the script of @Ralph Versteegen (see his great answer!) I get the following results: What is the reason for higher cost of the division by  compared to division by  for some processors, if the array sizes are large (>10^6).  The @nneonneo's answer states, that for some intel processors there is an optimization when divided by powers of two, but this does not explain, why we can see the benefit of it only for large arrays.The original question was \"How can these different behaviors (division by  vs. division by ) be explained?\"Here also, my original testing script, which produced the timings:At first I suspected that numpy is invoking BLAS, but at least on my machine (python 2.7.13, numpy 1.11.2, OpenBLAS), it doesn't, as a quick check with gdb reveals:In fact, numpy is running exactly the same generic loop regardless of the constant used. So all timing differences are purely due to the CPU.Actually, division is an instruction with a highly variable execution time. The amount of work to be done depends on the bit patterns of the operands, and special cases can also be detected and sped up. According to  (whose accuracy I do not know), on your E5-2620 (a Sandy Bridge) DIVPD has a latency and an inverse throughput of 10-22 cycles, and MULPS has latency 10 cycles and inverse throughput of 5 cycles. Now, as for  being slower than . gdb shows that exactly the same function is being used for multiplication, except now the output  differs from first input . So it has to be purely an artifact of the extra memory being drawn into cache slowing down the non-inplace operation for the large input (even though MULPS is producing only 2*8/5 = 3.2 bytes of output per cycle!). When using the 1e4-sized buffers, everything fits in cache, so that doesn't have a significant effect, and other overheads mostly drown out the difference between  and .Still, there are lots of weird effects in those timings, so I plotted some a graph (code to generate this is below)I've plotted size of the A array against the number of CPU cycles per DIVPD/MULPD/ADDPD instruction. I ran this on a 3.3GHz AMD FX-6100. Yellow and red vertical lines are L2 and L3 cache size. The blue line is the supposed maximum throughput of DIVPD according to those tables, 1/4.5cycles (which seems dubious). As you can see, not even  gets anywhere near this, even when the \"Overhead\" of performing an numpy operation falls close to zero. So there is about 24 cycles of overhead just looping and reading and writing 16 bytes to/from L2 cache! Pretty shocking, maybe the memory accesses aren't aligned.Lots of interesting effects to note:Unfortunately, on another machine with a CPU with different FPU speed, cache size, memory bandwidth, numpy version, etc, these curves could look quite different.My take-away from this is: chaining together multiple arithmetic operations with numpy is going to be many times slower than doing the same in Cython while iterating over the inputs just once, because there is no \"sweet spot\" at which the cost of the arithmetic operations dominates the other costs.Intel CPUs have special optimizations when dividing by powers of two. See, for example, , where it statesAlthough this applies to FDIV and not DIVPD (as @RalphVersteegen's answer notes), it would be quite surprising if DIVPD did not also implement this optimization.Division is normally a very slow affair. However, a division by a power of two is just an exponent shift, and the mantissa usually doesn't need to change. This makes the operation very fast. Furthermore, it's easy to detect a power of two in floating-point representation as the mantissa will be all zeros (with an implicit leading 1), so this optimization is both easy to test for and cheap to implement.
Python

I have encountered an interesting case in my programming job that requires me to implement a mechanism of dynamic class inheritance in python. What I mean when using the term \"dynamic inheritance\" is a class that doesn't inherit from any base class in particular, but rather chooses to inherit from one of several base classes at instantiation, depending on some parameter.My question is thus the following: in the case I will present, what would be the best, most standard and \"pythonic\" way of implementing the needed extra functionality via dynamic inheritance.To summarize the case in point in a simple manner, I will give an example using two classes that represent two different image formats:  and  images. I will then try to add the ability to support a third format: the  image. I realize my question isn't that simple, but I hope you are ready to bare with me for a few more lines.This script contains two classes:  and , both inheriting\nfrom the  base class. To create an instance of an image object, the user is asked to call the  function with a file path as the only parameter.This function then guesses the file format ( or ) from the path and\nreturns an instance of the corresponding class.Both concrete image classes (and ) are able to decode\nfiles via their  property. Both do this in a different way. However,\nboth ask the  base class for a file object in order to do this.Building on the first image example case, one would like to\nadd the following functionality:An extra file format should be supported, the  format. Instead of\nbeing a new image file format, it is simply a compression layer that,\nonce decompressed, reveals either a  image or a  image.The  function keeps its working mechanism and will\nsimply try to create an instance of the concrete image class \nwhen it is given a  file. Exactly in the same way it would\ncreate an instance of  when given a  file.The  class just wants to redefine the  property.\nIn no case does it want to redefine the  property. The crux\nof the problem is that, depending on what file format is hiding\ninside the zip archive, the  classes needs to inherit\neither from  or from  dynamically. The correct class to\ninherit from can only be determined upon class creation when the \nparameter is parsed.Hence, here is the same script with the extra  class\nand a single added line to the  function.Obviously, the  class is non-functional in this example.\nThis code requires Python 2.7.I have found a way of getting the wanted behavior by intercepting the  call in the  class and using the  function. But it feels clumsy and I suspect there might be a better way using some Python techniques or design patterns I don't yet know about.Bear in mind if you want to propose a solution that the goal is not to change the behavior of the  function. That function should remain untouched. The goal, ideally, is to build a dynamic  class.I just don't really know what the best way to do this is. But this is a perfect occasion for me to learn more about some of Python's \"black magic\". Maybe my answer lies with strategies like modifying the  attribute after creation or maybe using the  class attribute? Or maybe something to do with the special  abstract base classes could help here? Or other unexplored Python territory?What about defining the  class on function-level ?\nThis will enable your .: Without need to change I would favor composition over inheritance here.  I think your current inheritance hierarchy seems wrong.  Some things, like opening the file with or gzip have little to do with the actual image format and can be easily handled in one place while you want to separate the details of working with a specific format own classes.  I think using composition you can delegate implementation specific details and have a simple common Image class without requiring metaclasses or multiple inheritance.I only tested this on a few local png and jpeg files but hopefully it illustrates another way of thinking about this problem.If you ever need \u201cblack magic\u201d, first try to think about a solution that doesn't require it. You're likely to find something that works better and results in needs clearer code.It may be better for the image class constructors to take an  instead of a path.\nThen, you're not limited to files on the disk, but you can use file-like objects from urllib, gzip, and the like.Also, since you can tell JPG from PNG by looking at the contents of the file, and for gzip file you need this detection anyway, I recommend not looking at the file extension at all.For black magic, go to , but think twice before using that, especially at work.You should use composition in this case, not inheritance. Take a look at the . The  class should decorate other image classes with the desired functionality.With decorators, you get a very dynamic behavior depending on the composition that you create:It's more flexible also, you can have other decorators:Each decorator just encapsulates the functionality it adds and delegates to the composed class as needed.
Python

If  is not set, the Flask framework will not allow you to set or access the session dictionary. This is all that the flask user guide has to say on the subject.I am very new to web development and I have no idea how/why any security stuff works. I would like to understand what flask is doing under the hood.\nWhy does flask force us to set this secret_key property? How does flask use the secret_key property? Anything that requires encryption (for safe-keeping against tampering by attackers) requires the secret key to be set. For  Flask itself, that 'anything' is the  object, but other extensions can make use of the same secret. is merely the value set for the  configuration key, or you can set it directly.The  has good, sane advice on what kind of server-side secret you should set.Encryption relies on secrets; if you didn't set a server-side secret for the encryption to use, everyone would be able to break your encryption; it's like the password to your computer. The secret plus the data-to-sign are used to create a signature string, a hard-to-recreate value using a ; only if you have the exact same secret  the original data can you recreate this value, letting Flask detect if anything has been altered without permission. Since the secret is never included with data Flask sends to the client, a client cannot tamper with session data and hope to produce a new, valid signature. Flask uses the  to do all the hard work; sessions use the  with a customized JSON serializer.
Python

Python's NOSE testing framework has the concept of . The purpose of this is not to test concurrency in the code, but to make tests for code that has \"no side-effects, no ordering issues, and no external dependencies\" run faster. The performance gain comes from concurrent I/O waits when they are accessing different devices, better use of multi CPUs/cores, and by running time.sleep() statements in parallel.I believe the same thing could be done with Python's unittest testing framework, by having a plugin Test Runner.Has anyone had any experience with such a beast, and can they make any recommendations?Python unittest's builtin testrunner does not run tests in parallel.  It probably wouldn't be too hard write one that did.  I've written my own just to reformat the output and time each test.  That took maybe 1/2 a day.  I think you can swap out the TestSuite class that is used with a derived one that uses multiprocess without much trouble.The  package is an extension of unittest which supports running tests concurrently. It can be used with your old test classes that inherit .For example:Please use , if you want parallel run.More info: 
Python

I have a triangle (A, B, C) and am trying to find the angle between each pair of the three points.The problem is that the algorithms I can find online are for determining the angle between vectors. Using the vectors I would compute the angle between the vector that goes from (0, 0) to the point I have, and that doesn't give me the angles inside the triangle.OK, here's some code in Python after the method on the Wikipedia page and after subtracting the values:That gives me 60.2912487814, 60.0951900475 and 120.386438829, so what am I doing wrong?There are two errors here.If I make these modifications I get a result that makes sense:which prints outI'd probably make things more symmetrical and use A, B, C vectors that are cyclic and sum to zero:which prints outThe minus signs in the dot product come because we're trying to get the inside angles.I'm sorry we drove you away in your time of need, by closing the question.I would use the , since you can easily calculate the length of each side of the triangle and then solve for each angles individually.Alternatively, if you only know the length of the sides of the triangle, you can use the .Suppose that you want the angle at A.  Then you need to find the angle between the vector from A to B and the vector from A to C.  The vector from A to B is just B-A.  (Subtract the coordinates.)Create three vectors, one from v2 to v1 (v2-v1), one from v3 to v1 (v3-v1), and one from v3 to v2 (v3-v2). Once you have these three vectors, you can use the algorithms you already found along with the fact that all the angles will add to 180 degrees.
Python

This question likely betrays a misconception, but I'm curious what the \"Tomcat\" of the Python world is.All of my web programming experience is in Java (or Groovy) so I think in Java terms. And when I think of making a basic web-app, I think of writing some servlets, building a WAR file, and deploying it in Tomcat or another servlet container.In Python, suppose I wrote some code that was capable of responding to HTTP requests, what would I do with it? How would I deploy it?Specifically: What is the most commonly used container in Python? And is there an equivalent of a WAR file, a standard packaging of a web-app into one file that works in the various containers?There are different approaches which have one thing in common: They usually communicate via WSGI with their \"container\" (the server receiving the HTTP requests before they go to your Python code).There are various containers:That's nice, but irrelevant.  That's just a Java-ism, and doesn't apply very widely outside Java.That depends.There isn't one.There isn't one.HTTP is a protocol for producing a response to a request.  That's it.  It's really a very small thing.You have CGI scripts which can respond to a request.  The Python  library can do that.  .This is relatively inefficient because the simple CGI rule is \"fire off a new process for each request.\"  It can also be insecure if the script allows elevated privileges or badly planned-out uploads.You have the  framework to connect Apache to Python.  This can behave like CGI, or it can have a dedicated Python \"daemon\" running at the end of a named pipe.  The WSGI standard defines a format for request and response processing that's very handy and very extensible.  Most of the frameworks -- in one way or another -- are WSGI compatible.Finally, there are more complete frameworks that include class definitions for requests and responses, URL parsing, Authentication, Authorization, etc., etc.Here's a list: Maybe 'uwsgi' will help. Here is the link:There are many web-servers available for python. Some of the webservers like CherryPy was written in Python itself. The most coolest part of the answer is that tomcat server itself support Python-based applications.For further details look into this site: 
Python

Why python 2.7 doesn't include Z character (Zulu or zero offset) at the end of UTC datetime object's isoformat string unlike JavaScript?Whereas in javascriptPython  objects don't have time zone info by default, and without it, Python actually violates the ISO 8601 specification (). You can use the  to get some default time zones, or directly subclass  yourself:Then you can manually add the time zone info to :Note that this DOES conform to the ISO 8601 format, which allows for either  or  as the suffix for UTC. Note that the latter actually conforms to the standard better, with how time zones are represented in general (UTC is a special case.)Python datetimes are a little clunky. Use .Arrow has essentially the same api as datetime, but with timezones and some extra niceties that should be in the main library.Python's  does not support the  suffixes like 'Z' suffix for UTC. The following simple string replacement does the trick: is essentially the same as See: Or you could use  to achieve the same effect:Note: This option works only when you know the date specified is in UTC. Going further, you may be interested in displaying human readable timezone information,  with   timezone flag: 
Python

I've been playing with various ways of doing literate programming in Python.  I like , but I have two main problems with it: first, it is hard to build on Windows, where I spend about half my development time; and second, it requires me to indent each chunk of code as it will be in the final program --- which I don't necessarily know when I write it.  I don't want to use Leo, because I'm very attached to Emacs.Is there a good literate programming tool that:Thanks!Correction:   allow me to indent later --- I misread the paper I found on it.  That leaves me with only the \"Runs on Windows\" problem.I did this:You can get any number of web/weave products that will help you construct a document and code in one swoop.You can -- pretty easily -- write your own.  It's not rocket science to yank the Python code blocks out of RST source and assemble it.  Indeed, I suggest you write your own Docutils directives to assemble the Python code from an RST source document.You run the RST through docutils rst2html (or Sphinx) to produce your final HTML report.You run your own utility on the same RST source to extract the Python code blocks and produce the final modules.I have written Pweave , that is aimed for dynamic report generation and uses noweb syntax. It is a pure python script so it also runs on Windows. It doesn't fix your indent problem, but maybe you can modify it for that, the code is really quite simple. The de-facto standard in the community is IPython notebooks.Excellent example in which Peter Norvig demonstrates algorithms to solve the Travelling Salesman Problem: More examples listed at You could use org-mode and babel-tangle.That works quite well, since you can give :noweb-ref to source blocks.Here\u2019s a minimal example: , then put this into the file :You can also use properties of headlines for giving the noweb-ref. It can then even automatically concatenate several source blocks into one noweb reference.Add  to the  line of the second block to see the print results under that block when you hit  in the block.You might find  easier to build on Windows.   It was designed to be more portable than standard noweb.See also my last LP tool: . It does not requires special input format, supports Markdown/MultiMarkdown, reStructuredText, OpenOffice/LibreOffice, Creole, TeX/LaTeX and has super light and clean syntax - no more cryptic literate programs.Found this tool to be useful: 
Python

Using py.test, two tests called the same in different directory causes py.test to fail. Why is that? How can I change this without renaming all the tests?To duplicate do:Putting an  is one way of resolving the conflict.  Unlike nose, current pytest does not try to unload test modules in order to import test modules with the same import name.  I used to think it's a bit magic to do this auto-unimporting and might mess up people's expectation from what the import mechanism does; sometimes people rely on the global state of a test module and with auto-unloading you loose it (a test module importing from another test module might then do unexpected things).  But maybe it's not a practical issue and thus pytest could add a similar hack ...This is an actual feature of py.test. You can find the reason for this behavior stated in :As that's the recommended workflow of working with py.test: install the package under development with , then test it.Because of this, I myself opt for unique test names, in the convention over configuration manner. It also ensures that you don't get ambiguous test names in the various test run output.If you need to keep the test names and don't care about the above mentioned functionality, you should be ok with putting an .
Python

In python is there an easy way to tell if something is not a sequence? I tried to just do:\n but python did not like that will raise a  if  cannot be iterated on -- but that check \"accepts\" sets and dictionaries, though it \"rejects\" other non-sequences such as  and numbers.On the other hands, strings (which most applications want to consider \"single items\" rather than sequences)  in fact sequences (so, any test, unless specialcased for strings, is going to confirm that they are).  So, such simple checks are often not sufficient.In Python 2.6 and better,  were introduced, and among other powerful features they offer more good, systematic support for such \"category checking\".You'll note strings are  considered \"a sequence\" (since they ), but at least you get dicts and sets out of the way.  If you want to exclude strings from your concept of \"being sequences\", you could use  (but that also excludes tuples, which, like strings, are sequences, but are not mutable), or do it explicitly:Season to taste, and serve hot!-)The  describes the following sequence types: string, Unicode string, list, tuple, buffer, and xrange.Why are you doing this? The normal way here is to require a certain type of thing (A sequence or a number or a file-like object, etc.) and then use it without checking anything. In Python, we don't typically use classes to carry semantic information but simply use the methods defined (this is called \"duck typing\"). We also prefer APIs where we know exactly what to expect; use keyword arguments, preprocessing, or defining another function if you want to change how a function works.Since Python \"adheres\" duck typing, one of the approach is to check if an object has some member (method).A sequence has length, has sequence of items, and support slicing []. So, it would be like this:They are all special methods,  should return number of items,  should return an item (in sequence it is -th item,  not with mapping),  should return subsequence, and  and  like you expect. This is such a contract, but whether the object really do these or not depends on whether the object adheres the contract or not. that, the function above will also return  for mapping, e.g. , since mapping also has these methods. To overcome this, you can do a  work: most of the time you don't need this, just do what you want as if the object is a sequence and catch an exception if you wish. This is more pythonic.I think the below code snippet does what you want:why ask whytry getting a length and if exception return false
Python

I have the following data frame in IPython, where each row is a single stock:I want to apply a groupby operation that computes cap-weighted average return across everything, per each date in the \"yearmonth\" column.This works as expected:But then I want to sort of \"broadcast\" these values back to the indices in the original data frame, and save them as constant columns where the dates match.I realize this naive assignment should not work. But what is the \"right\" Pandas idiom for assigning the result of a groupby operation into a new column on the parent dataframe?In the end, I want a column called \"MarketReturn\" than will be a repeated constant value for all indices that have matching date with the output of the groupby operation.One hack to achieve this would be the following:But this is slow, bad, and unPythonic.While I'm still exploring all of the incredibly smart ways that  concatenates the pieces it's given, here's another way to add a new column in the parent after a groupby operation.May I suggest the  method (instead of aggregate)? If you use it in your original example it should do what you want (the broadcasting).As a general rule when using groupby(), if you use the .transform() function pandas will return a table with the same length as your original. When you use other functions like .sum() or .first() then pandas will return a table where each row is a group. I'm not sure how this works with apply but implementing elaborate lambda functions with transform can be fairly tricky so the strategy that I find most helpful is to create the variables I need, place them in the original dataset and then do my operations there. If I understand what you're trying to do correctly (I apologize if I'm mistaken) first you can calculate the total market cap for each group: This will add a column called \"group_MarketCap\" to your original data which would contain the sum of market caps for each group. Then you can calculate the weighted values directly: And finally you would calculate the weighted average for each group using the same transform function:I tend to build my variables this way. Sometimes you can pull off putting it all in a single command but that doesn't always work with groupby() because most of the time pandas needs to instantiate the new object to operate on it at the full dataset scale (i.e. you can't add two columns together if one doesn't exist yet). Hope this helps :) Does this work?I use  for this:
Python

I am quite new to programing so I hope this question is simple enough.I need to know how to convert a string input of numbers separated by spaces on a single line:and convert this to a float listHow can this be done?Try a list comprehension:In Python 2.x it can also be done with map:Note that in Python 3.x the second version returns a map object rather than a list. If you need a list you can convert it to a list with a call to , or just use the list comprehension approach instead.
Python

I have an array like this:And I am trying to get an array like this:Where each row (of a fixed arbitrary width) is shifted by one. The array of A is 10k records long and I'm trying to find an efficient way of doing this in Numpy. Currently I am using vstack and a for loop which is slow. Is there a faster way?Edit:Actually, there's an even more efficient way to do this... The downside to using  etc, is that you're making a copy of the array.  Incidentally, this is effectively identical to @Paul's answer, but I'm posting this just to explain things in a bit more detail...There's a way to do this with just views so that  memory is duplicated.I'm directly borrowing this from , who in turn, borrowed it from Keith Goodman's  (Which is quite useful!).The basic trick is to directly manipulate the  (For one-dimensional arrays):Where  is your input array and  is the length of the window that you want (3, in your case).This yields:However, there is absolutely no duplication of memory between the original  and the returned array.  This means that it's fast and scales  better than other options.For example (using  and ):If we generalize this to a \"rolling window\" along the last axis for an N-dimensional array, we get Erik Rigtorp's \"rolling window\" function:So, let's look into what's going on here... Manipulating an array's  may seem a bit magical, but once you understand what's going on, it's not at all.  The strides of a numpy array describe the size in bytes of the steps that must be taken to increment one value along a given axis.  So, in the case of a 1-dimensional array of 64-bit floats, the length of each item is 8 bytes, and  is .Now, if we reshape this into a 2D, 3x3 array, the strides will be , as we would have to jump 24 bytes to increment one step along the first axis, and 8 bytes to increment one step along the second axis.Similarly a transpose is the same as just reversing the strides of an array:Clearly, the strides of an array and the shape of an array are intimately linked.  If we change one, we have to change the other accordingly, otherwise we won't have a valid description of the memory buffer that actually holds the values of the array.Therefore, if you want to change  the shape and size of an array simultaneously, you can't do it just by setting  and , even if the new strides and shape are compatible.  That's where  comes in.  It's actually a very simple function that just sets the strides and shape of an array simultaneously.  It checks that the two are compatible, but not that the old strides and new shape are compatible, as would happen if you set the two independently.  (It actually does this through , which allows arbitrary classes to describe a memory buffer as a numpy array.)So, all we've done is made it so that steps one item forward (8 bytes in the case of a 64-bit array) along one axis, but .  In other words, in case of a \"window\" size of 3, the array has a shape of , but instead of stepping a full  for the second dimension, it , effectively making the rows of new array a \"moving window\" view into the original array. (This also means that  will not be the same as  for your new array.)At any rate, hopefully that makes things slightly clearer..This solution is not efficiently implemented by a python loop since it comes with all kinds of type-checking best avoided when working with numpy arrays.  If your array is exceptionally tall, you will notice a large speed up with this:This gives a  of the array A.  If you want a new array you can edit, do the same but with  at the end.Details on strides:The  tuple in this case will be (4,4) because the array has 4-byte items and you want to continue to step thru your data in single-item steps in the i-dimension.  The second value '4' refers to the strides in the j-dimension (in a normal 4x4 array it would be 16).  Because in this case you want to also also increment your read from the buffer in 4-byte steps in the j-dimension.Joe give a nice, detailed description and makes things crystal-clear when he says that all this trick does is change strides and shape simultaneously. Which approach are you using?If your width is relatively low (3) and you have a big  (10000 elements), then the difference is even more important: 32.4ms for the first and 44\u00b5s for the second.Just to further go with the answer of @Joe generalwhich outputs:To generalize further for the 2d case,i.e use it for patch extraction from an imagewhich outputs:I think this might be faster than looping, when the width is fixed at a low number...EDIT Clearly, the solutions using strides are superior to this, with the only major disadvantage being that they are not yet well documented...Take a look at: .Around 1 second.I'm using a more generalized function similar to that of @JustInTime but applicable to An example,
Python

How do I execute the following shell command using the Python  module?The input data will come from a string, so I don't actually need .  I've got this far, can anyone explain how I get it to pipe through  too?:  Note that while the accepted answer below doesn't actually answer the question as asked, I believe S.Lott is right and it's better to avoid having to solve that problem in the first place!You'd be a little happier with the following.Delegate part of the work to the shell.  Let it connect two processes with a pipeline.You'd be a lot happier rewriting 'script.awk' into Python, eliminating awk and the pipeline..  Some of the reasons for suggesting that awk isn't helping.[There are too many reasons to respond via comments.]Bottom line: awk can't add significant value.  In this case, awk is a net cost; it added enough complexity that it was necessary to ask this question.  Removing awk will be a net gain. Why building a pipeline () is so hard.When the shell is confronted with  it has to do the following.I think that the above can be used recursively to spawn , but you have to implicitly parenthesize long pipelines, treating them as if they're .Since Python has ,  and , and you can replace  and , there's a way to do the above in pure Python.  Indeed, you may be able to work out some shortcuts using  and .However, it's easier to delegate that operation to the shell.To emulate a shell pipeline:without invoking the shell (see ): provides some syntax sugar:The analog of:is: covered this pretty well. Is there some part of this you didn't understand?Your program would be pretty similar, but the second  would have stdout= to a file, and you wouldn't need the output of its .Inspired by @Cristian's answer. I met just the same issue, but with a different command. So I'm putting my tested example, which I believe could be helpful:This is tested. I like this way because it is natural pipe conception gently wrapped with  interfaces.  is available on Windows but, crucially, doesn't appear to actually  on Windows. See comments below.The Python standard library now includes the  module for handling this:, I'm not sure how long this module has been around, but this approach appears to be vastly simpler than mucking about with .
Python

I would like to convert a python variable name into the string equivalent as shown. Any ideas how?There is an usage scenario where you might need this. I'm not implying there are not better ways or achieving the same functionality.This would be useful in order to 'dump' an arbitrary list of dictionaries in case of error, in debug modes and other similar situations.What would be needed, is the reverse of the  function:which would take an identifier name ('variable','dictionary',etc) as an argument, and return a \nstring containing the identifier\u2019s name.Consider the following current state of affairs:If one is passing an identifier name ('function','variable','dictionary',etc)  to a  (another identifier name), one actually passes an identifier (e.g.: ) to another identifier  (e.g.: ):From my understanding, only the memory address is passed to the function:Therefore, one would need to pass a string as an argument to  in order for that function to have the argument's identifier name:Inside the random_function(), one would use the already supplied string  to:Unfortunately, this doesn't work in all cases. It only works if the  can resolve the  string to an actual identifier. I.e. If  identifier name is available in the 's namespace.This isn't always the case:Expected results would be:Because  identifier name is not available in the 's namespace, this would yield instead:Now, consider the hypotetical usage of a  which would behave as described above.Here's a dummy Python 3.0 code: .Expected results would be:Unfortunately,  would not see the 'original' identifier names (,,). It would only see the  identifier name.Therefore the real result would rather be:So, the reverse of the  function won't be that useful in this case.Currently, one would need to do this:This can be achieved by passing both the  and  to the called function at the same time. I think this is the most 'general' way of solving this egg-chicken problem across arbitrary functions, modules, namespaces, without using corner-case solutions. The only downside is the use of the  function which may easily lead to unsecured code. Care must be taken to not feed the  function with just about anything, especially unfiltered external-input data.Technically the information is available to you, but as others have asked, how would you make use of it in a sensible way?This shows that the variable name is present as a string in the globals() dictionary.In this case it happens to be the third key, but there's no reliable way to know where a given variable name will end upYou could filter out system variables like this, but you're still going to get all of your own items. Just running that code above created another variable \"k\" that changed the position of \"x\" in the dict.But maybe this is a useful start for you. If you tell us what you want this capability for, more helpful information could possibly be given.This is not possible.In Python, there really isn't any such thing as a \"variable\".  What Python really has are \"names\" which can have objects bound to them.  It makes no difference to the object what names, if any, it might be bound to.  It might be bound to dozens of different names, or none.Consider this example:Now, suppose you have the integer object with value 1, and you want to work backwards and find its name.  What would you print?  Three different names have that object bound to them, and all are equally valid.In Python, a name is a way to access an object, so there is no way to work with names directly.  There might be some clever way to hack the Python bytecodes or something to get the value of the name, but that is at best a parlor trick.If you know you want  to print , you might as well just execute  in the first place.EDIT: I have changed the wording slightly to make this more clear.  Also, here is an even better example:In practice, Python reuses the same object for integers with common values like 0 or 1, so the first example should bind the same object to all three names.  But this example is crystal clear: the same object is bound to foo, bar, and baz.I searched for this question because I wanted a Python program to print assignment statements for some of the variables in the program. For example, it might print \"foo = 3, bar = 21, baz = 432\". The print function would need the variable names in string form. I could have provided my code with the strings \"foo\",\"bar\", and \"baz\", but that felt like repeating myself. After reading the previous answers, I developed the solution below.The globals() function behaves like a dict with variable names (in the form of strings) as keys. I wanted to retrieve from globals() the key corresponding to the value of each variable. The method globals().items() returns a list of tuples; in each tuple the first item is the variable name (as a string) and the second is the variable value. My variablename() function searches through that list to find the variable name(s) that corresponds to the value of the variable whose name I need in string form.The function itertools.ifilter() does the search by testing each tuple in the globals().items() list with the function . In that function x is the tuple being tested; x[0] is the variable name (as a string) and x[1] is the value. The lambda function tests whether the value of the tested variable is the same as the value of the variable passed to variablename(). In fact, by using the  operator, the lambda function tests whether the name of the tested variable is bound to the exact same object as the variable passed to variablename(). If so, the tuple passes the test and is returned by ifilter().The itertools.ifilter() function actually returns an iterator which doesn't return any results until it is called properly. To get it called properly, I put it inside a list comprehension . The list comprehension saves only the variable name , ignoring the variable value. The list that is created contains one or more names (as strings) that are bound to the value of the variable passed to variablename().In the uses of variablename() shown below, the desired string is returned as an element in a list. In many cases, it will be the only item in the list. If another variable name is assigned the same value, however, the list will be longer.You somehow have to refer to the variable you want to print the name of. So it would look like:There is no such function, but if there were it would be kind of pointless. You have to type out , so you can as well just type quotes to the left and right of it to print the name as a string:What are you trying to achieve? There is absolutely no reason to ever do what you describe, and there is likely a much better solution to the problem you're trying to solve..The most obvious alternative to what you request is a dictionary. For example:Mostly as a.. challenge, I implemented your desired output. Do not use this code, please!Does Django not do this when generating field names?Seems reasonable to me.I think this is a cool solution and I suppose the best you can get. But do you see any way to handle the ambigious results, your function may return?\nAs  shows, low integers and strings of the same value get cached by python so that your variablename-function might priovide ambigous results with a high probability. \nIn my case, I would like to create a decorator, that adds a  new variable to a class by the varialbename i pass it:But if your method returns ambigous results, how can I know the name of the variable I added?Maybe if I will also check the local list I could at least remove the \"dependency\"-Variable from the list, but this will not be a reliable result.as long as it's a variable and not a second class, this here works for me:this happens for class members:ans this for classes (as example):So for classes it gives you the name AND the properteriesOr did you mean something_else?This will work for simnple data types (str, int, float, list etc.)
Python

I can't figure out how to make  add a scrip to the the user's  or  or whatever.E.g., I'd like to add a  to  so that the user can call  from any directory.The Python documentation explains it under the  section.Consider using :Where  is a main function in your main module.\ncommand-name is a name under which it will be saved in /usr/local/bin/ (usually)If you're willing to build and install the entire python package, this is how I would go about it:There are two ways in order to get a working command line tool from setuptools and PyPI infrastructure:
Python

How do I remove  chars from the following dictionary?  This data is coming from   query  so that it looks like  Some databases such as Sqlite3 let you define  and  functions so you can retrieve text as  rather than .  Unfortunately, MongoDB doesn't provide this option for any of the commonly needed types such as str, decimal or datetime:Having eliminated Mongo options, that leaves writing Python code to do the conversion after the data is retrieved.  You could write a recursive function that traverses the result to convert each field.As a quick-and-dirty alternative, here is a little hack that may be of use:The  characters that you are seeing simply mean that they are unicode strings.If you do not want them to be unicode, you can encode them as something else, such as ASCII.You need to let psycopg2 encode your strings, not try to insert Python-syntax strings into your queries raw \u2014 you are putting yourself in danger of a SQL injection problem if some of the strings contain characters that SQL will interpret as ending the string. You should pass parameters to psycopg2 like this:Because psycopg2 knows SQL syntax very, very well, it will leave off the  characters as it gets your  and  strings and quotes and escapes them in exactly the way that this SQL statement needs.As sven mentions in his comment, the  is an indication of the types represented in mongodb (actually it's because json is defined to use unicode).  This fact should be totally transparent to you, in fact you can use  and  values interchangeably in the dicts.If you simply want to convert the dict to json data string you can do:You cannot simply remove the u from the strings, as it symbolizes, that the strings are in Unicode.One solution is to use the encode function:This would just ignore non ascii characters.
Python

I'm trying to do an animation of a scatter plot where colors and size of the points changes at different stage of the animation. For data I have two numpy ndarray with an x value and y value:Now I want to plot a scatter plot of the typeand create an animation over the index . How do I do this?Here's a quick example using the new animation module.  It's slightly more complex than it has to be, but this should give you a framework to do fancier things.  If you're on OSX and using the OSX backend, you'll need to change  to  in the  initialization below.  The OSX backend doesn't fully support blitting.  The performance will suffer, but the example should run correctly on OSX with blitting disabled.For a simpler example, have a look at the following:Here is the thing. I used to a user of Qt and Matlab and I am not quite familiar with the animation system on the matplotlib.But I do have find a way that can make any kind of animation you want just like it is in matlab. It is really powerful. No need to check the module references and you are good to plot anything you want. So I hope it can help.The basic idea is to use the time event inside PyQt( I am sure other Gui system on the Python like wxPython and TraitUi has the same inner mechanism to make an event response. But I just don't know how). Every time a PyQt's Timer event is called I refresh the whole canvas and redraw the whole picture, I know the speed and performance may be slowly influenced but it is not that much. Here is a little example of it:You can adjust the refresh speed in the I am just like you who want to use the Animated scatter plot to make a sorting animation. But I just cannot find a so called \"set\" function. So I refreshed the whole canva.Hope it helps..
Python

I have a list containing data as such:I'd like to print out the ranges of consecutive integers:Is there a built-in/fast/efficient way of doing this?From :You can adapt this fairly easily to get a printed set of ranges.Built-In: No, as far as I'm aware.You have to run through the array. Start off with putting the first value in a variable and print it, then as long as you keep hitting the next number do nothing but remember the last number in another variable. If the next number is not in line, check the last number remembered versus the first number. If it's the same, do nothing. If it's different, print \"-\" and the last number. Then put the current value in the first variable and start over.\nAt the end of the array you run the same routine as if you had hit a number out of line.I could have written the code, of course, but I don't want to spoil your homework :-)This will print exactly as you specified:If the list has any single number ranges, they would be shown as n-n:Here is another basic solution without using any module, which is good for interview, generally in the interview they asked without using any modules:Output:I had a similar problem and am using the following for a sorted list. It outputs a dictionary with ranges of values listed in a dictionary. The keys separate each run of consecutive numbers and are also the running total of non-sequential items between numbers in sequence. Your list gives me an output of Using set operation, the following algorithm can be executedOutput for the above list \"a\"  \n1-4 \n6-8 \n14-15 \n21 
Python

I am trying to build lxml for Python 2.7 on Windows 64 bit machine. I couldn't find lxml egg for Python 2.7 version. So I am compiling it from sources. I am following instructions on this siteunder static linking section. I am getting errorCan any one help me with this? I tried setting the path to have Microsoft Visual Studio..\nI can run vcvarsall.bat from the commandline.. but python is having problemsI bet you're not using VS 2008 for this :)  There's  function (guess what, it looks for vcvarsall.bat) in distutils with the following commentIf you're not using VS 2008 then you have neither the registry key nor suitable environment variable and that's why distutils can't find vcvarsall.bat file. It does  check if the bat file is reachable through the PATH environment variable.  The solution is to define VS90COMNTOOLS variable to point to Tools directory of Visual Studio.That being said take a look at  section in Python's docs which statesMartin v. Loewis in the email titled  on python-list mailing list states the sameIn the light of above statements you  use VS 2008 if you want to build lxml for Python 2.7 so although setting VS90COMNTOOLS takes care of finding vcvarsall.bat file it's not  solution.That being said :) people do try to use older CRT with newer compiler:\n\n\n  I'd like to thank Kev Dwyer (for pointing out importance of version of VS which is used) and Stefan Behnel (for pointing me to distutils as a place dealing with compiler's configuration) in the thread  on lxml mailing list. I'd like to also thank  from freenode #distutils IRC channel for confirmation that distutils does contain code which looks for vcvarsall.bat file.After following the recommended solution:my problem still existed (want to build a Python extension in C).I had to do the following 2 unbelievably dirty tweaks, before everything now is indeed working:I cannot tell who was doing something wrong here - probably I.EDIT. Moving directories works because of the issue described in .The described workaround is using the Visual C++ command prompt:Jorj McKie was almost correct: indeed installing  isn't enough, and yes there is an issue in distutils which prevent it from finding find_vcvarsall. In fact the issue is not directly in distutils, but in how VCForPython27.msi was packaged and where vcvarsall.bat is placed (the folders layout is different from the VS2008 SDK).A simple workaround meanwhile this gets patched maybe in Python 2.7.11: use setuptools instead of distutils.Another manual workaround if you're stuck with distutils:Bug report and workaround by Gregory Szorc:\nMore info and a workaround for using %%cython magic inside IPython: I had similar issues. This worked instantly without anything other than using an install wizard and setting one preference.
Python

I am using Sphinx for generating docs for a python project.\nThe output html is not preserving the line breaks which are present in the docstring.\nExample:CodeSphinx O/P:Any idea how to fix it ?In general in restructured text useto keep line breaksIf you add the following to your main .rst file:Then in your markup you can add in  to create linebreaks just for HTML. From: This answer comes late, but maybe it'll still be useful to others.You could use  in your docstrings. This would look something likeFrom the looks of your example however it seems you're using the Google Style for docstrings ().Sphinx does not natively support those. There is however an extension named  that parses Google and Numpy style docstrings at .To use the extension you have to append  to the -list in your Sphinx  (usually ), so it becomes something likeIn your case you can write:In my particular case, I was trying to get autodoc to read a doc string ().  I ended up using  everywhere I needed to add a line break:
Python

I just upgraded to Django 1.9 and noticed these changes. What is the logic behind them?Is anything different because of these changes?It is explained in issue  (emphasis mine):Also see  for a more up-to-date discussion.Another  (not directly related to this issue) demonstrates that  is actually faster with a . It is correct that the above issue was closed years ago, but I included it because it explained the rationale behind the decision and many similar discussions refer to the same ticket. The actual implementation decision was triggered after the  started by core Django developer :And the switch to lists actually happened in  which also referred to the above discussion.In , there is:So it appears that it was just done for consistency. Both tuples and lists should work fine. If you use a tuple with 1 element, remember the comma  because otherwise it's not a tuple but simply an expression in parens.As for urlpatterns, those used to be defined using a  function, but that was deprecated in Django 1.8, as a list of url instances works fine. As the function will be removed in the future, it shouldn't be used in new apps and projects.
Python

How can i receive and send email in python? A 'mail server' of sorts.I am looking into making an app that listens to see if it recieves an email addressed to foo@bar.domain.com, and sends an email to the sender.Now, am i able to do this all in python, would it be best to use 3rd party libraries? Here is a very simple example:For more options, error handling, etc, look at the .I do not think it would be a good idea to write a real mail server in Python. This is certainly possible (see mcrute's and Manuel Ceron's posts to have details) but it is a lot of work when you think of everything that a real mail server must handle (queuing, retransmission, dealing with spam, etc).You should explain in more detail what you need. If you just want to react to incoming email, I would suggest to configure the mail server to call a program when it receives the email. This program could do what it wants (updating a database, creating a file, talking to another Python program).To call an arbitrary program from the mail server, you have several choices:Found a helpful example for reading emails by connecting using IMAP: Python has an SMTPD module that will be helpful to you for writing a server. You'll probably also want the SMTP module to do the re-send. Both modules are in the standard library at least since version 2.3.poplib and smtplib will be your friends when developing your app.The sending part has been covered, for the receiving you can use  or Yes, you can do pretty much everything with the built-in libraries.  Do a search here looking for the tags  and  and you'll see how it's done.Depending on the amount of mail you are sending you might want to look into using a real mail server like postifx or sendmail (*nix systems) Both of those programs have the ability to send a received mail to a program based on the email address. The best way to do this would be to create a windows service in python that receives the emails using imaplib2Below is a sample python script to do the same.You can install this script to run as a windows service by  running the following command on the command line \"python THENAMEOFYOURSCRIPTFILE.py install\".
Python

On a django site, I want to generate an excel file based on some data in the database.I'm thinking of using , but it only has a method to save the data to a file. How can get the file to the HttpResponse object? Or maybe do you know a better library?I've also found this  but it doesn't do what I need. All I want is a way to get the stream from the xlwt object to the response object (without writing to a temporary file)neat package! i didn't know about thisAccording to the doc, the  method takes either a filename to save on, or a file-like stream to write on.And a Django response object happens to be a file-like stream!  so just do .  Look the Django docs about  with ReportLab to see a similar situation. (adapted from ShawnMilo's comment):then, from your view function, just create the  object and finish with ***UPDATE: django-excel-templates no longer being maintained, instead try Marmir Still in development as I type this but  Django excel templates project aims to do what your asking.Specifically look at the tests. Here is a simple case:You can save your XLS file to a  object, which is file-like.You can return the StringIO object's  in the response.  Be sure to add headers to mark it as a downloadable spreadsheet.You might want to check  which comes fith a function called  do convert a queryset into an downloadable Excel Sheet.Use If your data result doesn't need formulas or exact presentation styles, you can always use CSV.  any spreadsheet program would directly read it.  I've even seen some webapps that generate CSV but name it as .XSL just to be sure that Excel opens it
Python

Anyone could recommend a good guide/tutorial/article with tips/guidelines in how to organize and partition a large Django project? I'm looking for advices in what to do when you need to start factorizing the initial unique files (models.py, urls.py, views.py) and working with more than a few dozens of entities.Each \"application\" should be small -- a single reusable entity plus a few associated tables.  We have about 5 plus/minus 2 tables per application model.  Most of our half-dozen applications are smaller than 5 tables.  One has zero tables in the model.  Each application should be designed to be one reusable concept.  In our case, each application is a piece of the overall site; the applications could be removed and replaced separately.Indeed, that's our strategy.  As our requirements expand and mature, we can remove and replace applications independently from each other.It's okay to have applications depend on each other.  However, the dependency has to be limited to the obvious things like \"models\" and \"forms\".  Also, applications can depend on the names in each other's URL's.  Consequently, your named URL's must have a form like \"application-view\" so the  function or the  tag can find them properly.Each application should contain it's own batch commands (usually via a formal Command that can be found by the  script.Finally, anything that's more complex than a simple model or form that's shared probably doesn't belong to either application, but needs to be a separate shared library.  For example, we use , but wrap parts of it in our own class so it's more like the built-in  module.  This wrapper for XLRD isn't a proper part of any one application, to it's a separate module, outside the Django applications.I've found it to be helpful to take a look at large open-source Django projects and take note of how that project does it. Django's site has a good list of open-source projects:As does Google (although most of these are smaller add-in template tags and Middleware:Of course, just because one project does it one way does not mean that that way is The Right Way (or The Wrong Way). Some of those projects are more successful than others.In the end, the only way to really learn what works and doesn't work is to try it out yourself. All the tips and hints in the world wont help unless you try it out yourself, but they may help you get started in the right direction.
Python

I am interested in taking an arbitrary dict and copying it into a new dict, mutating it along the way.One mutation I would like to do is swap keys and value. Unfortunately, some values are dicts in their own right. However, this generates a \"unhashable type: 'dict'\" error. I don't really mind just stringifying the value and giving it the key. But, I'd like to be able to do something like this:Is there a clean way to do this that  involve trapping an exception and parsing the message string for \"unhashable type\" ?Since Python 2.6 you can use the abstract base class :This approach is also mentioned briefly in the documentation for .All hashable built in python objects have a  method. You can check for that.outputWhy not use duck typing?
Python

I'm currently in the process of making my Nintendo Wiimote (Kinda sad actually) to work with my computer as a mouse. I've managed to make the nunchuk's stick control actually move the mouse up and down, left and right on the screen! This was so exciting. Now I'm stuck.I want to left/right click on things via python when I press A, When I went to do a search, All it came up with was tkinter?So my question is, What do I call to make python left/right click on the desktop, and if it's possible, maybe provide a snippet?Thank you for your help!NOTE: I guess I forgot to mention that this is for Linux.python-uinput is very easy to use.Here's an example You can use  which has now merged with . I installed it via pip:apt-get install python-pippip install pymouseIn some cases it used the cursor and in others it simulated mouse events without the cursor.You can also specify which mouse button you want used. Ex left button:Keep in mind, on Linux it requires Xlib.The  package provides bindings to parts of the input handling subsystem in Linux. It also happens to include a pythonic interface to uinput. Example of sending a relative motion event and a  with :PyAutoGui works superb.. Thanks to Al Sweigart...An example of mine...you might find this helpful:Good luck!You can try to interface  program from the Python script.Open your terminal and goto \nmay this   python script will work for you,check them out.You can install the PyAutoGUI GUI automation module from PyPI (run ) and then call the  to click on a certain X and Y coordinates of the screen:PyAutoGUI works on Windows, Mac, and Linux, and on Python 2 and 3. It also can emulate the keyboard, do mouse drags, take screenshots, and do simple image recognition of the screenshots.Full docs are at I didn't see this mentioned, so here it goes - there is also ; see:It requires \"Enable assistive technologies\" in the Gnome Desktop - but can in principle obtain e.g. names of GUI buttons of an application, and allow virtual clicks on them (rather than via x/y coordinates).
Python

I fear that this is a messy way to approach the problem but... let's say that I want to make some imports in Python based on some conditions.For this reason I want to write a function:Now how can I have the imported modules globally available?For example:Imported modules are just variables - names bound to some values.  So all you need is to import them and make them global with  keyword.Example:You can make the imports global within a function like this:You could have this function return the names of the modules you want to import, and then useYou can use the built-in function  to conditionally import a module with global scope.To import a top level module (think: ):Import from a hierarchy (think: ):Import from a hierarchy and alias (think: ):
Python

I have the  object and i need to pass that along many pages to store data in single itemLIke my item isNow those three description are in three separate pages. i want to do somrething likeNow this works good for But i want something likeNo problem. Instead ofDoIn order to guarantee an ordering of the requests/callbacks and that only one item is ultimately returned you need to chain your requests using a form like:Each callback function returns an iterable of items or requests, requests are scheduled and items are run through your item pipeline. If you return an item from each of the callbacks, you'll end up with 4 items in various states of completeness in your pipeline, but if you return the next request, then you can guaruntee the order of requests and that you will have exactly one item at the end of execution.The accepted answer returns a total of three items [with desc(i) set for i=1,2,3].If you want to return a single item, Dave McLain's item does work, however it requires , , and  to succeed and run without errors in order to return the item.For my use case, some of the subrequests MAY return HTTP 403/404 errors at random, thus I lost some of the items, even though I could have scraped them partially.Thus, I currently employ the following workaround: Instead of only passing the item around in the  dict, pass around a  that knows what request to call next. It will call the next item on the stack (so long as it isn't empty), and returns the item if the stack is empty.The  request parameter is used to return to the dispatcher method upon errors and simply continue with the next stack item.This solution is still synchronous, and will still fail if you have any exceptions within the callbacks.For more information, .
Python

I have a set of data which I want plotted as a line-graph.  For each series, some data is missing (but different for each series).  Currently matplotlib does not draw lines which skip missing data: for example results in a plot with gaps in the lines.  How can I tell matplotlib to draw lines through the gaps? (I'd rather not have to interpolate the data). You can mask the NaN values this way: This leads toQouting @Rutger Kassies () :A solution if you are using , :Without interpolation you'll need to remove the None's from the data.  This also means you'll need to remove the X-values corresponding to None's in the series.  Here's an (ugly) one liner for doing that:The lambda function returns False for None values, filtering the x,series pairs from the list, it then re-zips the data back into its original form.For what it may be worth, after some trial and error I would like to add one clarification to Thorsten's solution. Hopefully saving time for users who looked elsewhere after having tried this approach.I was unable to get success with an identical problem while usingand attempting to plot withIt seemed it was required to use  to get the proper NaNs handling, though I cannot say why.Perhaps I missed the point, but I believe Pandas now .  The example below is a little involved, and requires internet access, but the line for China has lots of gaps in the early years, hence the straight line segments.  
Python

In my code I use the  from  like thisHowever, all of the sudden I get the following error when I load the cursor:Maybe something is dorked in my installation but I have no clue where to start looking. I made some updates with pip, but as far as I know no dependencies of .You need to explicitly import :
Python

Simple models just to ask my question.I wonder how can i query blogs using tags in two different ways.Tag and Blog is just used for an example.You could use Q objects for #1:Unions and intersections, I believe, are a bit outside the scope of the Django ORM, but its possible to to these.  The following examples are from a Django application called called  that provides the functionality. : For part two, you're looking for a union of two queries, basicallyFor part #3 I believe you're looking for an intersection. See  I've tested these out with Django 1.0:The \"or\" queries:or you could use the Q class:The \"and\" query:I'm not sure about the third one, you'll probably need to drop to SQL to do it.Please don't reinvent the wheel and use  which was made exactly for your use case. It can do all queries you describe, and much more.If you need to add custom fields to your Tag model, you can also take a look at .This will do the trick for you
Python

I am currently working on a wrapper for a dedicated server running in the shell. The wrapper spawns the server process via subprocess and observes and reacts to its output.The dedicated server must be explicitly given a command to shut down gracefully. Thus, CTRL-C must not reach the server process.If I capture the KeyboardInterrupt exception or overwrite the SIGINT-handler in python, the server process still receives the CTRL-C and stops immediately.So my question is:\nHow to prevent subprocesses from receiving CTRL-C / Control-C / SIGINT?Somebody in the #python IRC-Channel (Freenode) helped me by pointing out the  parameter of :Thus, the following code solves the problem (UNIX only): The signal is actually not prevented from reaching the subprocess. Instead, the  above overwrites the signal's default handler so that the signal is ignored. Thus, this solution  not work if the subprocess overwrites the  handler again. This solution works for all sorts of subprocesses, i.e. it is not restricted to subprocesses written in Python, too. For example the dedicated server I am writing my wrapper for is in fact written in Java.Combining some of other answers that will do the trick - no signal sent to main app will be forwarded to the subprocess.Try setting SIGINT to be  before spawning the subprocess (reset it to default behavior afterward).If that doesn't work, you'll need to read up on  and learn how to put a process in its own background process group, so that  doesn't even cause the kernel to send the signal to it in the first place.  (May not be possible in Python without writing C helpers.)See also .you can do something like this to make it work in windows and unix:
Python

It's a thing that bugged me for a while. Why can't I do:...while I can do the following?What's the rule here? Could you please point me to some description?You can add attributes to any object that has a .If an object is using  / doesn't have a , it's usually to save space. For example, in a  it would be overkill to have a dict - imagine the amount of bloat for a very short string.If you want to test if a given object has a , you can use . might also be interesting to read:Another interesting article about Python's data model including , , etc. is  from the python reference.
Python

I have some values in a Python Pandas Series (type: pandas.core.series.Series)I would like to get values of histogram (not necessary plotting histogram)... I just need to get the frequency for each interval.Let's say that my intervals are going from [-200; -150] to [950; 1000]so lower bounds areand upper bounds areI don't know how to get frequency (the number of values that are inside each interval) now...\nI'm sure that defining lwb and upb is not necessary... but I don't know what\nfunction I should use to perform this!\n(after diving in Pandas doc, I think  function can help me because it's a discretization problem... but I'm don't understand how to use it)After being able to do this, I will have a look at the way to display histogram (but that's an other problem)You just need to use the histogram function of numpy:where division is the automatically calculated border for your bins and count is the population inside each bin.If you need to fix a certain number of bins, you can use the argument bins and specify a number of bins, or give it directly the boundaries between each bin.to plot the results you can use the matplotlib function hist, but if you are working in pandas each Series has its own handle to the hist function, and you can give it the chosen binning:Inorder to get the frequency counts of the values in a given interval binned range, we could make use of  which returns indices of half open bins for each element along with  for computing their respective counts. To plot their counts, a bar plot can be then made.Frequency for each interval sorted in descending order of their counts:To modify the plot to include just the lower closed interval of the range for aesthetic purpose, you could do:If you say you want to get values of histogram, you are simply looking for frequency of each unique value in your series, if I'm not mistaken. In that case, you can simply do , which will give you:
Python

I have a Python Pandas  object containing textual data. My problem is, that when I use  function, it truncates the strings in the output.For example:The output is truncated at There is a related question on SO, but it uses placeholders and search/replace functionality to postprocess the HTML, which I would like to avoid:Is there a simpler solution to this problem? I could not find anything related from the .What you are seeing is pandas truncating the output for display purposes only. The default  value is 50 which is what you are seeing.You can set this value to whatever you desire or you can set it to -1 which effectively turns this off:Although I would advise against this, it would be better to set it to something that can be displayed easily in your console or ipython.A list of the options can be found here: it seems that  is indeed the only option. To prevent irreversible global changes of how dataframes are presented in the console, you may save the previous setting in a variable and restore it immediately after the usage, as follows:
Python

I know  is an old school way of defining a class. But I would like to understand in more detail the difference between these two.Prior to python 2.2 there were essentially two different types of class: Those defined by C extensions and C coded builtins (types) and those defined by python class statements (classes).  This led to problems when you wanted to mix python-types and builtin types.  The most common reason for this is subclassing.  If you wanted to subclass the list type in python code, you were out of luck, and so various workarounds were used instead, such as subclassing the pure python implementation of lists (in the UserList module) instead.This was a fairly ugly, so in 2.2 there was a  to unify python and builtin types, including the ability to  from them. The result is \"new style classes\".  These do have some incompatible differences to old-style classes however, so for backward compatability the bare class syntax creates an old-style class, while the new behaviour is obtained by inheriting from object.  The most visible behaviour differences are: is the 'new' way of declaring classes.This change was made in python 2.2, see  of the differences. Subclassing  yields a new-style class. Two well known advantages of new-style classes are:
Python

Profiling shows this is the slowest segment of my code for a little word game I wrote:Notes:Results:Thanks everyone, with combinations of different suggestions I got the program running twice as fast now (on top of the optimizations I did on my own before asking, so 4 times speed increase approx from my initial implementation)I tested with 2 sets of inputs which I'll call A and B ... fromto Got execution time from 11.92 to 9.18 for input A, and 79.30 to 74.59 for input BOptimization2:\nAdded a separate method for differs-by-one in addition to the distance-method (which I still needed elsewhere for the A* heuristics)Got execution time from 9.18 to 8.83 for input A, and 74.59 to 70.14 for input BOptimization3:\nBig winner here was to use  instead of Got execution time from 8.83 to 5.02 for input A, and 70.14 to 41.69 for input BI could probably do better writing it in a lower level language, but I'm happy with this for now.  Thanks everyone!Edit again: More results\nUsing Mark's method of checking the case where the first letter doesn't match got it down from 5.02 -> 3.59 and 41.69 -> 29.82Building on that and , I ended up with this:Which squeezed a little bit more, bringing the times down from 3.59 -> 3.38 and 29.82 -> 27.88Even more results!Trying Sumudu's suggestion that I , instead of the is_neighbor function I ended up with this:Which ended up being slower (3.38 -> 3.74 and 27.88 -> 34.40) but it seemed promising.  At first I thought the part I'd need to optimize was \"one_letter_off_strings\" but profiling showed otherwise and that the slow part was in fact I thought if there'd be any difference if I switched \"oneoff\" and \"wordlist\" and did the comparison the other way when it hit me that I was looking for the intersection of the 2 lists.  I replace that with :Bam! 3.74 -> 0.23 and 34.40 -> 2.25This is truely amazing, total speed difference from my original naive implementation:\n23.79 -> 0.23 and 180.07 -> 2.25, so approx 80 to 100 times faster than the original implementation.If anyone is interested, I made blog post  and  made including one that isn't mentioned here (because it's in a different section of code).Ok, me and Unknown are having a big debate which you can read in the comments of . He claims that it would be faster using the original method (using is_neighbor instead of using the sets) if it was ported to C.  I tried for 2 hours to get a C module I wrote to build and be linkable without much success after trying to follow  and  example, and it looks like the process is a little different in Windows? I don't know, but I gave up on that.  Anyway, here's the full code of the program, and the text file come from the  using the \"2+2lemma.txt\" file.  Sorry if the code's a little messy, this was just something I hacked together.  Also I forgot to strip out commas from the wordlist so that's actually a bug that you can leave in for the sake of the same comparison or fix it by adding a comma to the list of chars in cleanentries.I left the is_neighbors method in even though it's not used.  This is the method that is proposed to be ported to C.  To use it, just replace getchildren with this:As for getting it to work as a C module I didn't get that far, but this is what I came up with:I profiled this using:And the time recorded was the total time of the AStar method call.  The fast input set was \"verse poets\" and the long input set was \"poets verse\".  Timings will obviously vary between different machines, so if anyone does end up trying this give result comparison of the program as is, as well as with the C module.If your wordlist is very long, might it be more efficient to generate all possible 1-letter-differences from 'word', then check which ones are in the list?  I don't know any Python but there should be a suitable data structure for the wordlist allowing for log-time lookups.I suggest this because if your words are reasonable lengths (~10 letters), then you'll only be looking for 250 potential words, which is probably faster if your wordlist is larger than a few hundred words.Your function  is calculating the total distance, when you really only care about distance=1. The majority of cases you'll know it's >1 within a few characters, so you could return early and save a lot of time.Beyond that, there might be a better algorithm, but I can't think of it. Another idea.You can make 2 cases, depending on whether the first character matches. If it doesn't match, the rest of the word has to match exactly, and you can test for that in one shot. Otherwise, do it similarly to what you were doing. You could even do it recursively, but I don't think that would be faster. I've deleted the check to see if the strings are the same length, since you say it's redundant. Running  on my own code and on the is_neighbors function , I get the following: (Probably getting into community wiki territory here, but...)Trying your final definition of is_neighbors() with izip instead of zip: 2.9 seconds.Here's my latest version, which still times at 1.1 seconds:Or maybe in-lining the  code:And a rewritten :People are mainly going about this by trying to write a quicker function, but there might be another way..Why is this? Perhaps a better way to optimise is to try and reduce the number of calls to , rather than shaving milliseconds of  execution time. It's impossible to tell without seeing the full script, but optimising a specific function is generally unnecessary.If that is impossible, perhaps you could write it as a C module?How often is the distance function called with the same arguments? A simple to implement optimization would be to use . You could probably also create some sort of dictionary with frozensets of letters and lists of words that differ by one and look up values in that. This datastructure could either be stored and loaded through pickle or generated from scratch at startup.Short circuiting the evaluation will only give you gains if the words you are using are very long, since the hamming distance algorithm you're using is basically O(n) where n is the word length. I did some experiments with timeit for some alternative approaches that may be illustrative.Well you can start by having your loop break if the difference is 2 or more.Also you can changeto Because xrange generates sequences on demand instead of generating the whole range of numbers at once.You can also try comparing word lengths which would be quicker. Also note that your code doesn't work if word1 is greater than word2There's not much else you can do algorithmically after that, which is to say you'll probably find more of a speedup by porting that section to C.Attempting to explain my analysis of Sumudu's algorithm compared to verifying differences char by char.When you have a word of length L, the number of \"differs-by-one\" words you will generate will be 25L. We know from implementations of sets on modern computers, that the  search speed is approximately , where n is the number of elements to search for. Seeing that most of the 5 million words you test against is  in the set, most of the time, you will be traversing the entire set, which means that it really becomes  instead of only log(25L)/2. (and this is assuming best case scenario for sets that comparing string by string is equivalent to comparing char by char)Now we take a look at the time complexity for determining a \"differs-by-one\". If we assume that you have to check the entire word, then the number of operations per word becomes . We know that most words differ by 2 very quickly. And knowing that most prefixes take up a small portion of the word, we can logically assume that you will break most of the time by , or half the word (and this is a conservative estimate).So now we plot the time complexities of the two searches, L/2 and log(25L), and keeping in mind that  (highly in favor of sets). You have the equation log(25*L) > L/2, which can be simplified down to log(25) > L/2 - log(L). As you can see from the graph, it should be quicker to use the char matching algorithm until you reach  large numbers of L.I was the first person in this question to suggest breaking on a difference of 2 or more. The thing is, that Mark's idea of string slicing (if word1[0] != word2[0]: return word1[1:] == word2[1:]) is simply putting what we are doing into C. How do you think  is calculated? The same way that we are doing.As for producing the C code, I am a bit busy. I am sure you will be able to do it since you have written in C before. You could also try C#, which probably has similar performance characteristics.Here is a more indepth explanation to Davy8Your one_letter_off_strings function will create a set of 25L strings(where L is the number of letters). Creating a set from the wordlist will create a set of D strings (where D is the length of your dictionary). By creating an intersection from this, you  iterate over each  and see if it exists in . The time complexity for this operation is detailed above. This operation is less efficient than comparing the  you want with each word in . Sumudu's method is an optimization in C rather than in algorithm.To create the intersection of 125 one-letter-off words with a dictionary of 4500, you need to make 125 * 4500 comparisons. This is not log(125,2). It is at best 125 * log(4500, 2) assuming that the dictionary is presorted.  You are also doing a string by string instead of char by char comparison here.For such a simple function that has such a large performance implication, I would probably make a C library and call it using .  One of reddit's founders claims they made the website 2x as fast using this technique.You can also use  on this function, but beware that it can eat up a lot of memory.I don't know if it will significantly affect your speed, but you could start by turning the list comprehension into a generator expression.  It's still iterable so it shouldn't be much different in usage:toThe main problem would be that a list comprehension would construct itself in memory and take up quite a bit of space, whereas the generator will create your list on the fly so there is no need to store the whole thing.Also, following on unknown's answer, this may be a more \"pythonic\" way of writing distance():But it's confusing what's intended when len (word1) != len (word2), in the case of zip it will only return as many characters as the shortest word. (Which could turn out to be an optimization...)Try this:Also, do you have a link to your game? I like being destroyed by word gamesFirst thing to occur to me:which has a decent chance of going faster than other functions people have posted, because it has no interpreted loops, just calls to Python primitives. And it's short enough that you could reasonably inline it into the caller.For your higher-level problem, I'd look into the data structures developed for similarity search in metric spaces, e.g.  or , neither of which I've read (they came up in a search for a paper I have read but can't remember).for this snippet:i'd use this one:the same pattern would follow all around the provided code...Everyone else focused just on explicit distance-calculation without doing anything about constructing the distance-1 candidates.\nYou can improve by using a well-known data-structure called a  to merge the  with the task of . A Trie is a linked-list where each node stands for a letter, and the 'next' field is a dict with up to 26 entries, pointing to the next node.Here's the pseudocode: walk the Trie iteratively for your given word; at each node add all distance-0 and distance-1 neighbors to the results; keep a counter of distance and decrement it. You don't need recursion, just a lookup function which takes an extra distance_so_far integer argument.A minor tradeoff of extra speed for O(N) space increase can be gotten by building separate Tries for length-3, length-4, length-5 etc. words. 
Python

I'm using Python logging, and for some reason, all of my messages are appearing twice.I have a module to configure logging:Later on, I call this method to configure logging:And then within say, the buy_ham module, I'd call:And for some reason, all the messages are appearing twice. I commented out one of the stream handlers, still the same thing. Bit of a weird one, not sure why this is happening...lol. Assuming I've missed something obvious.Cheers,\nVictorYou are calling  twice (maybe in the  method of ) :  will return the same object, but  does not check if a similar handler has already been added to the logger. Try tracing calls to that method and eliminating one of these. Or set up a flag  initialized to  in the  method of  and change  to do nothing if  is , and to set it to  after you've initialized the logger. If your program creates several  instances, you'll have to change the way you do things with a global  function adding the handlers, and the  method only initializing the  attribute.Another way of solving this is by checking the handlers attribute of your logger:The handler is added each time you call from outside. Try Removeing the Handler after you finish your job:I'm a python newbie, but this seemed to work for me (Python 2.7)If you are seeing this problem and you're not adding the handler twice then see abarnert's answer From the :So, if you want a custom handler on \"test\", and you don't want its messages also going to the root handler, the answer is simple: turn off its propagate flag:logger.propagate = False
Python

I have write a python library app(which contains several *.py files). And several of my python projects need to reuse the code in the library app. What's the recommended best practice for reusing python code? Currently I have thought out three options:Among the three options above which one do you prefer? What advantage does it have compared to the other two options?  Do you have any other better options? It is much appreciated that if some one with years of python development experiences could answer this question. Allow me to propose a fourth alternative: take the time to learn how to package your library and install it in your site-packages; it's easier than one may think and I'm convinced it's time well spent. This is a very good starting point: UPDATE:\nThe original URL is not valid anymore. Read the  instead.Of your three options, PYTHONPATH is the way to go.  Copy & paste is clearly out, and adding code to your other projects to modify sys.path simply pollutes those files with knowledge about their environment.A fourth option is, create a true installable package from your common code, and install it into your Python installation.  Then you can simply import those modules like any other 3rd-party install code.The first way is, as you noted yourself, hardly acceptable as it has .The other two have their own problems. For starters, they require manual work when files move (particular bad if you mix it with the application logic, i.e. put it in *.py files instead of leaving it to the computer it runs on) and requires either fixed installation locations (absolute paths) or at least a certain directory structure (relative paths). IMHO, these ways are only acceptable if the applications aren't ever going to move anywhere else. As soon as that becomes required, you should give up and use the existing solution as the one reason not to use it, being overkill for small and local scripts, doesn't apply any more:Make the common parts, which you apparently already treat as a free-standing library (good!), a fully-fledged project in its own right, with a  that allows installing and adding to PYTHONPATH in a cross-platform way with a single command. You don't need to actually publish it at PyPI, but it makes doing so easier if you should change your mind in the future. Should you do so and also publish some of your projects on PyPI, you also made installing the project in question and its dependencies easier for every potential user.If its a shared library you should package it up and add it to site-packages and then you wont have to worry about setting anything up.  This is the best option.If you dont want to use site-packages, then use PYTHONPATH.  Its why it exists, and it is  to do what you want.You might want to look into using , path.append does not prevent duplicates.  It will also allow you to leverage .pth files.Dynamically setting/adding things to PYTHONPATH via  achieves the same result, but it can complicate things if you choose to reuse your new library.  It also causes issues if your paths change, you have to change  versus an environment variable. Unless it is completely necessary, you should not dynamically setup your python path.  Copy & Paste is not a re-use pattern.  You aren't reusing anything you are duplicating and increasing maintenance. 
Python

I had a very difficult time with understanding the root cause of a problem in an algorithm. Then, by simplifying the functions step by step I found out that evaluation of default arguments in Python doesn't behave as I expected.The code is as follows:The problem is that every instance of Node class shares the same  attribute, if the attribute is not given explicitly, such as:I don't understand the logic of this design decision? Why did Python designers decide that default arguments are to be evaluated at definition time? This seems very counter-intuitive to me.The alternative would be quite heavyweight -- storing \"default argument values\" in the function object as \"thunks\" of code to be executed over and over again every time the function is called without a specified value for that argument -- and would make it much harder to get early binding (binding at def time), which is often what you want.  For example, in Python as it exists:...writing a memoized function like the above is quite an elementary task.  Similarly:...the simple , relying on the early-binding (definition time) of default arg values, is a trivially simple way to get early binding.  So, the current rule is simple, straightforward, and lets you do all you want in a way that's extremely easy to explain and understand: if you want late binding of an expression's value, evaluate that expression in the function body; if you want early binding, evaluate it as the default value of an arg.The alternative, forcing late binding for both situation, would not offer this flexibility, and would force you to go through hoops (such as wrapping your function into a closure factory) every time you needed early binding, as in the above examples -- yet more heavy-weight boilerplate forced on the programmer by this hypothetical design decision (beyond the \"invisible\" ones of generating and repeatedly evaluating thunks all over the place).In other words, \"There should be one, and preferably only one, obvious way to do it [1]\": when you want late binding, there's already a perfectly obvious way to achieve it (since all of the function's code is only executed at call time, obviously everything evaluated  is late-bound); having default-arg evaluation produce early binding gives you an obvious way to achieve early binding as well (a plus!-) rather than giving TWO obvious ways to get late binding and no obvious way to get early binding (a minus!-).[1]: \"Although that way may not be obvious at first unless you're Dutch.\"The issue is this.It's too expensive to evaluate a function as an initializer .The construct  is literal, like , that means \"this exact object\".The problem is that some people hope that it to means  as in \"evaluate this function for me, please, to get the object that is the initializer\".It would be a crushing burden to add the necessary  statement to do this evaluation all the time.  It's better to take all arguments as literals and not do any additional function evaluation as part of trying to do a function evaluation.Also, more fundamentally, it's technically  to implement argument defaults as function evaluations.Consider, for a moment the recursive horror of this kind of circularity.  Let's say that instead of default values being literals, we allow them to be functions which are evaluated each time a parameter's default values are required.[This would parallel the way  works.]What is the value of ?  To get the default for , it must evaluate , which requires an eval of .  Oops.Of course in your situation it is difficult to understand. But you must see, that evaluating default args every time would lay a heavy runtime burden on the system.Also you should know, that in case of container types this problem may occur -- but you could circumvent it by making the thing explicit:The workaround for this,  (and very solid), is:As for why look for an answer from von L\u00f6wis, but it's likely because the function definition makes a code object due to the architecture of Python, and there might not be a facility for working with reference types like this in default arguments.I thought this was counterintuitive too, until I learned how Python implements default arguments.A function's an object.  At load time, Python creates the function object, evaluates the defaults in the  statement, puts them into a tuple, and adds that tuple as an attribute of the function named .  Then, when a function is called, if the call doesn't provide a value, Python grabs the default value out of .For instance:So all calls to  that don't provide an argument will use the same instance of , because that's the default value.As far as why Python does it this way:  well, that tuple  contain functions that would get called every time a default argument value was needed.  Apart from the immediately obvious problem of performance, you start getting into a universe of special cases, like storing literal values instead of functions for non-mutable types to avoid unnecessary function calls.  And of course there are performance implications galore.The actual behavior is really simple.  And there's a trivial workaround, in the case where you  a default value to be produced by a function call at runtime:This comes from python's emphasis on syntax and execution simplicity.  a def statement occurs at a certain point during execution.  When the python interpreter reaches that point, it evaluates the code in that line, and then creates a code object from the body of the function, which will be run later, when you call the function.  It's a simple split between function declaration and function body.  The declaration is executed when it is reached in the code.  The body is executed at call time.  Note that the declaration is executed every time it is reached, so you can create multiple functions by looping.Five separate functions have been created, with a separate list created each time the function declaration was executed.  On each loop through , the same function is executed twice on each pass through, using the same list each time.  This gives the results:Others have given you the workaround, of using param=None, and assigning a list in the body if the value is None, which is fully idiomatic python.  It's a little ugly, but the simplicity is powerful, and the workaround is not too painful.Edited to add: For more discussion on this, see effbot's article here: , and the language reference, here: Python function definitions are just code, like all the other code; they're not \"magical\" in the way that some languages are. For example, in Java you could refer \"now\" to something defined \"later\":but in PythonSo, the default argument is evaluated at the moment that that line of code is evaluated!Because if they had, then someone would post a question asking why it wasn't the other way around :-pSuppose now that they had. How would you implement the current behaviour if needed? It's easy to create new objects inside a function, but you cannot \"uncreate\" them (you can delete them, but it's not the same).
Python

Is it possible to use strings as indices in an array in python?For example:What you want is called an . In python these are called .Alternative way to create the above dict:Accessing values:Getting the keys (in Python v2):If you want to learn about python dictionary internals, I recommend this ~25 min video presentation: . It's called the \"The Mighty Dictionary\".Even better, try an  (assuming you want something like a list).  Closer to a list than a regular dict since the keys have an order just like list elements have an order.  With a regular dict, the keys have an arbitrary order.Note that this is available in Python 3 and 2.7.  If you want to use with an earlier version of Python you can find installable modules to do that.
Python

I have a range of points x and y stored in numpy arrays.\nThose represent x(t) and y(t) where t=0...T-1I am plotting a scatter plot usingI would like to have a colormap representing the time (therefore coloring the points depending on the index in the numpy arrays) What is the easiest way to do so?Here is an exampleHere you are setting the color based on the index, , which is just an array of .\nPerhaps an easier-to-understand example is the slightly simplerNote that the array you pass as  doesn't need to have any particular order or type, i.e. it doesn't need to be sorted or integers as in these examples.  The plotting routine will scale the colormap such that the minimum/maximum values in  correspond to the bottom/top of the colormap.You can change the colormap by addingImporting  is optional as you can call colormaps as  just as well.  There is a  of colormaps showing what each looks like.  Also know that you can reverse a colormap by simply calling it as .  So eitherwill work.  Examples are  or .  Here's an example with the new 1.5 colormap viridis:You can add a colorbar by usingNote that if you are using figures and subplots explicitly (e.g.  or ), adding a colorbar can be a bit more involved. Good examples can be found  and .To add to wflynny's answer above, you can find the available colormaps Example:\nor alternatively,\n
Python

My code1st file:2nd file:in the above code, only keys of \"data\" dictionary were get passed to , but i want key-value pairs to pass. How to correct this ?I want the  to get modified like this and this is my requirement, give answers according to this  dictionary key  is changed to  If you want to use them like that, define the function with the variable names as normal (but use  for , you can't use reserved words):Now (as long as you rename class to klass in your dictionary) you can use  when you  the function:and it will work as you want.*data interprets arguments as tuples, instead you have to pass **data which interprets the arguments as dictionary. You can call the function like this:You can just pass itor if you really want to
Python

I am going through Zed Shaw's Python Book. I am currently working on the opening and reading files chapters. I am wondering why we need to do a truncate, when we are already opening the file in a 'w' mode?Its redundant since, as you noticed, opening in write mode will overwrite the file, more info at  section of Python documentation.So Zed Shaw calls truncate() on a file that is already truncated. OK, that's pretty pointless. Why does he do that? Who knows!? Ask him! Maybe he does it to show that the method exists? Could be, but that would be pretty daft, since I've never needed to truncate a file in my 15 years as a programmer so it has no place in a newbie book.Maybe he does it because he thinks he has to truncate the file, and he simply isn't aware that it's pointless?Maybe he does it intentionally to confuse newbies? That would fit with his general modus operandi, which seems to be to intentionally piss people off for absolutely no reason. The reason he does this is now clear. In later editions he lists this question as a \"common question\" in the chapter, and tells you to go read the docs. It's hence there to:You can debate if this is good teaching style or not, I wouldn't know.The number of \"Help I don't understand Zed Shaws book\"-questions on SO had dwindled, so I can't say that it's any worse than any other book out there, which probably means it's better than many. :-)If you would READ the questions before asking it, he answers it for you: He explicitly wants you to find these things out for yourself, this is why his extra credit is important.He also EXPLICITLY states that he wants you to PAY ATTENTION TO DETAIL. Every little thing matters. With , you can declare how much of the file you want to remove, based on where you're currently at in the file. Without parameters,  acts like w, whereas w always just wipes the whole file clean. So, these two methods  act identically, but they don't necessarily.While it's not useful to truncate when opening in 'w' mode, it is useful in 'r+'. Though that's not the OP's question, I'm going to leave this here for anyone who gets lead here by Google as I did.Let's say you open (with mode 'r+', ) a 5 line indented json file and modify the -ed object to be only 3 lines. If you  before writing the data back to the file, you will end up with 2 lines of trailing garbage. If you  it you will not.I know this seems obvious, but I'm here because I am fixing a bug that occurred after an object that stayed the exact same size for years... shrank because of a signing algorithm change. (What is not obvious is the unit tests I had to add to prevent this is the future. I wrote my longest docstring ever explaining why I'm testing signing with 2 ridiculously contrived algorithms.)Hope this helps someone.That's just a reflection of the standard posix semantics. see man fopen(3). Python just wraps that.
Python

In Python, I'd like to write a function  which returns another function. That returned function should be callable with a parameter , and return the volume of a cylinder with height  and radius .I know how to return  from functions in Python, but how do I return ?Try this, using Python:Use it like this, for example with  and :Notice that returning a function was a simple matter of defining a new function inside the function, and returning it at the end - being careful to pass the appropriate parameters for each function. FYI, the technique of returning a function from another function is known as .Just want to point out that you can do this with pymonad
Python

given the following dataframe in pandas:where  is an id for each point consisting of an  and  value, how can I bin  and  into a specified set of bins (so that I can then take the median/average value of  and  in each bin)?   might have  values for  or  (or both) for any given row in . thanks.Here's a better example using Joe Kington's solution with a more realistic df. The thing I'm unsure about is how to access the df.b elements for each df.a group below:There may be a more efficient way (I have a feeling  would be useful here), but here's how I'd do it:Edit: As the OP was asking specifically for just the means of  binned by the values in , just do Also if you wanted the index to look nicer (e.g. display intervals as the index), as they do in @bdiamante's example, use  instead of .  (Kudos to bidamante. I didn't realize  existed.)This results in:Not 100% sure if this is what you're looking for, but here's what I think you're getting at:Of course, I don't know what bins you had in mind, so you'll have to swap mine out for your circumstance.Joe Kington's answer was very helpful, however, I noticed that it does not bin all of the data. It actually leaves out the row with a = a.min(). Summing up  gave 99 instead of 100.To guarantee that all data is binned, just pass in the number of bins to cut() and that function will automatically pad the first[last] bin by 0.1% to ensure all data is included.In this case, summing up groups.size() gave 100.I know this is a picky point for this particular problem, but for a similar problem I was trying to solve, it was crucial to obtain the correct answer.
Python

I have values like this:I want to sort the values in each  in increasing order. I don't want to sort between the sets, but the values in each set.From a comment:That's easy. For any set  (or anything else iterable),  returns a list of the elements of  in sorted order:Note that  is giving you a , not a . That's because the whole point of a set, both in  and in ,* is that it's not ordered: the sets  and  are the same set.You probably don't really want to sort those elements as strings, but as numbers (so 4.918560000 will come before 10.277200999 rather than after).The best solution is most likely to store the numbers as numbers rather than strings in the first place. But if not, you just need to use a  function:For more information, see the  in the official docs.* See the comments for exceptions.
Python

I'm using the pdb module to debug a program. I'd like to understand how I can exit pdb and allow the program to continue onward to completion. The program is computationally expensive to run, so I don't want to exit without the script attempting to complete.  doesn't seems to work. How can I exit pdb and continue with my program? should \"Continue execution, only stop when a breakpoint is encountered\", so you've got a breakpoint set somewhere. To remove the breakpoint (if you inserted it manually):Or, if you're using , you can try this (although if you're using pdb in more fancy ways, this may break things...)A simple - will break out of pdb. If you want to continue rather than breaking, just press  rather than the whole  commandIf you really wish to exit the debugger then you need to run something like  which allows you to detach from the process and then exit the debugger, (N.B. It is multi-platform).If you would like to continue debugging but no longer stop at a given breakpoint then you need to:For more detail on the above see .
Python

I am trying to find if the process is running based on process id. The code is as follows based on one of the post on the forum. I cannot consider process name as there are more than one process running with the same name. Output :It always return true as it can find the process id in the output string. Any suggestions? Thanks for any help.Try:Should succeed (and do nothing) if the process exists, or throw an exception (that you can catch) if the process doesn't exist.The simplest answer in my opinion (albiet maybe not ideal), would be to change yourTo:This will ignore the process listing for the grep search containing the PID of the process you are trying to find. It seems user9876's answer is far more \"pythonic\" however. This is a bit of a kludge, but on *nix you can use  or  to test the existence of the process ID.EDIT: Note that  works on Windows (as of Python 2.7), while  .   the Windows version calls , which will \"unconditionally cause a process to exit\", so I predict that it won't safely return the information you want without actually killing the process if it does exist.If you're using Windows, please let us know, because none of these solutions are acceptable in that scenario.You could check if the folder /proc/[process_id] exists.See this SO: If you don't mind using external module I'd suggest . It is cross-platform and easier to use than spawning subshell only for purpose of finding a running process.If that process belongs to the same user the checking process, you can just try to  it. If you use signal 0, kill will not send anything but still allow you to tell if the process is available.From :This should propagate appropriately to python's methods.I know this is old, but I've used this and it seems to work; you can do a quick adaptation to convert from process name to process id:On Windows another option is to use tasklist.exe:Syntax: tasklist.exe /NH /FI \"PID eq processID\"On Windows, you can use WMI. You can also use other filters.  For example, I'm much more likely to just want to tell if a process is running by name and take action.  For example, if DbgView isn't running, then start it.You can also iterate and do other interesting things.  Complete list of fields is .Recently I had to list the running processes and did so:You have to find it twice..Like this :If this returns  then this is actually running !!
Python

Can someone tell me how to install sqlite3 package to the very recent version of Python?\nI use Macbook, and on the command line I tried:but an error pops up.You don't need to install  module. It is included in the standard library (since Python 2.5).I have python 2.7.3 and this solved my problem:
Python

Any gotchas I should be aware of?  Can I store it in a text field, or do I need to use a blob?\n(I'm not overly familiar with either pickle or sqlite, so I wanted to make sure I'm barking up the right tree with some of my high-level design ideas.)If you want to store a pickled object, you'll need to use a blob, since it is binary data. However, you can, say, base64 encode the pickled object to get a string that can be stored in a text field.Generally, though, doing this sort of thing is indicative of bad design, since you're storing opaque data you lose the ability to use SQL to do any useful manipulation on that data. Although without knowing what you're actually doing, I can't really make a moral call on it.I needed to achieve the same thing too.  I turns out it caused me quite a headache before I finally figured out, , how to actually make it work in a binary format.You must specify the second argument to dumps to force a binary pickling.\nAlso note the  to make it fit in the BLOB field.When retrieving a BLOB field, sqlite3 gets a 'buffer' python type, that needs to be strinyfied using  before being passed to the loads method.I wrote a blog about this idea, except instead of a pickle, I used json, since I wanted it to be interoperable with perl and other programs.  Architecturally, this is a quick and dirty way to get persistence, transactions, and the like for arbitrary data structures.  I have found this combination to be really useful when I want persistence, and don't need to do much in the sql layer with the data (or it's very complex to deal with in sql, and simple with generators).  The code itself is pretty simple:Then, when you wnat to dump it into the db, Pickle has both text and binary output formats. If you use the text-based format you can store it in a TEXT field, but it'll have to be a BLOB if you use the (more efficient) binary format.Since Pickle can dump your object graph to a string it should be possible. Be aware though that TEXT fields in SQLite uses database encoding so you might need to convert it to a simple string before you un-pickle.If a dictionary can be pickled, it can be stored in text/blob field as well.Just be aware of the dictionaries that can't be pickled (aka that contain unpickable objects).Yes, you can store a pickled object in a TEXT or BLOB field in an SQLite3 database, as others have explained.Just be aware that some object .  The built-in container types can (dict, set, list, tuple, etc.).  But some objects, such as file handles, refer to state that is external to their own data structures, and other extension types have similar problems.Since a dictionary can contain arbitrary nested data structures, it might not be pickle-able.I have to agree with some of the comments here.  Be careful and make sure you really want to save pickle data in a db, there's probably a better way.In any case I had trouble in the past trying to save binary data in the sqlite db.\nApparently you have to use the sqlite3.Binary() to prep the data for sqlite.Here's some sample code:SpoonMeiser is correct, you need to have a strong reason to pickle into a database.  It's not difficult to write Python objects that implement persistence with SQLite.  Then you can use the SQLite CLI to fiddle with the data as well.  Which in my experience is worth the extra bit of work, since many debug and admin functions can be simply performed from the CLI rather than writing specific Python code.In the early stages of a project, I did what you propose and ended up re-writing with a Python class for each business object (note: I didn't say for each table!) This way the body of the application can focus on \"what\" needs to be done rather than \"how\" it is done.The other option, considering that your requirement is to save a dict and then spit it back out for the user's \"viewing pleasure\", is to use the  module which will let you persist any pickleable data to file. The python docs are .Depending on what you're working on, you might want to look into the  module. It does something similar, where it auto-stores Python objects inside a sqlite database (and all sorts of other options) and pretends to be a dictionary (just like the  module).It is possible to store object data as pickle dump, jason etc but it is also possible to index, them, restrict them  and run select queries that use those indices. Here is example with tuples, that can be easily applied for any other python class. All that is needed is explained in python sqlite3 documentation (somebody already posted the link). Anyway here it is all put together in the following example:See this solution at SourceForge:y_serial.py module :: warehouse Python objects with SQLite\"Serialization + persistance :: in a few lines of code, compress and annotate Python objects into SQLite; then later retrieve them chronologically by keywords without any SQL. Most useful \"standard\" module for a database to store schema-less data.\"
Python

In python how would I pass an argument from the command line to a unittest function.  Here is the code so far\u2026 I know it's wrong.To extend with the above comment about unit tests.  Unit tests should stand alone in that they have no dependencies outside of their setup and tear down requirements, such as in your case setting up a email.  This makes sure that each tests has very specific side effects and reactions to the test. Passing in a parameter defeats this property of unit tests and thus makes them in a sense invalid. Using a test configuration would be the easiest way and-also more proper because again a unit test should never rely on outside information to perform the test. That is for integration tests.So the doctors here that are saying \"You say that hurts?  Then don't do that!\" are probably right.  But if you really want to, here's one way of passing arguments to a unittest test:You need the s so your command line params don't mess with unittest's own...[update]  The other thing you might want to look into is .  All the cool kids are saying it's the best python testing framework these days, and it :  Another method for those who really want to do this in spite of the correct remarks that you shouldn't: is meant for testing the very basic functionality (the lowest level functions of the application) to be sure that your  work correctly.  There is probably no formal definition of what does that exactly mean, but you should consider other kinds of testing for the  -- see . The unit testing framework may not be ideal for the purpose.If you want to use  with , you can modify the original test loader (see ):Have a same problem. My solution is after you handle with parsing arguments using argparse or other way, remove arguments from sys.argvIf you need you can filter unittest arguments from main.parseArgs()
Python

I'm using a builder pattern to seperate a bunch of different configuration possibilities. Basically, I have a bunch of classes that are named an ID (something like ID12345). These all inherit from the base builder class. In my script, I need to instantiate an instance for each class (about 50) every time this app runs. So, I'm trying to see if instead of doing something like this:Can I do something like this (I know this doesn't work):That way, when I need to add a new one in the future, all I have to do is add the id to the IDS list, rather than peppering the new ID throughout the code. Looks like there are some different opinions based on where the data is coming from. These IDs are entered in a file that no one else has access to. I'm not reading the strings from the command line, and I'd like to be able to do as little alteration when adding a new ID in the future. Not totally sure this is what you want, but it seems like a more Python'y way to instantiate a bunch of classes listed in a string:If you wanted to avoid an eval(), you could just do:Provided that the class is defined in (or imported into) your current scope. use  if you can help it. Python has  many better options (dispatch dictionary, , etc.) that you should never have to use the security hole known as .Simplest way is to just create a dict.Then use it (your code example):There's some stuff missing from your question, so I'm forced to guess at the omitted stuff.  Feel free to edit your question to correct the omissions.This works very nicely.  It doesn't instantiate from a string -- in practice you don't often want this.  Sometimes, but rarely.  More commonly, you a list of class objects from which you want instance objects.If you actually are getting your class names from the command line, then you'd make the following small change.Everything else remains the same.[Also, if possible, try to start instance variable names with lowercase letters.  Names which start with Uppercase Letters  are usually class names.]Removed .  In spite of the fact that  is absolutely   a security hole.  Eval (and  and ) are only a problem if someone specifically grants access to malicious users.
Python

I'm debugging some Python that takes, as input, a list of objects, each with some attributes.I'd like to hard-code some test values -- let's say, a list of four objects whose \"foo\" attribute is set to some number.Is there a more concise way than this?Ideally, I'd just like to be able to say something like:(Obviously, that is made-up syntax. But is there something similar that really works?)Note: This will never be checked in. It's just some throwaway debug code. So don't worry about readability or maintainability.I like Tetha's solution, but it's unnecessarily complex.Here's something simpler:I found this: , and in my limited testing it seems like it works:Have a look at this:Non classy:Another obvious hack:But for your exact usecase, calling a function with anonymous objects directly, I don't know any one-liner less verbose thanUgly, does the job, but not really.So brief, such Python! O.oEDIT: Well okay, technically this creates a class object, not an object object. But you can treat it like an anonymous object or you modify the first line by appending a pair of parenthesis to create an instance immediately:
Python

I notice there is a comparison operator . Should I literally translate it into instead of To expand on what Ignacio said: and  test whether two objects have the same . You can override an object's  and  methods to determine what that means. and  test whether two objects are the same thing. It's like doing It's not relational comparison, it's identity. And it translates to .:and about operator  in the same chapter:means that \"A  B\", not \"A  B\".
Python

I'm looking for how to turn the frequency axis in a fft (taken via scipy.fftpack.fftfreq) into a frequency in Hertz, rather than bins or fractional bins.I tried to code below to test out the FFT:The sampling rate should be 4000 samples / 120 seconds = 33.34 samples/sec.The signal has a 2.0 Hz signal, a 8.0 Hz signal, and some random noise.I take the FFT, grab the frequencies, and plot it.  The numbers are pretty nonsensical.  If I multiply the frequencies by 33.34 (the sampling frequency), then I get peaks at about 8 Hz and 15 Hz, which seems wrong (also, the frequencies should be a factor of 4 apart, not 2!).Any thoughts on what I'm doing wrong here?I think you don't need to do fftshift(), and you can pass sampling period to fftfreq():from the graph you can see there are two peak at 2Hz and 8Hz. gives you the frequencies directly.  If you set , this will tell you the frequency in Hz for each point of the fft.The frequency width of each bin is (sampling_freq / num_bins).Your equation is messed up. This gives you 4000 samples of your function, sampled at 33.33 Hz, representing 120 seconds of data.Now take your FFT. Bin 0 will hold the DC result. Bin 1 will be 33.33, bin 2 will be 66.66, etc..Edit: I forget to mention that, since your sampling rate is 33.33 Hz, the maximum frequency that can be represented will be fs/2, or 16.665 Hz.
Python

I am trying to develop an sample project in Django and getting errors when I run the syncdb command.This is how my project structure looks like:/Users/django_demo/godjango/bookings:And my manage.py file is as follows:And my PYTHONPATH and DJANGO_SETTINGS_MODULE are set as belowAnd my WSGI.py file looks like below:When I run the python manage.py syncdb command, I am getting the following error.Could someone suggest what I am missing?The error says So, is your path  within the python-sys.path?Check it in your shell with:If not - you need to add it or simply move your  app into one of the paths represented in your Modify your wsgi.py file from to The significant part of the traceback here is right at the very end. It says \"No module named unipath\". You've referred to that somewhere in your code, but you don't seem to have it in your project - it's not part of the standard library, so you'll need to install it somewhere that Python can see it.Alternatively, you can even pass the settings path at run time like so:This should override the environment variable Review hour /etc/apache2/httpd.conf file; you must include the WSGIPythonPath directive, to indicate the folder which contains your Django project (manage.py file), like:WSGIPythonPath /home/user/Projects/Django/MyProjectalso if you used some weird port in your VirtualHost, specify if for listening:Listen 90Hope this helps somebodyIn my case I was using  to import other files and there was an error in it, so settings might actually exist but be flawed. 
Python

In the Python console, when I type:Gives:Though I'd expect to see such an output:What am I missing here?The console is printing the representation, not the string itself.If you prefix with , you'll get what you expect.See  for details about the difference between a string and the string's representation. Super-simplified, the representation is what you'd type in source code to get that string.You forgot to  the result. What you get is the  in  and not the actual printed result.In Py2.x you should so something like and in Py3.X, print is a function, so you should doNow that was the short answer. Your Python Interpreter, which is actually a REPL, always displays the representation of the string rather than the actual displayed output. Representation is what you would get with the  statementYou need to  to get that output.\nYou should doYou have to print it:When you print it with this  you would get:The  is a new line character specially used for marking END-OF-TEXT. It signifies the end of the line or text. This characteristics is shared by many languages like C, C++ etc.
Python

When i run the following code in Python - 3.3:I get the following error:I did this too to verify:What am i doing wrong? Thanks in advance!Import  instead of .Interestingly, I noticed some IDE-depending behavior.Both Spyder and PyCharm use the same interpreter on my machine : in PyCharm I need to do while in Spyder, does fineIf this is on PyCharm, as was mine, make sure your file name isn't urllib.py.
Python

I'd like to write a Python script for Amarok in Linux to automatically copy the stackoverflow podcast to my player. When I plug in the player, it would mount the drive, copy any pending podcasts, and eject the player. How can I listen for the \"plugged in\" event? I have looked through hald but couldn't find a good example.: As said in comments, Hal is not supported in recent distributions, the standard now is udev, Here is a small example that makes use of glib loop and , I keep the Hal version for historical reasons.This is basically the , adapted to work with older versions, and with the glib loop, notice that the filter should be customized for your specific needing:You can use D-Bus bindings and listen to  and  signals.\nYou will have to check the capabilities of the Added device in order to select the storage devices only.Here is a small example, you can remove the comments and try it.You need to connect to Hal Manager using the System Bus.And you need to connect a listener to the signals you are interested on, in this case .I'm using a filter based on capabilities. It will accept any  and will call  with if, you can read Hal documentation to find the more suitable queries for your needs, or more information about the properties of the Hal devices.Example function that shows some information about the volume:I haven't tried writing such a program myself, however I've just looked at the following two links (thanks Google!), which I think will be of help:In particular, read about the  interface, and its  and  events. :-)Hope this helps!I think D-Bus would work as Chris mentioned, but if you're using KDE4, you might use the Solid framework in a manner similar to the KDE4 \"New Device Notifier\" applet.The C++ source for that applet is , which shows how to use Solid to detect new devices.  Use PyKDE4 for Python bindings to these libraries, as shown .Here is a solution in 5 lines.Save this to a file say , run . Plug any usb and it will print device detailsTested on Python 3.5 with . 
Python

 If you get the character encoding wrong than your output will be messed up.People usually use some rudimentary technique to detect the encoding. They either use the charset from the header or the charset defined in the meta tag or they use an  (which does not care about meta tags or headers).\nBy using only one these techniques, sometimes you will not get the same result as you would in a browser.Browsers do it this way:(Well... at least that is the way I believe most browsers do it. Documentation is really scarce.) I'm sure I'm not the first who needs a proper solution to this problem.According to .Beautiful Soup tries the following encodings, in order of priority, to turn your document into Unicode:I would use  for this.When you download a file with urllib or urllib2, you can find out whether a charset header was transmitted:You can use BeautifulSoup to locate a meta element in the HTML:If neither is available, browsers typically fall back to user configuration, combined with auto-detection. As rajax proposes, you could use the chardet module. If you have user configuration available telling you that the page should be Chinese (say), you may be able to do better.Use the :The other option would be to just use wget:It seems like you need a hybrid of the answers presented:I honestly don't believe you're going to find anything better than that.  In fact if you read further into the FAQ you linked to in the comments on the other answer, that's what the author of detector library advocates.If you believe the FAQ, this is what the browsers do (as requested in your original question) as the detector is a port of the firefox sniffing code.Scrapy downloads a page and detects a correct encoding for it, unlike requests.get(url).text or urlopen. To do so it tries to follow browser-like rules - this is the best one can do, because website owners have incentive to make their websites work in a browser. Scrapy needs to take HTTP headers,  tags, BOM marks and differences in encoding names in account. Content-based guessing (chardet, UnicodeDammit) on its own is not a correct solution, as it may fail; it should be only used as a last resort when headers or  or BOM marks are not available or provide no information.You don't have to use Scrapy to get its encoding detection functions; they are released (among with some other stuff) in a separate library called w3lib: . To get page encoding and unicode body use  function, with a content-based guessing fallback:instead of trying to get a page then figuring out the charset the browser would use, why not just use a browser to fetch the page and check what charset it uses.. BeautifulSoup dose this with UnicodeDammit : 
Python

I'm trying to install couchapp, which uses easy_install - and is quite explicit in stating a particular version of easy_install/setuptools is needed: 0.6c6. I seem to have easy_install already on my Mac, but there's no command-line arguments to check the version. Instead of just installing a new version over the top, I'd like to see whether it's necessary first.So: Any pointers on how I can see what version of setuptools/easy_install I have installed on my machine?I'm not a Python developer, so I'm assuming this is a simple question. However, I've not found anything via Google or here on SOF.One way would be to look at the actual source file for easy_install. Doto see where it's located, and then use that path inThe second line in my easy_install script says:which suggests that I have easy_install version 0.6c11.This seems to get a lot of hits from google, so I thought I'd update for those folks.  I was able to do:which produced the outputI believe this only works for some (newer?) versions of setuptoolsOn Windows, where Python is in the Path:For me, I get\nsetuptools 7.0\nas the response.
Python

I am using Python to parse entries from a log file, and display the entry contents using Tkinter and so far it's been excellent. The output is a grid of label widgets, but sometimes there are more rows than can be displayed on the screen. I'd like to add a scrollbar, which looks like it should be very easy, but I can't figure it out.The documentation implies that only the List, Textbox, Canvas and Entry widgets support the scrollbar interface. None of these appear to be suitable for displaying a grid of widgets. It's possible to put arbitrary widgets in a Canvas widget, but you appear to have to use absolute co-ordinates, so I wouldn't be able to use the grid layout manager?I've tried putting the widget grid into a Frame, but that doesn't seem to support the scrollbar interface, so this doesn't work:Can anyone suggest a way round this limitation? I'd hate to have to rewrite in PyQt and increase my executable image size by so much, just to add a scrollbar!You can only associate scrollbars with a few widgets, and the root widget and  aren't part of that group of widgets. The most common solution is to create a canvas widget and associate the scrollbars with that widget. Then, into that canvas embed the frame that contains your label widgets. Determine the width/height of the frame and feed that into the canvas  option so that the scrollregion exactly matches the size of the frame.Drawing the text items directly on the canvas isn't very hard, so you might want to reconsider that approach if the frame-embedded-in-a-canvas solution seems too complex. Since you're creating a grid, the coordinates of each text item is going to be very easy to compute, especially if each row is the same height (which it probably is if you're using a single font).For drawing directly on the canvas, just figure out the line height of the font you're using (and there are commands for that). Then, each y coordinate is . The x coordinate will be a fixed number based on the widest item in each column. If you give everything a tag for the column it is in, you can adjust the x coordinate and width of all items in a column with a single command.Here's an example of the frame-embedded-in-canvas solution, using an object-oriented approach:Here is a solution that doesn't use objects: to make this work in python 2.x, use  rather than  in the import statement
Python

I am using Numpy to store data into matrices. Coming from R background, there has been an extremely simple way to apply a function over row/columns or both of a matrix.Is there something similar for python/numpy combination? It's not a problem to write my own little implementation but it seems to me that most of the versions I come up with will be significantly less efficient/more memory intensive than any of the existing implementation. I would like to avoid copying from the numpy matrix to a local variable etc., is that possible?The functions I am trying to implement are mainly simple comparisons (e.g. how many elements of a certain column are smaller than number x or how many of them have absolute value larger than y).Almost all numpy functions operate on whole arrays, and/or can be told to operate on a particular axis (row or column). As long as you can define your function in terms of numpy functions acting on numpy arrays or array slices, your function will automatically operate on whole arrays, rows or columns.It may be more helpful to ask about how to implement a particular function to get more concrete advice.Numpy provides  and  to turn Python functions which operate on numbers into functions that operate on numpy arrays.For example,(The elements of the first array get replaced by the corresponding element of the second array when the second is bigger.)But don't get too excited;  and  are . They don't actually make your code any faster. If your underlying Python function is operating on one value at a time, then  will feed it one item at a time, and the whole \noperation is going to be pretty slow (compared to using a numpy function which calls some underlying C or Fortran implementation).To count how many elements of column  are smaller than a number , you could use an expression such as:For example:Selecting elements from a NumPy array based on one or more conditions is straightforward using NumPy's  beautifully dense syntax:\n\n\nNumPy's indexing syntax is pretty close to R's; given your fluency in R, here are the key differences between R and NumPy in this context:NumPy , in R, indexing begins with 1NumPy (like Python) allows you to  using negative indices--e.g.,NumPy uses , e.g., in R, to\n   get the first three rows in A, you would use, A[1:3, ]. In NumPy, you\n   would use A[0:2, :] (in NumPy, the \"0\" is not necessary, in fact it\n   is preferable to use A[:2, :]I also come from a more R background, and bumped into the lack of a more versatile apply which could take short customized functions. I've seen the forums suggesting using basic numpy functions because many of them handle arrays. However, I've been getting confused over the way \"native\" numpy functions handle array (sometimes 0 is row-wise and 1 column-wise, sometimes the opposite). My personal solution to more flexible functions with apply_along_axis was to combine them with the implicit lambda functions available in python. Lambda functions should very easy to understand for the R minded who uses a more functional programming style, like in R functions apply, sapply, lapply, etc.So for example I wanted to apply standardisation of variables in a matrix. Tipically in R there's a function for this (scale) but you can also build it easily with apply:(R code)You see how the body of the function inside apply (x-mean(x))/sd(x) is the bit we can't type directly for the python apply_along_axis. With lambda this is easy to implement FOR ONE SET OF VALUES, so:(Python)Then, all we need is to plug this inside the python apply and pass the array of interest through apply_along_axisObviously, the lambda function could be implemented as a separate function, but I guess the whole point is to use rather small functions contained within the line where apply originated.I hope you find it useful ! is very useful for this. For instance,  and  should help you.
Python

I have a Python regular expression that contains a group which can occur zero or many times - but when I retrieve the list of groups afterwards, only the last one is present. Example:()this returns the list ('g',)I need it to return ('a','b','c','d','e','f','g',)Is that possible? How can I do it? In addition to , here is the explanation:In regular expressions the group count is fixed. Placing a quantifier behind a group does not increase group count (imagine all other group indexes increment because an eralier group matched more than once).Groups with quantifiers are the way of making a complex sub-expression atomic, when there is need to match it more than once. The regex engine has no other way than saving the last match only to the group. In short: There is no way to achieve what you want with a single \"unarmed\" regular expression, and you have to find another way.
Python

I want to compare UTC timestamps from a log file with local timestamps. When creating the local  object, I use something like:I want to find an automatic tool that would replace the with the current local time zone.Any ideas?Try , which has a  type that does what you need.It is  in a portable manner. Fortunately, you don't need it to perform the comparison. returns a pytz timezone corresponding to the local timezone:Unlike other solutions presented so far the above code avoids the following issues:Note: to get timezone-aware datetime object from a naive datetime object, you should use:instead of: forces an exception if given local time is ambiguous or non-existent.If you are certain that all local timestamps use the same (current) utc offset for the local timezone then you could perform the comparison using only stdlib: and  can be compared directly.Note: I was asking the same to myself, and I found the answer in 1:Take a look at section 8.1.7: the format \"%z\" (lowercase, the Z uppercase returns also the time zone, but not in the 4-digit format, but in the form of timezone abbreviations, like in [3]) of strftime returns the form \"+/- 4DIGIT\" that is standard in email headers (see section 3.3 of RFC 2822, see [2], which obsoletes the other ways of specifying the timezone for email headers).So, if you want your timezone in this format, use: [1] [2] [3] Timezone abbreviations:  , only for reference.In Python 3.x, local timezone may can be figure out like this:It's a tricky use of 's .First get pytz and tzlocal modulespip install pytz tzlocalthenthen you can do things likeAvoiding non-standard module (seems to be a missing method of datetime module):Based on Thoku's answer above, here's an answer that resolves the time zone to the nearest half hour (which is relevant for some timezones eg South Australia's) :Here's a way to get the local timezone using only the standard library, (only works in a *nix environment):You can use this to create a  timezone:...which you can then apply to a :Based on J. F. Sebastian's comment, you can do this with the standard library:Tested in 3.4, should work on 3.4+For simple things, the following  implementation can be used, which queries the OS for time zone offsets:First, note that the question presents an incorrect initialization of an aware datetime object:creates an invalid instance.  One can see the problem by computing the UTC offset of the resulting object:(Note the result which is an odd fraction of an hour.)To initialize an aware datetime properly using pytz one should use the  method as follows:Now, if you require a local pytz timezone as the new tzinfo, you should use the tzlocal package as others have explained, but if all you need is an instance with a correct local time zone offset and abbreviation then tarting with Python 3.3, you can call the  method with no arguments to convert an aware  instance to your local timezone: from .Code example follows. Last string suitable for use in filenames.
Python

I want to store a datetime object with a localized UTC timezone. The method that stores the datetime object can be given a non-localized datetime (naive) object or an object that already has been localized. How do I determine if localization is needed?Code with missing if condition:From :Though if  is a datetime object representing time in UTC timezone then you could use in both cases:It works regardless  is timezone-aware or naive.Note:  (it is ok to use it with UTC timezone but otherwise you should use  method).If you want to support arbitrary timezones for aware datetime objects i.e., only naive datetime objects are required to represent time in UTC timezone in your application then you could use  to convert  to  timezone:Note: you don't need to call  method after  here because the destination timezone is UTC.It works even if  uses non-pytz timezones.if you want to check if a datetime object 'd' is localized, check the d.tzinfo, if it is None, no localization.Here's a more complete function to convert or coerce a timestamp obj to utc. If it reaches the exception this means the timestamp is not localized. Since it's good practice to always work in UTC within the code, this function is very useful at the entry level from persistence. The small addition from the 'try catch' in the answer by J.F. Sebastian is the additional catch condition, without which not all naive cases will be caught by the function. 
Python

I just solved some problems in my Django 1.3 app by using PyMySQL instead of MySQLdb. I followed this tutorial on how to make the switch: Now I want to know what PyMySQL actually is and how it is different from MySQLdb.I am using it on localhost and will then upload it to some hosting.Is it fine to use PyMySQL on localhost and on hosting whatever they provide? Since I have changed \"MySQLdb\" in base.py and introspection.py to \"PyMySQL\", will I need to upload it to the server after changing these files? Or as it is Django's files, since Django will be uploaded there already, does it not matter much?PyMySQL and MySQLdb are both database connectors for Python, libraries to enable Python programs to talk to a MySQL server.You would normally never upload core Django files when deploying an app. If Django is working fine on your deployment server, you definitely don't need to change anything there. The DB driver is a step or two below the ORM even, and certainly none of the code you have written depends on which of these is in use.PyMySQL and MySQLdb provide the same functionality - they are both database connectors. The difference is in the implementation where MySQLdb is a C extension and PyMySQL is pure Python.There are a few reasons to try PyMySQL:The proper way to use it with Django is to import it and tell it to impersonate MySQLdb in your top-level file, usually manage.py. Put the following code at the very top of your manage.py (or whatever file you call when starting your server):Your first point:According to  page:Your second point:
Python

I'm trying to understand the following piece of code:Specifically, I don't understand what the index  refers to. If the index  refers to the first element, then what does  refer to?Negative numbers mean that you count from the right instead of the left. So,  refers to the last element,  is the second-last, and so on.List indexes of -x mean the xth item from the end of the list, so  means the last item in the list . Any good Python tutorial should have told you this.It's an unusual convention that few languages other than Python have adopted, but it is extraordinarily useful; in any other language you'll spend a lot of time writing  to access the last item of a list.
Python

The code below produces gaps between the subplots.  How do I remove the gaps between the subplots and make the image a tight grid?You can use  to control the spacing between axes. There's more  here. The problem is the use of , which prevents the subplots from stretching to an arbitrary aspect ratio and filling up all the empty space.Normally, this would work:The result is this:However, with , as in the following code:This is what we get:The difference in this second case is that you've forced the x- and y-axes to have the same number of units/pixel. Since the axes go from 0 to 1 by default (i.e., before you plot anything), using  forces each axis to be a square. Since the figure is not a square, pyplot adds in extra spacing between the axes horizontally.To get around this problem, you can set your figure to have the correct aspect ratio. We're going to use the object-oriented pyplot interface here, which I consider to be superior in general:Here's the result:Have you tried ?with \n\nwithout it:\nOr: something like this (use )If you don't need to share axes, then simply \n
Python

Python's built-in unittest module makes assertions with  methods: I have generally used a testrunner such as  or  which allow use of the built-in  keyword when making assertions:What is the motivation for unittest's  approach and what are the strengths and weaknesses of this vs asserting with the built-in assert keyword? Are there reasons why unittest's syntax should be favoured?The problem with the  keyword is that it is optimized out, and thus , when Python is run in 'optimized' mode (with the  argument or with the  environment variable set.) If tests were to use  then testing with  would be impossible.Additionally, the use of the assert methods makes it trivial to report about what the values involved actually were, without having to dig into the stack and the source and figure out what they were supposed to be (which, I believe, is the technique  and  use for this.)I don't see a concrete design decision for this. Looking at the  it states \nthat So I would say it is an implementation decision to help produce more meaningful errors etc.The main strength of this approach is providing several built in tests that are commonly performed so that one doesn't have to write them over and over again. Additionally, assertRaises lets you customize the exact behavior of the assert by throwing an exception.
Python

I have a signal_handler connected through a decorator, something like this very simple one:What I want to do is to mock it  in a test, to check how many times django calls it. My code at the moment is something like:The problem here is that the original signal handler is called even if mocked, most likely because the  decorator is storing a copy of the signal handler somewhere, so I'm mocking the wrong code.So the question: how do I mock my signal handler to make my test work?Note that if I change my signal handler to:and I mock  instead, everything works as expected.So, I ended up with a kind-of solution: mocking a signal handler simply means to connect the mock itself to the signal, so this exactly is what I did:Notice that  in  is required in order to make  to correctly work on a , otherwise django will raise some exceptions and the connection will fail.Possibly a better idea is to mock out the functionality  the signal handler rather than the handler itself. Using the OP's code:Then mock :There is a way to mock django signals with a small class.You should keep in mind that this would only mock the function as a django signal handler and not the original function; for example, if a m2mchange trigers a call to a function that calls your handler directly, mock.call_count would not be incremented. You would need a separate mock to keep track of those calls.Here is the class in question:Example usagetake a look at mock_django . It has support for signalsYou can mock a django signal by mocking the ModelSignal class at  like this:That should do the trick. Note that this will mock ALL signals no matter which object you are using.If by any chance you use the  library instead, it can be done like this:It's more lines but it works pretty well too :)In django 1.9 you can mock all receivers with something like thisThis replaces all receivers with mocks, eg ones you've registered, ones pluggable apps have registered and ones that django itself has registered. Don't be suprised if you use this on  and things start breaking. You may want to inspect the receiver to determine if you actually want to mock it.
Python

Alright, I have a fairly simple design.Is there an easy-ish way to allow a user to create an update all on one page?What I  is for a user to be able to go to the admin interface, add a new Update, and then while editing an Update add one or more Posts, with each Post having one or more Media items.  In addition, I want the user to be able to reorder Posts within an update.My current attempt has the following in admin.py:This let's the user add a new Post item, select the relevant Update, add the Media items to it, and hit save - which is fine.  But there's no way to see all the Posts that belong to a given Update in a single place, which in turn means you can't roderder Posts within an update.  It's really quite confusing for the end user.Help?As of now there is no \"built-in\" way to have nested inlines (inline inside inline) in django.contrib.admin. Pulling something like this off is possible by having your own ModelAdmin and InlineModelAdmin subclasses that would enable this kind of functionality. See the patches on this ticket  for ideas on how to implement this. You'd also need to provide your own templates that would have nested iteration over both the top level inline and it's child inline.There is now this egg available, which is a collation of the relevant patches mentioned in the other answer:however, it appears that it is not stable yet (they mention some known issues, and are looking for bugfix pull requests).  They don't say what the issues are.Edit: I'm using it, it seems to be working, no issues so far.I have just ran into this issue as well... Seems this thread which contains the request for the nested inlines feature () has been updated with further information. A custom made app called \"django-super-inline\" has been released. More details here: Installation and usage instructions below. Hope this is useful for whomever comes across this.I ran into a similar issue to this.  My approach was to make an UpdateAdmin that held inlines for both Media and Post... it basically just makes it so you have a list of all of the media entries followed by all of the posts in an update.It isn't an ideal solution but it works for a quick and dirty work around.I have done this using , for the following Data structure:My file: appears to be much more actively maintained than the other apps already mentioned ( and )
Python

I have the following code in my template:It works as expected when there is more than one item in the friendslist. But if there is just 1 item, then the content inside the forloop.last\nconditional does not display. I guess this is because the loop in that case is the first, but I mean it's also the last right? So why dosn't both contents inside first and last\nconditional show?In my code they both execute if there is only one element in friendslist. Here is a test you can run in the shell where maybe you can figure out what isn't working:couldn't you just use an \"or\" tag like {% if forloop.last or friendlist.count == 1 %}
Python

I'm trying to extract named entities from my text using NLTK. I find that NLTK NER is not very accurate for my purpose and I want to add some more tags of my own as well. I've been trying to find a way to train my own NER, but I don't seem to be able to find the right resources. \nI have a couple of questions regarding NLTK-I would really appreciate help in this regardAre you committed to using NLTK/Python?  I ran into the same problems as you, and had much better results using Stanford's named-entity recognizer: .  The process for training the classifier using your own data is very well-documented in the FAQ.  If you really need to use NLTK, I'd hit up the mailing list for some advice from other users: .  Hope this helps!You can easily use the Stanford NER alongwith nltk.\nThe python script is likeTo train your own data and to create a model you can refer to the first question on Stanford NER FAQ.The link is 
Python

As a self-development exercise, I want to develop a simple classification algorithm that, given a particular cell of a Dilbert cartoon, is able to identify which characters are present in the cartoon (Dilbert, PHB, Ratbert etc.). I assume the best way to do this is to (1) apply some algorithm to the image, which converts it into a set of features, and (2) use a training set and one of many possible machine learning algorithms to correlate the presence/absence of certain features with a particular character being present in the cell.So my questions are - (a) is this the correct approach, (b) since there's a number of classification algorithms and ML algorithms to test, what is a good methodology for finding the right one, and (c) which algorithms would you start with, given that we're essentially conducting a classification exercise on a cartoon.So i think you are on the right track w/r/t your step 1 (. This project is more challenging that most ML problems because here you will actually have to create your training data set from the raw data (the individual frames comprising the cartoons). For instance, grab a frame, identify two characters in that frame, Dilbert and the character with horns (Dilbert's boss i believe, don't know his name), extract those two characters from that frame and append to each the appropriate class label (e.g., \"1\" for Dlibert).\n\nTo extract the individual characters from each of the frames comprising the a Dilbert cartoon, i would suggest  a  of each frame. If you are not familiar with this technique, at its core, it's just an eigenvector decomp. If you like python (or R, given that you can use python-to-R bindings like ) then i would strongly encourage you to look at . In particular, this excellent library (which was originally developed under the  project umbrella, and therefore uses NumPy + SciPy for matrix computation) has several algorithms for image segmentation, one of which is based on . For this step in your Project, you would most likely want to look at these two scikits.learn modulesIncluded with these two modules are two good example scripts, one  and the  segmenting an image comprised of three partially super-imposed circles with minimal contrast w/r/t each other and w/r/t the background--both, i suspect are more difficult problems that the decompositions you will need to perform. In other words,  has two complete, well-documented example scripts included in the source distribution, both of which process data similar to yours. Either or both would be an excellent template for this step.\nSo that's the first step; here's the second:  all of the components of the decomposed images into groups, . Next, assign a class label to each Group, e.g., if there are four characters from your decomposition step, then a decent choice for class labels is \"0\", \"1\", \"2\", and \"3.\" Append those class labels to the component matrices (the decomposition products from step 1) so each character matrix is mapped to its corresponding class (Dilbert character).\nSelect a suitable ML technique. You have many choices for this step; the only criteria are that the technique is in the  category (because you have assigned class labels to your data) and that it function as a  (i.e., it returns a class label, versus a regressor which outputs a numerical value). Given this is a personal project, i would chose the one that seems most interesting to you. A few that satisfy the criteria i just mentioned are:  (neural network),  (SVM), and  (kNN).\ntrain, validate, and test your classifier: Once Step 1 is completed (each image is decomposed into a set of objects, some of which will no doubt represent the characters) you can manually sift through these decomposition products and collect exemplars for each character in the cartoon. The are the .Next you compare objects segmented from an image with this set of unique templates. In , another scipy scikit, you can use the method , to which you pass in a template image and a candidate image, and this method returns a 2D array showing the pixel-by-pixel correlation (between -1 and 1).  I think, in general, this is the correct approach and that there are two techniques you could have a look at.This question was asked 5 years back, therefore the answers provided above are outdated given the fact that deep learning has changed the face of computer vision over the past 3-4 years. A deep learning based solution would involve training a Convolutional Neural Network, which would learn features and perform classification in an end-to-end learning framework. However, since multiple cartoons may be present in the same image, the standard softmax cross entropy loss used in image classification may not be appropriate. Hence, independent logistic regression should be used as a loss function. Threshold for each class can be obtained based on accuracy obtained over a held-out validation set. Even for cartoons, it is better to use a pre-trained model initialized using imagenet instead of training from scratch (, although the final task in this paper is different, they still do processing on cartoons). If you have abundant data, pre-training may not be that important. This task can be performed using standard libraries like / etc.You can try building a model by uploading your training data (images of comics) to  (free to use)Then query the API using the following (Python Code):the response looks like:
Python

What is the current status of easy_install, pip and the repository (pypi.python.org) with regards to Python 3.x?Are there versions of easy_install and/or pip that can install the right versions of packages from there? Else, are they expected soon?PyPi itself supports Python 3.  The  package provides a version of easy_install that works with Python 3.According to , pip support Python 3 since v 1.0.There is ongoing effort to provide support for Python 3 in pip.\nSee  thread on virtualenv mailing list or head directly to Vinay Sajip's  on bitbucket.orgAs of version 1.0,  supports Python 3.Notice that easy_install is shipped with Python 3.4 and higher
Python

I think the best way to ask this question is with some code... can I do this? (: ANSWER: no)\n: you can keep the column name as 'foo' in the database by passing a db_column to the model field. This is very helpful when you are working on an existing system and you don't want to have to do db migrations for no reasonA model field is already property, so I would say you have to do it the second way to avoid a name clash.When you define foo = property(..) it actually overrides the foo = models.. line, so that field will no longer be accessible.You will need to use a different name for the property and the field. In fact, if you do it the way you have it in example #1 you will get an infinite loop when you try and access the property as it now tries to return itself.EDIT: Perhaps you should also consider not using _foo as a field name, but rather foo, and then define another name for your property because properties cannot be used in QuerySet, so you'll need to use the actual field names when you do a filter for example.As mentioned, a correct alternative to implementing your own django.db.models.Field class, one should use -  argument and a custom (or hidden) class attribute. I am just rewriting the code in the edit by @Jiaaro following more strict conventions for OOP in python (e.g. if _foo should be actually hidden): will be resolved into  (as seen by ) thus hidden (). Note that this form also permits using of  which would be ultimately a nicer way to write readable code.Again, django will create *_MyModel table with two fields  and .The previous solutions suffer because @property causes problems in admin, and .filter(_foo).  A better solution would be to override  except that this can cause problems initializing the ORM object from the DB.  However, there is a trick to get around this, and it's universal.The secret is ''.  When the model initializes either from new or hydrated from the !
Python

What is the most elegant way to solve this:The built-in functions work like thisscr.txt now contains '111'.scr.txt was overwritten and now contains '222' (on Windows, Python 2.4).The solution should work inside the same process (like in the example above) as well as when another process has opened the file.\nIt is preferred, if a crashing program will not keep the lock open.I don't think there is a fully crossplatform way.  On unix, the fcntl module will do this for you.  However on windows (which I assume you are by the paths), you'll need to use the win32file module.Fortunately, there is a portable implementation () using the platform appropriate method at the python cookbook.To use it, open the file, and then call:where flags are portalocker.LOCK_EX for exclusive write access, or LOCK_SH for shared, read access.If by 'another process' you mean 'whatever process' (i.e. not your program), in Linux there's no way to accomplish this relying only on system calls ( & friends). What you want is , and the Linux way to obtain it is a bit more involved:Remount the partition that contains your file with the  option:Set the  flag for your file:In your Python code, obtain an exclusive lock on that file:Now even  will not be able to read the file until you release the lock. Here's a start on the win32 half of a portable implementation, that does not need a seperate locking mechanism.Requires the  to get down to the win32 api, but that's pretty much mandatory for python on windows already, and can alternatively be done with . The code could be adapted to expose more functionality if it's needed (such as allowing  rather than no sharing at all). See also the MSDN documentation for the  and  system calls, and the .As has been mentioned, you can use the standard  module to implement the unix half of this, if required.Here's how your example from above behaves:EDIT:  By using  & age as a locking mechanism! Locking by file is safe only on Windows (because Linux silently overwrites), but locking by directory works perfectly both on Linux and Windows. See my GIT where I created an easy to use class  for that:At the bottom of the readme, you find 3 GITplayers where you can see the code examples execute live in your browser! Quite cool, isn't it? :-)Thanks for your attentionI would like to answer to parity3 () but I can neither comment directly ('You must have 50 reputation to comment'), nor do I see any way to contact him/her directly. What do you suggest to me, to get through to him?My question:I have implemented something similiar to what parity3 suggested here as an answer:  (\"Assuming your Python interpreter, and the ...\")And it works brilliantly - on Windows. (I am using it to implement a locking mechanism that works across independently started processes.  )But other than parity3  says, it does NOT work the same on Linux:The silent replacing is the problem. On Linux.\nThe \"if dst already exists, OSError will be raised\" is great for my purposes. But only on Windows, sadly.I guess parity3's example still works most of the time, because of his if conditionBut then the whole thing is not atomic anymore. Because the if condition might be true in two parallel processes, and then both will rename, but only one will win the renaming race. And no exception raised (in Linux).Any suggestions? Thanks! P.S.: I know this is not the proper way, but I am lacking an alternative. PLEASE don't punish me with lowering my reputation. I looked around a lot, to solve this myself. How to PM users in here? And  why can't I?To make you safe when opening files within one application, you could try something like this:That way you subclass the  class. Now just do:If you open it first with 'w' mode, it won't allow anymore opens, even in read mode, just as you wanted...Assuming your Python interpreter, and the underlying os and filesystem treat os.rename as an atomic operation and it will error when the destination exists, the following method is free of race conditions.  I'm using this in production on a linux machine.  Requires no third party libs and is not os dependent, and aside from an extra file create, the performance hit is acceptable for many use cases.  You can easily apply python's function decorator pattern or a 'with_statement' contextmanager here to abstract out the mess.You'll need to make sure that lock_filename does not exist before a new process/task begins.It has come to light that os.rename silently overwrites the destination on a non-windows OS. Thanks for pointing this out @ akrueger!Here is a workaround, gathered from :Instead of using os.rename you can use:@ akrueger You're probably just fine with your directory based solution, just giving you an alternate method.
Python

Suppose I have a module  and a package . If I callwhich one will be loaded? How can I specify I wand to load the module, or the package?I believe the package will always get loaded. You can't work around this, as far as I know. So change either the package or the module name. Docs: Actually, it is possible (this code is not well tested, but seems to work).File File File File RunningMaybe you want to move your classes from  module to .This way you'll be able to import them from the package as well as importing optional subpackages:File :File :Nonetheless I would like somebody to double-check this approach and let me know if it's correct or the  module shouldn't be used like that.
Python

I'm working with some rather large, dense numpy float arrays that currently reside on disk in PyTables s. I need to be able to perform efficient dot products using these arrays, for example , where  is a huge (~1E4 x 3E5 float32) memory-mapped array, and  and  are smaller numpy arrays that are resident in core memory.What I'm doing at the moment is copying the data into memory-mapped numpy arrays using , then calling  directly on the memory-mapped arrays. This works, but I suspect that the standard  (or rather the underlying BLAS functions it calls) is probably not very efficient in terms of the number of I/O operations required in order to compute the result.I came across an interesting example in . A naive dot product computed using 3x nested loops, like this:requires  I/O operations to compute.However, by processing the arrays in appropriately-sized blocks:where  is the maximum number of elements that will fit into core memory, the number of I/O operations is reduced to .How smart is  and/or ? Does calling  perform an I/O-efficient blockwise dot product? Does  do any fancy caching that would improve the efficiency of this type of operation?If not, is there some pre-existing library function that performs I/O efficient dot products, or should I try and implement it myself?I've done some benchmarking with a hand-rolled implementation of  that operates on blocks of the input array, which are explicitly read into core memory. This data at least a partially addresses my original question, so I'm posting it as an answer.I've implemented a function for applying  to blocks that are explicitly read into core memory from the memory-mapped array: I then did some benchmarking to compare my  function to the normal  function applied directly to a memory-mapped array (see below for the benchmarking script). I'm using numpy 1.9.0.dev-205598b linked against OpenBLAS v0.2.9.rc1 (compiled from source). The machine is a quad-core laptop running Ubuntu 13.10, with 8GB RAM  and an SSD, and I've disabled the swap file.As @Bi Rico predicted, the time taken to compute the dot product is beautifully  with respect to the dimensions of . Operating on cached blocks of  gives a huge performance improvement over just calling the normal  function on the whole memory-mapped array:It's surprisingly insensitive to the size of the blocks being processed - there's very little difference between the time taken to process the array in blocks of 1GB, 2GB or 4GB. I conclude that whatever caching  arrays natively implement, it seems to be very suboptimal for computing dot products.It's still a bit of a pain to have to manually implement this caching strategy, since my code will probably have to run on machines with different amounts of physical memory, and potentially different operating systems. For that reason I'm still interested in whether there are ways to control the caching behaviour of memory-mapped arrays in order to improve the performance of .I noticed some odd memory handling behaviour as I was running the benchmarks - when I called  on the whole of  I never saw the resident set size of my Python process exceed about 3.8GB, even though I have about 7.5GB of RAM free. This leads me to suspect that there is some limit imposed on the amount of physical memory an  array is allowed to occupy - I had previously assumed that it would use whatever RAM the OS allows it to grab. In my case it might be very beneficial to be able to increase this limit.Does anyone have any further insight into the caching behaviour of  arrays that would help to explain this?I don't think numpy optimizes dot product for memmap arrays, if you look at the code for matrix multiply, which I got , you'll see that the function  (as currently implemented) computes the values of the result matrix in c memory order:In the above code,  is the return matrix,  is the 1d dot product function and  and  are iterators over the input matrices.That being said, it looks like your code might already be doing the right thing. In this case the optimal performance is actually much better than O(n^3/sprt(M)), you can limit your IO to only reading each item of A once from disk, or O(n). Memmap arrays naturally have to do some caching behind the scene and inner loop operates on , so if A is in C-order and the memmap cache is big enough, your code might already be working. You can enforce caching of rows of A explicitly by doing something like:I recomend you to use  instead of numpy.memmap. Also read their presentations about compression, it sounds strange to me but seems that sequence .Also use np.dot with MKL. And I don't know how numexpr() can be used for matrix multiplication, but for example for calculating euclidean norm it's the fastest way(comparing with numpy).Try to benchmark this sample code:The problem that I don't know how to tune chunk size and compression rate to current machine, so I think performance can be dependent on parameters.Also please note that all matrices in sample code are stored on disk, if some of them will be stored in RAM I think it will be faster.By the way I'm using x32 machine and with numpy.memmap I have some limitations on matrix size(I'm not sure but it seems that view size can be only ~2Gb) and PyTables have no limitations.
Python

I am having an issue deploying a flask app on apache2 using wsgi. I have posted the error logs and config files below. I have tried moving things around, renaming them, etc, but all give me an internal server error. Not sure why I'm getting the import error. Any input / suggestions are appreciated, thanks!Here is my apache error.logwsgi.pyapp.pyHere is the basics of the directory tree, to give you an idea.Here is the apache virtualhost fileThanks to  and  on irc.freenode.org at #pocoo, they were able to help me get this fixed. The problem was the PythonPath was not correct. We fixed this by using the following wsgi.pyI used your solution to get it working but it kept duplicating the path in sys.path (you can write it out to see if it happens to you) so I made a little modification:That way it's only included once
Python

I have some classes looking like this:Now, this fails because Sub1 and Sub3 are not defined when Base.subs is. But obviously I can't put the subclasses before Base either. Is there a way to forward-declare classes in Python? I want to work with  so the types in subs actually have to be the same as the later declared subclasses, it's not enough that they have the same name and other properties.One workaround is to do:   the subclasses have been defined, but I don't like having to split my class in that way.Edit: Added information about orderThis is a hybrid version of @Ignacio Vazquez-Abrams and @aaronasterling's answers which preserves the order of the subclasses in the list. Initially the subclass names are manually placed in the  list in the desired order. Then as each subclass is defined, a class decorator causes the corresponding string to be replaced with the actual subtype. It important to note that there's a perhaps subtle difference between my original answer above and the update which follows below -- namely which is that the while the former will work with  class name that is registered with , whether  or not its a subclass of . I'm pointing this out for two reasons. First because in your comments you said that  was a \"bunch of classes in a list, some of which might be its subclasses\", and more importantly because that is  the case with the code in my update, which only works for  subclasses since they are effectively \"registered\" automatically via the metaclass -- but leave anything other in the list alone.\nExactly the same thing can also be done using a metaclass -- which has the advantage that it eliminates the need to explicitly decorate each subclass as shown in the accepted answer above and instead makes it happen automagically. Note that even though the metaclass's  is called for the creation of every subclass, it only updates the  list if that subclass's name appears in it -- so the initial Base class definition of the contents of  still controls what gets put in it and in what order.Write a decorator that adds it to the registry in . Because of the added requirement of order I completely reworked my answer. I also make use of a class decorator, which was used here first by @Ignacio Vazquez-Abrams.  code now tested and some stupidity slightly correctedI'm pretty sure this should work for you. Just assign the depended class attribute afterwards.\nThis is also a lot less complicated.There is no way to directly declare forward-references in Python, but there are several workarounds, a few of which are reasonable: Add the subclasses manually after they are defined.Example: Create  with  values, and use a  to substitute the actual subclasses (this can be a class method on Base or a function -- I'm showing the function version, although I would probably use the method version).Example:) Create  with  values, and have the method that uses  do the substitution.Example:I would use option  myself, as it keeps the functionality and the data all in one place.  The only thing you have to do is keep  up to date (and write the appropriate subclasses, of course).I would just define the subclasses as strings and have the inevitable decorator replace the strings with the classes that they name. I would also define the decorator on a metaclass because I think that that's more in line with the objective: we're modifying class behavior and just like you modify object behavior by modifying its class, you modify class behavior by modifying its metaclass.This outputs:
Python

My production system occasionally exhibits a memory leak I have not been able to reproduce in a development environment.  I've used a  (specifically, Heapy) with some success in the development environment, but it can't help me with things I can't reproduce, and I'm reluctant to instrument our production system with Heapy because it takes a while to do its thing and its threaded remote interface does not work well in our server.What I think I want is a way to dump a snapshot of the production Python process (or at least gc.get_objects), and then analyze it offline to see where it is using memory.    Once I have one, how do I do something useful with it?Using Python's  garbage collector interface and  it's possible to dump all the python objects and their sizes. Here's the code I'm using in production to troubleshoot a memory leak:Note that I'm only saving data from objects that have a  attribute because those are the only objects I care about. It should be possible to save the complete list of objects, but you will need to take care choosing other attributes. Also, I found that getting the referrers for each object was extremely slow so I opted to save only the referents. Anyway, after the crash, the resulting pickled data can be read back like this:Could you record the traffic (via a log) on your production site, then re-play it on your development server instrumented with a python memory debugger? (I recommend dozer: ), then clone an instance of the program on a sufficiently similar box using .  There are  to help with debugging python programs within gdb, but if you can get your program to concurrently , you could just continue the program's execution, and query it with python.I have never had to do this, so I'm not 100% sure it'll work, but perhaps the pointers will be helpful. looks promising:I don't know how to dump an entire python interpreter state and restore it. It would be useful, I'll keep my eye on this answer in case anyone else has ideas.If you have an idea where the memory is leaking, you can add checks the refcounts of your objects. For example:You could also check for reference counts higher than some number that is reasonable for your app. To take it further, you could modify the python interpreter to do these kinds of check by replacing the  and  macros with your own. This might be a bit dangerous in a production app, though.Here is an essay with more info on debugging these sorts of things. It's more geared for plugin authors but most of it applies.The  has some functions that might be useful, like listing all objects the garbage collector found to be unreachable but cannot free, or a list of all objects being tracked.If you have a suspicion which objects might leak, the  module could be handy to find out if/when objects are collected.
Python

For now, when I try to save the m2m data, it just dies and says I should use the ClientGroupe Manager...so what's missing?:and here's the ClientForm code::\nhere's the error message:If you use the save method right now, Django will try to save using the manager (which Django doesn't allow).  Unfortunately, the behavior you want is a little bit trickier than what  does by default.  What you need to do is create a .First of all, you will need to change the options of your  so that it doesn't display the  attribute.Next, you must change the view to display the formset:And obviously, you must also tweak your template to render the formset.If you need any other advice on formsets, see these articles:\nYou probably need to remove the ManyToMany field from your Client model, or else carefully exclude it from your form.  Unfortunately, the default widget for the ManyToMany field cannot populate the ClientGroupe Model properly (even if the missing field, dt, had been set to autonow=True).  This is something you'll either need to break out into another form, or handle in your view.When you save your form, you save Client object. Now if you want to assign client to the group you should do this:where client_instance and groupe_instance your client and groupe objets.I'm providing an alternative solution due to issues I encountered with forms_valid not being called:I've copied the logic from djangos forms/models.py, my field Genres is a manytomany with an intermediary table - I exclude it from the save_instance and then save it separately.
Python

I successfully built/installed NumPy on my mac os x for python 2.7.3.\nNow I would like to build/install scipy as well. I downloaded it from git hub.\nWent into the directory. Ran python setup.py build and it seemed to be working until it came across this error:I thought that I had Fortran installed for NumPy...guess not? How would I download it?Your problem is that you need to install a Fortran compiler to build .Also, if you already have a  that's built with Fortran support disabled, you may have to replace it. Some of Apple's pre-installed Python versions have such a  build pre-installed.The easiest way to get Fortran is with . As  say, you need to install Xcode and its Command Line Tools first. (The way to install the Command Line Tools changes with almost each major version of Xcode, so see the linked docs for an up-to-date explanation.) Then install Homebrew. The installation URL has changed a few times, so see the Homebrew home page or installation instructions(), but it will be something like:Then:(Note that until some time in 2014,  was a separate recipe from , so the command was . But if you try that now, you'll get an error saying \"GNU Fortran is now provided as part of GCC, and can be installed with: \".)You really want to use  to install , so if you don't have that, get it first. Apple's pre-installed Python, at least in 10.7 and 10.8, includes  but not , so the easiest way to do that is:However, you may want to consider using a  instead of a global install (in which case you also want to remove the  on the following commands).Now that you've got  and , all you have to do is this:Caveats:If you're using a non-Apple build of Python 2.7, and you want to avoid the PATH problems, you have to do two things:First, do not, ever, install any Python packages that include scripts or binaries (including  itself) in more than one Python. For example, if you install  for both Apple 2.7 and Homebrew 2.7, both will attempt to create scripts named  and . If you're lucky, one install will fail. Otherwise, they'll both succeed, one will end up overwriting the other, and you will have no way of running the overwritten version.Second, make sure the path to the alternate Python's scripts and binaries comes before Apple's in the PATH. Depending on which alternate Python you've installed and which instructions you followed, this could be:Whatever the path is, you need to edit your PATH variable.If you want to affect GUI apps (and LaunchAgents, etc.), there is apparently no longer a supported way to do this, but the deprecated  does seem to still work in Lion. It's also what the Homebrew  and  suggest.If you only care about command-line sessions (both Terminal.app and remote ssh), you can instead just do the standard Unix thing of editing the appropriate profile file. Which profile file is appropriate depends on what you want to affect. (All users or just one user? bash or any shell? And so on.) If you don't know which one you want, you really should do some research. If you don't want to bother learning, just do  and then don't complain if it wasn't what you wanted.Either way, you need to make sure that the appropriate path comes before  in the PATH. So, for example, you could add the following to :(You will of course need to either create a new Terminal shell, or source the script, before it takes effect.)If you're using ,  will tell you if you got it right.It looks like your actual problem was just an intermittent download failure from Sourceforge:Homebrew should just recover automatically from this error if you try  again. So, that's the first thing to try.If that doesn't work, see if  finds any problems, then  to see where it's storing the partially-downloaded file so you can delete it manually and try again.If all else fails, you can force it to not use the bottle by using . Of course building from source takes a lot longer than installing a binary bottle, but it should give the same result.As of 5/20/2014, if you're using brew, Fortran is installed as part of gcc.  There is no separate Fortran package required.  Here's what worked for me to install numpy:I don't think this problem is too complicated at all.1) Install pipcd /Library/Frameworks/Python.framework/Versions/\nln -s 2.7 Currentcd /usr/bin\nrm -f python\nln -s /Library/Frameworks/Python.framework/Versions/Current/bin/python python2) download egg from \nsudo sh setuptools-0.6c11-py2.7.egg3) Simply download and install the gfotran from this link:\n4) After that, you need to type:\nsudo pip install -U scipy\nsudo pip install -U numpy\nsudo pip install -U matplotlibHopefully, you should have everything you want to have.I met the same problem, using following steps:\n1. brew install gfortran\n2. pip install scipy  then it's ok.I had  installed and the binary was . So, everytime I was trying to install SciPy the compiler couldn't be found because it was trying to use .What I did was create a symlink of  to .To find where you should create the symlink run:Then symlink it:i have homebree installed so I'm going to try: $brew install gfortran\nhopefully this worksFor OSX yosemite and possibly older osx releases too, you may want to download and install the fortran compiler before running . To download the latest fortran compiler, just go to the following link:I think your . I had Xcode: 6.4 and Os X 10.11.1 and was still getting the same error messages (could not locate gfortran, etc). I tried many things, including the thorough response by @abarnert, but the solution for me was upgraded Xcode (to 7.1.1).Here are detailed instructions for a clean install on OSX 10.7. If I were you, I'd go this route instead of trying to download and build the sources yourself.
Python

how would I stop a while loop after 5 minutes if it does not achieve what I want it to achieve.This code throws me in an endless loop.Try the following:You may also want to add a short sleep here so this loop is not hogging CPU (for example  at the beginning or end of the loop body).Try this module:  RegardsYou do not need to use the  loop in this case. There is a much simpler way to use the time condition directly:
Python

How would I parse the string  (one million) into it's integer value in Python?There's also a simple way to do this that should handle internationalization issues as well:I found though that I have to explicitly set the locale first otherwise it doesn't work for me and I end up with an ugly traceback instead:So if that happens to you:Replace the ',' with '' and then cast the whole thing to an integer.
Python

Am i able to overload the print function? and call the normal function? What i want to do is after a specific line i want print to call my print which will call the normal print and write a copy to file.Also i dont know how to overload print. I dont know how to do variable length arguments. i'll look it up soon but   just told me i cant overload print in 2.x which is what i am using.Overloading  is a design feature of python 3.0 to address your lack of ability to do so in python 2.x.However, you can override sys.stdout. (.) Just assign it to another file-like object that does what you want.Alternatively, you could just pipe your script through the the unix  command.  will print to both stdout and to output.txt, but this will capture all output.For those reviewing the previously dated answers, as of version release \"Python 2.6\" there is a new answer to the original poster's question.In Python 2.6 and up, you can disable the print statement in favor of the print function, and then override the print function with your own print function:Of course you'll need to consider that this print function is only module wide at this point. You could choose to override , but you'll need to save the original ; likely mucking with the  namespace.I came across the same problem.How about this:It worked like a charm for me. \nIt was taken from  I don't think you can overload print, but Python has a robust logging package that is highly customizable.Though you can't replace the  keyword (in Python 2.x  is a keyword), it's common practice to replace  to do something similar to  overriding; for example, with an instance of . This will capture all of the printed data in the  instance, after which you can manipulate it.In Python 2.x you can't, because print isn't a function, it's a statement. In Python 3 print is a function, so I suppose it could be overridden (haven't tried it, though).I answered the same question Essentially, simplest solution is to just redirect the output to stderr as follows, in the wsgi config file.just thought I'd add my idea... suited my purposes of being able to run sthg in Eclipse and then run from the (Windows) CLI without getting encoding exceptions with each print statement.\nWhatever you do don't make EncodingStdout a subclass of class file: the line \"self.encoding = encoding\" would then result in the encoding attribute being None!NB one thing I found out during a day grappling with this stuff is that the encoding exception gets raised BEFORE getting to \"print\" or \"write\": it is when the parameterised string (i.e. \"mondodod %s blah blah %s\" % ( \"blip\", \"blap\" )) is constructed by... what??? the \"framework\"?For a very simple example, as of Python3.4 (haven't tested with older versions) this works well for me (placed at top of module):Note, this only works if the string parameter is a str...  YMMV
Python

This is a slightly weird request but I am looking for a way to write a list to file and then read it back some other time.I have no way to remake the lists so that they are correctly formed/formatted as the example below shows.My lists have data like the following:If you don't need it to be human-readable/editable, the easiest solution is to just use .To write:To read:If you  need them to be human-readable, we need more information.If  is guaranteed to be a list of strings with no embedded newlines, just write them one per line:If they're Unicode strings rather than byte strings, you'll want to  them. (Or, worse, if they're byte strings, but not necessarily in the same encoding as your system default.)If they might have newlines, or non-printable characters, etc., you can use escaping or quoting. Python has a variety of different kinds of escaping built into the stdlib.Let's use  here to solve both of the above problems at once:You can also use the 3.x-style solution in 2.x, with either the  module or the  module:*As long as your file has consistent formatting (i.e. line-breaks), this is easy with just basic file IO and string operations:That will store your data file as a list of items, one per line. To then put it into a file, you would do the opposite:Hopefully that fits what you're looking for.
Python

I want to get a fixed length list from another list like:And I want to get a list like this: . In other words, if , i want to fill up list  with values from list  up to length of the list , somewhat similar to what  does.This is my code:But it shows error:What can i do?Why not just:Use itertools repeat.Why not just  Can't you just do:If you want to fill with mutable values, for example with s:Where  is the number of elements in the array.Populating without the  would cause every element to be !To be more explicit, this solution replaces the first elements of  with all of the elements of  regardless of the values in  or :This will also work with:If you do not want to the result to be longer than :Just another solution:I like some of the other solutions better.
Python

sqlautocode - has issues with many-to-many relationssqlsoup - doesn't support relationselixir - it's note auto-generateIs there something else I could try?In theory reflection in sqlalchemy should work for you.  In this case I'm using an mssql database with two tables which have a simple Many-to-one relation:\"Tests\" with fields:\"Users\" with fields:So the following should reflect the database:So this appears to work with table relations.  Although you still haven't given much detail to exactly what you are trying to do.Well I went through that, tried on Northwind database and it looks promising. Although, I had to add relationship field to be able to follow database relations. Let's consider that I don't know relations between tables at the moment of starting the application so I need is a way to generate automatically. You could use  to generate all the models from the database. However you need to take care of the foreign key manually.
Python

So, lets say I have 100,000 float arrays with 100 elements each.  I need the highest X number of values, BUT only if they are greater than Y.  Any element not matching this should be set to 0.   What would be the fastest way to do this in Python?  Order must be maintained.  Most of the elements are already set to 0.sample variables:expected result:This is a typical job for , which is very fast for these kinds of operations:Now, if you only need the highCountX largest elements, you can even \"forget\" the small elements (instead of setting them to 0 and sorting them) and only sort the list of large elements:Of course, sorting the whole array if you only need a few elements might not be optimal.  Depending on your needs, you might want to consider the standard  module.:)Using :Where  could be:The expression  can be written without  as follows:There's a special MaskedArray class in NumPy that does exactly that.  You can \"mask\" elements based on any precondition.  This better represent your need than assigning zeroes: numpy operations will ignore masked values when appropriate (for example, finding mean value).As an addded benefit, masked arrays are well supported in matplotlib visualisation library if you need this.The simplest way would be:In pieces, this selects all the elements greater than :This array only contains the number of elements greater than the threshold. Then, sorting it so the largest values are at the start:Then a list index takes the threshold for the top  elements:Finally, the original array is filled out using another list comprehension:There is a boundary condition where there are two or more equal elements that (in your example) are 3rd highest elements. The resulting array will contain that element more than once.There are other boundary conditions as well, such as if . Handling such conditions is left to the implementor.Settings elements below some threshold to zero is easy:(plus the occasional abs() if needed.)The requirement of the N highest numbers is a bit vague, however. What if there are e.g. N+1 equal numbers above the threshold? Which one to truncate?You could sort the array first, then set the threshold to the value of the Nth element:Note: this solution is optimized for readability not performance.You can use map and lambda, it should be fast enough.Use a .This works in time .deletemin works in heap  and insertion  or  depending on which heap type you use.Using a heap is a good idea, as egon says.  But you can use the  function to cut down on some effort:
Python

I need to convert (0, 128, 64) to something like this #008040. I'm not sure what to call the latter, making searching difficult. Use the format operator :Note that it won't check bounds...This uses the preferred method of string formatting, as . It also uses  and  to ensure that . added the clamp function as suggested below. From the title of the question and the context given, it should be obvious that this expects 3 ints in [0,255] and will always return a color when passed 3 such ints. However, from the comments, this may not be obvious to everyone, so let it be explicitly stated: orpython3 is slightly differentThis is an old question but for information, I developed a package with some utilities related to colors and colormaps and contains the rgb2hex function you were looking to convert triplet into hexa value (which can be found in many other packages, e.g. matplotlib). It's on pypiand thenValidity of the inputs is checked (values must be between 0 and 255).Hello i have created a full python program for it the following functions can convert rgb to hex and vice versa.You can see the full code and tutorial at the following link : 
Python

What is the simple basic explanation of what the return statement is, how to use it in Python?And what is the difference between it and the  statement?The  function writes, i.e., \"prints\", a string in the console. The  statement causes your function to exit and hand back a value to its caller. The point of functions in general is to take in inputs and return something. The  statement is used when a function is ready to return a value to its caller. For example, here's a function utilizing both  and :Now you can run code that calls foo, like so:If you run this as a script (e.g. a  file) as opposed to in the Python interpreter, you will get the following output:I hope this makes it clearer. The interpreter writes return values to the console so I can see why somebody could be confused.Here's another example from the interpreter that demonstrates that:You can see that when  is called from , 1 isn't written to the console. Instead it is used to calculate the value returned from .   is a function that causes a side effect (it writes a string in the console), but execution resumes with the next statement.  causes the function to stop executing and hand a value back to whatever called it.I think the  is your best reference here and In short:  or  to the caller of the function while  Think of the print statement as causing a , it makes your function write some text out to the user, but it can't be I'll attempt to explain this better with some examples, and a couple definitions from Wikipedia.Here is the definition of a function from WikipediaThink about that for a second. What does it mean when you say the function has a value?What it means is that you can actually substitute the value of a function with a normal value! (Assuming the two values are the same type of value)Why would you want that you ask?What about other functions that may accept the same type of value as an ?There is a fancy mathematical term for functions that only depend on their inputs to produce their outputs: Referential Transparency. Again, a definition from Wikipedia.It might be a bit hard to grasp what this means if you're just new to programming, but I think you will get it after some experimentation.\nIn general though, you can do things like print in a function, and you can also have a return statement at the end.Just remember that when you use return you are basically saying \"A call to this function is the same as writing the value that gets returned\"Python will actually insert a return value for you if you decline to put in your own, it's called \"None\", and it's a special type that simply means nothing, or null. means, \"output this value from this function\". means, \"send this value to (generally) stdout\"In the Python REPL, a function return will be output to the screen by default (this isn't quite the same as print).This is an example of print:\n\n\n\n\nThis is an example of return:\n\n\n\n\n\n\n\n\n\nIn python, we start defining a function with \"def\" and end the function with \"return\".A function of variable x is denoted as f(x). What this function does? Suppose, this function adds 2 to x. So, f(x)=x+2Now, the code of this function will be:After defining the function, you can use that for any variable and get result. Such as:We could just write the code slightly differently, such as:That would also give \"4\".Now, we can even use this code:That would also give 4. See, that the \"x\" beside return actually means (x+2), not x of \"A_function(x)\".I guess from this simple example, you would understand the meaning of return command.Just to add to @Nathan Hughes's excellent answer:The  statement can be used as a kind of control flow. By putting one (or more)  statements in the middle of a function, we can say: \"stop executing this function. We've either got what we wanted or something's gone wrong!\"Here's an example:See the  of the Python Guide for more advice on this way of using .Difference between \"return\" and \"print\" can also be found in the following example:RETURN:The above code will give correct results for all inputs.PRINT:NOTE: This will fail for many test cases.ERROR:        Here is my understanding. (hope it will help someone and it's correct). So this simple piece of code counts number of occurrences of something. The placement of return is significant. It tells your program where do you need the value. So when you print, you send output to the screen. When you return you tell the value to go somewhere. In this case you can see that count = 0 is indented with return - we want the value (count + 1) to replace 0. \nIf you try to follow logic of the code when you indent the return command further the output will always be 1, because we would never tell the initial count to change.\nI hope I got it right. \nOh, and return is always inside a function. should be used for  functions/methods or you want to use the returned value for later applications in your algorithm. should be used when you want to display a meaningful and desired output to the user and you don't want to clutter the screen with intermediate results that the user is not interested in, although they are helpful for debugging your code.The following code shows how to use  and  properly:This explanation is true for all of the programming languages not just . is part of a function definition, while  outputs text to the standard output (usually the console).A function is a procedure accepting parameters and returning a value.  is how the latter, while the former is done with .Example:Best thing about  function is you can return a value from function but you can do same with  so whats the difference ?\nBasically  not about just returning it gives output in object form so that we can save that return value from function to any variable but we can't do with  because its same like  in .We are now doing our own math functions for  and . The important thing to notice is the last line where we say return  (in ). What this does is the following:
Python

I'm writing an application in Python (2.6) that requires me to use a dictionary as a data store.I am curious as to whether or not it is more memory efficient to have one large dictionary, or to break that down into many (much) smaller dictionaries, then have an \"index\" dictionary that contains a reference to all the smaller dictionaries.I know there is a lot of overhead in general with lists and dictionaries. I read somewhere that python internally allocates enough space that the dictionary/list # of items to the power of 2.I'm new enough to python that I'm not sure if there are other unexpected internal complexities/suprises like that, that is not apparent to the average user that I should take into consideration.One of the difficulties is knowing how the power of 2 system counts \"items\"? Is each key:pair counted as 1 item? That's seems important to know because if you have a 100 item monolithic dictionary then space 100^2 items would be allocated. If you have 100 single item dictionaries (1 key:pair) then each dictionary would only be allocation 1^2 (aka no extra allocation)?Any clearly laid out information would be very helpful!Three suggestions:If you're using Python, you really shouldn't be worrying about this sort of thing in the first place.  Just build your data structure the way it best suits  needs, not the computer's.This smacks of premature optimization, not performance improvement.  Profile your code if something is actually bottlenecking, but until then, just let Python do what it does and focus on the actual programming task, and not the underlying mechanics.\"Simple\" is generally better than \"clever\", especially if you have no tested reason to go beyond \"simple\". And anyway \"Memory efficient\" is an ambiguous term, and there are tradeoffs, when you consider persisting, serializing, cacheing, swapping, and a whole bunch of other stuff that someone else has already thought through so that in most cases you don't need to.Think \"Simplest way to handle it properly\" optimize much later.Premature optimization bla bla, don't do it bla bla.I think you're mistaken about the  of two extra allocation does.  I think its just a  of two.  x*2, not x^2.I've seen this question a few times on various python mailing lists.With regards to memory, here's a paraphrased version of one such discussion (the post in question wanted to store hundreds of millions integers):So, the fewer objects you have, the less memory you're going to be using, and the fewer lookups you're going to do (since you'll have to lookup in the index, then a second lookup in the actual value).Like others, said, profile to see your bottlenecks.  Keeping an membership set() and value dict() might be faster, but you'll be using more memory.I'd also suggest reposting this to a python specific list, such as comp.lang.python, which is full of much more knowledgeable people than myself who would give you all sorts of useful information.If your dictionary is so big that it does not fit into memory, you might want to have a look at , a very mature object database for Python.The 'root' of the db has the same interface as a dictionary, and you don't need to load the whole data structure into memory at once e.g. you can iterate over only a portion of the structure by providing start and end keys.It also provides transactions and versioning.Honestly, you won't be able to tell the difference either way, in terms of either performance or memory usage.  Unless you're dealing with tens of millions of items or more, the performance or memory impact is just noise.From the way you worded your second sentence, it sounds like the one big dictionary is your first inclination, and matches more closely with the problem you're trying to solve.  If that's true, go with that.  What you'll find about Python is that the solutions that everyone considers 'right' nearly always turn out to be those that are as clear and simple as possible.Often times, dictionaries of dictionaries are useful for other than performance reasons.  ie, they allow you to store context information about the data without having extra fields on the objects themselves, and make querying subsets of the data faster.In terms of memory usage, it would stand to reason that one large dictionary will use less ram than multiple smaller ones.  Remember, if you're nesting dictionaries, each additional layer of nesting will roughly double the number of dictionaries you need to allocate.In terms of query speed, multiple dicts will take longer due to the increased number of lookups required.So I think the only way to answer this question is for you to profile your own code.  However, my suggestion is to use the method that makes your code the cleanest and easiest to maintain.  Of all the features of Python, dictionaries are probably the most heavily tweaked for optimal performance.
Python

I am trying to print out Python path folders using this:The output is like this:How do I print them into separate lines so I can parse them properly?It should be like this:(The outer parentheses are included for Python 3 compatibility and are usually omitted in Python 2.)Use the print function (Python 3.x) or import it (Python 2.6+):Another good option for handling this kind of option is the  module, which (among other things) pretty prints long lists with one element per line:Sven Marnach's answer is pretty much it, but has one generality issue... It will fail if the list being printed doesn't just contain strings.So, the more general answer to \"How to print out a list with elements separated by newlines\"...Then again, the print function approach JBernardo points out is superior.  If you can, using the print function instead of the print statement is almost always a good idea.
Python

I have a Spark DataFrame (using PySpark 1.5.1) and would like to add a new column.I've tried the following without any success:Also got an error using this:So how do I add a new column (based on Python vector) to an existing DataFrame with PySpark?You cannot add an arbitrary column to a  in Spark. New columns can be created only by using literals (other literal types are described in )transforming an existing column:included using :or generated with function / udf:Performance-wise, built-in functions (), which map to Catalyst expression, are usually preferred over Python user defined functions.If you want to add content of an arbitrary RDD as a column you can To add a column using a UDF:For You can define a new  when adding a :
Python

[Using Python 3.2]\nI was wondering if it was possible to remove items you have printed in python, not from the python gui but from the command propt.\ne.g.so it printsBut, My problem is I want this all on one line, and for it it remove it self when somthing else comes along.  so instead of going, \"loading\", \"loading.\", \"loa.... I want it to got \"Loading.\", then it removes what is on the line and replaces it with \"Loading..\" and then removes \"Loading..\" and replaces it (on the same line) with \"Loading...\".  Its kinda hard to discribe.p.s\nI have tried to use the Backspace charactor but it doesnt seem to work (\"\\b\")ThanksJust use CR to go to beginning of the line.One way is to use :Also sometimes useful (for example if you print something shorter than before):
Python

I am playing in Python a bit again, and I found a neat book with examples. One of the examples is to plot some data. I have a .txt file with two columns and I have the data. I plotted the data just fine, but in the exercise it says: Modify your program further to calculate and plot the running average of the data, defined by:where  in this case (and the  is the second column in the data file). Have the program plot both the original data and the running average on the same graph.So far I have this:So how do I calculate the sum? In Mathematica it's simple since it's symbolic manipulation (Sum[i, {i,0,10}] for example), but how to calculate sum in python which takes every ten points in the data and averages it, and does so until the end of points?I looked at the book, but found nothing that would explain this :\\heltonbiker's code did the trick ^^ :DAnd I got this: Thank you very much ^^ :) One common way to apply a moving/sliding average (or any other sliding window function) to a signal is by using .Here, interval is your  array, and  is the number of samples to consider. The window will be centered on each sample, so it takes samples before and after the current sample in order to calculate the average. Your code would become:Hope this helps!A moving average is a convolution, and numpy will be faster than most pure python operations. This will give you the 10 point moving average. I would also  suggest using the great pandas package if you are working with timeseries data. There are some nice . As  is pretty slow, those who need a fast performing solution might prefer an easier to understand  approach. Here is the code:where  contains your data, and  will contain moving averages of  length.On average,  is about 30-40 times faster than .This isn't the most efficient approach but it will give your answer and I'm unclear if your window is 5 points or 10. If its 10, replace each 5 with 10 and the 4 with 9.There is a problem with the accepted answer. I think we need to use  instead of  here   -  .As an Example try out the MA of this data-set =  - the result should be , but having \"same\" gives us an incorrect output of Rusty code to try this out -:Try this with valid & same and see whether the math makes sense. See also -: I think something like:But I always have to double check the indices are doing what I expect. The range you want is (0, 5, 10, ...) and data[0:6] will give you data[0]...data[5]ETA: oops, and you want ave rather than sum, of course. So actually using your code and the formula:My Moving Average function, without numpy function:
Python

I need to make an export like this in Python :I've tried to do :But when I list export, \"MY_DATA\" not appear :How I can do an export with Python without saving \"my_export\" into a file ?You actually want to do is a command that you give directly to the shell (e.g. ), to tell it to add or modify one of its environment variables. You can't change your shell's environment from a child process (such as Python), it's just not possible.Here's what's happening with you try ...When the bottom-most  subprocess finishes running your  command, then it's discarded, along with the environment that you have just changed.Not that simple:But:Another way to do this, if you're in a hurry and don't mind the hacky-aftertaste, is to execute the output of the python script in your bash environment and print out the commands to execute setting the environment in python. Not ideal but it can get the job done in a pinch. It's not very portable across shells, so YMMV.(you can also enclose the statement in backticks in some shells ``)You could try os.environ[\"MY_DATA\"] instead.os.system ('/home/user1/exportPath.ksh')exportPath.ksh:
Python

I have a pandas dataframe and I wish to divide it to 3 separate sets. I know that using  from , one can divide the data in two sets (train and test). However, I couldn't find any solution about splitting the data into three sets. Preferably, I'd like to have the indices of the original data. I know that a workaround would be to use  two times and somehow adjust the indices. But is there a more standard / built-in way to split the data into 3 sets instead of 2?Numpy solution (thanks to  for the randomizing hint) - we will split our data set into the following parts: (60% - train set, 20% - validation set, 20% - test set):PS [int(.6*len(df)), int(.8*len(df))] - is an  array for Here is a small demo for  usage - let's split 20-elements array into the following parts: 90%, 10%, 10%:Function was written to handle seeding of randomized set creation.  You should not rely on set splitting that doesn't randomize the sets.However, one approach to dividing the dataset into , ,  with , ,  would be to use the  method twice.
Python

From :\"A file name like exercise_1.py is better than the name execise-1.py. We can run both programs equally well from the command line, but the name with the hyphen limits our ability to write larger and more sophisticated programs.\"Why?The issue here is that importing files with dashes in their name doesn't work since dashes are minus signs in python. So, if you had your own module you wanted to import, it couldn't have a dash in its name:Larger programs tend to be logically separated into many different modules, hence the quoteFrom that very document (p.368, Section 30.2 'Module Definition'):
Python

I've been using string.join() method in python 2 but it seems like it has been removed in python 3. What is the equivalent method in python 3? string.join() method let me combine multiple strings together with a string in between every other string. For example, string.join((\"a\", \"b\", \"c\"), \".\") would result \"a.b.c\".  or .. So any string  has the method  works fine in Python 3, you just need to get the order of the arguments correctThere are method  for string objects: Visit ab cd efab.cd.ef
Python

I have a program that writes a list to a file. \nThe list is a list of pipe delimited lines and the lines should be written to the file like this:BUT it wrote them line this ahhhh:This program wrote all the lines into like one line without any line breaks.. This hurts me a lot and I gotta figure-out how to reverse this but anyway, where is my program wrong here? I thought write lines should write lines down the file rather than just write everything to one line..This is actually a pretty common problem for newcomers to Python\u2014especially since, across the standard library and popular third-party libraries, some reading functions strip out newlines, but almost no writing functions (except the -related stuff) add them.So, there's a lot of Python code out there that does things like:orEither one is correct, and of course you could even write your own writelinesWithNewlines function that wraps it up\u2026But you should only do this if you can't avoid it.It's better if you can create/keep the newlines in the first place\u2014as in Greg Hewgill's suggestions:And it's even better if you can work at a higher level than raw lines of text, e.g., by using the  module in the standard library, as esuaro suggests. For example, right after defining , you might do this:Then, instead of this:You do this:And at the end, instead of this:You do this:Finally, your design is \"open a file, then build up a list of lines to add to the file, then write them all at once\". If you're going to open the file up top, why not just write the lines one by one? Whether you're using simple writes or a , it'll make your life simpler, and your code easier to read. (Sometimes there can be simplicity, efficiency, or correctness reasons to write a file all at once\u2014but once you've moved the  all the way to the opposite end of the program from the , you've pretty much lost any benefits of all-at-once.)The  states:So you'll need to add them yourself. For example:whenever you append a new item to . does not add line separators. You can alter the list of strings by using  to add a new  (line break) at the end of each string.As others have mentioned, and counter to what the method name would imply,  does not add line separators. This is a textbook case for a generator. Here is a contrived example:Benefits: adds newlines explicitly without modifying the input or output values or doing any messy string concatenation. And, critically, does not create any new data structures in memory. IO (writing to a file) is when that kind of thing tends to actually matter. Hope this helps someone!I kept ending up on this thread when looking to solve a similar problem when writing to files in R. So for those who have had the same issue, here is my solution:
Python

Is there an easy way to export a data frame (or even a part of it) to LaTeX?  DataFrames have a  method:You can simply write this to a tex file.By default latex will render this as:Just write to a textfile. It's no magic:
Python

say df is a pandas DataFrame.\nI would like to find all columns of numeric type.\nsomething like:You could use  method of DataFrame. It includes two parameters include and exclude. So isNumeric would look like:You can use the following command to filter only numeric columnsExampleAdapting , you could doHere,  shows whether every cell in the data frame is numeric, and  checks if all values in a column are True and returns a series of Booleans that can be used to index the desired columns.
Python

Is there a way to map a signal number (e.g. signal.SIGINT) to its respective name (i.e. \"SIGINT\")?I'd like to be able to print the name of a signal in the log when I receive it, however I cannot find a map from signal numbers to names in Python, i.e.:For some dictionary sig_names, so when the process receives SIGINT it prints:There is none, but if you don't mind a little hack, you can generate it like this:With the addition of the   in Python 3.5 this is now as easy as:The Python Standard Library By Example shows this function in the chapter on signals:You can then use it like this:I found this article when I was in the same situation and figured the handler is only handling one signal at a time, so I don't even need a whole dictionary, just the name of one signal:there's probably a notation that doesn't need the tuple(...)[0] bit, but I can't seem to figure it out.Well,  says at the bottom:So this should work:Building on :
Python

I have a simple image that I'm showing with imshow in matplotlib. I'd like to apply a custom colormap so that values between 0-5 are white, 5-10 are red (very simple colors), etc.  I've tried following this tutorial:  with the following code:But this ends up showing strange colors, and I only need 3-4 colors that I want to define.  How do I do this?You can use a  to specify the white and red as the only colors in the color map, and the bounds determine where the transition is from one color to the next:The resulting figure has only two colors:I proposed essentially the same thing for a somewhat different question: The solution is inspired by a . The example explains that the  must be one more than the number of colors used. The  is a normalization that maps a series of values to integers, which are then used to assign the corresponding colors. , in the example above, just defines the number of colors. for why  shows strange color, I think this link would be helpful.
Python

I have several  files that look like this:I would like to add a new column to all CSV files so that it would look like this:The script I have so far is this:(Python 3.2)But in the output, the script skips every line and the new column has only Berry in it: This should give you an idea of what to do:Edit, note in py3k you must use Thanks for accepting the answer. Here you have a bonus (your working script):Please note I'm surprised no one suggested Pandas. Although using a set of dependencies like Pandas might seem more heavy-handed than is necessary for such an easy task, it produces a very short script and Pandas is a great library for doing all sorts of CSV (and really all data types) data manipulation. Can't argue with 4 lines of code:Check out  for more information!Contents of :Maybe something like that is what you intended?Also, csv stands for comma separated values.  So, you kind of need commas to separate your values like this I think:I don't see where you're adding the new column, but try this:
Python

Is it possible to add some meta-information/metadata to a pandas DataFrame?For example, the instrument's name used to measure the data, the instrument responsible, etc.Sure, like most Python objects, you can attach new attributes to a :Note, however, that while you can attach attributes to a DataFrame, operations performed on the DataFrame (such as , ,  or  to name just a few) may return a new DataFrame  the metadata attached. Pandas does not yet have a robust method of  .Preserving the metadata  is possible. You can find an example of how to store metadata in an HDF5 file .Not really. Although you could add attributes containing metadata to the DataFrame class as @unutbu mentions, many DataFrame methods return a new DataFrame, so your meta data would be lost. If you need to manipulate your dataframe, then the best option would be to wrap your metadata and DataFrame in another class. See this discussion on GitHub: There is currently an open  to add a MetaDataFrame object, which would support metadata better. Just ran into this issue myself. As of pandas 0.13, DataFrames have a _metadata attribute on them that does persist through functions that return new DataFrames. Also seems to survive serialization just fine (I've only tried json, but I imagine hdf is covered as well).Coming pretty late to this, I thought this might be helpful if you need metadata to persist over I/O. There's a relatively new package called  that I've been using to accomplish this.It should let you do a quick read/write from HDF5 for a few common formats, one of them being a dataframe. So you can, for example, put a dataframe in a dictionary and include metadata as fields in the dictionary. E.g.:Another option would be to look into a project like , which is more complex in some ways, but I think it does let you use metadata and is pretty easy to convert to a DataFrame.As mentioned in other answers and comments,  is not a part of public API, so it's definitely not a good idea to use it in a production environment. But you still may want to use it in a research prototyping and replace it if it stops working. And right now it works with /, which is helpful. This is an example (which I couldn't find in other answers):Output:
Python

I have a pandas dataframe with the following columns;How do I combine data['Date'] & data['Time']  to get the following? Is there a way of doing it using ?It's worth mentioning that you may have been able to read this in  e.g. if you were using  using .Assuming these are just strings you could simply add them together (with a space), allowing you to apply :The accepted answer works for columns that are of datatype . For completeness: I come across this question when searching how to do this when the columns are of datatypes: date and time. I don't have enough reputation to comment on  so:I had to amend  for it to work:This might help others.Also, I have tested a different approach, using  instead of :which in the OP's case would be:I have timed both approaches for a relatively large dataset (>500.000 rows), and they both have similar runtimes, but using  is faster (59s for  vs 50s for ).
Python

Suppose I have code that maintains a parent/children structure. In such a structure I get circular references, where a child points to a parent and a parent points to a child. Should I worry about them? I'm using Python 2.5.I am concerned that they will not be garbage collected and the application will eventually consume all memory.\"Worry\" is misplaced, but if your program turns out to be slow, consume more memory than expected, or have strange inexplicable pauses, the cause is indeed likely to be in those garbage reference loops -- they need to be garbage collected by a different procedure than \"normal\" (acyclic) reference graphs, and that collection is occasional and may be slow if you have a lot of objects tied up in such loops (the cyclical-garbage collection is also inhibited if an object in the loop has a  special method).So, reference loops will not affect your program's correctness, but may affect its performance and/or footprint.If and when you want to remove unwanted loops of references, you can often use the  module in Python's standard library.If and when you want to exert more direct control (or perform debugging, see what exactly is happening) regarding cyclical garbage collection, use the  module in Python's standard library.Experimentally: you're fine:It consistently stays at using 3.6\u00a0MB of RAM.Python will detect the cycle and release the memory when there are no outside references.Circular references are a normal thing to do, so I don't see a reason to be worried about them.  Many tree algorithms require that each node have links to its children and its parent.  They're also required to implement something like a doubly linked list.I don't think you should worry. Try the following program and will you see that it won't consume all memory:There seems to be a issue with references to methods in lists in a variable. Here are two examples. The first one does not call . The second one with weakref is ok for . However, in this later case the problem is that you cannot weakly reference methods: 
Python

Say I have a python file in directory  like this:Under directory  I have a few folders I want to access but if file.py is executed from anywhere else rather than from folder  the relative path won't work for me. Also folder  could be located anywhere but always with the a set of sub folders so absolute path will not work.First, is there any function to get the absolute path in relation to the source files location?If not, any ideas how to sort this out? Grab the command line used and add the CWD together?My problem here is that this folder are being installed on 20 different machines and OS's and I want it to be as dynamic as possible with little configurations and \"rules\" where it has to be installed etc.Here is my solution which (a) gets the .py file rather than the .pyc file, and (b) sorts out symlinks.Working on Linux, the  files are often symlinked to another place, and the  files are generated in the directory next to the symlinked py files. To find the  path of the source file, here's part of a script that I use to find the source path.
Python

I have a system (developed in Python) that accepts  and i have to   them..Currently datetime string formats are : Now i want a  that can convert any of these datetime formats in appropriate datetime object...Otherwise, i have to go with parsing them individually. So please also provide method for parsing them individually (if there is no generic parser)..!!As @TimPietzcker suggested, the dateutil package is the way to go, it handles the first 3 formats correctly and automatically:The unixtime format it seems to hick up on, but luckily the standard  is up for the task:It is rather easy to make a function out of this that handles all 4 formats:You should look into the  package.
Python

I'm writing a Python script that needs to write some data to a temporary file, then create a subprocess running a C++ program that will read the temporary file.  I'm trying to use  for this, but according to the docs,And indeed, on Windows if I flush the temporary file after writing, but don't close it until I want it to go away, the subprocess isn't able to open it for reading.I'm working around this by creating the file with , closing it before spawning the subprocess, and then manually deleting it once I'm done:This seems inelegant.  Is there a better way to do this?  Perhaps a way to open up the permissions on the temporary file so the subprocess can get at it?At least if you open a temporary file using existing Python libraries, accessing it from multiple processes is not possible in case of Windows. According to  you can specify a 3rd parameter () shared mode flag  to  function which:So, you can write a Windows specific C routine to create a custom temporary file opener function, call it from Python and then you can make your sub-process access the file without any error. But I think you should stick with your existing approach as it is the most portable version and will work on any system and thus is the most elegant implementation.EDIT: Turns out it is possible to open & read the temporary file from multiple processes in Windows too. See Piotr Dobrogost's .Since nobody else appears to be interested in leaving this information out in the open... does expose a function, , which can trivialize this problem:I leave the implementation of the intermediate functions up to the reader, as one might wish to do things like use  to tighten up the security of the temporary file itself, or overwrite the file in-place before removing it. I don't particularly know what security restrictions one might have that are not easily planned for by perusing the source of .Anyway, yes, using  on Windows might be inelegant, and my solution here might also be inelegant, but you've already decided that Windows support is more important than elegant code, so you might as well go ahead and do something readable. to Richard Oudkerk and he gives an example of how to do this in Python 3.3+Because there's no  parameter in the built-in  in Python 2.x, we have to combine lower level  and  functions to achieve the same effect:You can always go low-level, though am not sure if it's clean enough for you:
Python

My work recently involves programmatically making videos. In python, the typical workflow looks something like this:This workflow creates an image for each frame in the video and saves it to disk. After all images have been saved, ffmpeg is called to construct a video from all of the images.Saving the images to disk (not the creation of the images in memory) consumes the majority of the cycles here, and does not appear to be necessary. Is there some way to perform the same function, but without saving the images to disk? So, ffmpeg would be called and the images would be constructed and fed to ffmpeg immediately after being constructed.Ok I got it working. thanks to LordNeckbeard suggestion to use image2pipe. I had to use jpg encoding instead of . The first script is essentially the same as your question's code except I implemented a simple image creation that just creates images going from black to red. I also added some code to time the execution.the results are interesting, I ran each script 3 times to compare performance:\n So it seems the parallel version is faster about 1.5 times faster.
Python

I have functions that contribute to small parts of a figure generation. I'm trying to use these functions to generate multiple figures? So something like this:If anyone could help, that'd be great!There are several ways to do this, and the simplest is to use the figure numbers.   The code below makes two figures, #0 and #1, each with two lines.  #0 has the points 1,2,3,4,5,6, and #2 has the points 10,20,30,40,50,60.For a more general answer to this question and to questions you may soon have, I would recommend the .The best way to show multiple figures is use matplotlib or pylab. (for windows)\nwith matplotlib you can prepare the figures and then when you finish the process with them you can show with the comand \"matplotlib.show()\" and all figures should be shown.(on linux) you don\u00b4t have problems adding changes to figures because the interactive mode is enable (on windows the interactive mode don't work OK). 
Python

Python has an identifier  that allows for storing the result of the  which makes it great for speeding up data exploration and introspection.Is there a similar command in R?Tis a faff to type, but .Last.value:
Python

Which is it better to use generally?Is there any advantage to writing:over:Or is it a direct alias? Is there any difference? Which is more pythonic/django-nic?There is a difference between the two: In the case of  the first argument can only be a .  which will  return a  can accept a , , or  as it's \"to\" argument. So it is a little more flexible in what it can \"redirect\" to. I also like how  is shorter. So I'd use  over . Both are fine to use though.From documentation - from the definition its the same. Thats what shortcuts are for. Both are one and the same.shortcuts generally are written one level above the actual API's. So  encapsulates  and  with the arg . There is no major downside to using  over . Hope this clears it.
Python

I have developed a python C-extension that receives data from python and compute some cpu intensive calculations.\nIt's possible to profile the C-extension?The problem here is that writing a sample test in C to be profiled would be challenging because the code rely on particular inputs and data structures (generated by python control code).Do you have any suggestions?After the comment by pygabriel I decided to upload a package to pypi that implements a profiler for python extensions using the cpu-profiler from google-perftools: I've found my way using . The trick was to wrap the functions StartProfiler and StopProfiler in python (throught cython in my case).To profile the C extension is sufficient to wrap the python code inside the StartProfiler and StopProfiler calls.Then to analyze for example you can export in callgrind format and see the result in kcachegrind:With , you can profile any program that was  and linked ( etc, in 's case).  If you're using a Python version not built with  (e.g., the Windows precompiled version the PSF distributes), you'll need to research what equivalent tools exist for that platform and toolchain (in the Windows PSF case, maybe  can help).  There may be \"irrelevant\" data there (internal C functions in the Python runtime), and, if so, the percentages shown by  may not be applicable -- but the absolute numbers (of calls, and durations thereof) are still valid, and you can post-process 's output (e.g., with a little Python script;-) to exclude the irrelevant data and compute the percentages you want.
Python

I'm trying to create a super-simplistic Virtual In / Out Board using wx/Python.  I've got the following code in place for one of my requests to the server where I'll be storing the data:Nothing special going on there.  The problem I'm having is that, based on how I read the docs, this should perform a Post Request because I've provided the data parameter and that's not happening.  I have this code in the index for that url:And every time I run my Python App I get the 'No action specified' text printed to my console.  I'm going to try to implement it using the Request Objects as I've seen a few demos that include those, but I'm wondering if anyone can help me explain why I don't get a Post Request with this code.  Thanks!-- EDITED --This code does work and Posts to my web page properly:I am still unsure why the urllib2 library doesn't Post when I provide the data parameter - to me the docs indicate that it should.Using the path  without a trailing  doesn't fetch . Instead the server will issue a  redirect to the version with the trailing .Doing a 302 will typically cause clients to convert a POST to a GET request.
Python

Both list comprehensions and map-calculations should -- at least in theory -- be relatively easy to parallelize: each calculation inside a list-comprehension could be done independent of the calculation of all the other elements. For example in the expressioneach x*x-Calculation could (at least in theory) be done in parallel.My question is: Is there any Python-Module / Python-Implementation / Python Programming-Trick to parallelize a list-comprehension calculation (in order to use all 16 / 32 / ... cores or distribute the calculation over a Computer-Grid or over a Cloud)?As Ken said, no, it can't, but with 2.6's  module, it's pretty easy to parallelize computations.There are also examples in the  that shows how to do this using Managers, which should allow for distributed computations as well. Using the  and  functions from the new 3.2  package could help.It's also available as a 2.6+ .IMHO,  automatic parallisation of list comprehension would be impossible without additional information (such as those provided using directives in OpenMP), or limiting it to expressions that involve only built-in types/methods.Unless there is a guarantee that the processing done on each list item has no side effects, there is a possibility that the results will be invalid (or at least different) if done out of order.There is also the issue of task distribution. How should the problem space be decomposed? If the processing of each element forms a task (~ task farm), then when there are many elements each involving trivial calculation, the overheads of managing the tasks will swamps out the performance gains of parallelisation. One could also take the data decomposition approach where the problem space is divided equally among the available processes. The fact that list comprehension also works with generators makes this slightly tricky, however this is probably not a show stopper if the overheads of pre-iterating it is acceptable. Of course, there is also a possibility of generators with side-effects which can change the outcome if subsequent items are prematurely iterated. Very unlikely, but possible.A bigger concern would be load imbalance across processes. There is no guarantee that each element would take the same amount of time to process, so statically partitioned data may result in one process doing most of the work while the idle your time away. Breaking the list down to smaller chunks and handing them as each child process is available is a good compromise, however, a good selection of chunk size would be application dependent hence not doable without more information from the user.As mentioned in several other answers, there are many approaches and  to choose from depending on one requirements.Having used only MPI (in C) with no experience using Python for parallel processing, I am not in a position to vouch for any (although, upon a quick scan through,\n, ,  and  stand out).If a requirement is to stick as close as possible to list comprehension, then  seems to be the closest match. From the , distributing tasks across multiple instances can be as simple as:While that does something similar to ,  can use different backends for synchronising process and storing intermediate results (redis, filesystem, in-memory) which means the processes can span across nodes in a cluster.No, because list comprehension itself is a sort of a C-optimized macro. If you pull it out and parallelize it, then it's not a list comprehension, it's just a good old fashioned .But you can easily parallelize your example. Here's a good tutorial on using MapReduce with Python's parallelization library:For shared-memory parallelism, I recommend :Not within a list comprehension AFAIK.You could certainly do it with a traditional for loop and the multiprocessing/threading modules.There is a comprehensive list of parallel packages for Python here:I'm not sure if any handle the splitting of a list comprehension construct directly, but it should be trivial to formulate the same problem in a non-list comprehension way that can be easily forked to a number of different processors. I'm not familiar with cloud computing parallelization, but I've had some success with mpi4py on multi-core machines and over clusters. The biggest issue that you'll have to think about is whether the communication overhead is going to kill any gains you get from parallelizing the problem.  The following might also be of interest:
Python

I need to create a Python REST/JSON web service for an iOS app to interact with. There will be no front end on the web.What will be the fastest, most lightweight framework to use for this? Learning curve to implement also considered?From the research I've done Django-Tastypie or Djanjo-Piston look like the best options, with Tastypie winning because the codebase is being maintained actively?In general, I think you'll find  to be one of the easiest frameworks to set up, learn, and use. web2py makes it very easy to  (just add a .json extension), and it now includes new functionality to automatically create  to access database models. In particular, check out the  and  functionality.If you need any help, ask on the .At Pycon Australia, Richard Jones compared the most popular lightweight web frameworks.   came out on top.  Here is the .When it comes to lightweight,  is pretty up there.If I were you I would use  that is really convenient to do that kind of rapid prototyping of .\nCheck out this snippet from the home page:Take a look to  and its extension You might also want to check out . They are free to use right now, and will give you a nice  for you mobile apps. However, as @iksnar points out, you don't write anything in Python, or anything at all for the backend. If you need to have the backend running in Python on your own servers I am a big fan of TastyPie if you are using Django already and the Django ORM already. 
Python

I am trying to assign a new value to a tensorflow variable in python.But the output I get isSo the value has not changed. What am I missing?The statement  does not actually assign the value  to , but rather creates a  that you have to explicitly  to update the variable.* A call to  or  can be used to run the operation:(* In fact, it returns a , corresponding to the updated value of the variable, to make it easier to chain assignments.)First of all you can assign values to variables/constants just by feeding values into them the same way you do it with placeholders. So this is perfectly legal to do:Regarding your confusion with the  operator. In TF nothing is executed before you run it inside of the session. So you always have to do something like this:  and then inside of the session you run . Using assign as an example you will do something like this:There is an easier approach: 
Python

This is the code that's giving me trouble. If I comment out the lines with the Label, the Frame displays with the right width.  However, adding the Label seems to shrink the Frame down to the Label's size.  Is there a way to prevent that from happening? By default, tk frames , which is what you want 99% of the time. The term that describes this feature is \"geometry propagation\". There is a  to turn geometry propagation on or off.Since you are using pack, the syntax would be:or maybe , depending on which widget(s) you actually want to affect.That being said, the vast majority of the time you should let tkinter compute the size. When you turn geometry propagation off your GUI won't respond well to changes in resolution, changes in fonts, etc. tkinter's geometry managers (,  and ) are remarkably powerful. Learn to take advantage of that power. 
Python

Is there any way to set the directory where you want to start a SimpleHTTPServer or BaseHTTPServer?If you're using  directly from command line, you can simply use shell features:
Python

Is it possible to define a recursive list comprehension in Python?Possibly a simplistic example, but something along the lines of:Is anything like this possible?No, there's no (documented, solid, stable, ...;-) way to refer to \"the current comprehension\".  You could just use a loop:of course this is very costly (O(N squared)), so you can optimize it with an auxiliary  (I'm assuming that keeping the order of items in  congruent to that of the items in , otherwise  would do you;-)...:this is enormously faster for very long lists (O(N) instead of N squared).: in Python 2.5 or 2.6,  might actually work in the role you want for  (for a non-nested listcomp)... which is why I qualified my statement by clarifying there's no  way to access \"the list being built up\" -- that peculiar, undocumented \"name\"  (deliberately chosen not to be a valid identifier;-) is the apex of \"implementation artifacts\" and any code relying on it deserves to be put out of its misery;-).Actually you can! This example with an explanation hopefully will illustrate how. define recursive example to get a number only when it is 5 or more and if it isn't, increment it and call the 'check' function again. Repeat this process until it reaches 5 at which point return 5.result:essentially the two anonymous functions interact in this way:make g,f the 'same' function except that in one or both add a clause where the parameter is modified so as to cause the terminal condition to be reached and then go\nf(g,x) in this way g becomes a copy of f making it like:You need to do this because you can't access the the anonymous function itself upon being executed. i.e  so in this example let A = the first function and B the second. We call A passing B as f and i as v. Now as B is essentially a copy of A and it's a parameter that has been passed you can now call B which is like calling A. This generates the factorials in a listno. it won't work, there is no  to refer to while list comprehension is being executed.And the main reason of course is that list comprehensions where not designed for this use.Do this:or even this:Not sure if this is what you want, but you can write nested list comprehensions:From your code example, you seem to want to simply eliminate duplicates, which you can do with sets:No.But it looks like you are trying to make a list of the unique elements in nums.You could use a :Note that items in nums need to be hashable.You can also do the following. Which is a close as I can get to your original idea. But this is not as efficient as creating a .
Python

Consider the following code:This will raise . I expected it to raise  (need I explain why?). Why does the final  raise the original exception rather than (what I thought) was the last exception raised?On python2.6I guess, you are expecting the finally block to be tied with the \"try\" block where you raise the exception \"B\". The finally block is attached to the first \"try\" block.If you added an except block in the inner try block, then the finally block will raise exception B.Output:Another variation that explains whats happening hereOutput:If you see here, replacing the finally block with except does raise the exception B.(reposted from comments for clarity)
Python

How can I reverse the results of a ? That is, how can I obtain a quoted string that would , given a  of strings I wish quoted?I've located a Python bug, and made corresponding feature requests .We now (3.3) have a  function.  It\u2019s none other that  moved and documented (code using  will still work).  See  for the whole discussion. is a private function that should not be used.  It could however be moved to  and made officially public.  See also .How about using ?. uses .  It's not an official public API, but it's mentioned in the  documentation and I think it's pretty safe to use.  It's more sophisticated than  (for better or worse).Both  and  are transformed by  to the same list:So I don't think it is possible to reverse  in all cases, but  might get you close:
Python

I have a Python application which opens a simple TCP socket to communicate with another Python application on a separate host. Sometimes the program will either error or I will directly kill it, and in either case the socket may be left open for some unknown time.The next time I go to run the program I get this error:Now the program always tries to use the same port, so it appears as though it is still open. I checked and am quite sure the program isn't running in the background and yet my address is still in use.SO, how can I manually (or otherwise) close a socket/address so that my program can immediately re-use it?Based on Mike's answer I checked out the  page and looked at SO_REUSEADDR:Assume your socket is named ... you need to set  on the server's socket before binding to an interface...  this will allow you to immediately restart a TCP server...You might want to try using Twisted for your networking.  Mike gave the correct low-level answer, , but he didn't mention that this isn't a very good option to set on Windows.  This is the sort of thing that Twisted takes care of for you automatically.  There are many, many other examples of this kind of boring low-level detail that you have to pay attention to when using the socket module directly but which you can forget about if you use a higher level library like Twisted.You are confusing sockets, connections, and ports. Sockets are endpoints of connections, which in turn are 5-tuples {protocol, local-ip, local-port, remote-ip, remote-port}. The killed program's socket has been closed by the OS, and ditto the connection. The only relic of the connection is the peer's socket and the corresponding port at the peer host. So what you should really be asking about is how to reuse the local  To which the answer is SO_REUSEADDR as per the other answers.
Python

I'm using  to manage asynchronous tasks. Occasionally, however, the celery process goes down which causes none of the tasks to get executed. I would like to be able to check the status of celery and make sure everything is working fine, and if I detect any problems display an error message to the user. From the Celery Worker documentation it looks like I might be able to use  or  for this, but ping feels hacky and it's not clear exactly how inspect is meant to be used (if inspect().registered() is empty?).Any guidance on this would be appreciated. Basically what I'm looking for is a method like so:EDIT: It doesn't even look like registered() is available on celery 2.3.3 (even though the 2.1 docs list it). Maybe ping is the right answer.EDIT: Ping also doesn't appear to do what I thought it would do, so still not sure the answer here.Here's the code I've been using.   returns a dict containing lots of details about the currently available workers, None if there are no workers running, or raises an  if it can't connect to the message broker.  I'm using RabbitMQ - it's possible that other messaging systems might behave slightly differently.  This worked in Celery 2.3.x and 2.4.x; I'm not sure how far back it goes.To check the same using command line in case celery is running as daemon,Source:\nThe following worked for me:
Python

I want output from execute Test_Pipe.py, I tried following code on Linux but it did not work. The line  was blocked, so no data prints out.You obviously can use subprocess.communicate but I think you are looking for real time input and output.readline was blocked because the process is probably waiting on your input. You can read character by character to overcome this like the following:Nadia's snippet does work but calling read with a 1 byte buffer is highly unrecommended. The better way to do this would be to set the stdout file descriptor to nonblocking using fcntland then using select to test if the data is readyShe was correct in that your problem must be different from what you posted as Caller.py and Test_Pipe.py do work as provided.To avoid the many problems that can always arise with buffering for tasks such as \"getting the subprocess's output to the main process in real time\", I always recommend using  for all non-Windows platform,  on Windows, instead of , when such tasks are desired. buffers its stdout by default so  in  don't see any output until the child's buffer is full (if the buffer size is 8KB then it takes around a minute to fill 's stdout buffer).To make the output unbuffered (line-buffered for text streams) you could pass  to the child Python script. It allows to read subprocess' output line by line in \"real-time\":See links in  on how to solve the block-buffering issue for non-Python child processes.
Python

I use the following method to break the double loop in Python.Is there a better way to break the double loop?Probably not what you are hoping for, but usually you would want to have a  after setting  to Another way is to use a generator expression to squash the  into a single loopYou may also consider using The recommended way in Python for breaking nested loops is... ExceptionMost times you can use a number of methods to make a single loop that does the same thing as a double loop.In your example, you can use  to replace your code snippet withThe other itertools functions are good for other patterns too.Refactor using functions so you can return when you find your \"bingo\".The proposal to allow explicit breaking out of nested loops has been rejected:\n
Python

I went through this example here:All my tasks are in files called tasks.py.After updating celery and adding the file from the example django is throwing the following error, no matter what I try:Is the problem possibly caused by the following?Because it goes through all tasks.py files which all have the following import.::The error happens, when I try to access a url that is not valid, like /foobar.:Adding the following lines to cloud/celery.py:gave me the file itself and not the celery module from the library. After renaming celery.py to celeryapp.py and adjusting the imports all errors were gone.Note:That leads to a change in starting the worker:For those running celery==3.1.2 and getting this error:Apply the patch mentioned here: With Django 1.7.5, Celery 3.1.17, and Python 2.7.6 I found that I was still getting these . But only when running tests under PyCharm 4.0.4.I found that a solution was  to rely on  as described in . Instead I renamed  to  and then changed the content of  to match: . No more multiple instances of files named  to cause import confusion seemed to be a simpler approach. Work for me ( some bug after deploy in server ):\nRemove all *.pyc files from project and restart him. :\nI have meet this problem just now, then I found the problem --- sys.path.\nMaybe you add some path to sys.path like me, I add below code in manage.py,so,  would search celery in  and  first, that's the problem.change  to   It would search in python's  and  first. Solved perfectly.Did you add the line:to the top of your  module?Read the breakdown of the example here:\nNote that older Django projects have the  script in the same directory as the project directory. That is, the structure looks like this:instead of this:In this case, you will just have to rename the  file to something different, like  as suggested in the accepted answer above.I got the same error. It turns out there was a problem with my Celery version. I upgraded to 3.1 and  is now deprecated for this version (). So I had to downgrade to the version 3.0.19 that was the previous stable version used for the project, and it works good so far. Anyway, if you don't want to downgrade, the replacement for celeryd in the version 3.1 is . Check here for more info: .Hope this helps! :)I got the same error.Seems that  DOES NOT work for Python 2.6.1, still not raising an error.Upgraded to Python 2.7.5 and it just worked.
Python

I want to add multiple values to a specific key. How can I do that?Make the value a list, e.g.UPDATE:There are a couple of ways to add values to key, and to create a list if one isn't already there. I'll show one such method in little steps.Results:Next, try:Results:The magic of  is that it initializes the value for that key  that key is not defined, otherwise it does nothing. Now, noting that  returns the key you can combine these into a single line:Results:You should look at the  methods, in particular the  method, and do some experiments to get comfortable with this.How aboutThis will result in:Is that what you were looking for?
Python

I wonder if it is bad manner to skip , when it is not needed.Example:In both cases, when condition is false, function will return with .Like you said,  is (almost) never needed.But you should consider that the  of your code is much clearer with an explicit . Remember: a piece of code also needs to be readable by human-beings, and being explicit usually helps.To expound on what others have said, I use a  if the function is supposed to return a value.  In Python, all functions return a value, but often we write functions that only ever return None, because their return value is ignored.  In some languages, these would be called procedures.So if a function is supposed to return a value, then I make sure all code paths have a return, and that the return has a value, even if it is None.If a function \"doesn't\" return a value, that is, if it is never called by someone using its return value, then it's ok to end without a return, and if I need to return early, I use the bare form, .Yes and No. \"return None\" because it returns None in only single negative condition. But if there are nested condition evaluation and multiple scenarios where a function could return None. I tend to include them as .[Editing: Based on comment below] as It is explicit and later, no one will be in doubt if the return meant returning None or was it an error as something was missing.Yes, if you do not return any value from a Python function, it returns None. So, whether to explicitly return None is a stylistic decision.Personally, I prefer to always return a value for clarity.or I do not believe in half defined function, but this False can be usefull in search type failure pruning.The more I think about it, the less I think the case you describe shows good practice. It forces the client to discriminate, so client code would almost always look like:You couldn't even write:since, if  is overwritten, b could evaluate to False, even if it's not None. It would be better to have a  instance (AKA ), e.g.:The point is: help the client (who might be yourself!) to keep  low. The fewer branches, the better. 
Python

I've just recently started using SQLAlchemy and am still having trouble wrapping my head around some of the concepts.Boiled down to the essential elements, I have two tables like this (this is through Flask-SQLAlchemy):How would I go about querying for a list of users and their newest post (excluding users with no posts). If I was using SQL, I would do:So I know exactly the \"desired\" SQL to get the effect I want, but no idea how to express it \"properly\" in SQLAlchemy.Edit: in case it's important, I'm on SQLAlchemy 0.6.6.This should work (different SQL, same result):the previous answer works, but also the exact sql you asked for is written much as the actual statement:I guess the \"concept\" that isn't necessarily apparent is that as_scalar() is currently needed to establish a subquery as a \"scalar\" (it should probably assume that from the context against ==).Edit:  Confirmed, that's buggy behavior, completed ticket #2190.  In the current tip or release 0.7.2, the as_scalar() is called automatically and the above query can be:
Python

For simplicity this is a stripped down version of what I want to do:I know how to do this in PHP:Any way to do this?If it's a global variable, then you can do:A note about the various \"eval\" solutions: you should be careful with eval, especially if the string you're evaluating comes from a potentially untrusted source -- otherwise, you might end up deleting the entire contents of your disk or something like that if you're given a malicious string.(If it's not global, then you'll need access to whatever namespace it's defined in.  If you don't have that, there's no way you'll be able to access it.)Edward Loper's answer only works if the variable is in the current module. To get a value in another module, you can use :tada!
Python

In Matplotlib, I would like to draw a  (or a cross), but the one provided in the  is too .Even as I increase its size, it doesn't get any thicker.For :\n\nThe  drawing the red plus sign are:If I add an extra parameter , the marker will only stretch. It will be as thin as before. Can I make it thick?You can use  (or ). You'll want to combine it with , otherwise you get thick but tiny markers. For example:Use  in connection with .
Python

I have Pythong2.6, psycopg2 and pgAdmin3 installed using Macports. My settings.py is:The error I get when I run python manage.py syncdb is:Please note, I am a complete beginner in this stuff. I am originally a PHP-guy and trying out Python for a small personal project. Do I need to \"turn on\" Postgres?Also, when I  sudo python manage.py runserver 8080\nI get this error:Please guide me. Any reply will be appreciated.Thanks,Wenbert!There seems to be a problem with your  installation \u2013 Python does not find it. This is a Python installation problem, not a Django issue.You can try to load it manually using the Python interpreter and see if it works:If you get an  exception, your installation is erroneous. To get a list of all directories Python looks for modules, use :You can also add custom directories to Python's module search path by modifying the  variable. Do this somewhere before the respective  statement(s):If you have  installed, simply install the missing extension by running:For the record I got the same error for a different reason:I had putinstead ofin Although you installed it, Python can apparently not find the module psycopg2. This is usually due to the module not being in Python's path. See if you can find a folder named psycopg2 in . If it's not there, did MacPorts tell you where it put psycopg2? If you can locate it, just move it to the  directory and you should be fine.I realized I didn't have psycopg2 installedWorked like a charmHere's the solution: \nYou've to install python-dev and libpq-dev libraries before executing \"easy_install psycopg2\"Yes Tim's answer works for me too.It works without prefix 'django.db.backends.' also. But remember to create database or schema you mentioned in settings.py:manually using your database client so when you run 'python manage.py syncdb' you don't get the same problem. I was stuck because i didn't create it manually. I got the same problem may be because I used buildout. I got the same error, but it was because I was using  when my virtualenv only had  and  executables (thus the system  was being used, which didn't have  installedTim's answer worked for me too. \nBy default, settings.py shows options like 'postgresql_psycopg2', 'mysql', etc, without a package name. Prefixing with 'django.db.backends.' worked for me (for postgresql_psycopg2, at least).For me, psycopg2 was indeed installed, but not into the virtualenv in which Django was running. These two steps fixed it:I had this issue recently after updating homebrew on OSX.\npsycopg2 was already listed in my virtualenv\nI just reinstalled psycopg2 and it worked againI'm on Windows and had installed psycopg2, but the 64 bit version. So my fix was to download the 32 bit one from  then in PowerShell with my virtual environment activated, my fix was: (The Windows Python 3.4 installer automatically installs easy_install and pip, and pip is the easiest way to remove the package, even if originally installed using easy_install.)THIS HAS HELPED ME:I just added PostgreSQL bin path to ENV and it was able to fine the needed dll:\nC:\\Program Files (x86)\\PostgreSQL\\9.4\\bin
Python

I am using py.test for unit testing my python program. I wish to debug my test code with the python debugger the normal way (by which i mean pdb.set_trace() in the code) but I can't make it work. Putting pdb.set_trace() in the code doesn't work (raises IOError: reading from stdin while output is captured). I have also tried running py.test with the option --pdb but that doesn't seem to do the trick if I want to explore what happens before my assertion. It breaks when an assertion fails, and moving on from that line means terminating the program.Does anyone know a way to get debugging, or is debugging and py.test just not meant to be together?it's real simple: put an  where you want to start debugging in your code and run your tests with:done :) Alternatively, if you are using pytest-2.0.1 or above, there also is the  helper which you can put anywhere in your test code.  Here are the .  It will take care to internally disable capturing before sending you to the pdb debugger command-line.I found that I can run py.test with capture disabled, then use pdb.set_trace() as usual.The easiest way is using the py.test mechanism to create breakpointOr if you want 's debugger as a one-liner, change your  into  I'm not familiar with py.test, put for unittest, you do the following. Maybe py.test is similar:In your test module (mytestmodule.py):Then run the test withYou will get an interactive pdb shell.Looking at the docs, it looks like py.test has a  command line option:
Python

How can I clear a queue. For example I have datas in a queue, but for some reason I don't need the existing data, and  just want to clear the queue.Is there any way? Will this work:\nI omitted the issue of thread safety for clarity and brevity, but @Dan D is quite correct, the following is better.You just can not clear the queue, because every put also add the unfinished_tasks member.\nThe join method depends on this value.\nAnd all_tasks_done needs to be notified also.or in decent way, use get and task_done pair to safely clear the tasks.or just create a new Queue and delete old one.This seems to do it pretty well for me. I welcome comments/additions in case I missed anything important.
Python

How do you convert a grayscale OpenCV image to black and white? I see a  has already been asked, but I'm using OpenCV 2.3, and the proposed solution no longer seems to work.I'm trying to convert a greyscale image to black and white, so that anything not absolutely black is white, and use this as a mask for , in order to ignore keypoints found on the edge of the black mask area.The following Python gets me almost there, but the threshold value sent to Threshold() doesn't appear to have any effect. If I set it to 0 or 16 or 128 or 255, the result is the same, with all pixels with a value > 128 becoming white, and everything else becoming black.What am I doing wrong?Step-by-step answer similar to the one you refer to, using the new cv2 Python bindings:which determines the threshold automatically from the image using Otsu's method, or if you already know the threshold you can use:Specifying  causes the threshold value to be ignored. From : This code reads frames from the camera and performs the binary threshold at the value 20.While converting a gray scale image to a binary image, we usually use  and set a threshold value manually. Sometimes to get a decent result we opt for .I have a small hack I came across while reading some blog posts.This is because  works for most of the images/data-set.You can also work out the same approach  by replacing  with the .Another approach would be to take an  number of standard deviations () from the mean, either on the positive or negative side; and set a threshold. So it could be one of the following: Before applying threshold it is advisable to enhance the contrast of the gray scale image  (See ).Simply you can write the following code snippet to convert an OpenCV image into a grey scale imageObserve that the image.jpg and the code must be saved in same folder. Note that:Pay attention, if you use  means every pixel greater than threshold becomes the maxValue (in your case 255), otherwise the value is 0. Obviously if your threshold is 0 everything becomes white (maxValue = 255) and if the value is 255 everything becomes black (i.e. 0).If you don't want to work out a threshold, you can use the Otsu's method. But this algorithm only works with 8bit images in the implementation of OpenCV. If your image is 8bit use the algorithm like this:No matter the value of threshold if you have a 8bit image.
Python

I work in Python and would like to read user input (from command line) in Unicode format, ie a Unicode equivalent of ?Also, I would like to test Unicode strings for equality and it looks like a standard  does not work.Thank you for your help ! returns strings as encoded by the OS or UI facilities. The difficulty is knowing which is that decoding. You might attempt the following:which should work correctly in most of the cases.We need more data about not working Unicode comparisons in order to help you. However, it might be a matter of normalization. Consider the following: and  are equivalent but not equal:So you might want to use the  method:If you give us more information, we might be able to help you more, though.It should work.  returns a byte string which you must decode using the correct encoding to get your  object. For example, the following works for me under Python 2.5 / Terminal.app / OSX:As for comparing unicode strings: can you post an example where the comparison doesn't work?I'm not really sure, which format you mean by \"Unicode format\", there are several. UTF-8? UTF-16? In any case you should be able to read a normal string with  and then decode it using the strings  method:If you have a different input encoding just use \"utf-16\" or whatever instead of \"utf-8\". Also see  for different kinds of encodings.Comparing then should work just fine with . If you have string literals containing special characters you should prefix them with \"u\" to mark them as unicode:And if you want to output these strings again, you probably want to encode them again in the desired encoding:In the general case, it's probably not possible to compare unicode strings.  The problem is that there are several ways to compose the same characters.  A simple example is accented roman characters.  Although there are codepoints for basically all of the commonly used accented characters, it is also correct to compose them from unaccented base letters and a non-spacing accent.  This issue is more significant in many non-roman alphabets.  
Python

I am looking for a Python3.0 version of \"py2exe\". I tried running 2to3 on the source for py2exe but the code remained broken.Any ideas?Did you check out ? It seems to create standalone executables from your Python scripts, including support for Python 3.0 and 3.1py2exe for Python 3.x is now released! .Have a look at the py2exe SourceForge project SVN repository at:The last I looked at it, it said the last update was August 2009. But keep an eye on that to see if there's any Python 3 work in-progress.I've also submitted two feature requests on the py2exe tracker. So far, no feedback on them:Here is the original bug report:\nHere is the comment mentioning the release:\nHere is the package on pypi:\nThe  and  programs serve completely different purposes, so I'm not sure what your ultimate goal is.If you want to build an executable from a working Python program, use the version of  that is suitable for whichever Python you are using (version 2 or version 3).If you want to convert an existing Python 2 program to Python 3, use  plus any additional editing as necessary. The Python 3 documentation describes .: I now understand that you might have been trying to run  against  itself to try to make a Python 3 compatible version. Unfortunately, this is definitely beyond the capabilities of . You will probably have to wait for the  to release a Python 3 compatible version.If you have easy setup installed, type  in a shell to install.
Python

I have a list which I shuffle with the Python built in shuffle function ()However, the Python reference states:Now, I wonder what this \"rather small len(x)\" means. 100, 1000, 10000,...TL;DR: It \"breaks\" on lists with over 2080 elements, but don't worry too much :)Complete answer:First of all, notice that \"shuffling\" a list can be understood (conceptually) as generating all possible permutations of the elements of the lists, and picking one of these permutations at random. Then, you must remember that all self-contained computerised random number generators are actually \"pseudo\" random. That is, they are not actually random, but rely on a series of factors to try and generate a number that is hard to be guessed in advanced, or purposefully reproduced. Among these factors is usually the previous generated number. So, in practice, if you use a random generator continuously a certain number of times,  you'll eventually start getting the same sequence all over again (this is the \"period\" that the documentation refers to).Finally, the docstring on Lib/random.py (the random module) says that \"The period [of the random number generator] is .\"So, given all that, if your list is such that there are  or more permutations, some of these will never be obtained by shuffling the list. You'd (again, conceptually) generate all permutations of the list, then generate a random number x, and pick the xth permutation. Next time, you generate another random number y, and pick the yth permutation. And so on. But, since there are more permutations than you'll get random numbers (because, at most after  generated numbers, you'll start getting the same ones again), you'll start picking the same permutations again.So, you see, it's not exactly a matter of how long your list is (though that does enter into the equation). Also,  is quite a long number. But, still, depending on your shuffling needs, you should bear all that in mind. On a simplistic case (and with a quick calculation), for a list without repeated elements, 2081 elements would yield  permutations, which is more than .I wrote that comment in the Python source originally, so maybe I can clarify ;-)When the comment was introduced, Python's Wichmann-Hill generator had a much shorter period, and we couldn't even generate all the permutations of a deck of cards.The period is astronomically larger now, and 2080 is correct for the current upper bound.  The docs could be beefed up to say more about that - but they'd get awfully tedious.There's a very simple explanation:  A PRNG of period P has P possible starting states.  The starting state wholly determines the permutation produced.  Therefore a PRNG of period P cannot generate more than P distinct permutations (and that's an absolute upper bound - it may not be achieved).  That's why comparing N! to P is the correct computation here.  And, indeed:What they mean is that permutations on n objects (noted n!) grows absurdly high very fast.Basically n! = n x n-1 x ... x 1; for example, 5! = 5 x 4 x 3 x 2 x 1 = 120 which means there are 120 possible ways of shuffling a 5-items list.On the same Python page documentation they give 2^19937-1 as the period, which is 4.something \u00d7 10^6001 or something. Based on the Wikipedia page on factorials, I guess 2000! should be around that. (Sorry, I didn't find the exact figure.)So basically there are so many possible permutations the shuffle will take from that there's probably no real reason to worry about those it won't.But if it really is an issue (pesky customer asking for a guarantee of randomness perhaps?), you could also offload the task to some third-party; see  for example.
Python

The new version of Pandas uses  to load Excel files:but what if I don't know the sheets that are available? For example, I am working with excel files that the following sheetsbut I don't know  a priori.Is there any way to get the list of sheets from an excel document in Pandas?You can still use the  class (and the  attribute):
Python

I'm working with boolean index in Pandas.\nThe question is why the statement:works fine whereasexists with error?Example:When you sayYou are implicitly asking Python to convert  and  to boolean values. NumPy arrays (of length greater than 1) and Pandas objects such as Series do not have a boolean value -- in other words, they raise when used as a boolean value. That's because its . Some users might assume they are True if they have non-zero length, like a Python list. Others might desire for it to be True only if  its elements are True. Others might want it to be True if  of its elements are True. Because there are so many conflicting expectations, the designers of NumPy and Pandas refuse to guess, and instead raise a ValueError.Instead, you must be explicit, by calling the ,  or  method to indicate which behavior you desire.In this case, however, it looks like you do not want boolean evaluation, you want  logical-and. That is what the  binary operator performs:returns a boolean array.
Python

Is it possible to import a Python module into a Jinja template so I can use its functions? For example, I have a  file that contains methods for formatting dates and times. In a Jinja macro, can I do something  the following? Because  is not a template, the code above gives me this error: ...but I was wondering if there was another way to achieve this. Within the template, no, you cannot import python code.The way to do this is to register the function as a jinja2 , like this:In your python file:In your template:Just pass the function into the template, like soand in the template, just call it like any other function,Functions are first-class citizens in python, so you can pass them around just like anything else. You could even pass in a whole module if you wanted.You can export all of the symbols available in a module by providing the modules __dict__ as a parameter to the jinja template render method. The following will make available functions and types of __builtin__, inspect and types module to the template.Within template, to use a function of the exported modules similar to the following:
Python

pretty sure there is a common idiom but couldn't find it with google..\nHere is what I want to do (in java):How is this done \"pythonic\" in python?Also would be great if I can get answer for this as well:Do you mean something like:Here is an example that checks if a list contains all zeros:Alternative you can also do:You can use 'all' and 'any' builtin functions in pythonhere somePredicate is a function\nand 'all' will check if bool() of that element is True
Python

I'm new to Scrapy and I'm looking for a way to run it from a Python script. I found 2 sources that explain this:I can't figure out where I should put my spider code and how to call it from the main function. Please help. This is the example code:Thank you.All other answers reference Scrapy v0.x. According to , Scrapy 1.0 demands:Though I haven't tried it I think the answer can be found within the . To quote directly from it:From what I gather this is a new development in the library which renders some of the earlier approaches online (such as that in the question) obsolete.In scrapy 0.19.x you should do this:Note these lines     Without it your spider won't use your settings and will not save the items.\nTook me a while to figure out why the example in documentation wasn't saving my items. I sent a pull request to fix the doc example.One more to do so is just call command directly from you scriptCopied this answer from my first answer in here:\nWhen there are multiple crawlers need to be run inside one python script, the reactor stop needs to be handled with caution as the reactor can only be stopped once and cannot be restarted. However, I found while doing my project that using is the easiest. This will save me from handling all sorts of signals especially when I have multiple spiders.If Performance is a concern, you can use multiprocessing to run your spiders in parallel, something like:Put this code to the path you can run  from command line. (Tested with Scrapy==0.24.6)
Python

I am trying to pip install mysql-python connector but it keeps erroring on me. Works fine on my mac and another windows machine but not this one. I have downloaded visual studio c++ and tried it as 32 bit and 64. Does anyone have an idea on how to get around this. for 64-bit windows well this worked for me:this is for python 3.x in window 7 i am not sure about other windows os versions
Python

Given a string \"VAR=value\" I want to split it (only) at the  '=' sign (< value > may contain more '=' signs), something like this:Is there a way to NOT declare a variable 'sep'? Like this (just made up the syntax):Just for completeness, I'm targetting Python v 2.6 is indeed a very popular choice for \"a name which doesn't matter\" -- it's a legal name, visually unobtrusive, etc.  However sometimes these very qualities can hinder you.  For example, the GNU  module for I18N and L10N, which is part of Python's standard library, idiomatically uses  very differently, with idioms such as...:to mark and translate all the literal-string messages in the code (also exploiting the relative visual unobtrusiveness of .  Obviously any code using this module and idiom shouldn't also be using  to mean something completely different (\"a don't care name\").So a second useful alternative can be to devote the name  to indicate such \"don't care\" situations in a visually more explicit way.  Google's  recommends using either  or a  of  -- the latter can be a bit verbose but tends to be very clear, e.g.:makes crystal-clear that  is a three-item sequence (probably a tuple) and the item you're skipping (and not using at all) is the surname (because you want to print a friendly message like \"Hello, Mr Alex!\" or \"Hello, Miss Piggy!\" ;-).  ( and similar tools can warn you if you have unused variables named otherwise than  or , and of course also warn you if you ever  use a variable named !-).Almost there: is conventionally considered a don't-care variable.There isn't anything official in the language for that; you can just use any throw-away variable.  As far as standards go, I've seen underscores used occasionally in Python and other languages.  The only issue there is that underscore is used as an alias for  when localizing.  But if you aren't doing localization, or aren't using the global-binding for it, then underscore should work fine.Really strange question, because you can do just:and don't care about  variable, but  is just a name as , as  or . By the way use Why don't you use  instead? That disregards the delimiter. (to accommodate Cristi's example in the comment):From :The _ is commonly used as a name for you  * For example, in a tuple containing the name, surname and nickname in a moment in which we are interested only in name and surname, could use _ to indicate that the name is not important at this point:As others have said, underscore () is the standard. But if underscore is being used for translations, I think double underscore is the best alternative.Better than these:There is also the option of using indexes:
Python

I don't understand what this single underscore means. Is it a magic variable? I can't see it in locals() and globals().In the standard Python REPL,  represents the last returned value -- at the point where you called ,  was the value .For example:Note that there is no such functionality within Python .  In a script,  has no special meaning and will not be automatically set to the value produced by the previous statement.Also, beware of reassigning  in the REPL if you want to use it like above!To undo the assignment (and remove the  from globals), you'll have to:then the functionality will be back to normal (the  will be visible again).Why you can't see it? It is in So it's neither global nor local. And where does this assignment happen? : 2012 Edit : I'd call it  since 's members are available everywhere, in any module.Usually, we are using _ in Python to bind a ugettext function.
Python

I'm building some predictive models in Python and have been using scikits learn's SVM implementation. It's been really great, easy to use, and relatively fast.Unfortunately, I'm beginning to become constrained by my runtime. I run a rbf SVM on a full dataset of about 4 - 5000 with 650 features. Each run takes about a minute. But with a 5 fold cross validation + grid search (using a coarse to fine search), it's getting a bit unfeasible for my task at hand. So generally, do people have any recommendations in terms of the fastest SVM implementation that can be used in Python? That, or any ways to speed up my modeling?I've heard of LIBSVM's GPU implementation, which seems like it could work. I don't know of any other GPU SVM implementations usable in Python, but it would definitely be open to others. Also, does using the GPU significantly increase runtime?I've also heard that there are ways of approximating the rbf SVM by using a linear SVM + feature map in scikits. Not sure what people think about this approach. Again, anyone using this approach, is it a significant increase in runtime?All ideas for increasing the speed of program is most welcome.The most scalable kernel SVM implementation I know of is . It's written in C hence wrap-able in Python if you know ,  or . Alternatively you can use it from the command line. You can use the utilities in  to load convert data from a  or CSR format into svmlight formatted files that LaSVM can use as training / test set.Alternatively you can run the grid search on 1000 random samples instead of the full dataset:It's very likely that the optimal parameters for 5000 samples will be very close to the optimal parameters for 1000 samples. So that's a good way to start your coarse grid search. makes it possible to use all your CPUs to run the individual CV fits in parallel. It's using mulitprocessing so the python GIL is not an issue.Firstly, according to scikit-learn's benchmark (), scikit-learn is already one of the fastest if not fastest SVM package around. Hence, you might want to consider other ways of speeding up the training. As suggested by bavaza, you can try to multi-thread the training process. If you are using Scikit-learn's GridSearchCV class, you can easily set n_jobs argument to be larger than the default value of 1 to perform the training in parallel at the expense of using more memory.\nYou can find its the documentation  An example of how to use the class can be found Alternatively, you can take a look at Shogun Machine Learning Library\nShogun is designed for large scale machine learning with wrappers to many common svm packages and it is implemented in C/C++ with bindings for python. According to Scikit-learn's benchmark above, it's speed is comparable to scikit-learn. On other tasks (other than the one they demonstrated), it might be faster so it is worth giving a try.Lastly, you can try to perform dimension reduction e.g. using PCA or randomized PCA to reduce the dimension of your feature vectors. That would speed up the training process. The documentation for the respective classes can be found in these 2 links: ,  . You can find examples on how to use them in Scikit-learn's examples section.If you are interested in only using the RBF kernel (or any other quadratic kernel for that matter), then I suggest using LIBSVM on  or . I train a model of 7000 observations and 500 features in about 6 seconds.The trick is to use precomputed kernels that LIBSVM provides, and use some matrix algebra to compute the kernel in one step instead of lopping over the data twice. The kernel takes about two seconds to build as opposed to a lot more using LIBSVM own RBF kernel. I presume you would be able to do so in Python using , but I am not sure as I have not tried it.Without going to much into comparing SVM libraries, I think the task you are describing (cross-validation) can benefit from real multi-threading (i.e. running several CPUs in parallel). If you are using , it does not take advantage of your (probably)-multi-core machine, due to .You can try other implementations of Python which don't have this limitation. See  or  if you are willing to go to .NET.Try !It is a wicked-fast C implementation from the , with good Python bindings, and you can install it with .If your problem is in two classes, this wrapping of CUDA-based SVM with scikit-learn is useful:I suggest looking at Scikit-Learn's  implementation. The default hinge loss is a linear SVM. I've found it to be blazingly fast.I'd consider using a  to reduce the number of features you input.There is an option with the ExtraTreesRegressor and ExtraTreesClassifier to generate feature importances. You can then use this information to input a subset of features into your SVM.
Python

The following works when I paste it on the browser: But when I try reading the URL with Python nothing happens:Do I need to encode the URL, or is there something I'm not seeing?To answer your question:You need to , not Or, just get this library here:  and seriously use it :)A solution with works with Python 2.X and Python 3.X makes use of the Python 2 and 3 compatibility library :The URL should be a string:
Python

I created Django project in home directory so it is in home directory.Permissions of Permissions of Permissions of I am getting error on browser  Please help me out with the configuration .For now I am moving forward by changing toSo,this has definitely something to do with  file configuration,but my worry is that I only added 5 lines in that file and not able to figure out what's wrong .Apparently this is an issue that is related to Apache 2.4 and older versions.\nYou need to replace in your apache configuration:within the  sectionYou can use the following:This has been reported in Django ticket 19319:Your Apache config now needs the following for your file .There is one other gotcha:Check your httpd.conf file for the following configuration:This will cause the error..py MUST NOT be configured as a CGI script
Python

when i try to send mail using gmail and python error occurred this type of question are already in this site but doesn't help to me error:Your code looks correct. Try logging in through your browser and if you are able to access your account come back and try your code again.\nJust make sure that you have typed your username and password correct:\nGoogle blocks sign-in attempts from apps which do not use modern security standards (mentioned on their support ). You can however, turn on/off this safety feature by going to the link below:Go to this link and select \nI have just sent an email with gmail through Python.\nTry to use smtplib.SMTP_SSL to make the connection. Also, you may try to change the gmail domain and port.So, you may get a chance with:As a plus, you could check the email builtin module. In this way, you can improve the readability of you your code and handle emails headers easily.Your code looks correct but sometimes google block an ip when you try to send a email since a unusual  location, so, you can unblock in the next link and clicked in accounts.google.com/DisplayUnlockCaptcha .
Python

I have the following code:When I run it in the Python Shell, it returns:I've searched and it seems this is called a , but how does it work? About your question, the list comprehension does the same thing as the following \"plain\" Python code:How do you write it in one line? Hmm...we can...probably...use  with :But isn't it clearer and simpler to just use a list comprehension?Basically, we can do anything with . Not only . For example, run a method of :Or use  as another function's argument:We can also, for example, use  as the key of a  object. Let's see:How about a combination?  And so on.You can also use  or  in a list comprehension. For example, you only want odd numbers in . You can do:Ah that's too complex. What about the following version?To use an  ternary expression, you need put the  after ,  after :Have you heard about ? You can put . For example:Let's talk about the first part,  which gives  and . Then,  gives , ,  and , , .  You always need put   :We also have , , and . and list comprehensions are basically the same, but the former returns a  instead of a :It's the same as:A   a set comprehension, but it uses  or  instead of  .For example:And it equals:Does  give a ? No!, it's a . Which returns a :It's the same as:And you can use it as a generator: If you use a list comprehension , you don't need the  if that function could loop over a generator. For example, : (about generators): .There are list, dictionary, and set comprehensions, but no tuple comprehensions (though do explore \"generator expressions\").They address the problem that traditional loops in Python are statements (don't return anything) not expressions which return a value.They are not the solution to every problem and can be rewritten as traditional loops. They become awkward when state needs to be maintained & updated between iterations.They typically consist of:but can be twisted in lots of interesting and bizarre ways.They can be analogous to the traditional  and  operations which still exist in Python and continue to be used.When done well, they have a high satisfaction quotient.
Python

I have installed tensorflow in my ubuntu 16.04 using the second answer  with ubuntu's builtin apt cuda installation.Now my question is how can I test if tensorflow is really using gpu? I have a gtx 960m gpu. When I  this is the outpIs this output enough to check if tensorflow is using gpu ? No, I don't think \"open CUDA library\" is enough to tell, because different nodes of the graph may be on different devices.To find out which device is used, you can enable log device placement like this:This will confirm that tensorflow using GPU while training also ?Apart from using  which is outlined in other answers as well as in TF official , you can try to assign a computation to the gpu and see whether you have an error.Here If you have a gpu and can use it, you will see the result. Otherwise you will see an error with a long stacktrace. In the end you will have something like this: 
Python

I want a program to do one thing if executed like this:and do another thing if run like thisBut if I read from stdin, then it will wait for user input, so I want to see if there is anything to read before trying to read from stdin.If you want to detect if someone is piping data into your program, or running it interactively you can use isatty to see if stdin is a terminal:You want the select module ( on unix) It will allow you to test if there is anything readable on stdin. Note that select won't work on Window with file objects. But from your pipe-laden question I'm assuming you're on a unix based os :)Bad news.  From a Unix command-line perspective those two invocations of your program  identical.Unix can't easily distinguish them.  What you're asking for isn't really sensible, and you need to think of another way of using your program.In the case where it's not in a pipeline, what's it supposed to read if it doesn't read stdin?Is it supposed to launch a GUI?  If so, you might want to have a \"-i\" (--interactive) option to indicate you want a GUI, not reading of stdin.You can, sometimes, distinguish pipes from the console because the console device is \"/dev/tty\", but this is not portable.I do not know the Python commands off the top of my head, but you should be able to do something with poll or select to look for data ready to read on standard input.That might be Unix OS specific and different on Windows Python.
Python

I'm checking to see if a directory exists, but I noticed I'm using  path.exists instead of path.isdir.  Both work just fine, but I'm curious as to what the advantages are for using isdir instead of exists.  will also return  if there's a regular file with that name.  will only return  if that path exists and is a directory.Just like it sounds like: if the path exists, but is a file and not a directory,  will return . Meanwhile,  will return  in both cases.Most of the time, it is the same.But, path can exist physically whereas  returns False. This is the case if os.stat() returns False for this file.If path exists physically, then  will always return True. This does not depend on platform.
Python

In numpy, I have two \"arrays\", X is (m,n) and y is a vector (n,1)using I am getting the errorWhen  (97,2)x(2,1) is clearly a legal matrix operation and should give me a (97,1) vectorEDIT:I have corrected this using  but the original question still remains.We have two arrays:With Numpy arrays the operationis done element-wise, but one or both of the values can be expanded in one or more dimensions to make them compatible. This operation are called broadcasting. Dimensions where size is 1 or which are missing can be used in broadcasting.In the example above the dimensions are incompatible, because:Here there are conflicting numbers in the first dimension (97 and 2). That is what the ValueError above is complaining about. The second dimension would be ok, as number 1 does not conflict with anything.For more information on broadcasting rules: (Please note that if  and  are of type , then asterisk can be used as matrix multiplication. My recommendation is to keep away from , it tends to complicate more than simplify things.)However, your arrays should be fine with , so there something else must have happened. If  throws an exception, it complains:If you still get this error, please post a minimal example of the problem. It works:returns a (97,1) array.Per Wes McKinney's In other words, if you are trying to multiply two matrices (in the linear algebra sense) then you want  but if you are trying to broadcast scalars from matrix  onto  then you need to perform .\nIt's possible that the error didn't occur in the dot but after.\nFor example try thisnp.dot(a,b) will be fine; however np.dot(a,b) * c is clearly wrong (12x5 X 5x5 = 12x5 which cannot element-wise multiply 5x12) but numpy will give youThe error is misleading; however there is an issue on that line.
Python

What are the main differences between Python metaclasses and class decorators? Is there something I can do with one but not with the other?Decorators are much, much simpler and more limited -- and therefore should be preferred whenever the desired effect can be achieved with either a metaclass or a class decorator.Anything you can do with a class decorator, you can of course do with a custom metaclass (just apply the functionality of the \"decorator function\", i.e., the one that takes a class object and modifies it, in the course of the metaclass's  or  that make the class object!-).There are many things you can do in a custom metaclass but not in a decorator (unless the decorator internally generates and applies a custom metaclass, of course -- but that's cheating;-)... and even then, in Python 3, there are things you can only do with a custom metaclass, not after the fact... but that's a pretty advanced sub-niche of your question, so let me give simpler examples).For example, suppose you want to make a class object  such that  (or in Python 3  of course;-) displays .  You cannot possibly do that without a custom metaclass, because the metaclass's override of  is the crucial actor here, i.e., you need a  in the custom metaclass of class .The same applies to all magic methods, i.e., to all kinds of operations as applied to the class object itself (as opposed to, ones applied to its , which use magic methods as defined in the class -- operations on the class object itself use magic methods as defined in the metaclass).
Python

Say I have my object layout defined as:...and my type definition:How do I create a new instance of  somewhere within my C extension? The best way is to  the class object, just like in Python itself:
Python

I want to override my Python class's  and  methods. My use case is the usual one: I have a few special names that I want to handle, and I want the default behavior for anything else. For , it seems that I can request the default behavior simply by raising . However, how can I achieve the same in ? Here is a trivial example, implementing a class with immutable fields \"A\", \"B\", and \"C\".What goes in place of the question marks? With old-style classes, the answer was apparently , but documentation indicates that this is wrong for new-style classes.It'sin Python 2, orin Python 3.Also, raising  is  how you fall back to the default behavior for . You fall back to the default withon Python 2 oron Python 3.Raising  skips the default handling and goes to , or just produces an  in the calling code if there's no .See the documentation on . ?
Python

  How do I implement a static constructor in Python?Here is my code...  The  doesn't fire when I call App like this. The  is not a static constructor or static initializer.I have to call it like this, which instantiates the App class every time:Here is my class:The problem with calling  every time is that the App object gets recreated.  My \"real\" App class is quite long.  Hint: anything that references  is going to require an instantiation of the class. You could do it like this:But come on, that seems like a lot of fluff. I'm with SLaks, just initialize it outside of the class. Alternatively, you could look into the .There's a fundamental difference between static and dynamic languages that isn't always apparent at first.  In a static language the class is defined at compile time and everything is all nice and set in concrete before the program ever runs.  In a dynamic language the class is actually defined at runtime.  As soon as the interpreter parses and starts executing all of those class and def statements the equivalent of a static constructor is being run.  The class definitions are being executed at that point.  You can put any number of statements under the class body that you want and they are in effect a static constructor.  If you want you can place them all in a function that doesn't take self and at the end of the class call that function.You need to instantiate your App, then use that instead:
Python

I am trying to predict weekly sales using  ARIMA models. I could not find a function for tuning the order(p,d,q) in . Currently R has a function  which will tune the (p,d,q) parameters. How do I go about choosing the right order for my model? Are there any libraries available in python for this purpose?You can implement a number of approaches:actuallyI wrote these utility functions to directly calculate pdq values \n require three inputs data which is series with timestamp(datetime) as index. n_jobs will provide number of parallel processor. output will be dataframe with aic and bic value with order=(P,D,Q) in index\np and q range is [0,12] while d is [0,1]possible solutionfrom also see 
Python

 question got me thinking: should we apply the principle that \"flat is better than nested\" to data as well as to code? Even when there is a \"logical tree structure\" to the data?In this case, I suppose it would mean representing children as a list of IDs, rather than an actual list of children, with all the nodes in a single list:(I used tuples because I prefer not to give myself the flexibility to mutate an object until that flexibility proves itself to be useful and usable in a clear manner. In any case I would never use  here instead of an empty sequence, because it complicates the logic, and \"special cases aren't special enough\" - here, it isn't special at all.)Certainly this is shorter, but the tree structure is obscured. Does that contradict \"explicit is better than implicit\"?Personally I find that \"flat is better than nested\" is of limited applicability, and nowhere near the most important aspect of the Zen. (Certainly I could not do a lot of the nice functional-programming things that I do if I didn't allow myself significant nesting.) I suspect that the problem with \"nested\" is that it requires context switching when you comprehend the information. I really think this is more of a problem when following imperative logic than for parsing data or functional-style code - where it's easier to just mentally name the nested block, and consider its workings separately from the outer context.What say you?I wouldn't inherently prefer either, but rather use whatever seems best suited to the task.If the structure is important, nesting makes life simple. If you're regularly operating over each node, the flat structure makes it easy to use . Of course, if you define your own class, its easy enough to abstract it so both options are simple; but it may be harder to use with external systems, such as converting to JSON.This is a completely subjective question.  The answer is, \"it depends.\"It depends on the primary use of your data.  If you continually have to reference the nested structure, then it makes sense to represent it that way.  And if you never reference the flat representation except when building the nested structure, then why have the flat structure at all?The \"flat\" representation is one of the basics of the relational database model:  each type of data exists in a table just for that type, and any relationships among the items are contained in separate tables.  It's a useful abstraction, but at times difficult to work with in code.  On the other hand, processing all the data of a particular type is trivial.Consider, for example, if I wanted to find all the descendants of the record with id 2 in your example data.  If the data is already in the hierarchy (i.e. native representation is the \"nested\" structure), then it's trivial to locate record id 2 and then traverse its children, children's children, etc.But if the native representation is sequential as you've shown it then I have to pass through the entire data set to create the hierarchical structure and  find record 2 and its children.So, as I said, \"it depends.\"No.That's what \"flat is better than nested\" doesn't apply to data.  Only to code.It's not even comparable.  The \"flat tree\" is a common SQL implementation because SQL can't handle indefinite recursion of a proper tree.  Comparing the Zen of Python (the language) with data structure design is nonsensical.  The two are no more comparable than than the number \"2\" and splitting a brick of cheese into \"2\" pieces.  One's a thing, the other's an action.  Data structures are things.Python describes actions.  Yes, particularly when being explicit prevents you from implicitly shooting yourself in the foot. The \"tree\" in your example can have multiple parents claiming to own the same children. It can also have multiple root nodes (and it does: 2 is a root node; 4 is a root as well as a leaf node.)This question can't be answered \"in general\" - there is no right answer.    For this particular example, I actually like the tree structure better.  Without knowing anything about the original application, and just looking at the structure, the relationship between the items is obvious.  With the flat structure, I have to read some documentation, or application code to \"know\" that your tuple of children refer to id's.  The tree structure is self-documenting - the flat structure isn't.\"Everything should be made as simple as possible, but not simpler.\" Flat is simpler than nested. If you're dealing with data with  nesting, then flattening it probably violates the \"but not simpler\" part. I took the Zen of Python instead to be encouraging you not to complicate your life with nesting you don't really need, like an XML config file where a simpler flat format might suffice.
Python

I'm trying to understand the basics of threading and concurrency. I want a simple case where two threads repeatedly try to access one shared resource. The code:  So, I have two threads, both trying to increment the counter. I thought that if thread 'A' called , the  would be established, preventing 'B' from accessing until 'A' has released. Running the makes it clear that this is not the case. You get all of the random data race-ish increments.How exactly is the lock object used?  Edit, Additionally, I've tried putting the locks inside of the thread functions, but still no luck. You can see that your locks are pretty much working as you are using them, if you slow down the process and make them block a bit more. You had the right idea, where you surround critical pieces of code with the lock. Here is a small adjustment to your example to show you how each waits on the other to release the lock.Sample output:
Python

I am trying to get the mercurial revision number/id (it's a hash not a number) programmatically in python.The reason is that I want to add it to the css/js files on our website like so:So that whenever a change is made to the stylesheet, it will get a new url and no longer use the old cached version. if you know where to find good documentation for the mercurial , that would also be helpful. I can't seem to find it anywhere.I ended up using subprocess to just run a command that gets the hg node. I chose this solution because the api is not guaranteed to stay the same, but the bash interface probably will:example use:It's true there's no official API, but you can get an idea about best practices by reading other extensions, particularly those bundled with hg. For this particular problem, I would do something like this: At some point the parameter order changed, now it's like this:Do you mean ?\nNote that, as stated in that page, there is no  API, because they still reserve the right to change it at any time. But you can see the list of changes in the last few versions, it is not very extensive.An updated, cleaner subprocess version (uses , added in Python 2.7/3.1) that I use in my Django settings file for a crude end-to-end deployment check (I dump it into an HTML comment):You could wrap it in a  if you don't want some strange hiccup to prevent startup:give a try to \n I don't know what to use if you're using Python 3, sorry. Probably .Mercurial has two official APIs.Installation:Usage:More usage information on the .Because it is maintained by the Mercurial team, and it is what the Mercurial team recommend for interfacing with Mercurial. , the following statement on interfacing with Mercurial:From the command server page:The Python interface to the Mercurial command-server, as said, is .The per-command overhead of the command line interface is no joke, by the way. I once built a very small test suite (only about 5 tests) that used  via  to create, commit by commit, a handful of repos with e.g. merge situations. Throughout the project, the runtime of suite stayed between 5 to 30 seconds, with nearly all time spent in the  calls.The signature of a Python hook function is like so: and  are part of the aforementioned discouraged unofficial . The fact that they are right there in your function args makes them terribly convenient to use, such as in this example of a  hook that disallows merges between certain branches.If your hook code is not so important, and you're not publishing it, you might choose to use the discouraged unofficial internal API. If your hook is part of an extension that you're publishing, better use .FWIW to avoid fetching that value on every page/view render, I just have my deploy put it into the  file.  Then I can reference  without all the overhead of accessing mercurial and/or another process.  Do you ever have this value change w/o reloading your server?I wanted to do the same thing the OP wanted to do, get  from a script (get tip revision of the whole REPOSITORY, not of a single FILE in that repo) but I did not want to use popen, and the code from  got me started, but wasn't what I wanted. So I wrote this... Comments/criticism welcome.  This gets the tip rev in hex as a string.
Python

Is one correct in stating the following: --> can I safely use this in every situation? (haven't run into one where it caused me problems)With 'C type as an attribute' I mean bar and baz:First, read this more carefully, specifically the last paragraph, Easy way to think about it is thinking about the reference counts.The caveats to these answers are outlined in the link above.  You really shouldn't even need my poor explanation after reading that.  I hope I clarified and didn't confuse more.
Python

Like many a foolhardy pioneer before me, I'm endeavoring to cross the trackless wasteland that is Understanding Monads.I'm still staggering through, but I can't help noticing a certain monad-like quality about Python's  statement.  Consider this fragment:Consider the open() call as the \"unit\" and the block itself as the \"bind\".  The actual monad isn't exposed (uh, unless  is the monad), but the pattern is there.  Isn't it?  Or am I just mistaking all of FP for monadry?  Or is it just 3 in the morning and anything seems plausible?A related question: if we have monads, do we need exceptions?In the above fragment, any failure in the I/O can be hidden from the code.  Disk corruption, the absence of the named file, and an empty file can all be treated the same.  So no need for a visible IO Exception.Certainly, Scala's  typeclass has eliminated the dreaded Null Pointer Exception.  If you rethought numbers as Monads (with NaN and DivideByZero as the special cases)...Like I said, 3 in the morning.Right below the definition, :This sounds to me exactly like the context manager protocol, the implementation of the context manager protocol by the object, and the  statement.From @Owen in a comment on this post:The full Wikipedia definition:This sounds like the  to me.The actual implementation of the context manager protocol by the object.This corresponds to  and its suite.So yes, I'd say  is a monad. I searched  and all the related rejected and withdrawn PEPs, and none of them mentioned the word \"monad\". It certainly applies, but it seems the  of the  statement was resource management, and a monad is just a useful way to get it.It's almost too trivial to mention, but the first problem is that  isn't a function and doesn't take a function as an argument. You can easily get around this by writing a function wrapper for :Since this is so trivial, you could not bother to distinguish  and .The second problem with  being a monad is that, as a statement rather than an expression, it doesn't have a value. If you could give it a type, it would be  (this is actually the type of  above). Speaking practically, you can use Python's  to get a value for the  statement. In Python 3.1:Since  uses a function rather than a code block, an alternative to  is to return the value of the function:There is another thing preventing  (and ) from being a monadic bind. The value of the block would have to be a monadic type with the same type constructor as the  item. As it is,  is more generic. Considering agf's note that every interface is a type constructor, I peg the type of  as , where M is the context manager interface (the  and  methods). In between the types of  and  is the type . To be a monad,  would have to fail at runtime when  wasn't . Moreover, while you could use  monadically as a bind operation, it would rarely make sense to do so.The reason you need to make these subtle distinctions is that if you mistakenly consider  to be monadic, you'll wind up misusing it and writing programs that will fail due to type errors. In other words, you'll write garbage. What you need to do is distinguish a construct that is a particular thing (e.g. a monad) from one that can be used in the manner of that thing (e.g. again, a monad). The latter requires discipline on the part of a programmer, or the definition of additional constructs to enforce the discipline. Here's a nearly monadic version of  (the type is ):In the final analysis, you could consider  to be like a combinator, but a more general one than the combinator required by monads (which is bind). There can be more functions using monads than the two required (the list monad also has cons, append and length, for example), so if you defined the appropriate bind operator for context managers (such as ) then  could be monadic in the sense of involving monads.Haskell has an equivalent of  for files, it's called . This:is equivalent to:Now,  might look like something monadic. Its type is:right side looks like .Another similarity: In Python you can skip , and in Haskell you can use  instead of  (or, a  block without  arrow).So I'll answer this question: is  monadic?You could think that it can be written like this:But this doesn't type check. And it cannot.It's because in Haskell : if you writeafter  is executed,  is executed and then . There is no \"backtrack\"\nto clean  at the end or something like that. , on the other hand,\nhas to close the handle after the block is executed.There is another monad, called continuation monad, which allows to do such\nthings. However, you have now two monads, IO and continuations, and using effects of two monads at once requires using monad transformers.That's ugly. So the answer is: somewhat, but that requires dealing with a lot of  subtleties that make the issue rather opaque.Python's  can simulate only a limited bit of what monads can do - add entering and finalization code. I don't think you can simulate e.g.using  (it might be possible with some dirty hacks). Instead, use for:And there's a Haskell function for this - :I recommed reading about  which bears more resemblance to monads than :\nBasically no, instead of a function that throws A or returns B you can make a function that returns . The monad for  will then behave just like exceptions - if one line of code will return an error, the whole block will.However, that would mean that division would have type  and so on, to catch division by zero. You would have to detect errors (explicitly pattern match or use bind) in any code that uses division or has even slightest possibility of going wrong. Haskell uses exceptions to avoid doing this.I have thought unnecesarily long about this and I believe the answer is \"yes, when it's used a certain way\" (thanks outis :),\nbut not for the reason I thought before.I mentioned in a comment to agf that  is just continuation passing style --\ngive it a producer and a callback and it \"runs\" the producer and feeds it to the\ncallback. But that's not quite true. Also important is that  has to run\nsome  between the producer and the result of the callback.In the case of the List monad, this would be concatenating lists. This\ninteraction is what makes monads special.But I believe that Python's   do this interaction, just not in the\nway you might expect.Here's an example python program employing two with statements:When run the output isNow, Python is an imperative language, so instead of merely producing data, it\nproduces side-effects. But you can think of those side-effects as being data\n(like ) -- you can't combine them in all the cool ways you could combine\n, but they're getting at the same goal.So what you should focus on is the  of those operations -- that is,\nthe order of the print statements.Now compare the same program in Haskell:Which produces:And the ordering is the same.The analogy between the two programs is very direct: a  has some\n\"entering\" bits, a \"body\", and some \"exiting\" bits. I used Strings instead of\nIO actions because it's easier -- I think it should be similar with IO actions\n(correct me if it's not).And  for  does  what  in Python does: it runs the\nentering statements, feeds the value to the , and runs the exiting\nstatements.(There's another huge difference which is that the body should be depend on the\nentering statements. Again I  that should be fixible).
Python

Sorry basic question I'm sure but I can't seem to figure this out.Say I have this program , the file is called :How can I call it in another program?\nI tried:Instead of 'hello world', I get  ...I have done this in the past by making the first file a class, but I was wondering how to import the function correctly?  If it helps, in my real file, I am printing a dictionaryYou need to print the result of calling the function, rather than the function itself:Additionally, rather than , you can omit the  clause:If it's more convenient, you can also use :
Python

For various reasons, I am trying to get an collections of objects out of a database and pass it to another process that is not connected to the database.  My code looks like the one below but I keep getting When I try to look at the elements of my list outside of the  method.However, if I use this I am able to use the elements but worry about the state of the session since it was not closed.  What am I missing here?If you want a bunch of objects produced by querying a session to be usable outside the scope of the session, you need to  them for the session.In your first function example, you will need to add a line:beforeMore generally, let's say the session is not closed right away, like in the first example. Perhaps this is a session that is kept active during entire duration of a web request or something like that. In such cases, you don't want to do . You will want to be more surgical:In my case, I was saving a related entity as well, and this recipe helped me to  all instances within a session, leveraging the fact that Session is iterable:This is extremely ineffective, but works. Should be fine for unit-tests.Final note: in Python3  is a generator and won't do anything. Use real loops of list comprehensions
Python

I've been searching around, and there appear to be scattered discussions about s in different programming languages, including some specific cases, but nothing exhaustive or clear.What are the most common operations that would cause a , in Python, which originate while working with NumPy or SciPy? If you do any of the following without horsing around with the floating-point environment, you should get a NaN where you didn't have one before:The canonical reference for these aspects of machine arithmetic is the .  Section 7.1 describes the invalid operation exception, which is the one that is raised when you're about to get a NaN.  \"Exception\" in IEEE 754 means something different than it does in a programming language context.Lots of special function implementations document their behaviour at singularities of the function they're trying to implement.  See the man page for  and , for instance.You're asking specifically about NumPy and SciPy.  I'm not sure whether this is simply to say \"I'm asking about the machine arithmetic that happens under the hood in NumPy\" or \"I'm asking about  and stuff.\"  I'm assuming the former, but the rest of this answer tries to make a vague connection to the higher-level functions in NumPy.  The basic rule is:  For , for instance, you're liable to get s if your input values are around  or larger and a silent loss of precision if your input values are around  or smaller.  Apart from truly ridiculously scaled inputs, though, you're quite safe with .For things involving matrix math, NaNs can crop up (usually through the  route) if your numbers are huge  your matrix is extremely ill-conditioned.  A complete discussion of how you can get screwed by numerical linear algebra is too long to belong in an answer.  I'd suggest going over a numerical linear algebra book (Trefethen and Bau is popular) over the course of a few months instead.One thing I've found useful when writing and debugging code that \"shouldn't\" generate NaNs is to tell the machine to trap if a NaN occurs.  In GNU C, I do this:
Python

I'm having some weird issues with pytz's .localize() function. Sometimes it wouldn't make adjustments to the localized datetime:.localize behaviour:As you can see, time has not been changed as a result of localize/normalize operations.\nHowever, if .replace is used:Which seems to make adjustments into datetime. Question is - which is correct and why other's wrong? just assumes that the naive datetime you pass it is \"right\" (except for not knowing about the timezone!) and so just sets the timezone, no other adjustments.You can (and it's advisable...) internally work in UTC (rather than with naive datetimes) and use  when you need to perform I/O of datetimes in a localized way ( will handle DST and the like).I realize I'm a little late on this... \nbut here is what I found to work well.\nWork in UTC as Alex stated: Then to localize:And this method does handle DST perfectlyThis DstTzInfo class is used for timezones where the offset from UTC changes at certain points in time.  For example (as you are probably aware), many locations transition to \"daylight savings time\" at the beginning of Summer, and then back to \"standard time\" at the end of Summer.  Each DstTzInfo instance only represents one of these timezones, but the \"localize\" and \"normalize\" methods help you get the right instance.For Abidjan, there has only ever been one transition (according to pytz), and that was in 1912:The tz object we get out of pytz represents the pre-1912 timezone:Now looking up at your two examples, see that when you call tz.localize(d) you do  get this pre-1912 timezone added to your naive datetime object.  It assumes that the datetime object you give it represents local time , which is the post-1912 timezone.However in your second example using d.replace(tzinfo=tz), it takes your datetime object to represent the time in the pre-1912 timezone.  This is probably not what you meant.  Then when you call dt.normalize it converts this to the timezone that is correct for that datetime value, ie the post-1912 timezone. is the correct function to use for creating datetime aware objects with an initial fixed datetime value. The resulting datetime aware object will have the original datetime value. A very common usage pattern in my view, and one that perhaps pytz can better document. is unfortunately named. It is a function that is random in its behaviour. I would advise avoiding the use of this function to set timezones unless you enjoy self-inflicted pain. I have already suffered enough from using this function.
Python

When I upgrade my Ubuntu into 14.04 from 12.04, this time I get this error:This happened to me when I created a virtualenv and then upgraded from 12.04 to 14.04.I had to delete my virtualenv and recreate it, and after doing that, everything worked again.Just run this command. It worked like a charm!This just happened to me after the 14.10 update, and it seems to be because my virtual environments have old copies of  that \u2014 unlike the new binary \u2014 do not include  built-in, and so get an error when they cannot find it on disk anywhere. The new interpreter seems to import it without any file I/O (try running it under strace to check).I tried to re-install it by these steps.And it works perfectly. Thanks guys :)just reinitialize the virtualenv by:If you use , updating it might solve this issue If by chance you come across this error while trying to renew your LetsEncrypt certificate (like I did) I found the solution here:Remove this folder and rerun LetsEncrypt and it will recreate all the relevant files and avoid the error from this thread.Try...if lib-dynload not included in sys.path, You could not check it!I upgraded from Ubuntu 12.04 to 14.04 and  helped me solve it:Installing the dependencies:Making a symbolic link as suggested by mrudult:Install Pillow as usual:Same happened to me on upgrading Ubuntu from 14.04 to 15.10.I solved it by upgrading pip and then removing and recreating the virtual env:(I use virtualenvwrapper)If you face datetime import issue using IntelliJ PyCharm or Idea and from Console/Terminal it works fine, you should just duplicate/recreate running configurations.
Python

In python 2.6, the following code:Gives the following output:Which means that even though there is only one value for test, it is still being parsed into a list. Is there a way to ensure that if there's only one value, it is not parsed into a list, so that the result would look like this?You could fix it afterwards...However, I don't think  would want this.  If a parameter that is normally a list happens to arrive with only one item set, then I would have a string instead of the list of strings I normally receive.A sidenote for someone just wanting a simple dictionary and never needing multiple values with the same key, try:This will give you a nice . Please note that if there  multiple values for the same key, you'll only get the last one.
Python

Given this harmless little list:My goal is to pythonically concatenate the little devils using one of the following ways:A. plain ol' string function to get the job done, short, no importsB. lambda, lambda, lambda C. globalization (do nothing, import everything)Please suggest other pythonic ways to achieve this magnanimous task.Please rank (pythonic level) and rate solutions giving concise explanations.In this case, is the most pythonic solution the best coding solution?Have a look at Guido's  on python optimization, it covers converting lists of numbers to strings. Unless you have a  reason to do otherwise, use the  example.the only pythonic way:Of course it's . How do I know?  Let's do it in a really stupid way:\nIf the problem was only adding 2 strings, you'd most likely use . What does it take to get that to the next level? Instinctively, for most (I think), will be to use . Let's see how that goes:Wow! Python simply told me what to use! :)Here's the least Pythonic way:I myself use the \"join\" way, but from python 2.6 there is a base type that is little used: .Bytearrays can be incredible useful -- for string containing texts, since the best thing is to have then in unicode, the \"join\" way is the way to go -- but if you are dealing with binary data instead, bytearrays can be both more pythonic and more efficient:it is a built in data type: no imports needed - just use then -- and you can use a bytearray isntead of a list to start with - so they should be more efficinet than the \"join\", since there is no data copying to get the string representation for a bytearray.Great answer from SilenGhost BUT, just a few words about the presented  \"alternative\"Unless you've got a very very  good reason to concatenate strings using  or  (the most frequent one, that you've got few, fixed number of strings), you should use always .Just because each  generates a new string which is the concatenation of two strings, unless join that only generates one final string. So, imagine you've got 3 strings:Ok, doesn't seems not much, but you've got to reserve memory for D. Also, due python use of strings, generating a new, intermediate, string, it's somehow expensive...Now, with 5 stringsAssuming the best scenario (if we do (A+B) + (C+D) + E, we'll end having three intermediate strings at the same time on memory), that's generating 3 intermediate strings... You've got to generate a new python object, reserve memory space, release the memory a few times... Also the overhead of calling a Python function (that is not small)Now think of it with 200 strings. We'll end up with a ridiculous big number of intermediate strings, each of one consuming combining quite a lot time on being a complete list over python, and calling a lot of  functions, each with its overhead... Even if you use  functions, it won't help. It's a problem that has to be managed with a different approach: , which only generates  complete python string, the final one and calls ONE python function.(Of course, , or other similar, specialized function for arrays)
Python

I am looking for ideas on how to translate one range values to another in Python. I am working on hardware project and am reading data from a sensor that can return a range of values, I am then using that data to drive an actuator that requires a different range of values.For example lets say that the sensor returns values in the range 1 to 512, and the actuator is driven by values in the range 5 to 10. I would like a function that I can pass a value and the two ranges and get back the value mapped to the second range. If such a function was named  it could be used like this:In this example I would expect the output  to be  since the  is in the middle of the possible input range.One solution would be:You could possibly use algebra to make it more efficient, at the expense of readability.You can also use  package to do such conversions (if you don't mind dependency on SciPy):or to convert it back to normal float from 0-rank scipy array:You can do also multiple conversions in one command easily:As a bonus, you can do non-uniform mappings from one range to another, for intance if you want to map [1,128] to [1,10], [128,256] to [10,90] and [256,512] to [90,100] you can do it like this: creates piecewise linear interpolation objects (which are callable just like functions).As noted by ,  is also an option (with less dependencies):This would actually be a good case for creating a closure, that is write a function that returns a function.  Since you probably have many of these values, there is little value in calculating and recalculating these value spans and factors for every value, nor for that matter, in passing those min/max limits around all the time.Instead, try this:Now you can write your processor as:
Python

I want to build a general tree whose root node contains 'n' children, and those children may contain other children.....A tree in Python is quite simple. Make a class that has data and a list of children. Each child is an instance of the same class. This is a general n-nary tree.Then interact:This is a very basic skeleton, not abstracted or anything. The actual code will depend on your specific needs - I'm just trying to show that this is very simple in Python.I've published a Python [3] tree implementation on my site: .Hope it is of use,Ok, here's the code:I recommend  has also a powerful API with:just to show another thought on implementation if you stick to the \"OOP\"
Python

I have written the following code, which should check if the entered number is a prime number or not, but there is an issue i couldn't get through:If the entered number is not a prime number, it displays \"not prime\", as it is supposed to, but if the number is a prime number, it doesn't display anything. Could you please help me with it?There are many efficient ways to test primality (and this isn't one of them). But the loop you wrote can be concisely represented in Python:That is, a is prime if all numbers between 2 and a (not inclusive) give non-zero remainder when divided into a.I don't actually think the best solution has been found in these answers, so I'm gonna post mine, and explain why this is a better one:: the  check is needed since that , and so is zero and any negative number.I'm gonna give you some insides about that almost esoteric single line of code that will check for prime numbers:I'm including an \"unpacked\" version of the  function, to make it easier to understand and read it:This is the most efficient way to see if a number is prime, if you only have a few query. If you ask a lot of numbers if they are prime try .If  is a prime then the  in your code will run forever, since  will remain .So why is that  there?I think you wanted to end the for loop when you found a factor, but didn't know how, so you added that while since it has a condition. So here is how you do it:it worked with me just fine :D
Python

Given a listhow can I getThat is, produce a new list in which each successive element is alternately taken from the two sides of the original list?\nThis code picks numbers from the beginning () and from the end () of , alternatingly (). A total of  numbers are picked, so this produces no ill effects even if  is odd.\n yields ,\n yields ,\nand  alternates between  and ,\nso the indices we extract from  are: .\nThe nice thing about this one-liner is that it's short and shows symmetry ( and ).\n\nOne might think that  were the same as  with the sign flipped.  of the result instead of truncating towards zero. So .\nAlso, I find accessing list elements by index less pythonic than iteration. between getting items from the forward  and the  one. Just make sure you stop at  with .This can easily be put into a single line but then it becomes much more difficult to read:Putting it in one line would also prevent you from using the other half of the iterators if you wanted to:A very nice one-liner in Python 2.7:First you zip the list with its reverse, take  that list, sum the tuples to form one tuple, and  convert to list. In Python 3,  returns a generator, so you have have to use  from :: It appears this only works perfectly for even-list lengths - odd-list lengths will omit the middle element :( A small correction for  to  will give you a duplicate middle value, so be warned. You can just  back and forth:Note: This destroys the original list, .Not terribly different from some of the other answers, but it avoids a conditional expression for determining the sign of the index. alternates between 0 and 1. This causes the exponent to alternate between 1 and -1.  causes the index divisor to alternate between 2 and -2, which causes the index to alternate from end to end as  increases. The sequence is , , , , , , etc.(I iterate  over  since in this case each value of  is equal to its index. In general, iterate over .)The basic principle behind your question is a so-called roundrobin algorithm. The  contains a possible implementation of it:so all you have to do is split your list into two sublists one starting from the left end and one from the right end:alternatively you could create a longer list (containing alternating items from sequence going from left to right and the items of the complete sequence going right to left) and only take the relevant elements:or using it as explicit generator with :or the  suggested by @Tadhg McDonald-Jensen (thank you!):Not sure, whether this can be written more compactly, but it is efficient as it only uses iterators / generatorsFor fun, here is an itertools variant:This works where  is even.  It would need a special code for odd-lengthened input.Enjoy!Not at all elegant, but it is a clumsy one-liner: If that breaks, then this breaks (it drops the middle term). Note that I got some of the idea from .Use the right .First, I tried something similar to Raymond Hettinger's solution with itertools (Python 3).One way to do this for even-sized lists (inspired by ):I would do something like thisTwo versions not seen yet:andYou can partition the list into two parts about the middle, reverse the second half and zip the two partitions, like so:Output:
Python

I am newbie in Python facing a problem: How to insert some fields in already existing string?For example, suppose I have read one line from any file which contains:Now I have to insert 3rd Field(Group) 3 times more in the same line before Class field. It means the output line should be: I can retrieve 3rd field easily (using  method), but please let me know the easiest way of inserting into the string?An important point that often bites new Python programmers but the other posters haven't made explicit is that strings in Python are immutable -- you can't  modify them in place. You need to retrain yourself when working with strings in Python so that instead of thinking, \"How can I modify this string?\" instead you're thinking \"how can I create a new string that has some pieces from this one I've already gotten?\"For the sake of future 'newbies' tackling this problem, I think a quick answer would be fitting to this thread.Like  said: Python strings are immutable, and so, in order to modify a string you have to make use of the pieces you already have.In the following example I insert  in to , to create In the example above, I used the index value to 'slice' the string in to 2 substrings:\n1 containing the substring before the insertion index, and the other containing the rest.\nThen I simply add the desired string between the two and voil\u00e0, we have inserted a string inside another. has a great answer explaining the subject of string slicing.I know it's malapropos, but IMHO easy way is:There are several ways to do this:One way is to use slicing:Another would be to use regular expressions:I had a similar problem for my DNA assignment and I used bgporter's advice to answer it. Here is my function which creates a new string...
Python

If only timedelta had a month argument in it's constructor.  So what's the simplest way to do this? I wasn't thinking too hard about this as was pointed out below.  Really what I wanted was any day in the last month because eventually I'm going to grab the year and month only.  So given a datetime object, what's the simplest way to return ?Try this: Corrected to handle the day as well. See also the answer from puzzlement which points out a simpler calculation for :You can use the third party  module (PyPI entry ).output:After the original question's edit to \"any datetime object in the previous month\", you can do it pretty easily by subtracting 1 day from the first of the month.What do you want the result to be when you subtract a month from, say, a date that is March 30?  That is the problem with adding or subtracting months: months have different lengths!  In some application an exception is appropriate in such cases, in others \"the last day of the previous month\" is OK to use (but that's truly crazy arithmetic, when subtracting a month then adding a month is  overall a no-operation!), in others yet you'll want to keep in addition to the date some indication about the fact, e.g., \"I'm saying Feb 28 but I really would want Feb 30 if it existed\", so that adding or subtracting another month to that can set things right again (and the latter obviously requires a custom class holding a data plus s/thing else).There can be no real solution that is tolerable for all applications, and you have not told us what your specific app's needs are for the semantics of this wretched operation, so there's not much more help that we can provide here.A variation on  (I don't have sufficient reputation to comment), which uses calendar.monthrange to dramatically simplify the computation of the last day of the month:Info on monthrange from If all you want is any day in the last month, the simplest thing you can do is subtract the number of days from the current date, which will give you the last day of the previous month.For instance, starting with any date:Subtracting the days of the current date we get:This is enough for your simplified need of any day in the last month.But now that you have it, you can also get any day in the month, including the same day you started with (i.e. more or less the same as subtracting a month):Of course, you need to be careful with 31st on a 30 day month or the days missing from February (and take care of leap years), but that's also easy to do:Here is some  to do just that. Haven't tried it out myself...Given a (year,month) tuple, where month goes from 1-12, try this:Assumes there are 12 months in every year.I Used the following code to go back n Months from a specific Date:For eg:\ninput date = 28/12/2015\nCalculate 6 months previous date.I) CALCULATE MONTH: \nThis step will give you the start_date as 30/06/2015.\n that after the calculate month step you will get the last day of the required month.II)CALCULATE DAY:\nCondition   checks whether the day from input_date is present in the required month. This handles condition where input date is 31(or 30) and the required month has less than 31(or 30 in case of feb) days. It handles leap year case as well(For Feb). After this step you will get result as 28/06/2015If this condition is not satisfied, the start_date remains the last date of the previous month. So if you give 31/12/2015 as input date and want 6 months previous date, it will give you 30/06/2015
Python

I'm not asking for the  command.I want to create an application that works similarly to heidisql, where you can specify an SQL query and when executed, returns a result set with rows and columns representing your query result. The column names in the result set should match your selected columns as defined in your SQL query.In my Python program (using ) my query returns only the row and column results, but not the column names.  In the following example the column names would be , , and .  The SQL would eventually be external from the program. The only way I can figure to make this work, is to write my own SQL parser logic to extract the selected column names.Is there an easy way to get the column names for the provided SQL?\nNext I'll need to know how many columns does the query return?cursor.description will give you a tuple of tuples where [0] for each is the column header.This is the same as thefreeman but more in pythonic way using list and dictionary comprehension Similar to @James answer, a more pythonic way can be:You can get a single column with map over the result:or filter results:or accumulate values for filtered columns:I think this should do what you need (builds on the answer above) .  I am sure theres a more pythony way to write it, but you should get the general idea.Looks like MySQLdb doesn't actually provide a translation for that API call.  The relevant C API call is , and You could also use . This turns your result set into a python list of python dictionaries, although it uses a special cursor, thus technically less portable than the accepted answer. Not sure about speed. Here's the edited original code that uses this.Standard dictionary functions apply, for example,  to count the number of columns for the first row,  for a list of column names (for the first row), etc. Hope this helps!
Python

If I use MySQLdb to connect to MySQL-Server through python. I create a connection and a cursor like thisWhen the MySQL-processing is done one should close the connection. Now I was wondering: Is it sufficient to close the connection bydoingor do I have to close the cursor first and then the connection? Like this:Think less.  Use tools more.Closing the cursor as soon as you are done with it is probably the best bet, since you have no use for it anymore. However, I haven't seen anything where it's harmful to close it after the db connection. But since you can set it as:I recommend closing it before, in case you accidentally assign it again and the DB connection is closed as this would throw an error. So you may want to close it  in order to prevent an accidental reassignment with a closed connection.(Some don't even close it at all though as it gets collected by the garbage collector (see:))References:\nClosing a connection should be good enough here in this particular context.\nIf you are working with multiple cursors etc. you need to care about proper resource management.
Python

I came across these 2 papers which combined collaborative filtering (Matrix factorization) and Topic modelling (LDA) to recommend users similar articles/posts based on topic terms of post/articles that users are interested in. The papers (in PDF) are:\n\"\" and\n\"\"The new algorithm is called . I was hoping to find some python code that implemented this but to no avail. This might be a long shot but can someone show a simple python example?A very simple LDA implementation using gensin. \nYou can find more informations here: I hope it can help you[(0, u'0.066*animal + 0.065*, + 0.047*product + 0.028*philosophy'), (1, u'0.085*. + 0.047*product + 0.028*dietary + 0.028*veg')]This should get you started (although not sure why this hasn't been posted yet): More specifically: Looks nice and straightforward. I still suggest at least looking at . Radim has done a fantastic job of optimizing that software very well.As you have tagged  and , did you take a look at python  &  modules, because with both of them you Also there is a code example relative to  (with Non-negative Matrix Factorization and Latent Dirichlet Allocation)  which may fit  your exact needs and also help you to discover sklearn moduleRegards
Python

Given this initial graph:Can anyone recreate this error?The problem has something to do with the call to graphviz's agedge function, it seems to not like the format of the  parameter; when I change (line 480 of ):toit no longer fails (but loses the key labels). (so that  parameter values are retained) - Nothing I try seems to work.From , it appears that the  agedge function (which I can't see as it's in a .pyd binary) has the following format:where the  is the key.I cannot work out why it won't accept a  dtype as in the initial error.Note versions:networkx - 1.11,\npygraphviz - 1.3.1\n (installed from )\nPython 2.7 (32bit - isntalled via python(x,y)) on Windows 7 (64-bit), GraphViz - 2.38 I have also seen this issue crop up in these questions:I have tried adjusting the  input to the agedge function to a number of variants of char arrays (e.g.  (ct is ctypes module) based on ). This changes the error to:I can get it to run (but not return a multigraph) if I do this:In  replacing the linewithI don't know why just casting to a string  does not work.Found the function here - The source of the error is within  pygraphviz file, graphviz_wrap.c, line 3921:Or, it's within , graphviz.i, line 68. Either way, it seems like the error string \"agedge: no key\" is returned if  fails for any reason... Perhaps it's something to do with SWIG.Try changing the variable name from \"key\" to something else like \"temp_key\".  I mean that it is possible that you (or any previously imported module) has declared a non-string type \"key\" variable before...? Apparently if running :fails but running:give you no issue, it could only be relative to the \"key\" variable type.. did you try this: or\nIntegrate str()/unicode() in your orginal code give:both (str & unicode version) works fine on Linux.Best regardsMy environment is python2.7 32 bit on Windows 7 64-bit and I am doing a project that uses the pygraphviz/graphviz to draw a FSM. During use I also came across the same errorThis project has a closed issue that states that the error only shows up when you have transitions where the source state is the same as the destination state. Or in simpler terms when a state points to itself.I can confirm that I get error when there are states pointing to themselves, while if I create a graph that doesn't have any such transitions it works and produces an image file (.png) correctly in my case.P.S. I don't think this warrants a full answer because it is not a complete solution. But unfortunately I don't have enough reputation points to comment.
Python

 I learned that the behavior on  was dependent on the  in use by matplotlib.  At that time I was looking for a way to keep  from deleting the drawing elements of a figure, concluding that by switching from Qt4Agg to TkAgg, the drawing elements would be preserved even if the figures were closed.  I would like to increase my superpowers by learning, if possible, how to configure the Qt4agg backend to behave as desired.Instead of trying to exercise extra control over the backend, just create the figures and keep references to them yourself, as shown in the highest-rated answer to your first question. The problem with trying to manipulate the backend, as you are asking to do here, is that the backend is not  to hand your figures back to you intact once you have looked at them; that's not normally the backend's job. See:\n
Python

I know how to compile CPython file to exe using cx_freeze but is it possible to compile a simple program using PyPy to Exe ?There is no ready-made way or tutorial on how to do create an EXE from a program using the PyPy interpreter, as far as i know.  And it's not exactly trivial to get things going, i am afraid.In principle, there are two ways to consider for using PyPy's translations to get a EXE file, either using the PyPy interpreter or writing your own RPython program (The PyPy interpreter is itself an RPython program, i.e. using a restricted subset of Python).If you program uses a restricted subset of RPython and no dependencies, you could look into using the translate script in  where you'll also find a lot of target*.py files.  Take one and modify it for your purposes. You might first want to play with translating python functions starting from here:If you program is an application and depends on external packages, you should first try to make sure that your program works on pypy at all - not all external libraries are supported.  You might then look into modifying the targetpypystandalone script to load your application modules.  If in doubt, try to get some help on the pypy-dev mailing list or the #pypy channel on irc.freenode.net.This is a py2exe solution that might work for you: 
Python

I need to open a file for reading and writing. If the file is not found, it should be created. It should also be treated as a binary for Windows. Can you tell me the file mode sequence I need to use for this?I tried 'r+ab' but that doesn't create the files if they are not found.ThanksThe mode is  the  is implied and 'a'ppend and ('w'rite '+' 'r'ead) are redundant. Since the CPython (i.e. regular python)  is based on the C stdio  type, here are the relevant lines from the fopen(3) man page:With the \"b\" tacked on to make DOS happy. Presumably you want to do something like this:should work. It opens a binary file in append/update mode.
Python

I have two classes A and B and A is base class of B.I read that all methods in Python are virtual. So how do I call a method of the base because when I try to call it, the method of the derived class is called as expected?Using :Two ways:
Python

What happened is that I (by mistake) saved a dictionary with the command  (no error messages shown) and now I need to recover the data in the dictionary. When I load it with  it has type () and is 0-d, so it is not a dictionary any more and I can't access the data in it, 0-d arrays are not index-able so doing something like doesn't work. I also triedbut that didn't work either.Why numpy didn't warn me when I saved the dictionary with ?Is there a way to recover the data?Thanks in advance!Use  to obtain the array element as a Python scalar.0-d arrays can be indexed using the empty tuple:
Python

I need to search an ObjectId with python using pymongo but I always get this error. Any ideas how to search? I use pymongo 2.4.1.
Python

In development, it's a bit of a hassle to run the  as well as the Django development server. Is it possible to, for example, ask  to run tasks synchronously during development? Or something similar?Yes you can do this by setting  in your settings.\nThere's also a custom Django test runner in django-celery that helps with CELERY_ALWAYS_EAGER.\nRead more about using Celery with Django on .In version  of Celery  setting was replaced by  in Django  or  natively in .Since the numerous changes in the celery configuration from version 3.x to 4.x are spread over many lines, I suggest to use the built-in settings migration tool.source:
Python

I am attempting to put together a simple c++ test project that uses python 3.2. The project builds fine but Py_Initialize raises a fatal error:The OS is 32bit Vista.The python version used is a python 3.2 debug build, built from sources using VC++ 10.The python_d.exe file from the same build runs without any problems.Could someone explain the problem and how to fix it? My own google-fu fails me.[EDIT]After going through the python source code I've found that, as the error says, no codec search functions have been registered. Both  and  are as they should be. It's just that nowhere in the code are any of these functions called.I don't really know what this means as I still have no idea when and from where these functions should have been called. The code that raises the error is entirely missing from the source of my other python build (3.1.3).[EDIT]Answered my own question below.Check PYTHONPATH and PYTHONHOME system variable and make sure it doesn't points to Python 2.xParts of this have been mentioned before, but in a nutshell this is what worked for my environment where I have multiple Python installs and my global OS environment set-up to point to a  install than the one I attempt to work with when encountering the problem.Make sure your (local or global) environment is  set-up to point to the install you aim to work with, e.g. you have two (or more) installs of, let's say a python27 and python33 (sorry these are windows paths but the following should be valid for equivalent UNIX-style paths just as well, please let me know about anything I'm missing here (probably the DLLs path might differ)):Now, if you intend to work with your python33 install but your global environment is pointing to python27, make sure you update your environment as such (while  and   be optional (e.g. if you temporarily work in a local shell)):Note, that you might need/want to append any other library paths to your  if required by your development environment, but having your ,  and  properly set-up is of prime importance.Hope this helps.So, for some reason the python dll fails to locate the encodings module. The python.exe executable apparently finds it because it has the expected relative path. Modifying the search path works.The reason for all of this? Don't know but at least it works. I highly suspect a typo on my part somewhere, that's usually the reason for odd bugs it seems.I just ran into the exact same problem (same Python version, OS, code, etc).You just have to copy Python's Lib/ directory in your program's working directory ( on VC it's the directory where the .vcproj is )There appears to be something going wrong with the release build either failing to include the appropriate codecs or else misidentifying the codec to use for system APIs. Since the  executable is working, what does that return for ? (Use the C API to call that between your Initialize/Finalize calls)From python3k, the startup need the encodings module, which can be found in PYTHONHOME\\Lib directory. \nIn fact, the  do the init and import the encodings module.\nMake sure PYTHONHOME\\Lib is in sys.path and check the encodings module is there.I had this issue with python 3.5, anaconda 3, windows 7 32 bit. I solved it by moving my pythonX.lib and pythonX.dll files into my working directory and calling before initialize so that it could find the headers that it needed, where my path was to \"...\\Anaconda3\\\". The extra step of calling Py_SetPythonHome was required for me or else I'd end up getting other strange errors where python import files.
Python

Comparing boolean values with  works in Python. But when I apply the boolean  operator, the result is a syntax error:Why is this a syntax error? I would expect  to be an expression that returns a boolean value, and  to be valid syntax wherever  is an expression with valid syntax.It has to do with  (the interpreter thinks you're comparing True to not, since  has a higher precedence than ). You need some parentheses to clarify the order of operations:In general, you can't use  on the right side of a comparison without parentheses. However, I can't think of a situation in which you'd ever need to use a  on the right side of a comparison.It's just a matter of operator precedence.Try:Have a look in , you'll find that  binds tigher than , and thus  is parsed as  which is clearly an error.I think what you are looking for is \"and not\".  This gives you the results you are looking towards.  If your comparing booleans what you have is a compound boolean expression, here is an example website .  
Python

I'd like to be able to do something like this:Other module(s):But I don't know how to reference a modules variable from a function defined in the module.Is this possible? Or am I going to need to put a global declaration in every place I wan't to use this.\nOr am I going at this completely wrong?Just change Global variables are read-only from sibling methods. More accurately unless a variable is specified as global, Python consider it as local, but a read access to a local variable name will reach module-level scope if the name is not present in local scope.See also  and the  for more details about the  statementYou seem to mostly have it. You are missing only the fact that \"module-level\" variables are called global in Python. (They are not truly global, but only global to the module they are declared in, in other words.)In any function where you  a global variable (you want to make the name refer to a different object), it must be declared global. So your  function needs a  at the beginning. If you are only using the value of a global variable, or if it is a mutable type such as a list and you are modifying it, but not changing the object that the name points to, you needn't declare it global.The  statement is, as you have discovered, how you can import a module-level variable from one module into another.
Python

I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique.For example, say my input is:I would like my output to be:To clarify I would like my result to be the equivalent of the following:Any neat Pythonian way to achieve this?ThanksFrom Python 2.7 on, including 3.0+, there's an arguably shorter, more readable version:You could try:Beware that you cannot 'reverse' a dictionary ifSee  on the python mailing list for a discussion on the subject.You can make use of :or even better, but only works in Python 3:Suggestion for an improvement for Javier answer :Instead of  you can write just , because if you go through dictionary with an iterator, it will return the keys of the relevant dictionary.Ex. for this behavior : Another way to expand on 's response is to actually use the  function.In essence, your dictionary is iterated through (using ) where each item is a key/value pair, and those items are swapped with the  function. When this is passed to the  constructor, it turns them into value/key pairs which is what you want.If you're using Python3, it's slightly different:Using :- returns a list of tuples of .  goes through elements of the list and applies  to each its element (tuple) to reverse it, so each tuple becomes  in the new list spitted out of map. Finally,  makes a dict from the new list. Adding an in-place solution:In Python3, it is critical that you use  because  returns a  of the keys. If you are using Python2,  is enough.
Python

So I learned that I can use DataFrame.groupby without having a MultiIndex to do subsampling/cross-sections.On the other hand, when I have a MultiIndex on a DataFrame, I still need to use DataFrame.groupby to do sub-sampling/cross-sections.So what is a MultiIndex good for apart from the quite helpful and pretty display of the hierarchies when printing?Hierarchical indexing (also referred to as \u201cmulti-level\u201d indexing) was introduced in the pandas 0.4 release. This opens the door to some quite sophisticated data analysis and manipulation, especially for working with higher dimensional data. In essence, it enables you to effectively store and manipulate arbitrarily high dimension data in a 2-dimensional tabular structure (DataFrame), for example. Imagine constructing a dataframe using  like this:-This  is simply a data structure of two dimensions But we can imagine it, looking at the output, as a 3 dimensional data structure.A.k.a.: \"effectively store and manipulate arbitrarily high dimension data in a 2-dimensional tabular structure\"This is not just a \"pretty display\". It has the benefit of easy retrieval of data since we now have a hierarchal index.For example.will give us a new data frame only for the group of data belonging to \"one\".And we can narrow down our data selection further by doing this:-And of course, if we want a specific value, here's an example:-So if we have even more indexes (besides the 2 indexes shown in the example above), we can essentially drill down and select the data set we are really interested in without a need for .We can even grab a cross-section (either rows or columns) from our dataframe...By rows:-By columns:-
Python

I'm wondering what's the best way -- or if there's a simple way with the standard library -- to convert a URL with Unicode chars in the domain name and path to the equivalent ASCII URL, encoded with domain as IDNA and the path %-encoded, as per RFC 3986.I get from the user a URL in UTF-8. So if they've typed in  I get  in Python. And what I want out is the ASCII version: .What I do at the moment is split the URL up into parts via a regex, and then manually IDNA-encode the domain, and separately encode the path and query string with different  calls.Is this correct? Any better suggestions? Is there a simple standard-library function to do this?the code given by MizardX isnt 100% correct. This example wont work:example.com/folder/?page=2check out django.utils.encoding.iri_to_uri() to convert unicode URL to ASCII urls.there's some RFC-3896  work underway (e.g. as part of the Summer Of Code) but nothing in the standard library yet AFAIK -- and nothing much on the  side of things either, again AFAIK.  So you might as well go with MizardX's elegant approach.Okay, with these comments and some bug-fixing in my own code (it didn't handle fragments at all), I've come up with the following  function -- returns a canonical, ASCII form of the URL:You might use  instead, but otherwise you seem to have a very straightforward solution, there.(You can access the domain and port separately by accessing the returned value's named properties, but as port syntax is always in ASCII it is unaffected by the IDNA encoding process.)
Python

If I import a module defining a class of the same name belonging to a package, it is imported as a Class, not a Module because of the __init__.py of the parent package. See  for details. In Python shell or ipython shell, if I doMyModule is always imported as Class thus I can not reload it (reload() works only for modules). Run again does not seem to update the Class definition. Could anyone suggest a way to update the class in python shell? ps. without restarting the python interpreter. . Just in case you have the code in hand and want to test it: I am actually talking about BioPython, and I am working on Bio.PDB.PDBParser. I have an ipython shell (v0.10) and edit PDBParser.py. Just got no way to reload it in ipython.so here is what I did:I could not see the printed text. The changes were not applied somehow. On Python 3 only, import the  function:On both Python 2.x, and 3.x, you can then simply call  on the module:However, instances of the old class will not be updated (there's simply no code that describes the update mechanism).I finally found the answer:after editing  file, to reload the class  in the file , one needs to:I have one myfile.py file which contains one class MyClassTo import just do:To reload:This is very useful while building modules.\none can put these inside a function and just call the functionIt works for me using python 3.5.2:There are thee ways to solve this:Then you can write:and it works.You can use a magic function:
Python

I am trying to figure out how many times a string occurs in a string. For example:Say the string I want to find is 123. Obviously it occurs twice in nStr but I am having trouble implementing this logic into Python. What I have got at the moment:The answer it should return is 2. I'm stuck in an infinite loop at the moment.I was just made aware that count is a much better way to do it but out of curiosity, does anyone see a way to do it similar to what I have already got?Use :A working version of your code:The problem with  and these methods shown here is the case of overlapping substrings.For example:  returns 2If you want it to return 4 [] you might try something like this:Don't know if there's a better way of doing it, but posting just to clarify the way  works.We can say that the substring 'pattern' appears len(n) times in 'string'.string.count(substring) is not useful in case of overlapping.My approach:
Python

I've got a string, a signature, and a public key, and I want to verify the signature on the string. The key looks like this:I've been reading the pycrypto docs for a while, but I can't figure out how to make an RSAobj with this kind of key. If you know PHP, I'm trying to do the following:Also, if I'm confused about any terminology, please let me know.The data between the markers is the base64 encoding of the ASN.1 DER-encoding of a PKCS#8 PublicKeyInfo containing an PKCS#1 RSAPublicKey.That is a lot of standards, and you will be best served with using a crypto-library to decode it (such as M2Crypto as ). Treat the following as some fun info about the format:If you want to, you can decode it like this:Base64-decode the string:This is the DER-encoding of:For a 1024 bit RSA key, you can treat  as a constant header, followed by a 00-byte, followed by the 128 bytes of the RSA modulus. After that 95% of the time you will get , which signifies a RSA public exponent of 0x10001 = 65537.You can use those two values as  and  in a tuple to construct a RSAobj.Use . Here's how to verify for RSA and any other algorithm supported by OpenSSL:A public key contains both a modulus(very long number, can be 1024bit, 2058bit, 4096bit) and a public key exponent(much smaller number, usually equals one more than a two to some power). You need to find out how to split up that public key into the two components before you can do anything with it. I don't know much about pycrypto but to verify a signature, take the hash of the string. Now we must decrypt the signature. Read up on ; the formula to decrypt a signature is . The last step is to check if the hash you made and the decrypted signature you got are the same.Maybe this isn't the answer you're looking for, but if all you need is to turn the key into bits, it looks like it's Base64 encoded. Look at the  module (I think) in the standard Python library.  points out in the comments that  is hard-coded to use MD5, in which case ezPyCryto can't help Andrew unless he wades into its code. I defer to : consider .More on the DER decoding. DER encoding always follows a TLV triplet format: (Tag, Length, Value) Tag basically tells how to interpret the bytes data in the Value field. ANS.1 does have a type system, e.g. 0x02 means integer, 0x30 means sequence (an ordered collection of one or more other type instances) Length presentation has a special logic: For example, say I want to encode a number of 256 bytes long, then it would be like this Now looking at your example It interprets as just what Rasmus Faber put in his replyUsing M2Crypto, the above answers does not work. Here is a tested example.And that's about itI try the code given by joeforker but it does not work.\nHere is my example code and it works fine.
Python

I am trying to create a download progress bar in python using the urllib2 http client. I've looked through the API (and on google) and it seems that urllib2 does not allow you to register progress hooks. However the older deprecated urllib does have this functionality.Does anyone know how to create a progress bar or reporting hook using urllib2? Or are there some other hacks to get similar functionality?Here's a fully working example that builds on Anurag's approach of chunking in a response. My version allows you to set the the chunk size, and attach an arbitrary reporting function:Why not just read data in chunks and do whatever you want to do in between, e.g. run in a thread, hook into a UI, etc etc: has built-in support for progress notification.
Python

How do you store a password entered by the user in memory and erase it securely after it is no longer need?To elaborate, currently we have the following code:After calling the  method, what do we need to do to fill the area of memory that  contains password with garbled characters so that someone cannot recover the password by doing a core dump?There is a similar question, however it is in Java and the solution uses character arrays:\nCan this be done in Python?Python doesn't have that low of a level of control over memory.  Accept it, and move on.  The  you can do is to  after calling  so that no references to the password string object remain.  Any solution that purports to be able to do more than that is only giving you a false sense of security. Python string objects are immutable; there's no direct way to change the contents of a string after it is created.  you were able to somehow overwrite the contents of the string referred to by  (which is technically possible with stupid ctypes tricks), there would still be other copies of the password that have been created in various string operations:You would somehow have to get references to all of those strings and overwrite their memory as well.There actually -is- a way to securely erase strings in Python; use the memset C function, as per If you don't need the mail object to persist once you are done with it, I think your best bet is to perform the mailing work in a subprocess (see the  module.) That way, when the subprocess dies, so goes your password.This could be done using numpy chararray:You would have to determine the maximum size of password, but this should remove the data when it is overwritten.Store the password in a list, and if you just set the list to null, the memory of the array stored in the list is automatically freed.EDIT: removed the bad advice...You can also use arrays like the java example if you like, but just overwriting it should be enough.
Python

I created a module named  that provides classes and functions I often use in Python.\nSome of them need imported features. What are the pros and the cons of importing needed things inside class/function definition? Is it better than  at the beginning of a module file? Is it a good idea?It's the most common style to put  import at the top of the file. PEP 8 recommends it, which is a good reason to do it to start with. But that's not a whim, it has advantages (although not critical enough to make everything else a crime). It allows finding all imports at a glance, as opposed to looking through the whole file. It also ensures everything is imported before any other code (which may depend on some imports) is executed. s are usually easy to resolve, but they can be annoying.There's no (significant) namespace pollution to be avoided by keeping the module in a smaller scope, since all you add is the actual module (). Inside functions, you'd import again on every call (not really harmful since everything is imported once, but uncalled for)., the Python style guide, states that:Of course this is no hard and fast rule, and imports can go anywhere you want them to. But putting them at the top is the best way to go about it. You can of course import within functions or a class.But note you cannot do this:Because:I believe that it's best practice (according to some PEP's) that you keep import statements at the beginning of a module. You can add import statements to an  file, which will import those module to all modules inside the package.So...it's certainly something you can do the way you're doing it, but it's discouraged and actually unnecessary.While the other answers are mostly right, there is a reason why python allows this.It is not smart to import redundant stuff which isn\u2019t needed. So, if you want to e.g. parse XML into an element tree, but don\u2019t want to use the slow builtin XML parser if lxml is available, you would need to check this the moment you need to invoke the parser.And instead of memorizing the availability of lxml at the beginning, I would prefer to  importing and using ,  it\u2019s not there, in which case I\u2019d fallback to the builtin  module.Like flying sheep's answer, I agree that the others are right, but I put imports in other places like in  routines and function calls when I am DEVELOPING code. After my class or function has been tested and proven to work with the import inside of it, I normally give it its own module with the import following PEP8 guidelines. I do this because sometimes I forget to delete imports after refactoring code or removing old code with bad ideas. By keeping the imports inside the class or function under development, I am specifying its dependencies should I want to copy it elsewhere or promote it to its own module...Only move imports into a local scope, such as inside a function definition, if it\u2019s necessary to solve a problem such as avoiding a circular import or are trying to reduce the initialization time of a module. This technique is especially helpful if many of the imports are unnecessary depending on how the program executes. You may also want to move imports into a function if the modules are only ever used in that function. Note that loading a module the first time may be expensive because of the one time initialization of the module, but loading a module multiple times is virtually free, costing only a couple of dictionary lookups. Even if the module name has gone out of scope, the module is probably available in sys.modules.
Python

I have a Django model with a start and end date range. I want to enforce validation so that no two records have overlapping date ranges. What's the simplest way to implement this so that I don't have to repeat myself writing this logic?e.g. I don't want to re-implement this logic in a Form  a   an admin form  the model's overridden .As far as I know, Django doesn't make it easy to globally enforce these types of criteria. Googling hasn't been very helpful, since \"model validation\" typically refers to validating specific model fields, and not the entire model contents, or relations between fields.The basic pattern I've found useful is to put all my custom validation in  and then simply call  (which calls  and a few other methods) from inside , e.g.:This isn't done by default, as explained , because it interferes with certain features, but those aren't a problem for my application.I would override the  method on the model. To make sure you ignore the current object when validating, you can use the following: will automatically call this for you through a , which you can use manually too.PPR has a nice discussion of a simple, correct .I think you should use this:\nJust define clean() method in your model like this: (example from the docs link)
Python

I have this simple model of Author - Books and can't find a way to make firstName and lastName a composite key and use it in relation. Any ideas?The problem is that you have defined each of the dependent columns as foreign keys separately, when that's not really what you intend, you of course want a composite foreign key.  Sqlalchemy is responding to this by saying (in a not very clear way), that it cannot guess which foreign key to use ( or ).  The solution, declaring a composite foreign key, is a tad clunky in declarative, but still fairly obvious:The important thing here is that the  definitions are gone from the individual columns, and a  is added to a  class variable.  With this, the  defined on  works just right.
Python

What are the differences in performance and behavior between using Python's native  function and NumPy's ?  works on NumPy's arrays and  works on Python lists and they both return the same effective result (haven't tested edge cases such as overflow) but different types. I think my practical question here is would using  on a list of Python integers be any faster than using Python's own ?Additionally, what are the implications (including performance) of using a Python integer versus a scalar ? For example, for , is there a behavior or performance difference if the type of  is a Python integer or a ? I am curious if it is faster to use a NumPy scalar datatype such as  for a value that is added or subtracted a lot in Python code.For clarification, I am working on a bioinformatics simulation which partly consists of collapsing multidimensional s into single scalar sums which are then additionally processed. I am using Python 3.2 and NumPy 1.6.Thanks in advance!I got curious and timed it.  seems much faster for numpy arrays, but much slower on lists.Result when :Result when :I am using Python 2.7.2 and Numpy 1.6.1Numpy should be much faster, especially when your data is already a numpy array.Numpy arrays are a thin layer over a standard C array. When numpy sum iterates over this, it isn't doing type checking and it is very fast. The speed should be comparable to doing the operation using standard C. In comparison, using python's sum it has to first convert the numpy array to a python array, and then iterate over that array. It has to do some type checking and is generally going to be slower.The exact amount that python sum is slower than numpy sum is not well defined as the python sum is going to be a somewhat optimized function as compared to writing your own sum function in python.Note that Python sum on multidimensional numpy arrays will only perform a sum along the first axis:This is an extension to the the . From that answer you can see that  performs faster for  objects, whereas  performs faster for  objects. To expand upon that:On running  for an  object   for a  object, it seems that they perform neck to neck. Above,  is a  bit faster than , although, at times I've seen   timings to be , too. But mostly, it's . 
Python

I am trying to convert time-stamps of the format \"2012-07-24T23:14:29-07:00\" \nto datetime objects in python using strptime method. The problem is with the time offset at the end(-07:00). Without the offset i can successfully doBut with the offset i triedBut it gives a Value error saying \"z\" is a bad directive.Any ideas for a work around?The Python 2  function indeed does not support the  format for timezones (because the underlying  doesn't support it). You have two options:Quick demo on the command prompt:You could also upgrade to Python 3.2 or newer, where timezone support has been improved to the point that  would work, provided you remove the last  from the input, and the  from before the :In Python 3.2+:Note: it doesn't support  in the  part (both formats are allowed by ). See .On older Python versions such as Python 2.7, you could parse the utc offset manually:where .(note: I have to stick to python 2.7 in my case)I have had a similar problem parsing commit dates from the output of  which actually isn't the ISO8601 format (hence the addition of  in a later version).Since I am using  I can leverage the utilities there.Instead of  you could use your own regular expression.
Python

I would like to zoom a portion of data/image and plot it inside the same figure. It looks something like this figure.Is it possible to insert a portion of zoomed image inside the same plot. I think it is possible to draw another figure with subplot but it draws two different figures. I also read to add patch to insert rectangle/circle but not sure if it is useful to insert a portion of image into the figure. I basically load data from the text file and plot it using a simple plot commands shown below. I found one related example from matplotlib image gallery  but not sure how it works. Your help is much appreciated.Playing with runnable code is one of the\nfastest ways to learn Python.So let's start with the .Given the comments in the code, it appears the code is broken up into 4 main stanzas.\nThe first stanza generates some data, the second stanza generates the main plot,\nthe third and fourth stanzas create the inset axes.We know how to generate data and plot the main plot, so let's focus on the third stanza:Copy the example code into a new file, called, say, .What happens if we change the  to ?Run the script:You'll find the \"Probability\" inset moved to the left.\nSo the  function controls the placement of the inset.\nIf you play some more with the numbers you'll figure out that (.35, .6) is the\nlocation of the lower left corner of the inset, and (.2, .2) is the width and\nheight of the inset. The numbers go from 0 to 1 and (0,0) is the located at the\nlower left corner of the figure.Okay, now we're cooking. On to the next line we have:You might recognize this as the , but\nif not, changing the number 400 to, say, 10, will produce an image with a much\nchunkier histogram, so again by playing with the numbers you'll soon figure out\nthat this line has something to do with the image inside the inset.You'll want to call  here.The line \nobviously generates the text above the inset.Finally we come to . There are no numbers to play with,\nso what happens if we just comment out the whole line by placing a  at the beginning of the line:Rerun the script. Oh! now there are lots of tick marks and tick labels on the inset axes.\nFine. So now we know that  removes the tick marks and labels from the axes .Now, in theory you have enough information to apply this code to your problem.\nBut there is one more potential stumbling block: The matplotlib example uses\n\nwhereas you use . says \nis the recommended way to use matplotlib when writing scripts, while \n is for use in interactive sessions. So you are doing it the right way, (though I would recommend using  instead of  too).So how do we convert the matplotlib example to run with ?Doing the conversion takes some experience with matplotlib. Generally, you just\nadd  in front of bare names like  and , but sometimes the\nfunction come from numpy, and sometimes the call should come from an axes\nobject, not from the module . It takes experience to know where all these\nfunctions come from. Googling the names of functions along with \"matplotlib\" can help.\nReading example code can builds experience, but there is no easy shortcut. So, the converted code becomesAnd you could use it in your code like this:The simplest way is to combine \"zoomed_inset_axes\" and \"mark_inset\", whose description and \nrelated examples could be found here:\nThe nicest way I know of to do this is to use mpl_toolkits.axes_grid1.inset_locator (part of matplotlib).There is a great example with source code here: .
Python

In python classes, the @property is a nice decorator that avoids using explicit setter and getter functions. However, it comes at a cost of an overhead 2-5 times that of a \"classical\" class function. In my case, this is quite OK in the case of setting a property, where the overhead is insignificant compared to the processing that needs to be done when setting. However, I need no processing when getting the property. It is always just \"return self.property\". Is there an elegant way to use the setter but not using the getter, without needing to use a different internal variable?Just to illustrate, the class below has the property \"var\" which refers to the internal variable \"_var\". It takes longer to call \"var\" than \"_var\" but it would be nice if developers and users alike could just use \"var\" without having to keep track of \"_var\" too.For those interested, on my pc calling \"var\" takes 204 ns on average while calling \"_var\" takes 44 ns on average.Don't use a  in this case. A  object is a data descriptor, which means that any access to  will invoke that descriptor and Python will never look for an attribute on the instance itself.You have two options: use the  hook or build a descriptor that only implements .Now normal attribute lookups are used when   but when assigning to  the  method is invoked instead, letting you intercept  and adjust it as needed.Demo:A setter descriptor would only intercept variable assignment:Note how we need to assign to the instance  attribute to prevent invoking the setter again.Demo: python docs: output:
Python

There are several ways to iterate over a result set. What are the tradeoff of each?The canonical way is to use the built-in cursor iterator.You can use  to get all rows at once.It can be convenient to use this to create a Python list containing the values returned:This can be useful for smaller result sets, but can have bad side effects if the result set is large.If you know there's a single row being returned in the result set you can call  to get the single row.Finally, you can loop over the result set fetching one row at a time.  In general, there's no particular advantage in doing this over using the iterator.My preferred way is the cursor iterator, but setting first the arraysize property of the cursor. In this example, cx_Oracle will fetch rows from Oracle 256 rows at a time, reducing the number of network round trips that need to be performedThere's also the way  seems to do it... From what I gather, it seems to create dictionary-like row-proxies to map key lookup into the memory block returned by the query. In that case, fetching the whole answer and working with a similar proxy-factory over the rows seems like useful idea. Come to think of it though, it feels more like Lua than Python.Also, this should be applicable to all  interfaces, not just Oracle, or did you mean just  using ?
Python

I have a problem which requires a reversable 1:1 mapping of keys to values. That means sometimes I want to find the value given a key, but at other times I want to find the key given the value. Both keys and values are guaranteed unique. The obvious solution is to simply invert the dictionary every time I want a reverse-lookup: Inverting a dictionary is very easy, .The other alternative is to make a new class which unites two dictionaries, one for each kind of lookup. That would most likely be fast but would use up twice as much memory as a single dict. So is there a better structure I can use?Not really. Have you measured that? Since both dictionaries would use references to the  as keys and values, then the memory spent would be just the dictionary structure. That's a lot less than  and is a fixed ammount regardless of your data size.What I mean is that the actual data wouldn't be copied. So you'd spend little extra memory.Example:Only a single copy of the \"really big\" string exists, so you end up spending just a little more memory. That's generally affordable.I can't imagine a solution where you'd have the key lookup speed when looking by value, if you don't spend  enough memory to store a reverse lookup hash table (which is exactly what's being done in your \"unite two s\" solution).Not really, since they would just be holding two references to the same data. In my mind, this is not a bad solution. Have you considered an in-memory database lookup? I am not sure how it will compare in speed, but lookups in relational databases can be  fast.Here is my own solution to this problem: The goal is to make it as transparent to the user as possible. The only introduced significant attribute is . subclasses from  - I know that , but I think I have the common use cases covered. The backend is pretty simple, it () keeps a weakref to a 'partner'  () which is its inverse. When  is modified  is updated accordingly as well and vice versa.From the docstring:When I get some free time, I intend to make a version that doesn't store things twice. No clue when that'll be though :)Assuming that you have a key with which you look up a more complex mutable object, just make the key a property of that object. It does seem you might be better off thinking about the data model a bit.\"We can guarantee that either the key or the value (or both) will be an integer\"That's weirdly written -- \"key or the value (or both)\" doesn't feel right.  Either they're all integers, or they're not all integers.    It sounds like they're all integers.Or, it sounds like you're thinking of replacing the target object with an integer value so you only have one copy referenced by an integer.  This is a false economy.  Just keep the target object.  All Python objects are -- in effect -- references.  Very little actual copying gets done.Let's pretend that you simply have two integers and can do a lookup on either one of the pair.  One way to do this is to use heap queues or the bisect module to maintain ordered lists of integer key-value tuples.See See You have one heapq  tuples.  Or, if your underlying object is more complex, the ) tuples.You have another heapq  tuples.  Or, if your underlying object is more complex,  tuples.An \"insert\" becomes two inserts, one to each heapq-structured list.A key lookup is in one queue; a value lookup is in the other queue.  Do the lookups using .  How about using sqlite? Just create a :memory: database with a two-column table. You can even add indexes, then query by either one. Wrap it in a class if it's something you're going to use a lot. It so happens that I find myself asking this question all the time (yesterday in particular).  I agree with the approach of making two dictionaries.  Do some benchmarking to see how much memory it's taking.  I've never needed to make it mutable, but here's how I abstract it, if it's of any use:
Python

In my application I encountered the following and was surprised by the results: (both integers).what does this means?For the actual values, i.e. , the result is roughly .Your result using integer division is being rounded down toward the more negative value of . (This is also known as \"Floor division\")This is why you will get the somewhat perplexing answers of: This is \"fixed\" in Python 3, where the result of  would be . So if you have no reason to be using Python 2, you should upgrade. ;)In Python 3, if you still want integer division, you can use the  operator. This will give you the same answer as  would in Python 2.Here's a Python Enhancement Proposal on the subject: to have python automatically convert integer division to float, you can use:now:this feature is not in the standard python 2 not to break existing code that relied on integer division.\nHowever, this is the default behavior for python 3.Python always does the \"floor division\" for both negative numbers division and positive numbers division.That isBut sometime we need 1/-10 to be 0I figure out it can be done by using the float division first then cast result to int, e.g.That works fine for me, no need to import the future division or upgrade to Python 3Hope it can help you~When both values are integers when dividing Python uses Floor division.In python,  operator is for integer division. You can look at it as float division followed by a  operation.For example,  
Python

Is try-catch the only method to do that?If  is your deque, useThis will implicitly convert  to a , which yields  if the deque contains any items and  if it is empty.
Python

I am using PyDev for development and unit-testing of my Python application.\nAs for unit-testing, everything works great behalf the fact that content logged to any logging. Logger is not captured by the \"Captured output\" of PyDev.I already forward everything logged to the standard output like this:Nevertheless the \"Captured output\" does not display stuff logged to loggers.Here an example unittest-script: \nThe console output is:But the  for the test is:Does anybody knows how to capture everything is logged to a  during the execution of this test?The issue is that the  runner replaces / before the testing starts, and the  is still writing to the original . If you assign the 'current'  to the handler, it should work (see the code below).Although, a better approach would be adding/removing the handler during the test:I grew tired of having to manually add  to all s, so I subclassed  with some ing:Now your test case can simply inherit from , i.e.  instead of  and you're done. Alternatively, you can add the  line and define the  either in the test or a slightly modified .I'd suggest using a LogCapture and testing that you really are logging what you expect to be logging:I came across this problem also. I ended up subclassing StreamHandler, and overriding the stream attribute with a property that gets sys.stdout. That way, the handler will use the stream that the unittest.TestCase has swapped into sys.stdout:You can then setup the logging handler before running tests like so (this will add the custom handler to the root logger):If, like me, you have your tests in separate modules, you can just put a line after the imports of each unit test module that will make sure the logging is setup before tests are run:This might not be the cleanest approach, but it's pretty simple and worked well for me.
Python

I'm currently using hbase with my Python apps and wanted to try out Amazon . Is there a way to use Python to read, write and query data?You can use boto: docs: api reference: Another alternative is . PynamoDB provides an ORM like interface to DynamoDB and supports  Python 2 and Python 3. The entire DynamoDB API is supported by PynamoDB - including global and local secondary indexes, batch operations, binary attributes, queries, scans, etc. Disclaimer: I wrote PynamoDB.Disclaimer: I'm the current maintainerYou can use  Python library. It's a simple/tiny abstraction layer that allows you to . It also features a transaction engine.For advanced tasks such as table management it is still better to directly use  (which we rely on, anyway).
Python

I have a root-ish directory containing multiple subdirectories, all of which contain a file name data.txt. What I would like to do is write a script that takes in the \"root\" directory, and then reads through all of the subdirectories and reads every \"data.txt\" in the subdirectories, and then writes stuff from every data.txt file to an output file.Here's a snippet of my code:My dosomething() part -- I've tested and confirmed for it to work if I am running that part just for one file. I've also confirmed that if I tell it to print the file instead (the commented out line) the script prints out 'data.txt'.Right now if I run it Python gives me this error: I'm not sure why it can't find it -- after all, it prints out data.txt if I uncomment the 'print file' line. What am I doing incorrectly?You need to use absolute paths, your  variable is just a local filename without a directory path. The  variable is that path:
Python

Is it possible to embed rendered HTML output into iPython output?One way is to useor (IPython multiline cell alias)Which return a formatted link, butHow can I overcome thes shortcomings and make iPython output a bit more interactive?This seems to work for me:The trick is to wrap it in \"display\" as well.Source: 
Python

I'm trying to get gettext to work in Django on my OSX LeopardIn Terminal I get the same error, unless I put this in my bash profile:But then I get this error:After installing, try linking gettext. This solved the problem for me.I think you need to install gettext. Poedit includes only some of the programs provided by the gettext package.Probably the easiest way to install (not only) gettext is via . Once you have homebrew installed, run . After that, make sure that the programs in  are on your . Note that you need to have Xcode installed for homebrew to work as it usually installs packages from source (you can get Xcode for Lion for free from the Mac App Store). Edit: I overlooked that you don't use Lion. For Snow Leopard, you can get XCode from the App Store for $5. XCode For Leopard is I think on the installation disk.. It's better to modify virtual environment's PATH instead of force-linking. So,
Python

I am self teaching myself python 2.7. I  have some experience in using BATCH, which has a GOTO statement.  How do I do that in python? For example, suppose I want to jump from line 5 to line 18.I realize there have been previous questions regarding this topic, but I have not found them sufficiently informative or, are too high level in python for my current understanding.s are universally reviled in computer science and programming as they lead to very unstructured code.Python (like almost every programming language today) supports  which controls flow using if/then/else, loop and subroutines.The key to thinking in a structured way is to understand how and why you are branching on code.For example, lets pretend Python had a  and corresponding  statement . Look at the following code. In it if a number is greater than or equal to 0 we print if it If we want to know when a piece of code is executed, we need to carefully traceback in the program, and examine how a label was arrived at - which is something that can't really be done.For example, we can rewrite the above as:Here, there are two possible ways to arrive at the \"end\", and we can't know which one was chosen. As programs get large this kind of problem gets worse and results in In comparison, below is how you  write this program in Python:I can look at a particular line of code, and know under what conditions it is met by tracing back the tree of  blocks it is in. For example, I know that the line  will be run when a .Forgive me - I couldn't resist ;-)I entirely agree that  is poor poor coding, but no one has actually answered the question. There  in fact a  (though it was released as an April fool joke and is not recommended to be used, it  work).There's no  instruction in the Python programming language. You'll have to write your code in a  way... But really, why do you want to use a ? that's been  for decades, and any program you can think of can be written without using .Of course, there are some  where an unconditional jump might be , but it's never , there will always exist a semantically equivalent, structured solution that doesn't need .The modern equivalent of  (arguable, only my opinion, etc) is explicit exception handling:Pretend pseudocode in a fake python-like language with :Compared to python:Explicit named exceptions are a  better way to deal with non-linear conditional branching.Would give you what you want with no goto statement.  
Python

I have a temperature file with many years temperature records, in a format as below:Every year has different numbers, time of the records, so the pandas datetimeindices are all different.I want to plot the different year's data in the same figure for comparing . The X-axis is Jan to Dec, the Y-axis is temperature. How should I go about doing this? Although Chang's answer explains how to plot multiple times on the same figure, in this case you might be better off in this case using a  and ing:Now it's easy to plot (each year as a separate line):Try:
Python

So I'm trying to make this program that will ask the user for input and store the values in an array / list.\nThen when a blank line is entered it will tell the user how many of those values are unique.\nI'm building this for real life reasons and not as a problem set.My code is as follows:..and that's about all I've gotten so far.\nI'm not sure how to count the unique number of words in a list?\nIf someone can post the solution so I can learn from it, or at least show me how it would be great, thanks!You can use a  to remove duplicates, and then the  function to count the elements in the set:In addition, use  to refactor your code:Use a :Armed with this, your solution could be as simple as:The following should work. The lambda function filter out the duplicated words.I'd use a set myself, but here's yet another way:Although a set is the easiest way, you could also use a dict and use  to populate a dictionary with only unique keys and values.Assuming you have already populated  with input from the user, create a dict mapping the unique words in the list to a number:
Python

So in Ruby there is a trick to specify infinity:I believe in Python you can do something like thisThese are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it in a range be better than just using a boolean expression? For instanceTo summarize, what I'm looking for is a real world reason to use Infinity.: I'm looking for real world code. It's all well and good to say this is when you \"could\" use it, when have people  used it.Dijkstra's Algorithm typically assigns infinity as the initial edge weights in a graph.  This doesn't  to be \"infinity\", just some arbitrarily constant but in java I typically use Double.Infinity.  I assume ruby could be used similarly.Off the top of the head, it can be useful as an initial value when searching for a minimum value.For example:Which I prefer to setting  initially to the first value of Of course, in Python, you should just use the min() built-in function in most cases.  There seems to be an implied \"Why does this functionality even exist?\" in your question.  And the reason is that Ruby and Python are just giving access to the full range of values that one can specify in floating point form as specified by IEEE.  This page seems to describe it well: \nAs a result, you can also have NaN (Not-a-number) values and -0.0, while you may not immediately have real-world uses for those either.  In some physics calculations you can normalize irregularities (ie, infinite numbers) of the same order with each other, canceling them both and allowing a approximate result to come through.When you deal with limits, calculations like (infinity / infinity) -> approaching a finite a number could be achieved. It's useful for the language to have the ability to overwrite the regular divide-by-zero error.Use  and  when implementing a mathematical algorithm calls for it.In Ruby,  and  have nice comparative properties so that  <  <  for any real number .  For example,  returns , extending to  the property that  implies that .  Also,  is  if x > 0,  if x < 0, and 'NaN' (not a number; that is, undefined) if x is 0.For example, I use the following bit of code in part of the calculation of some . I explicitly reference  to define a value even if  is  or  AND  is  or .  I use it to specify the mass and inertia of a static object in physics simulations.  Static objects are essentially unaffected by gravity and other simulation forces.In Ruby infinity can be used to implement lazy lists. Say i want N numbers starting at 200 which get successively larger by 100 units each time:More info here: I've used it for cases where you want to define ranges of preferences / allowed.For example in 37signals apps you have like a limit to project numberthen you can do checks like I used it for representing camera focus distance and to my surprise in Python:I wonder why is that.I've used it in the . When I'm generating new moves, if the min player wins on that node then the value of the node is -\u221e. Conversely, if the max player wins then the value of that node is +\u221e.Also, if you're generating nodes/game states and then trying out several heuristics you can set all the node values to -\u221e/+\u221e which ever makes sense and then when you're running a heuristic its easy to set the node value:I've used it in a DSL similar to Rails'  and :This makes it easy to express concepts like Kleene star and plus in your DSL.I use it when I have a Range object where one or both ends need to be openI've used symbolic values for positive and negative infinity in dealing with range comparisons to eliminate corner cases that would otherwise require special handling:Given two ranges A=[a,b) and C=[c,d) do they intersect, is one greater than the other, or does one contain the other?If you have values for positive and negative infinity that respectively compare greater than and less than all other values, you don't need to do any special handling for open-ended ranges.  Since floats and doubles already implement these values, you might as well use them instead of trying to find the largest/smallest values on your platform.  With integers, it's more difficult to use \"infinity\" since it's not supported by hardware.I ran across this because I'm looking for an \"infinite\" value to set for a maximum, if a given value doesn't exist, in an attempt to create a binary tree.  (Because I'm selecting based on a range of values, and not just a single value, I quickly realized that even a hash won't work in my situation.)Since I expect all numbers involved to be positive, the minimum is easy:  0.  Since I don't know what to expect for a maximum, though, I would like the upper bound to be Infinity of some sort.  This way, I won't have to figure out what \"maximum\" I should compare things to.Since this is a project I'm working on at work, it's technically a \"Real world problem\".  It may be kindof rare, but like a lot of abstractions, it's convenient when you need it!Also, to those who say that this (and other examples) are contrived, I would point out that  abstractions are somewhat contrived; that doesn't mean they are useful when you contrive them.When working in a problem domain where trig is used (especially tangent) infinity is an answer that can come up.  Trig ends up being used heavily in graphics applications, games, and geospatial applications, plus the obvious math applications.  I'm sure there are other ways to do this, but you could use Infinity to check for reasonable inputs in a String-to-Float conversion. In Java, at least, the Float.isNaN() static method will return false for numbers with infinite magnitude, indicating they are valid numbers, even though your program might want to classify them as invalid. Checking against the Float.POSITIVE_INFINITY and Float.NEGATIVE_INFINITY constants solves that problem. For example:String representation: -999999999999999999999999999999999999999999999\nResult of isNaN: false\nThat number is too small.String representation: 12345\nResult of isNaN: false\nThat number is jussssst right.String representation: 999999999999999999999999999999999999999999999\nResult of isNaN: false\nThat number is too big.It is used quite extensively in graphics.  For example, any pixel in a 3D image that is not part of an actual object is marked as infinitely far away.  So that it can later be replaced with a background image.I'm using a network library where you can specify the maximum number of reconnection attempts. Since I want mine to reconnect forever:In my opinion, it's more clear than the typical \"set to -1 to retry forever\" style, since it's literally saying \"retry until the number of connection attempts is greater than infinity\".Some programmers use Infinity or s to show a variable has never been initialized or assigned in the program.If you want the largest number from an input but they might use very large negatives. If I enter -13543124321.431 it still works out as the largest number since it's bigger than -inf.I've seen it used as a sort value, to say \"always sort these items to the bottom\".If you're dealing with numbers,  represents an unknown quantity, and should be preferred to  for that case. Similarly,  represents an unbounded quantity, and should be preferred to  in that case.I think it can make the code cleaner. For example, I'm using   for exactly that: the user can specify a maximum string length for a message, or they can specify . In that case, I represent the maximum length as , so that later when I check \"is this message longer than the maximum length?\" the answer will always be false, without needing a special case.You can to use:or:
Python

Which is more pythonic?or is faster, because it doesn't create a temporary list object.From the :So: These are two different operations, what you are doing with += is the extend operation. Here is what Python documents have to say about this:So in += you provide a list, in append you just add a new element.Since there's alsowhich appends all elements of the given list, I would usefor symmetry and readability's sake.While most people here are preferring the append option, I personally prefer the other one because it looks nicer even though it may be slower (or maybe its optimized).When you write lots of Python code, I don't usually see something like this:It's more like this:So to me at least, it is nicer to see:Because its easy to recognize at a glance that you are adding to a list. Having said that, I sometimes find myself using both forms.list.append(1)\nmore readable and to consistent with the contextIf you've got a single element, , that you want to add to your list , then putting  into its own list and extending  with it seems like adding unnecessary complexity. I would thus prefer overIf  is already a list, then choosingor is a matter of preference, IMO. On the other hand, if you're going to be doing a lot of extends, you can get a performance boost by \"hoisting\" the method lookup:Finally, I think that the append operation isn't used too often in Pythonic code, because append is used very often in \"accumulator\" idioms, where I'd expect a more experienced Python programmer to use a list comprehension/etc.So instead of:You'd probably see:orHave you noticed the term \"more pythonic\" in your question?\nI think it implies that you are asking a not-so-helpful question.If one is merely  pythonic than the other (rather than being \npythonic while the other is not) it could be said that you have\nviolated the Zen of Python on a meta level:\n should also hold for the\nprocess of searching for the form in which you express\nyour logic -- once you have found something pythonic,\nthat is good enough. Keep the search simple.So my answer would be:\nNeither of them is more pythonic.\n
Python

I have used  to implement a client. It works fine. Now I want to be able to pass command line arguments to it, so I need to implement a   plugin. I have performed many searches to find resources that would show how to convert the program to a plugin. However I couldn't find exactly what I as looking for.Here is a related part of my  code:Here is what I wrote for my :I have used the same folder hierarchy mentioned in the documentation. As I haven't been able to find enough examples of plugins on the web, I'm really stuck at this point. I would appreciate any help. Could anybody tell me how to change the code? Thank you in advance.Should you perhaps be using the  files to run it from command line?Then using your  class should be easier in another program...You have to return a main service object from your  method. Try adding  then in  add this at the beginning: \nCreate the TCPServer service: \nAdd it to the top service: \nThen return the top service: You may also need to take a look at this excellent series of tutorials from   (article n\u00b016 is the one which is useful for your problem)
Python

For a project I am making some 3D scatter plots with the three corresponding projections under it. I use different colors to indicate a fourth parameter. First I plot data with a certain color and then I overplot that with other data with a different color, so that in the end the order is such that I can see everything as I want:In the beginning this worked fine, but when I try to do the same thing with slightly different data, the colors get messed up. The colors shown in the projections are the right ones, but some of them are missing in the 3D plot so they don't match anymore:When I rotate the 3D plot in a funny way, the colors are recovered and I can see them as they were supposed to be: However, I don't want a 3D plot that is rotated in a funny way, because the axes get messed up and it's impossible to read it properly like that. I found one solution to the problem here: \n.\nIt basically says that I should replace my ax.scatter(X,Y) with ax.plot(X,Y,'o'). When I do this the colors are shown the way they were supposed to be, but the plot is much messier and uglier this way.\nBasically I just want to be able to do this with a scatter plot.Does anyone know how to solve this?Here's a minimum example of my code, for only two colors:Rather than using  try  or . The  is specifying the  to use, and the 'o' marker is a large filled circle, which is why your plot looks ugly.
Python

I have shifted from OpenCV 2.4.9 to 3.0 to make use of  and  function. I came to know that it does not come along with non-free algorithms like SIFT , SURF. So I installed  from  by following stepsI also cross checked in modules of ,  was there. Then when I tried to do It gives me following errorWhat am I doing wrong here. Just FYI that I am using OpenCV 3.0 beta version . has OpenCV deactivated python wrappers for  or I have not installed it correct way?I am writing down an answer to my own question, as it might help somebody fixing the same issue.The opencv package I was trying for was downloaded from opencv . I just downloaded latest code from  for opencv and installed it. It is working fine now with opencv-contrib.
Python

Is it possible to increase the antialiasing in matplotlib?\nI can still see some aliasing in my data, I tried several backends and it is still there. The antialiasing flag of the lines is set.Here you can see what I mean It's a sample taken from a Screenshot. It's probably not the best example but I guess one can see the stairs in the line. It was taken with the wxagg backend.I'm using matplotlib version 1.01 with Windows 7.Update:\nI don't have the code which produced the previous picture anymore, but I still have the problem. Below is a simple code example which shows the aliasing.It print's \nAnd the resulting plot looks like the following.\nEspecially the lower red curve shows clear aliasing. The picture you added to your question is already perfectly anti-aliased. It doesn't get any better than this. Have a look at a zoomed version of the image:If you save the picture as a .svg file, you will have infinite precision. You can then edit this .svg with something like InkScape, and get how much precision/antialiasing as you like.
Python

Unfortunately, due to my oversight, I had an older version of MKL (11.1) linked against numpy. Newer version of MKL (11.3.1) gives same performance in C and when called from python. What was obscuring things, was even if linking the compiled shared libraries explicitly with the newer MKL, and pointing through LD_* variables to them, and then in python doing import numpy, was somehow making python call old MKL libraries. Only by replacing in python lib folder all libmkl_*.so with newer MKL I was able to match performance in python and C calls.Matrix multiplication was done via sgemm (single-precision) and dgemm (double-precision) Intel's MKL library calls, via numpy.dot function. The actual call of the library functions can be verified with e.g. oprof. Using here 2x18 core CPU E5-2699 v3, hence a total of 36 physical cores.\nKMP_AFFINITY=scatter. Running on linux.1) Why is numpy.dot, even though it is calling the same MKL library functions, twice slower at best compared to C compiled code?2) Why via numpy.dot you get performance decreasing with increasing number of cores, whereas the same effect is not observed in C code (calling the same library functions).I've observed that doing matrix multiplication of single/double precision floats in numpy.dot, as well as calling cblas_sgemm/dgemm directly from a compiled C  give noticeably worse performance compared to calling same MKL cblas_sgemm/dgemm functions from inside pure C code.Doing exactly the same as above, but with double precision A, B and C, you get:\n3 cores: 20s, 6 cores: 10s, 12 cores: 5s, 18 cores: 4.3s, 24 cores: 3s, 30 cores: 2.8s, 36 cores: 2.8s.The topping up of speed for single precision floating points seem to be associated with cache misses.\nFor 28 core run, here is the output of perf.\nFor single precision:And double precision:C shared library, compiled withPython wrapper function, calling the above compiled library:However, explicit calls from a C-compiled binary calling MKL's cblas_sgemm / cblas_dgemm, with arrays allocated through malloc in C, gives almost 2x better performance compared to the python code, i.e. the numpy.dot call. Also, the effect of performance degradation with increasing number of cores is NOT observed.  and was achieved when using all 36 physical cores via mkl_set_num_cores and running the C code with numactl --interleave=all.Perhaps any fancy tools or advice for profiling/inspecting/understanding  this situation further? Any reading material is much appreciated as well.\nFollowing @Hristo Iliev advice, running numactl --interleave=all ./ipython did not change the timings (within noise), but improves the pure C binary runtimes.I suspect this is due to unfortunate thread scheduling. I was able to reproduce an effect similar to yours. Python was running at ~2.2 s, while the C version was showing huge variations from 1.4-2.2 s.Applying:\n\nThis ensures that the 28 threads are always running on the same processor thread.Reduces both runtimes to more stable ~1.24 s for C and ~1.26 s for python.This is on a 28 core dual socket Xeon E5-2680 v3 system.Interestingly, on a very similar 24 core dual socket Haswell system, both python and C perform almost identical even without thread affinity / pinning.Why does python affect the scheduling? Well I assume there is more runtime environment around it. Bottom line is, without pinning your performance results will be non-deterministic.Also you need to consider, that the Intel OpenMP runtime spawns an extra management thread that can confuse the scheduler. There are more choices for pinning, for instance  - but for some reason that is totally messed up on my system. You can add  to the variable to see how the runtime is pinning your threads. is a useful alternative providing more convenient control.In general single precision should be at least as fast as double precision. Double precision can be slower because:I would think that once you get rid of the performance anomaly, this will be reflected in your numbers.When you scale up the number of threads for MKL/*gemm, considerI don't think there is a really simple way to measure how your application is affected by bad scheduling. You can expose this with  and there is  to visualize this, but this will come with a high learning curve. And then again - for parallel performance analysis you should have the threads pinned anyway.
Python

I used easy_install to install pip, pip to install django, virtualenv, and virtualenvwrapper.I have just returned to it a few weeks later and django does not seem to work anymore, but more concerning is I can't start the process over again as easy_install is returning the following error:After a good evening of hunting I am stumped as to how to resolve this.You seem to have a version conflict; note the  path, but the  script wants to load  instead.The latter is a development version; it has the revision number of a subversion repository embedded in the version ().I suspect you have  python installations; one is the system version (in  and the other is installed with the python installer into , and the stub script in  may be installed with the system python.If so, there'll be another copy of the stub at , which should work correctly.I had the same issue, eventually ended up running the 2.7.3 easy_install by\n/opt/python2.7.3/bin/easy_install which worked fine
Python

I'm trying to figure out if there is a defacto pattern for file access using twisted. Lots of examples I've looked at (twisted.python.log, twisted.persisted.dirdbm, twisted.web.static) actually don't seem to worry about blocking for file access. It seems like there should be some obvious interface, probably inheriting from abstract.FileDescriptor, that all file access should be going through it as a producer/consumer.Have I missed something or is it just that the primary use for twisted in asynchronous programming is for networking and it hasn't really been worked out for other file descriptor operations, not worrying about the purity of non-blocking IO ?I think you are looking for the . For more information on non-blocking I/O  in Python, you can also watch this .There is an open ticket for this in Twisted - .After plenty of searching, trial, and error, I finally figured how to use .[Edit: I also just figured out a simpler way that doesn't require the use of a protocol]Run either like so:The fdesc module might be useful for asynchronously talking to a socket or pipe, but when given an fd that refers to an ordinary filesystem file, it does blocking io (and via a rather odd interface at that). For disk io, fdesc is effectively snake oil; don't use it.As of May 2017, the only reasonable way to get async disk io in twisted is by wrapping synchronous io calls in a .I'm not sure what you want to achieve. When you do logging, then Python will make sure (by the global interpreter log) that log messages from several threads go into the file one after the other.If you're concerned about blocking IO, then the OS adds default buffers for your files (usually 4KB), and you can pass a buffer size in the  call.If you're concerned about something else, then please clarify your question.
Python

I have the following directory:mymodule.py:main.py:But when I compile it, then I get this error:This works:But I get no auto completion when I type this in and there is a message: \"unresolved reference: mymodule\" and \"unresolved reference: myclass\"\nAnd in my other project, which I am working on, I get the error: \"ImportError: No module named 'mymodule'What can I do?I had the same problem and I solved it by using an absolute import instead of a relative one.for example in your case, you will write something like this:You can see in the .if you just run the main.py under the app ,just import like if you want to call main.py on other folder, use:for example:so i think the main question of you is how to call app.mainIf you go one level up in running the script in the command line of your bash shell, the issue will be resolved. To do this, use  command to change the working directory in which your script will be running. The result should look like this:rather than this:Once you are there, instead of running the script in the following format:Change it to this:This process can be repeated once again one level up depending on the structure of your Tree diagram. Please also include the compilation command line that is giving you that mentioned error message. I usually use this workaround:Which means your IDE should pick up the right code location and the python interpreter will manage to run your code.
Python

I'm struggling to figure out how to profile a simple multiprocess python scriptI'm starting 5 processes and therefore cProfile generates 5 different files. Inside of each I want to see that my method 'worker' takes approximately 3 seconds to run but instead I'm seeing only what's going on inside the 'start'method.I would greatly appreciate if somebody could explain this to me.You're profiling the process startup, which is why you're only seeing what happens in  as you say\u2014and  returns once the subprocess is kicked off.  You need to profile inside the  method, which will get called in the subprocesses.
Python

In my Django website, I'm creating a class that interact dynamically with other applications installed in the website. I have to do a manipulation on each field of each application.So I want to save the name of all installed applications in a list and get the attributes of each one. There is a way to do that using an iterator or something else ?Under Django 1.6 and below.If you want all models, try:Under Django 1.7 and above (thanks Colin Anderson):I believe the older function still works.[edit]So the blessed way is:Older version of this answer:All applications are registered in the  file.You can import each application and list their attributes:In order to use the new print function instead of the print statement in older Python you may have to issue a  (or just change the line containing the  call).The list of installed applications is defined in . It contains a tuple of strings, so you can iterate on it to access each application's name.However, I'm not sure what you mean by each application's  and .You can retrieve installed apps like that (in interpreter) :To get the actual  themselves (), this is what I came up with:Though you may want to do some error handling, or filtering.
Python

I want to create \"heart rate monitor\" effect from a 2D array in numpy and want the tone to reflect the values in the array.You can use the  from  to create a wav file which you can then play however you wish. Note that the array must be integers, so if you have floats, you might want to scale them appropriately:If you want Python to actually play audio, then  provides an overview of some of the packages/modules.For the people coming here in 2016 scikits.audiolab doesn't really seem to work anymore. I was able to get a solution using sounddevice.In addition, you could try . It features file IO and the ability to 'play' arrays. Arrays don't have to be integers. To mimick dbaupp's example:I had some problems using , so I looked for another options for this task. I came up with , which seems a lot more up-to-date. I have not checked if it works with Python 3.A simple way to perform what you want is this:PyGame has the module  which can play numpy data as audio. The other answers are probably better, as PyGame can be difficult to get up and running. Then again, scipy and numpy come with their own difficulties, so maybe it isn't a large step to add PyGame into the mix.If you are using Jupyter, the best option is:Not sure of the particulars of how you would produce the audio from the array, but I have found  to be a great command-line audio player, and could potentially work for you. I use it as my player of choice for , which is written in python and has libraries that could be a great starting place for interfacing your code/arrays with audio.Check out:
Python

In the following, male_trips is a big pandas data frame and stations is a small pandas data frame. For each station id I'd like to know how many male trips took place. The following does the job, but takes a long time:how should I go about this instead?Update! So there were two main approaches:  followed by , and the simpler . I did a quick , and the  approach wins by quite a large margin! Here is the code:and here is the result:Note that, at this speed, for exploring data  value_counts is marginally quicker and less remembering!I'd do like Vishal but instead of using sum() using size() to get a count of the number of rows allocated to each group of 'start_station_id'. So:My answer below works in Pandas 0.7.3. Not sure about the new releases.This is what the  method is for:It should be straight-forward to then inspect  based on the values in . However, if you insist on  considering those values, you could do the following:and this will only give counts for station IDs actually found in .doesnt work?\nedit: after seeing in the answer above that  and  exist (and  even comes with its own entry in  and also  isn't simply ) I updated the three methods belowYou could also do an inner join on stations.id:\n followed by .\nOr:If you have the time I'd be interested how this performs differently with a huge DataFrame.how long would this take:
Python

I'm asking this because I know that the pythonic way to check whether a list is empty or not is the following: will print , etc. So this leads me to identify  with  truth-values; however, if I try to compare [] and False \"directly\", I obtain the following: etc... What's going on here? I feel like I'm missing something really obvious.The  statement evaluates everything in a Boolean context, it is like there is an implicit call to the  built-in function.Here is how you would actually check how things will be evaluated by an  statement:See the documentation on , empty lists are , but this doesn't mean they are equivalent to . also has some excellent information on why it was implemented this way, see the very last bullet in the  section for the part that deals with  and  specifically.The most convincing aspect to me is that  is generally transitive, so  and  implies .  So if it were the way you expected and  were true and  were true, one might assume that  should be true (even though it obviously should not be in a language without implicit type conversion).Empty containers are \"falsy,\" that is, they evaluate to  . That doesn't mean they are literally equal to the constant .In other words, the following is :The truth value of an object is determined by its  or its  method. (In Python 3,  has been renamed to .) Containers have a  method, so they are truthy when they have anything in them and falsy when they are empty.If empty containers were literally equal to , by the way, then any empty container would be equal to any other empty container: for example,  would be . And that just wouldn't make any sense at all!However, just to blow your mind, the following is :This is because Booleans are a subclass of integers in Python, and  is basically just a zero that gets printed a little differently.Built-in types in Python have a truth value which allows you to test them for truthfulness. See .This is different than saying  which is doing an actual value test (equality test). It is using the objects  method to determine if their values are equal.In your example, the not operator is causing your list to be converted to a boolean.  Try this:\"is\" and \"==\" don't do that conversion.
Python

I am trying to create a list of tuples where the tuple contents are the number  and the number before it in the list.  Cleaner Pythonic approach:What is the code above doing:Part of your issue is that  will always return an empty list. The end of a slice is exclusive, so when you do  you're trying to take the elements of  that exist  index 0 and index 0.You're on the right track, but you want to zip the list with itself.You were pretty close, I'll show you an alternative way that might be more intuitive if you're just starting out:Get the index in the range of the list lenght, and if the value at the position  is equal to , grab the adjacent elements.The result is:This is  but I decided to un-delete it to show you a different way of doing it. You can make it go a bit faster by using  instead: that  the behavior of the comprehension without  and the behavior of the comprehension with  is .Specifically, if  then:while:It is up to you to decide which of these fits your criteria, I'm just pointing out that they don't behave the same in all cases.You can also do it without slicing by creating iterators:Or use the  to create your pairsIf using python3, just import  and use the regular .It is really surprising that no one has added a functional approach. Another alternative answer is using a . This builtin function returns an iterator (list in Python2) consisting of all the elements present in the list that return  for a particular function It is to be noted that the . The difference between the functional approach and list comprehensions is discussed in . My solution is similar to one of Jim's advanced with zero-index check
Python

When reading lines from a text file using python, the end-line character often needs to be truncated before processing the text, as in the following example:Is there an elegant way or idiom for retrieving text lines without the end-line character?The  way to do this in Python is to use :Each of the other alternatives has a gotcha:Simple. Use What's wrong with your code?  I find it to be quite elegant and simple.  The only problem is that if the file doesn't end in a newline, the last line returned won't have a  as the last character, and therefore doing  would incorrectly strip off the last character of the line.The most elegant way to solve this problem would be to define a generator which took the lines of the file and removed the last character from each line only if that character is a newline:Long time ago, there was Dear, clean, old, BASIC code that could run on 16 kb core machines:\nlike that: Now, to read a file line by line, with far better hardware and software (Python), we must reinvent the wheel:I am induced to think that something has gone the wrong way  somewhere...What do you thing about this approach?Generator expression avoids loading whole file into memory and  ensures closing the fileYou may also consider using line.rstrip() to remove the whitespaces at the end of your line.
Python

I have a string that can be a hex number prefixed with \"0x\" or a decimal number without a special prefix except for possibly a minus sign. \"0x123\" is in base 16 and \"-298\" is in base 10.How do I convert this to an int or long in Python?I don't want to use eval() since it's unsafe and overkill.(why doesn't  do that?)Base 16 to 10 (return an integer):Base 10 to 16 (return a string):Something like this might be what you're looking for.If you are doing a lot of go between with different number systems, the bitstring library make a lot of binary/Hex operations easier.  It also supports string interpretation: This is a simpler version which works like a charm.\nReturns string since hex() returns the same type:
Python

I have a list with ~10^6 tuples in it like this:I want to find the maximum value of the Ys in this list, but also want to know the X that it is bound to.How do I do this?Use :\u00a0\nUsing :using : comparison:In addition to max, you can also sort:You could loop through the list and keep the tuple in a variable and then you can see both values from the same variable...
Python

I have some problem for a while now, I'm experiencing CSRF Cookie not set. Please look at the codes belowIn the HTML here is the codeIm stuck, I already cleared the cookie, used other browser but still csrf cookie not set.This can also occur if  is set and you are accessing the site non-securely.From \nYou can solve it by adding the  to your viewif this method doesn't work. you will try to comment csrf in middleware. and test again.This problem arose again recently due to a bug in Python itself.Among the versions affected were 2.7.8 and 2.7.9. \nThe cookie was not read correctly if one of the values contained a  character.Updating Python (2.7.10) fixes the problem.I was using Django 1.10 before.So I was facing this problem.\nNow I downgraded it to Django 1.9 and it is working fine.try to check if your have installed in the settings.pyIn the template the data are formatted with the csrf_token:Problem seems that you are not handling  requests appropriately or directly posting the data without first getting the form. When you first access the page, client will send  request, in that case you should send html with appropriate form.Later, user fills up the form and sends  request with form data.Your view should be:Check that chrome's cookies are set with default option for websites. Allow local data to be set (recommended).Method 1:Method 2 :Because render_to_response method may case some problem of response cookies.                       Make sure your django session backend is configured properly in settings.py. Then try this,Add this middleware in  under MIDDLEWARE_CLASSES or MIDDLEWARE depending on the django versionget_token - Returns the CSRF token required for a POST form. The token is an alphanumeric value. A new token is created if one is not already set.If you're using the  to make POST requests as a logged in user and getting , it could be because by default  does not include session cookies, resulting in Django thinking you're a different user than the one who loaded the page.You can include the session token by passing the option  to fetch:in your view are you using the csfr decorator ??I have just met once, the solution is to empty the cookies.\nAnd may be changed while debugging SECRET_KEY related.Clearing my browser's cache fixed this issue for me. I had been switching between local development environments to do the django-blog-zinnia tutorial after working on another project when it happened. At first, I thought changing the order of INSTALLED_APPS to match the tutorial had caused it, but I set these back and was unable to correct it until clearing the cache.
Python

I'm trying to parse timestamp strings like  in Python, but I'm having trouble finding a solution that will handle the abbreviated timezone.I'm using 's  function, but it doesn't parse the timezone. Is there an easy way to do this?That probably won't work because those abbreviations aren't unique. See  for details. You might wind up just having to manually handle it yourself if you're working with a known set of inputs.'s  accepts as keyword argument  a dictionary of the kind  (that is, matching the zone name to GMT offset in seconds). So assuming we have that, we can do:Regarding the content of , here is how i populated mine:ps. per @Hank Gay time zone naming is not clearly defined. To form my table i used  and  . I looked at each conflict and resolved conflicts between obscure and popular names towards the popular (more used ones). There was one -  - that was not as clear cut (it can mean , ,  or ), so i left it out of the table - you may need to chose what to add for it based on your location. Oh - and I left out the Republic of Kiribati with their absurd \"look at me i am first to celebrate New Year\" GMT+13 and GMT+14 time zones.You might try pytz module: The parse() function in dateutil can't handle time zones.  The thing I've been using is the %Z formatter and the time.strptime() function.  I have no idea how it deals with the ambiguity in time zones, but it seems to tell the difference between CDT and CST, which is all I needed.Background: I store backup images in directories whose names are timestamps using local time, since I don't have GMT clocks handy at home.  So I use time.strptime(d, r\"%Y-%m-%dT%H:%M:%S_%Z\") to parse the directory names back into an actual time for age analysis.I used  to generate a  mapping: Usage UsageThe UTC conversion is needed since there are many timezones available for each abbreviation. Since  is a , it only has the last timezone per abbreviation. And you may not get the one you were expecting pre conversion.
Python

According to , a bytes object is used to store a mutable sequence of bytes (0-255), raising if this is not the case.However, my python 2.7 says otherwiseDoes anyone have a clue on the reason why the PEP is declared Final, but the implementation does not conform ?The  type was introduced in Python 3, but what's being discussed in the PEP is a mutable sequence ( is immutable) which was introduced in Python 2.6 under the name .The PEP clearly wasn't implemented as stated (and it does say that it was partially superseded by ) but I think it's only a question of things being renamed, not features missing. In Python 2  is just an alias for  to aid forward compatibility and so is a red-herring here.Example bytearray usage:The new   is . The 2.x  built-in is just an alias to the  type. There is no new type called  in 2.x; Just a new alias and literal syntax for .Here's the  everybody loves: objects only really exist in Python 3.x.   is an alias for str in Python 2.7.  It exists to help writing portable code between Python 2 and 3.
Python

Is there a regexp which would find longest common prefix of two strings? And if this is not solvable by one regexp, what would be the most elegant piece of code or oneliner using regexp (perl, ruby, python, anything).PS: I can do this easily programatically, I am asking rather for curiosity, because it seems to me that this could be solveable by regexp.PPS: Extra bonus for O(n) solution using regexps. Come on, it should exist!If there's some character that neither string contains \u2014, say,  \u2014 you could writeand the longest common prefix would be saved as . This is obviously very inefficient. I think that if efficiency is a concern, then this simply isn't the approach we should be using; but we can at least improve it by changing  to  to prevent useless greediness that will just have to be backtracked again, and wrapping the second  in  to prevent backtracking that can't help. This:This will yield the same result, but much more efficiently. (But still not nearly  efficiently as a straightforward non\u2013regex-based approach. If the strings both have length , I'd expect its worst case to take at least O() time, whereas the straightforward non\u2013regex-based approach would take O() time in  worst case.)Here's a Python one-liner:Here's one fairly efficient way which uses a regexp.  The code is in Perl, but the principle should be adaptable to other languages:(A subtlety worth noting  is that Perl's string XOR operator () in effect pads the shorter string with nulls to match the length of the longer one.  Thus, if the strings might contain null characters,  if the shorter string happens to be a prefix of the longer one, the common prefix length calculated with this code might exceed the length of the shorter string.)simple and efficientThe problem you're going to have is that a regular expression matches against one string at a time so isn't intended for comparing two strings.If there's a character that you can be sure isn't in either string you can use it separate them in a single string and then search using back references to groups.So in the example below I'm using whitespace as the separatorHere's an O(N) solution with Foma-like pseudocode regular expressions over triples (for lcp, you have two inputs and an output). To keep it simple, I assume a binary alphabet {a,b}:Now you just need a language that implements multi-tape transducers.Another attempt for O(n) solution:it depends whether .{n} is considered O(1) or O(n), I do not know how efficiently this is implemented.Inspired by ruakh's answer, here is the O(n) regexp solution: well it is not correct as rukach metions, but the idea is correct, but we should push regexp machine not to check the beginning letters repeatedly. The basic idea can be also rewritten in this perl oneliner.I wonder if it can be incorporated back into regexp solution.Could be useful in some  cases so here it goes:RegEx only solution in 3 steps ():String A: \nString B: And here's the   in PHP:  Code live at: Non regexp, non duplicating string at each iteration solution:I second ruakh's answer for the regexp (with my suggested optimization in the comments). Simple to write, but not simple and efficient to run if the first string is long.Here is an efficient, non-regexp, readable, one-line answer:Using extended regular expressions as in Foma or Xfst.The hardest part here is to define \"longest\". Generally speaking, to\noptimize, you construct the set of non\u2013optimal strings (worsening) and\nthen remove these (filtering).This is really a purist approach, which avoids non-regular operations\nsuch a capturing. I have the idea this is most inefficient. No err checking, etc.
Python

Consider this Python code for printing a list of comma separated valuesWhat is the preferred method for printing such that a comma does not appear if  is the final element in the list.exA  as suggested in other answers is the typical Python solution; the normal approach, which peculiarly I don't see in any of the answers so far, isknown as a generator expression or genexp.If you prefer a loop (or need one for other purposes, if you're doing more than just printing on each item, for example), there are of course also excellent alternatives:this is a first-time switch (works for any iterable a, whether a list or otherwise) so it places the comma  each item but the first.  A last-time switch is slightly less elegant and it work only for iterables which have a  (not for completely general ones):this example also takes advantage of the last-time switch to terminate the line when it's printing the very last item.The  built-in function is very often useful, and well worth keeping in mind!That's what  is for.print (stringTokenizer(u\"\u043f\u0440\u0438\u0432\u0435\u0442 \u0441\u043a\u043e\u0442\u044b!  \u044f \u0432\u0430\u043c \u0441\u0442\u0438\u0445\u0430\u043c\u0438, \u043c\u043e\u0436\u0435\u0442 \u0431\u044b\u0442\u044c, \u0435\u0449\u0435  \u043e\u0442\u0432\u0435\u0447\u0443\",\", !\"))
Python

I'm trying to find out a way in python to redirect the script execution log to a file as well as stdout in pythonic way. Is there any easy way of acheiving this?I came up with this [untested] in python will expect a  function in . You could use your own custom object which has this. Or else, you could also have sys.stdout refer to your object, in which case it will be tee-ed even without .Use logging module ():I just want to build upon Serpens answer and add the line:This will allow you to chose what level of message gets logged.For example in Serpens example,Will not get recorded as it defaults to only recording Warnings and above.More about levels used can be read about   You should use the  library, which has this capability built in. You simply add handlers to a logger to determine where to send the output.The easiest solution is to redirect the standard output. In your python program file use the following:Any std output (e.g. the output of ) will be redirected to  or if you uncomment the second line, any output will just be suppressed.
Python

I'd like to take an HTML table and parse through it to get a list of dictionaries. Each list element would be a dictionary corresponding to a row in the table.If, for example, I had an HTML table with three columns (marked by header tags), \"Event\", \"Start Date\", and \"End Date\" and that table had 5 entries, I would like to parse through that table to get back a list of length 5 where each element is a dictionary with keys \"Event\", \"Start Date\", and \"End Date\".Thanks for the help!You should use some HTML parsing library like :printsSven Marnach  is directly translatable into  which is part of recent Python distributions:same output as Sven Marnach's answer...If the HTML is  XML you can't do it with . But even then, you don't have to use an external library for parsing a HTML table. In python 3 you can reach your goal with  from . I've the code of the simple derived HTMLParser class .You can use that class (here named ) the following way:The output of this is a list of 2D-lists representing tables. It looks maybe like this:
Python

I wrote this simple function:Examples:Whilst this is clear enough for me and fits my use case (a simple test tool for a simple printer) I can't help thinking there's a lot of room for improvement and this could be squashed down to something very concise.What other approaches are there to this problem?Use the new  string method:How about this:Use  to pass width and  for uppercaseAs suggested by  and 
Python

How can I make unique URL in Python a la  or \nWhen using uuid from python I get a very large one. I want something shorter for URLs.: Here, I wrote a module for you.  Use it. Counting up from 1 will guarantee short, unique URLS. /1, /2, /3 ... etc.Adding uppercase and lowercase letters to your alphabet will give URLs like those in your question.  And you're just counting in base-62 instead of base-10.Now the only problem is that the URLs come consecutively.  To fix that, read my answer to this question here:Basically the approach is to simply swap bits around in the incrementing value to give the appearance of randomness while maintaining determinism and guaranteeing that you don't have any collisions.I'm not sure most URL shorteners use a random string.  My impression is they write the URL to a database, then use the integer ID of the new record as the short URL, encoded base 36 or 62 (letters+digits).Python code to convert an int to a string in arbitrary bases is .This module will do what you want, guaranteeing that the string is globally unique (it is a UUID):If you need something shorter, you should be able to truncate it to the desired length and still get something that will reasonably probably avoid clashes.The reason UUIDs are long is because they contain lots of information so that they can be guaranteed to be globally unique.If you want something shorter, then you'll need to do something like generate a random string, checking whether it is in the universe of already generated strings, and repeating until you get an unused string. You'll also need to watch out for concurrency here (what if the same string gets generated by a separate process before you inserted into the set of strings?).If you need some help generating random strings in Python, this  might help.It doesn't really matter that this is Python, but you just need a hash function that maps to the length you want.  For example, maybe use MD5 and then take just the first  characters.  You'll have to watch out for collisions in that case, though, so you might want to pick something a little more robust in terms of collision detection (like using primes to cycle through the space of hash strings).I don't know if you can use this, but we generate content objects in Zope that get unique numeric ids based on current time strings, in millis (eg, 1254298969501)Maybe you can guess the rest. Using the recipe described here:\n, we encode and decode the real id on the fly, with no need for storage. A 13-digit integer is reduced to 7 alphanumeric chars in base 62, for example.To complete the implementation, we registered a short (xxx.yy) domain name, that decodes and does a 301 redirect for \"not found\" URLs, If I was starting over, I would subtract the \"starting-over\" time (in millis) from the numeric id prior to encoding, then re-add it when decoding. Or else when generating the objects. Whatever. That would be way shorter.. is an awesome tool for this.Edit:Here's how to use Hashids to generate a unique short URL with Python:Try this  ... It's still under development, but very useful!! Generate a unique identifier of a specified fixed length consisting of the characters  and . For example:Here's my solution. 
Python

I am translating a django app and I would like to translate also the homepage of the django admin site. On this page are listed the application names and the model class names. I would like to translate the model class name but I don't find how to give a user-friendly name for a model class.Does anybody know how to do that?Look at the   and , both of which are translatable.
Python

So AFAIK in CPython, function definitions are compiled into function objects when executed at parse time. But what about inner functions? Do they get compiled into function objects at parse time or do they get compiled (or interpreted) every single time the function is called? Do inner functions incur any performance penalty at all?To give a general explaination - assuming you have the following code in a module:When the file is parsed by python via , the above text is turned into bytecode for how to execute the . In the module bytecode, there are two \"code objects\", one for the bytecode of  and one for the bytecode . Note that I said code objects, not functions - the code objects contain little more than the bytecode used by the function, and any information that could be known at compile time - such as the bytecode for  containing a ref to the bytecode for . When the module actually loads, by evaluating the code object associated with the module, one thing which happens is an actual \"function object\" is created for , and stored in the module's  attribute. The function object acts as a collection of the bytecode and all context-relavant things that are needed to call the function (eg which globals dict it should pull from, etc) that can't be known at compile time. In a way, a code object is a template for a function, which is a template for execution of the actual bytecode with all variables filled in. None of this involved -as-a-function yet - Each time you actually get around to calling , that's when a new  function object is created , which binds the already-created inner bytecode object to a list of globals, including the value of  as passed into that call to outer. As you can imagine, this is pretty fast, since no parsing is needed, just filling in a quick struct with some pointers to other already-existing objects.I suspect this is heavily implementation dependent, but that was CPython 2.6.6, and the inner function looks like it was compiled. Here's another example:So we can conclude that they are compiled. As for their performance characteristics, use them. If you start having performance issues, profile. I know it's not really an answer, but it almost never matters and when it does, general answers don't cut it. Function calls incur some overhead and it looks like inner functions are just like functions.Easy test: the default arguments to a function are called once, at define time.So yes: this is a minor (very very! minor) performance hit.To extend nmichaels answer inner function are compiled in  time as he guessed and there byte code is saved in the  and they are accessed using the opcode  as you can see in the disassembly of the function.Example:I'm late on this, but as a little experimental complement to these thorough answers: you may use the  to verify whether a new object is created or not:The actual numbers may differ, but their difference indicates that two distinct instances of  are indeed created.This time, as expected, the two s are the same.Now for some  measurements. Inner first, outer second:So, on my machine, it seems that the inner version is 50% slower (Python 2.7, IPython Notebook).
Python

What I'm trying to do here is use a keyboard interrupt to exit all ongoing threads in the program. This is a pared down version of my code where the thread is created:The program itself is far more complicated, accounting for tons of different variables that affect the threads and even having the option to launch in a sequential mode, where tasks are not threaded, but instead launched one-by-one so there might be some problems with this small variation I just conjured up.\nI have done this in ways that produced 50/50 results. The interrupts would work but the threads would never cleanly exit. Sometimes they would keep going but halt the execution of future threads, some times they would exit with a massive error regarding the interrupt, other times the interrupts would do nothing at all. Last time I ran this the program stopped any future threads from executing but did not stop the current thread.\nIs there any way to exit the threads without going into the module the thread is actually executing in?A similar question is \"How do you kill a thread?\"You create an exit handler in your thread that is controlled by a lock or event object from the threading module. You then simply remove the lock or signal the event object. This informs the thread it should stop processing and exit gracefully. After signaling the thread in your main program, the only thing left to do is to use the  method in  which will wait for the thread to shut down.A short example:If you REALLY need the functionality of  a thread, use multiprocessing. It allows you to send SIGTERMs to individual \"processes\" (it's also very similar to the threading module). Generally speaking, threading is for when you are IO-bound, and multiprocessing is for when you are truly processor-bound.
Python

I am using sublime text 2 for python development along with virtualenv!The standard sublime text 2 build system uses the standard python install rather than my virtualenv where my packages are installed.How can I get sublime text 2 to build using my virtualenv? I currently use the terminal to activate my environment and run my scripts.UPDATE: Never got it working, but seeing as i am using flask and it builds when you make a change, it's not a big issueYou have to edit your  and add the following:You can also set the path for the build system to the  directory of your virtualenv, like so:This also allows other tools, like  in the example, to find the correct python binary from the virtualenv.In windows this works for me:Sublime's Build System supports variables which can be used with Sublime project files to make this a bit more portable across projects. If your virtual environments are in a standard spot, create a new project file (Project -> Save Project As) into the root directory of your project just above your virtual environment directory. Then create a new build file with something like this:It seems to then pick up the rest automatically - the same as if you typed ./venv/bin/python from the command line - no need to mess with paths, environment variables, etc. I'm using Flask, but I think it's apply to nearly every case.\nMy actual build is like this, where \"benicio\" is the directory of my project:Sorry to add yet another answer to this - but this caused me a large amount of grief figuring this out. Not only do you need to make a build system like:but you HAVE to change a setting in Sublime Text - go to Tools --> Build System --> \"Maths\". In my case I need to choose \"Maths\" because that's what I named my build system. If you don't do this - Sublime Text does not use your build system!!I have just got sublime text 3 to working in a virtualenv. Although the OP specified ST2, there all likely more like myself who are using ST3. Thanks to user1248490 and Russell Beattie I arrived at the following:Note that \"cmd\" is now \"shell_cmd\" in ST3. See Under MAC OSX, this works for meWhat i did was keep it simple:Went to root drive and created python folder:then went in there and created the virtualenvthen created a newbuild in ST2 with the above command and it worksThis is what I have as a build system (assuming my virtualenv is created as a folder called 'env' in my current project directory). This at least means I don't need to constantly change the build system between projects:I saved this as a New Build System (Tools -> Build System -> New Build System).I use this to build my Flask project. I have added the following code to my Project Settings: Project -> Edit Projectand then I just switch to my  file and hit this combination worked great:2 steps1) add the 2 appropriate keys to the 'env' key.\nA) DJANGO_SETTINGS_MODULE \nB) PYTHONPATH2) update cmd to reflect the version of python you want to use.I have an answer for anyone who uses Heroku and uses their foreman tool, and it works great. Simply create a new build system like so:This pulls in all of the environment variables available to Foreman,  your virtualenv's $PATH variable, which adds the virtualenv Python to your python path.source did not work for me inside the build on lubuntu.\nuse '.' or dot instead of 'source'.this did work:{}this worked for me:saved build in:as Selectdone!using windows 8.1, st2
Python

I've loaded uWSGI v 1.9.20, built from source.  I'm getting this error, but how do I tell which plugin is needed?Which plugin should be loaded?I had this problem and was stuck for hours.my issue is different than the answer listed, make sure you have  in your uwsgi ini file and you install the  plugin:After I did the above my application worked. Obviously this is for  projects, but a similar approach is required for other projects.It might be easiest to install uwsgi through pip instead of the package manager from the OS you're using, the package in pip is usually more up to date than the package managers from the OS you might be using:This solved it for me anyway.For using multiple Python versions on the same server, I would advice to take a look at virtualenv:\nOn my side, this is because instead of having  as the header of my configuration inside , I put something else (the name of the app). 
Python

I have a string representing a path.  Because this application is used on Windows, OSX and Linux, we've defined environment variables to properly map volumes from the different file systems.  The result is:What I want to do is evaluate the environment variables in the string so that they're replaced by their respective volume names.  Is there a specific command I'm missing, or do I have to take os.environ.keys() and manually replace the strings?Use  to expand the environment variables in the string, for example:
Python

I'm trying to get hold of Django. I use Pydev on Eclipse. I have written a simple signup page that I can't get to work. Eclipse complains that User.DoesNotExist is undefined. Most likely, I am missing something trivial. Here's the relevant portion of the code:The problem is really with PyDev, not your code. What you have done is absolutely correct, but IDEs will always have difficulty resolving attributes in a dynamic language like Python. In the case of the DoesNotExist exception, it is added via a  rather than through normal object inheritance, so PyDev is unlikely to be able to find it. However, it should definitely work.I just discovered Pydev actually has a nice workaround for this.Go to  > , then  >  > .Click the  tab and add \"DoesNotExist\" to the text box titled .Pydev has a workaround for such cases (when the members are defined at runtime).\nJust add #@UndefinedVariable at the end of the string which cause the warning (or ctrl+1 on keyboard when the cursor is at \"DoesNotExist\"), and it won't complain.Can Eclipse resolve attributes created runtime via es?Notice that you never define a  on any of your models and it is not defined on  either.You can also solve it in a different way: just go to the User class, and add @DynamicAttrs in the docstring.\nThis will tell PyDev that attributes of the class are added dynamically, and will make it not complain any longer for \"issues\" like DoesNotExist.I have same problem on Ubuntu in a VirtualEnv to solve problem I have used this snippets.In parituclar he make custom User Fields with code: What do you mean by that? Do you have python error and stack trace? This code have to work (as in ). Looks like an eclipse issue. Just run dev server and see if it works or not:
Python

Is it possible with Python to set the timezone just like this in PHP:I can't really install any other modules etc as I'm using shared web hosting.Any ideas?To get the specific values you've listed:See  for a complete list of directives. Keep in mind that the strftime() function will always return a string, not an integer or other type.It's not an answer, but...To get  components individually, better use :It's now easy to get the parts:
Python

I was wondering if it is possible to perform a certain number of operations without storing the loop iteration number anywhere.For instance, let's say I want to print two \"hello\" messages on the console. Right now I know I can do:but then the \"i\" variable is going to take the values 0 and 1 (which I don't really need). Is there a way to achieve the same thing without storing that anywhere?I know it's not big deal... I'm just curious :-)Thank you in advanceThe idiom (shared by quite a few other languages) for an unused variable is a single underscore . Code analysers typically won't complain about  being unused, and programmers will instantly know it's a shortcut for . There is no way to iterate without having an item variable - as the Zen of Python puts it, \"special cases aren't special enough to break the rules\".should work, but I'm kind of ashamed that I thought of it.  Just thought of another one:Well I think the forloop you've provided in the question is about as good as it gets, but I want to point out that unused variables that have to be assigned can be assigned to the variable named , a convention for \"discarding\" the value assigned. Though the  reference will hold the value you gave it, code linters and other developers will understand you aren't using that reference. So here's an example:Although I agree completely with delnan's answer, it's not impossible:Note, however, that this will not work for an arbitrary list: If the first value in the list (the last one popped) does not evaluate to , you will get another iteration and an exception on the next pass: . Also, your list () will be empty after the loop.Just for curiosity's sake. ;)Sorry, but in order to iterate over anything in any language, Python and English included, an index must be stored. Be it in a variable or not. Finding a way to obscure the fact that python is internally tracking the for loop won't change the fact that it is. I'd recommend just leaving it as is.Others have addressed the inability to completely avoid an iteration variable in a  loop, but there are options to reduce the work a tiny amount.  has to generate a whole bunch of numbers after all, which involves a tiny amount of work; if you want to avoid even that, you can use  to just get the same (ignored) value back over and over, which involves no creation/retrieval of different objects:This will run faster in microbenchmarks than , but if the loop body does meaningful work, it's a drop in the bucket. And unlike multiplying some anonymous sequence for your loop iterable,  has only a trivial setup cost, with no memory overhead dependent on length.It's not idiomatic Python, but neither is what you're trying to do.It turns out that using dummy* (starting word is dummy) as a variable do the same trick as _. But you don't mess with already defined and sometimes used variable or a function. 
Python

To deal with the  in django-admin, I've put special cases into two of the templates to create links between the admin change pages and inline admins of two models.I would like a general solution that I can apply to the admin change page or inline admin of any model.I have one model,  (not its real name) that is both an inline on the  admin page, and also has its own admin page. The reason it can't just be inline is that it has models with foreign keys to it that only make sense when edited with it, and it only makes sense when edited with .For the  admin page, I changed part of \"fieldset.html\" from:toto create a link to the  admin page, where  is a method on the model:I couldn't find the  of the  instance anywhere outside .On the  admin page, where  is inline, I modified part of \"stacked.html\" from:toto create a link to the  admin page since here I was able to find the  stored in the foreign key field.New in Django 1.8 : .Set  to  (False by default) in your inline model, so that inline objects have a link to their change form (where they can have their own inlines).Use :This is my current solution, based on what was suggested by Pannu (in his edit) and Mikhail.I have a couple of top-level admin change view I need to link to a top-level admin change view of a related object, and a couple of inline admin change views I need to link to the top-level admin change view of the same object. Because of that, I want to factor out the link method rather than repeating variations of it for every admin change view.I use a class decorator to create the  callable, and add it to .You can also pass a custom callable if you need to get your link text in some way than just calling  on the object you're linking to.I use it like this:Of course none of this would be necessary if I could nest the admin change views for  and  inside the inline admin of  on the  admin change page without patching Django.I think that agf's solution is pretty awesome -- lots of kudos to him. But I needed a couple more features:Solution:Usage:I am sorry that the example is so illogical, but I didn't want to use my data.I agree that its hard to do template editing so, I create a custom widget to show an  on the admin change view page(can be used on both forms and inline forms).So, I used the anchor widget, along with form overriding to get the link on the page.now in your  override the  attribute and you should get the desired result. I assumed you have a  relationship between these tables, If you have one to many then the  side will not work.  \n    I've made some changes to dynamically add links and that also solves the  issue with the  to  hope this solves the issue. :)\n   In Your  I noticed , that means your trying to show the  link on  which lists all the posts. If I'm correct then you should add a method to show the link on the page.As far as the showing  links on   you can do the same as above. My earlier solution will show you the link one level lower at the  page where you can edit each instance.If you want the  page to show the links to the  in the  page then you will have to include each in the  dynamically by overriding the  method for  and adding the link's dynamically, in  set the , but first don't use tuples to for  instead use a list.  Based on agfs and SummerBreeze's suggestions, I've improved the decorator to handle unicode better and to be able to link to backwards-foreignkey fields (ManyRelatedManager with one result). Also you can now add a short_description as a list header:Edit: updated due to link being gone.Looking through the source of the admin classes is enlightening: it shows that there is an object in context available to an admin view called \"original\".Here is a similar situation, where I needed some info added to a change list view:  (on my blog).
Python

In the below example I would expect all the elements to be tuples, why is a tuple converted to a string when it only contains a single string?Because those first two elements aren't tuples; they're just strings. The parenthesis don't automatically make them tuples. You have to add a comma after the string to indicate to python that it should be a tuple.To fix your example code, add a comma here:From the :Your first two examples are not tuples, they are strings. Single-item tuples require a trailing comma, as in: is not a tuple, but just a string.You need to add an extra comma at the end to make  take them as : -
Python

I am trying to solve a big numerical problem which involves lots of subproblems, and I'm using Python's multiprocessing module (specifically Pool.map) to split up different independent subproblems onto different cores. Each subproblem involves computing lots of sub-subproblems, and I'm trying to effectively memoize these results by storing them to a file if they have not been computed by any process yet, otherwise skip the computation and just read the results from the file. I'm having concurrency issues with the files: different processes sometimes check to see if a sub-subproblem has been computed yet (by looking for the file where the results would be stored), see that it hasn't, run the computation, then try to write the results to the same file at the same time. How do I avoid writing collisions like this?@GP89 mentioned a good solution. Use a queue to send the writing tasks to a dedicated process that has sole write access to the file. All the other workers have read only access. This will eliminate collisions.  Here is an example that uses apply_async, but it will work with map too:good luck,MikeIt looks to me that you need to use Manager to temporarily save your results to a list and then write the results from the list to a file.  Also, use starmap to pass the object you want to process and the managed list.  The first step is to build the parameter to be passed to starmap, which includes the managed list.from multiprocessing import Manager, Pool\n   import pandas as pdFrom this point you need to decide how you are going to handle the list.  If you have tons of RAM and a huge data set feel free to concatenate using pandas. Then you can save of the file very easily as a csv or a pickle.
Python

I have a yaml file that looks likeI am able to read this correctly in Perl using YAML but not in python using YAML. It fails with the error: Program:Error:The yaml documents are separated by , and if any stream (e.g. a file) contains more than one document then you should use the  function rather than .  The code:results in for the input file as provided in the question:
Python

I'm using Pandas 0.10.1Considering this Dataframe:How can i group subtotals per state?I tried with a pivot table but i only can have subtotals in columnsI can achieve this on excel, with a pivot table.If you put State and City not both in the rows, you'll get separate margins. Reshape and you get the table you're after:I admit this isn't totally obvious. You can get the summarized values by using groupby() on the State column.Lets make some sample data first:Then apply the groupby function and add a column City:We can append the original data to the summed df by using append:I added the set_index and sort_index to make it look more like your example output, its not strictly necessary to get the results.How about this one ?I Think this subtotal example code is what you want(similar to excel subtotal)I assume that you want group by columns A, B, C, D, than count column value of Eoutput:
Python

I want to handle s both to hide unnecessary parts of the stack trace from the user and to print a message as to why the error occurred and what the user should do about it.I don't want to have to add this to every assert statement:because it repeats information.Use the  module:
Python

I'm getting the following error when performing recursive feature selection with cross-validation:The code that generates the error is the following:I know I should also perform GridSearch for the parameters of the LogisticRegression classifier, but I don't think that's the source of the error (or is it?). I should mention that I'm testing with around 50 features, and almost all of them are categoric (that's why I use the DictVectorizer to transform them appropriately). Any help or guidance you could give me is more than welcome. Thanks!Here's some training data examples:I finally got to solve the problem. Two things had to be done:Thanks to everyone who tried to help!If anyone is still interested,I used the  on something very similar and it gave me the same error. I realized that the vectorizer gives me a COO sparse matrix which is basically a coordinate list. Elements in COO matrices can't be accessed through row indexes. It is best to convert it to a CSR matrix (Compressed Sparse Row) which indexes row-wise. The conversion can be done easily . No other change is required, this worked for me.
Python

Output: I roughly understand about decorators and how it works with one of it in most examples.In this example, there are 2 of it. From the output, it seems that  executes first, then .Does this mean that for decorated functions, it will first run the function first then moving towards to the top for other decorators? Like  first then , instead of the opposite.So this means that it is different from the norm of top-down approach in most programming lang? Just for this case of decorator? Or am I wrong? Decorators  the function they are decorating. So  decorated the result of the  decorator, which decorated the  function.The  syntax is really just syntactic sugar; the following:is really executed as:replacing the original  object with whatever  returned.Stacking decorators repeats that process .So your sample:can be expanded to:When you call  now, you are calling the object returned by , really.  returned a  that calls the function  wrapped, which is the return value of , which is also a lambda that calls the original . Expanding all these calls you get:so the output becomes:
Python

As a toy example I'm trying to fit a function  from 100 no-noise data points. The matlab default implementation is phenomenally successful with mean square difference ~10^-10, and interpolates perfectly.I implement a neural network with one hidden layer of 10 sigmoid neurons. I'm a beginner at neural networks so be on your guard against dumb code.Mean square difference ends at ~2*10^-3, so about 7 orders of magnitude worse than matlab. Visualising withwe can see the fit is systematically imperfect:\n\nwhile the matlab one looks perfect to the naked eye with the differences uniformly < 10^-5:\n\nI have tried to replicate with TensorFlow the diagram of the Matlab network:Incidentally, the diagram seems to imply a tanh rather than sigmoid activation function. I cannot find it anywhere in documentation to be sure. However, when I try to use a tanh neuron in TensorFlow the fitting quickly fails with  for variables. I do not know why.Matlab uses Levenberg\u2013Marquardt training algorithm. Bayesian regularization is even more successful with mean squares at 10^-12 (we are probably in the area of vapours of float arithmetic).Why is TensorFlow implementation so much worse, and what can I do to make it better?I tried training for 50000 iterations it got to 0.00012 error. It takes about 180 seconds on Tesla K40.It seems that for this kind of problem, first order gradient descent is not a good fit (pun intended), and you need Levenberg\u2013Marquardt or l-BFGS. I don't think anyone implemented them in TensorFlow yet.\nUse  for this problem. It gets to  after 4000 iterations. Also, GPU with default strategy also seems like a bad idea for this problem. There are many small operations and the overhead causes GPU version to run 3x slower than CPU on my machine.btw, here's a slightly cleaned up version of the above that cleans up some of the shape issues and unnecessary bouncing between tf and np.  It achieves 3e-08 after 40k steps, or about 1.5e-5 after 4000:All that said, it's probably not too surprising that LMA is doing better than a more general DNN-style optimizer for fitting a 2D curve.  Adam and the rest are targeting very high dimensionality problems, and  (see 12-15).
Python

I want my Python script to be able to read Unicode command line arguments in Windows. But it appears that sys.argv is a string encoded in some local encoding, rather than Unicode. How can I read the command line in full Unicode?Example code: On my PC set up for Japanese code page, I get:That's Shift-JIS encoded I believe, and it \"works\" for that filename. But it breaks for filenames with characters that aren't in the Shift-JIS character set\u2014the final \"open\" call fails:Note\u2014I'm talking about Python 2.x, not Python 3.0. I've found that Python 3.0 gives  as proper Unicode. But it's a bit early yet to transition to Python 3.0 (due to lack of 3rd party library support).A few answers have said I should decode according to whatever the  is encoded in. The problem with that is that it's not full Unicode, so some characters are not representable.Here's the use case that gives me grief: I have . I have file names with all sorts of characters, including some not in the system default code page. My Python script doesn't get the right Unicode filenames passed to it via sys.argv in all cases, when the characters aren't representable in the current code page encoding.There is certainly some Windows API to read the command line with full Unicode (and Python 3.0 does it). I assume the Python 2.x interpreter is not using it.Here is a solution that is just what I'm looking for, making a call to the Windows  function:\n (from ActiveState)But I've made several changes, to simplify its usage and better handle certain uses. Here is what I use:Now, the way I use it is simply to do:and from then on,  is a list of Unicode strings. The Python  module seems happy to parse it, which is great.Dealing with encodings is very confusing.I  if your inputing data via the commandline it will encode the data as whatever your system encoding is and is not unicode. (Even copy/paste should do this)So it should be correct to decode into unicode using the system encoding:running the following Will output:\n    Prompt> python myargv.py \"PC\u30fb\u30bd\u30d5\u30c8\u7533\u8acb\u66f808.09.24.txt\"Where the \"PC\u30fb\u30bd\u30d5\u30c8\u7533\u8acb\u66f808.09.24.txt\" contained the text, \"\u65e5\u672c\u8a9e\".\n(I encoded the file as utf8 using windows notepad, I'm a little stumped as to why there's a '?' in the begining when printing.  Something to do with how notepad saves utf8?)The strings 'decode' method or the unicode() builtin can be used to convert an encoding into unicode.Also, if your dealing with encoded files you may want to use the codecs.open() function in place of the built-in open().  It allows you to define the encoding of the file, and will then use the given encoding to transparently decode the content to unicode.So when you call   will be in unicode.codecs.open:\nIf I'm miss-understanding something please let me know.If you haven't already I recommend reading Joel's article on unicode and encoding:\nTry this:Maybe you have to substitute  or  for . You should be able to infer the proper encoding name from the registry key The command line might be in Windows encoding. Try decoding the arguments into  objects:
Python

With pytest, one can mark tests using a decoratorThen, from the command line, one can tell pytest to skip the tests marked \"slow\"If I have an additional tag:I would like to be able to skip both long AND slow tests.  I've tried this:and this:And neither seems to work.At the command line, how do I tell pytest to skip both the slow AND the long tests?Additionally, with the recent addition of the \"-m\" command line option you should be able to write:IOW, the \"-m\" option accepts an expression which can make use of markers as boolean values (if a marker does not exist on a test function it's value is False, if it exists, it is True).  Looking through the  code () and further experimentation shows the following seems to work:(Using the  option speeds up experimentation)It's also possible to stack the mark decorators.I then called  and only the tests with both decorators were called. resulted in the other tests running
Python

I have a dataframe  in pandas that was built using  from a csv file. The dataframe has several columns and it is indexed by one of the columns (which is unique, in that each row has a unique value for that column used for indexing.) How can I select rows of my dataframe based on a \"complex\" filter applied to multiple columns? I can easily select out the slice of the dataframe where column  is greater than 10 for example:But what if I wanted a filter like: select the slice of  where  of the columns are greater than 10? Or where the value for  is greater than 10 but the value for  is less than 5?How are these implemented in pandas?\nThanks.I encourage you to pose these questions on the , but in any case, it's still a very much low level affair working with the underlying NumPy arrays. For example, to select rows where the value in any column exceed, say, 1.5 in this example:Multiple conditions have to be combined using  or  (and parentheses!):I'd be very interested to have some kind of query API to make these kinds of things easierThere are at least a few approaches to shortening the syntax for this in Pandas, until it gets a full query API down the road (perhaps I'll try to join the github project and do this is time permits and if no one else already has started).One method to shorten the syntax a little is given below:To fully solve this, one would need to build something like the SQL select and where clauses into Pandas. This is not trivial at all, but one stab that I think might work for this is to use the Python  built-in module. This allows you to treat things like greater-than as functions instead of symbols. So you could do the following:Then a test example like yours would be to do the following:You can shorten the syntax even further by either building in more arguments to  to handle the different common logical operators automatically, or by importing them into the namespace with shorter names.Note that the  function above only works with logical-and chains of constraints. You'd have to modify it to get different logical behavior. Or use  and DeMorgan's Laws.
Python

Let we have this code:The Python documentation says about  statement:So, the question is:\nDoes  execute every time when  is invoked?\nQuestion is about  statement exactly, not the  body.You can check the bytecode with the  module:As you can see the code for the inner function is  only . Every time you call  it is loaded and a new function object is created(in this sense the   executed every time  is called), but this doesn't add much overhead.The code in the inner function is compiled only once, so there shouldn't be a significant runtime penalty.Only inner's function  gets updated each time the outer function is called.  See , for example, for more details about closures.Here's a quick demonstration, examining the closure:
Python

I understand that Django, PyPy, and Psycopg2 all work correctly together, and  claims great performance improvements over CPython. Are there any downsides?The PyPy  lists Django as compatible, but it doesn't go into great detail about how much of Django was tested. I am not aware of any major Django deployment that runs PyPy instead of CPython. A better question is why you'd want to switch to PyPy for a Django app, especially as Django has been extensively tested and deployed with CPython.PyPy is good for tasks that are computationally intensive. Web apps are usually not. The Django benchmark they base their performance numbers off is essentially a template rendering benchmark which is a CPU intensive task. This is not representative of most web apps where the bottle neck tends to be I/O. As such, PyPy may not speed up your site as much as those graphs lead you to believe.
Python

when I read the file I seeAm i doing anything wrong?This is the full text of the blog post linked below:If you've tried installing a package with pip recently, you may have encountered this error:This seems to be an issue with an old version of OpenSSL being incompatible with pip 1.3.1. If you're using a non-stock Python distribution (notably EPD 7.3), you're very likely to have a setup that isn't going to work with pip 1.3.1 without a shitload of work.The easy workaround for now, is to install pip 1.2.1, which does not require SSL:If you are using EPD, and you're not using it for a class where things might break, you may want to consider installing the new incarnation: Enthought Canopy. I know they were aware of the issues caused by the previous version of OpenSSL, and would imagine they are using a new version now that should play nicely with pip 1.3.1.I used to use the  workaround but I randomly  that if you're having this bug, you probably installed a 32bit version of python on a  64bit machine.In short : If you install a 64bit version of it by installing it from the source and then build your virtualenv upon it, you wont have that pip bug anymore.It's because in the pip configuration the index-url parameter should point to the new pypi url.Probably you have this:You shoudl change it for this:And then all should work as before.\nI hope it helps you.I had a similar problem with pip and easy_install:As suggested in the referenced blog post, there must be an issue with some older versions of OpenSSL being .Installing pip-1.2.1 is a working workaround..This definitely happens in RHEL/CentOS 4 distrosI faced the same issue and this error is because of 'Proxy Setting'. The syntax below helped me in resolving it successfully:The explanation is in your logs:Notice the . It seems the site was down when you were trying to do this. It's good to know that HTTP 5xx errors are server side errors, so you can know the problem was not in your local network but in the remote network.It means try again later ;-) (and cross fingers...) (It works for me now btw.)This has happened to my because of proxy-authntication, so I did this to resolve itOn Virtualenv try , like so:look at the first line and check if it corresponds to the project folder, if not just change it.pip has As of version 1.5, :Your system clock is likely set in the past.Check the time using the date command and set it rightI had the same issue with pip 1.5.6.I just deleted the ~/.pip folder and it worked like a charm.I had this error message occur as I had set a Windows Environment Variable to an invalid certificate file.Check if you have a CURL_CA_BUNDLE variable by typing  at the command prompt. You can override it for the current session with The pip.log contained the following:For me it worked a simple .As  states,  ignores installed packages, forcing reinstall instead.In my case the https port (443) wasn't open so my firewall blocked all traffic and pip couldn't download the packages. I had that problem too, after I tried to reset my network settings. it solves problem.This problem is most-likely caused by DNS setup: server cannot resolve the Domain Name, so cannot download the package. Solution: add a line: dns-nameservers 8.8.8.8save file and exitThen pip install should be working now. 
Python

I can get Python to work with Postgresql but I cannot get it to work with MySQL. The main problem is that on the shared hosting account I have I do not have the ability to install things such as Django or PySQL, I generally fail when installing them on my computer so maybe it's good I can't install on the host.I found  really good because it does not require an install, it's a single file that I can look at, read and then call the functions of. Does anybody know of something like this for MySQL?MySQLdb is what I have used before.If you host is using Python version 2.5 or higher, support for sqlite3 databases is built in (sqlite allows you to have a relational database that is simply a file in your filesystem).  But buyer beware, sqlite is not suited for production, so it may depend what you are trying to do with it.Another option may be to call your host and complain, or change hosts.  Honestly these days, any self respecting web host that supports python and mysql ought to have MySQLdb pre installed.I don't have any experience with  as a web host personally.  This is just a guess, but it's common for a shared host to support Python and MySQL with the MySQLdb module (e.g., GoDaddy does this).  Try the following CGI script to see if MySQLdb is installed.I uploaded it and got an internal errorAfter much playing around, I found that if I hadIt would give me a much more useful answer and say that it was not installed, you can see it yourself -> Oddly enough, this would produce an errorI looked at some of the other files I had up there and it seems that library was one of the ones I had already tried.You could try setting up your own python installation using .  Check out how to setup Django using it .  That was written a long time ago, but it shows how I got MySQLdb setup without having root access or anything like it.  Once you've got the basics going, you can install any python library you want.You really want MySQLdb for any MySQL + Python code.  However, you shouldn't need root access or anything to use it.  You can build/install it in a user directory (~/lib/python2.x/site-packages), and just add that to your PYTHON_PATH env variable.  This should work for just about any python library.Give it a shot, there really isn't a good alternative.Take a pick atMySQLdb is mostly used driver, but if you are using python3 and django 1.8.x that will not work, then you should use mysqlclient that is a folk of MySQLdb on the following link
Python

I see quit a few implementations of unique string generation for things like uploaded image names, session IDs, et al, and many of them employ the usage of hashes like SHA1, or others.I'm not questioning the legitimacy of using custom methods like this, but rather just the reason. If I want a unique string, I just say this:And I'm done with it. I wasn't very trusting before I read up on uuid, so I did this:Not one repeater (I wouldn't expect one now considering the odds are like 1.108e+50, but it's comforting to see it in action). You could even half the odds by just making your string by combining 2 s.So, with that said, why do people spend time on random() and other stuff for unique strings, etc? Is there an important security issue or other regarding uuid?Using a hash to uniquely identify a resource allows you to generate a 'unique' reference from the object. For instance, Git uses SHA hashing to make a unique hash that represents the exact changeset of a single a commit. Since hashing is deterministic, you'll get the same hash for the same file every time. Two people across the world could make the same change to the same repo independently, and Git would know they made the same change. UUID v1, v2, and v4 can't support that since they have no relation to the file or the file's contents.Well, sometimes you want collisions.  If someone uploads the same exact image twice, maybe you'd rather tell them it's a duplicate rather than just make another copy with a new name.One possible reason is that you want the unique string to be human-readable.  UUIDs just aren't easy to read.uuids are long, and meaningless (for instance, if you order by uuid, you get a meaningless result).And, because it's too long, I wouldn't want to put it in a URL or expose it to the user in any shape or form.In addition to the other answers, hashes are really good for things that should be immutable. The name is unique and can be used to check the integrity of whatever it is attached to at any time.Also note other kinds of UUID could even be appropriate.  For example, if you want your identifier to be orderable, UUID1 is based in part on a timestamp.  It's all really about your application requirements...
Python

No idea why this error is popping up. Here are the models I created -Here is the view from which I access these models - At this point I get an error - As you see this column is not even present in my models? Why this error?maybe your tables schema has been changed? Also, running  does not update already created tables.You might need to drop all the tables & then run  again. Also remember to take backup of your data!!As @inception said my tables schema had changed & running  did not update already created tables.Apparently any changes to the models when updated through  does not change (as in update/modify) the actual tables. So I dropped the relevant DB & ran  on empty DB. Now it works fine. :) For others,  data migration tool for Django seems to be favorite option. It seems to provide options which django models &  falls short on. Must check out...Normally I get this when when I'm trying to access field which doesn't exist in Database.Check if the field exist in the database. If you change model and perform syncdb it won't update the database, I'm not sure if that's the case. On other note Django offers shortcut to replace try/except block in your code using get_object_or_404. (available in django.shortcuts )can be changed to:I have met the same problems:First, run and you can find:and I add the column manual:and then it worked.I think django will add the column called id itself.you can click  for details.Good luck.I created a model file for my app and then did several  as I refined my tables. One of the changes I made was I set  to one of my fields. At the end called for . Added a dummy value and and tried to access it with ,  being my model class. Although this worked fine, this error came up while printing the list returned by the  call. It read Surprisingly, I tried and could get it resolved with another call to . I remember not having seen the id column in the table at any time throughout the exercise when I checked it through the mysql command line client.In the appropriate field explicitly setI received this error while trying to use Django Rest Framework serializers. Make sure if you have a serializer that subclasses , that you migrate any changes to the Models before writing your serializer classes (or just comment anything related to the serializer, migrate, then uncomment). 
Python

I have just started learning Python & have come across  concept in Python. While I got the jist of what it is, but am unable to appreciate the gravity of this concept. Some browsing on the net revealed that one of the reasons going against PHP is that it has no native support for namespaces. (not just in Python, as I assume namespaces in not a concept limited to a particular language). I am predominantly coming from Java and C programming backgrounds.Namespace is a way to implement scope.In Java (or C) the compiler determines where a variable is visible through static scope analysis.  In Python, each package, module, class, function and method function owns a \"namespace\" in which variable names are resolved.  Plus there's a global namespace that's used if the name isn't in the local namespace.Each variable name is checked in the local namespace (the body of the function, the module, etc.), and then checked in the global namespace.Variables are generally created only in a local namespace.  The  and  statements can create variables in other than the local namespace.When a function, method function, module or package is evaluated (that is, starts execution) a namespace is created.  Think of it as an \"evaluation context\".  When a function or method function, etc., finishes execution, the namespace is dropped.  The variables are dropped.  The objects may be dropped, also.Namespaces prevent conflicts between classes, methods and objects with the same name that might have been written by different people.Coming from a Java background you are probably familiar with how this is achieved using packages e.g. you might create a  class and I can create a  class and the package allows code using the classes to distinguish between them. (Python has .)Namespaces were added to PHP in 5.3.0 but in earlier versions (and in other languages that don't provide namespaces) you would have to prefix your class and method names with something to reduce the risk of a name clash. e.g. a  function.To understand namespaces, you also have to have some understanding of modules in Python. A module is simply a file containing Python code. This code can be in the form of Python classes, functions, or just a list of names. Each module gets it\u2019s own global namespaces. So you can\u2019t have two classes or two functions in the same module with the same name as they share the namespace of the module.reference: If you make a big program with someone else, you could write your own part of the program as you want. All variables in the file will be private, there will be no collisions.\nWhen you write PHP programs, it is easy to rewrite global variables by mistake. In python you can import other modules variables if you want, and they will be \"global\" on your module.You could think one file one object in Python. When you write PHP programs you can achieve the same by writing classes with instance variables.I complete the answer of S.Lott.I would say, namespace is a way to implement name management inside a scope, because a scope does more than name management.In C the scopes are of 4 types: global, function, block and function-parameters(prototype).  Each of these kinds can create one or more namespaces, depending on the needs. There are 4 ns in C\n -- tags for s/u/e\n -- ids for typenames, function names and var names\n -- parameters inside function prototype\n -- members and bitfields inside s/u.Like that, tag identifiers and function names do not collide, but typenames defined by typedef can collide with variable names.In  python there is a builtin namespace that encloses the global ns, and the global ns is provided by the loaded module. The builtin ns contain variables.  A symbol for a variable can define an object or a function -- for example,  is defined there.  The module's global ns lasts up to the termination.See also  and of course .
Python

I've seen this argument in a few places, and now, recently i saw it again on a reddit post.\nThis is by no means a flame against any of these two languages. I am just puzzled why there is this bad reputation about python not being scalable.\nI'm a python guy and now I'm getting started with Java and i just want to understand what makes Java so scalable and if the python setup that I have in mind is a good way to scale large python apps.Now back to my idea of scaling a Python app. Let's say you code it using Django. Django runs its apps in fastcgi mode. So what if you have a front Nginx server and behind it as many other servers as needed that will each run your Django app in fastcgi mode. The front Nginx server will then load balance between your backend Django fastcgi running servers. Django also supports multiple databases so you could write to one master DB and then read from many slaves, again for load balancing. Throw a memcached server in to this mix and there you go you have scalability. Don't you? Is this a viable setup? What does Java makes better? How do you scale a Java app?Scalability is a very overloaded term these days. The comments probably refer to in-process vertical scalability.Python has a global interpreter lock (GIL) that severely limits its ability to scale up to many threads. It releases it when calling native code (reacquiring it when the native returns), but this still requires careful design when trying to write scalable software in Python.While I don't agree with the statement, I suppose they think Java is more scalable because it runs a  faster. The JVM is very efficient (except perhaps in memory usage). Also Python's GIL (Global Interpreter Lock) doesn't allow \"real\" threading, while Java doesn't have a GIL and has true multithreading.Without getting into a flamewar, consider how Python handles multi-threaded apps as compared to Java? For example, what global locks are in place in both languages that hurt concurrency (hint, Python's GIL - Global Interpreter Lock)?I think this article sums up many of the arguments about scaling and dynamic languages:It's worth noting its two definition for scaling...One often used argument about any dynamic language scaling is that as the code-base grows it becomes harder to refactor it without IDE support. Due to the lack of type information at compile time this support is often impossible to implement in dynamic languages.Hmmm - scalable could mean many things - scalable by distributed architecture, scalable by speed?On the scalable by speed front, Java generally can process instructions faster than python - for the right kind of problem, much faster (I guess the main reason for that is that Java is compiled whereas Python is interpreted). From that point of view, Java can generally do more with less, and so is more scalable.I'm referring my source experimental information back to two sources;  and I get mad when I see arguments like this.  Not because I get all butthurt about haters harshing my Python mellow, but because to my mind, saying \"X doesn't scale\" is meaningless.  It is necessary to specify a dimension, at the very least.People are reluctant to do this, as it often reveals the fact that they don't have a good handle on the problem that they're speaking with confidence about.  The global interpreter lock is a good touchstone here:  threads are not the only way to perform concurrent operations.
Python

When I install ipython on my osx and run it, I get the following warning: I have have installed readline, and do not use the system python that was originally installed in . The  points to version 2.7 as shown belowI have read the question in  - I added  to the   so that it now looks like this: but I cannot figure out why I am getting the following error:I do not think the above path is an issue, and my goal is to get ipython to working without complaining about readline even though it is installed and imports correctly.When pip installs readline, it will never be imported, because readline.so goes in site-packages, which ends up behind the libedit System one, located in  (OSX Python path order is very odd).   will actually install usable readline.  So you can either use easy_install, or use pip and muck about with your PYTHONPATH/sys.path (which essentially means: DO NOT USE PIP).A bit more detail on the IPython list (though there really isn't anything IPython-specific about this issue): EDIT: extra note about virtualenv.There is a bug in virtualenv < 1.8.3, where readline would not be properly staged when you create an env.If you don't mind mucking around with your PYTHONPATH, here's how you can get rid of that pesky warning:If you're using Django, you can put this in the  method of your site-packages/django/core/management/commands/shell.py so that it runs when you run .Additional note to future readers of this answer.In my case -- running a MacPorts installation of IPython -- there were several versions of  in /opt/local/bin/, but no non-versioned symlink pointing to the most current. Performing  worked.
Python

Suppose I have an arrayHow can I (efficiently, Pythonically) find which elements of  are duplicates (i.e., non-unique values)?  In this case the result would be  or possibly  if efficient.I've come up with a few methods that appear to work:This one is cute but probably illegal (as  isn't actually unique):Is there anything I've missed?  I'm not necessarily looking for a numpy-only solution, but it has to work with numpy data types and be efficient on medium-sized data sets (up to 10 million in size).Testing with a 10 million size data set (on a 2.8GHz Xeon):The fastest is sorting, at 1.1s.  The dubious  is second at 2.6s, followed by masking and Pandas  at 3.1s,  at 5.6s, and  and senderle's  both at 7.3s.  Steven's  is only a little slower, at 10.5s; trailing behind are Burhan's  at 110s and DSM's  subtraction at 360s.I'm going to use sorting for performance, but I'm accepting Steven's answer because the performance is acceptable and it  clearer and more Pythonic.Edit: discovered the Pandas solution.  If Pandas is available it's clear and performs well.I think this is most clear done outside of .  You'll have to time it against your  solutions if you are concerned with speed.  This is similar to Burhan Khalid's answer, but the use of  without subscripting in the condition should be faster.People have already suggested  variants, but here's one which doesn't use a listcomp:[Posted not because it's efficient -- it's not -- but because I think it's cute that you can subtract  instances.]For Python 2.7+Here's another approach using set operations that I think is a bit more straightforward than the ones you offer:I suppose you're asking for -only solutions, since if that's not the case, it's very difficult to argue with just using a  instead. I think you should make that requirement explicit though.If  is made up of small integers you can use numpy.bincount directly:This is very similar your \"histogram\" method, which is the one I would use if  was not made up of small integers.If the array is a sorted numpy array, then just do:I'm adding my solution to the pile for this 3 year old question because none of the solutions fit what I wanted or used libs besides numpy. This method finds both the indices of duplicates and values for  sets of duplicates.
Python

What's the proper way to tell a looping thread to stop looping? I have a fairly simple program that pings a specified host in a separate  class. In this class it sleeps 60 seconds, the runs again until the application quits.I'd like to implement a 'Stop' button in my  to ask the looping thread to stop. It doesn't need to end the thread right away, it can just stop looping once it wakes up. Here is my  class (note: I haven't implemented looping yet, but it would likely fall under the run method in PingAssets)And in my wxPyhton Frame I have this function called from a Start button:This has been asked before on Stack. See the following links:Basically you just need to set up the thread with a stop function that sets a sentinel value that the thread will check. In your case, you'll have the something in your loop check the sentinel value to see if it's changed and if it has, the loop can break and the thread can die.Instead of subclassing , one can modify the function to allow\nstopping by a flag.We need an object, accessible to running function, to which we set the flag to stop running.We can use  object.The trick is, that the running thread can have attached additional properties. The solution builds\non assumptions:Running the code, we get following output:Other alternative is to use  as function argument. It is by\ndefault , but external process can \"set it\" (to ) and function can\nlearn about it using  function.We can  with zero timeout, but we can also use it as the sleeping timer (used below).Advantage of pill to kill is better seen, if we have to stop multiple threads\nat once, as one pill will work for all.The  will not change at all, only the  handles the threads a bit differently.I read the other questions on Stack but I was still a little confused on communicating across classes. Here is how I approached it:I use a list to hold all my threads in the  method of my wxFrame class: As recommended in  I use a signal in my thread class which is set to  when initializing the threading class.and I can stop these threads by iterating over my threads:
Python

I have searched for other posts, as I felt this is a rather common problem, but all other Python exception questions I have found didn't reflect my problem.I will try to be as specific here as I can, so I will give a direct example. And pleeeeease do not post any workarounds for this specific problem. I am not specifically interested how you can send an email much nicer with xyz.\nI want to know how you generally deal with dependent, error prone statements.My question is, how to handle exceptions nicely, ones that depend on one another, meaning:\nOnly if the first step was successful, try the next, and so on. One more criterion is: All exceptions have to be caught, this code has to be robust.For your consideration, an example:This looks extremely unpythonic to me, and the error handling code is triple the real business code, but on the other hand how can I handle several statements that are dependent on one another, meaning statement1 is prerequisite for statement2 and so on?I am also interested in proper resource cleanup, even Python can manage that for itself. Thanks, TomInstead of using the try/except's else block, you could simply return when it errors:That's perfectly readable and Pythonic..Another way of doing this is, rather than worry about the specific implementation, decide how you want your code to look, for example..Then write the code for the  method, catching any errors you expect, and raising your own custom one, and handle that where it's relevant. Your class may look something like..In general, you want to use as few try blocks as possible, distinguishing failure conditions by the kinds of exceptions they throw.  For instance, here's my refactoring of the code you posted:Here, we use the fact that smtplib.SMTP(), server.login(), and server.sendmail() all throw different exceptions to flatten the tree of try-catch blocks.  In the finally block we test server explicitly to avoid invoking quit() on the nil object.We could also use three  try-catch blocks, returning False in the exception conditions, if there are overlapping exception cases that need to be handled separately:This isn't quite as nice, as you have to kill the server in more than one place, but now we can handle specific exception types different ways in different places without maintaining any extra state.If it was me I would probably do something like the following:All errors are caught and debugged, the return value == True on success, and the server connection is properly cleaned up if the initial connection is made.Just using one try-block is the way to go. This is exactly what they\nare designed for: only execute the next statement if the previous\nstatement did not throw an exception. As for the resource clean-ups,\nmaybe you can check the resource if it needs to be cleaned up\n(e.g. myfile.is_open(), ...) This does add some extra conditions, but\nthey will only be executed in the exceptional case. To handle the case\nthat the same Exception can be raised for different reasons, you\nshould be able to retrieve the reason from the Exception.I suggest code like this:It is no uncommon, that error handling code exceeds business code. Correct error handling can be complex.\nBut to increase maintainability it helps to separate the business code from the error handling code.I would try something like this:All of the methods (including , really) follow the same protocol:  they return True if they succeeded, and unless they actually  an exception, they don't trap it.  This protocol also makes it possible to handle the case where a method needs to indicate that it failed without raising an exception.  (If the only way your methods fail is by raising an exception, that simplifies the protocol.  If you're having to deal with a lot of non-exception failure states outside of the method that failed, you probably have a design problem that you haven't worked out yet.)The downside of this approach is that all of the methods have to use the same arguments.  I've opted for none, with the expectation that the methods I've stubbed out will end up manipulating class members.The upside of this approach is considerable, though.  First, you can add dozens of methods to the process without  getting any more complex.  You can also go crazy and do something like this:...though at that point, I might say to myself, \"self, you're working the Command pattern pretty hard without creating a Command class.  Maybe now is the time.\"Why not one big try: block? This way, if any exception is caught, you'll go all the way to the except. And as long as all the exceptions for the different steps are different, you can always tell which part it was that fired the exception.I like David's answer but if you are stuck on the server exceptions you can also check for server if is None or states.  I flattened out the method a bit bit it is still a but unpythonic looking but more readable in the logic at the bottom.
Python

I'm writing a mixin which will allow my Models to be easily translated into a deep dict of values (kind of like .values(), but traversing relationships). The cleanest place to do the definitions of these seems to be in the models themselves, a la:However, Django complains about my including this in  with:(entire stack trace )Now, I suppose I could elaborately override this in my mixin, but is there a more elegant way of storing this information?I don't know about elegant, but one pragmatic way is:Obviously, this would break if Django ever added a 'schema' attribute of its own. But hey, it's a thought...you could always pick an attribute name which is less likely to clash.
Python

When I try to open a file in  mode with the following code:Gives me the following error:The \"w\" mode should create the file if it doesn't exist, right? So how can this error ever occur?You'll see this error if the  containing the file you're trying to open does not exist, even when trying to open the file in \"w\" mode.Since you're opening the file with a relative path, it's possible that you're confused about exactly what that directory is. Try putting a quick print to check:Since you don't have a 'starting' slash, your python script is looking for this file relative to the current working directory (and not to the root of the filesystem). Also note that the directories leading up to the file must exist!And: use  to combine elements of a path.e.g.: Check that that the script has write permissions on that directory. Try this:Note that this will give write permissions to everyone on that directory.I had the same error, but in my case the cause was, under Windows, a path longer than ~250 characters.
Python

I'm trying to compare a image to a list of other images and return a selection of images (like Google search images) of this list with up to 70% of similarity.I get this code in  and change for my contextMy question is, how can I compare the image with the list of images and get only the similar images? Is there any method to do this?I suggest you to take a look to the earth mover's distance (EMD) between the images.\nThis metric gives a feeling on how hard it is to tranform a normalized grayscale image into another, but can be generalized for color images. A very good analysis of this method can be found in the following paper:It can be done both on the whole image and on the histogram (which is really faster than the whole image method). I'm not sure of which method allow a full image comparision, but for histogram comparision you can use the  function.The only problem is that this method does not define a percentage of similarity, but a distance that you can filter on.I know that this is not a full working algorithm, but is still a base for it, so I hope it helps.Here is a spoof of how the EMD works in principle. The main idea is having two normalized matrices (two grayscale images divided by their sum), and defining a flux matrix that describe how you move the gray from one pixel to the other from the first image to obtain the second (it can be defined even for non normalized one, but is more difficult).In mathematical terms the flow matrix is actually a quadridimensional tensor that gives the flow from the point (i,j) of the old image to the point (k,l) of the new one, but if you flatten your images you can transform it to a normal matrix, just a little more hard to read.This Flow matrix has three constraints: each terms should be positive, the sum of each row should return the same value of the desitnation pixel and the sum of each column should return the value of the starting pixel.Given this you have to minimize the cost of the transformation, given by the sum of the products of each flow from (i,j) to (k,l) for the distance between (i,j) and (k,l).It looks a little complicated in words, so here is the test code. The logic is correct, I'm not sure why the scipy solver complains about it (you should look maybe to openOpt or something similar):the variable res contains the result of the minimization...but as I said I'm not sure why it complains about a singular matrix.The only problem with this algorithm is that is not very fast, so it's not possible to do it on demand, but you have to perform it with patience on the creation of the dataset and store somewhere the resultsI wrote a program to do something very similar maybe 2 years ago using Python/Cython. Later I rewrote it to Go to get better performance. The base idea comes from  IIRC.It basically computes a \"fingerprint\" for each image, and then compares these fingerprints to match similar images.The fingerprint is generated by resizing the image to 160x160, converting it to grayscale, adding some blur, normalizing it, then resizing it to 16x16 monochrome. At the end you have 256 bits of output: that's your fingerprint. This is very easy to do using :(The  in  is used to only extract the first frame of animated GIFs; if you're not interested in such images you can just remove it.)After applying this to 2 images, you will have 2 (256-bit) fingerprints,  and .The similarity score of these 2 images is then computed by XORing these 2 values and counting the bits set to 1. To do this bit counting, you can use the  function from : will be a number between 0 and 256 indicating how similar your images are. In my application I divide it by 2.56 (normalize to 0-100) and I've found that images with a normalized score of 20 or less are often identical.If you want to implement this method and use it to compare lots of images, I  suggest you use Cython (or just plain C) as much as possible: XORing and bit counting is very slow with pure Python integers.I'm really sorry but I can't find my Python code anymore. Right now I only have a Go version, but I'm afraid I can't post it here (tightly integrated in some other code, and probably a little ugly as it was my first serious program in Go...).There's also a very good \"find by similarity\" function in GQView/Geeqie; its source is .You are embarking on a massive problem, referred to as \"content based image retrieval\", or CBIR.  It's a massive and active field.  There are no finished algorithms or standard approaches yet, although there are a lot of techniques all with varying levels of success.Even Google image search doesn't do this (yet) - they do text-based image search - e.g., search for text in a page that's like the text you searched for.  (And I'm sure they're working on using CBIR; it's the holy grail for a lot of image processing researchers)If you have a tight deadline or need to get this done and working soon... yikes.Here's a ton of papers on the topic:Generally you will need to do a few things:This can involve , , . etc.
Python

Given a sparse matrix listing, what's the best way to calculate the cosine similarity between each of the columns (or rows) in the matrix? I would rather not iterate n-choose-two times.Say the input matrix is:The sparse representation is:In Python, it's straightforward to work with the matrix-input format:Gives:That's fine for a full-matrix input, but I really want to start with the sparse representation (due to the size and sparsity of my matrix). Any ideas about how this could best be accomplished? Thanks in advance.You can compute pairwise cosine similarity on the rows of a sparse matrix directly using sklearn.  As of version 0.17 it also supports sparse output:Results:If you want column-wise cosine similarities simply transpose your input matrix beforehand: The following method is about 30 times faster than . It works pretty quickly on large matrices (assuming you have enough RAM)See below for a discussion of how to optimize for sparsity.If your problem is typical for large scale binary preference problems, you have a lot more entries in one dimension than the other. Also, the short dimension is the one whose entries you want to calculate similarities between. Let's call this dimension the 'item' dimension.If this is the case, list your 'items' in rows and create  using .  Then replace the first line as indicated.If your problem is atypical you'll need more modifications. Those should be pretty straightforward replacements of basic  operations with their  equivalents.You should check out  (). You can apply operations on those sparse matrices just like how you use a normal matrix.Hi you can do it this wayI took all these answers and wrote a script to 1. validate each of the results (see assertion below) and 2. see which is the fastest.\nCode and results are below:Results:
Python

I remember when I was developing in C++ or Java, the compiler usually complains for unused methods, functions or imports.  In my Django project, I have a bunch of Python files which have gone through a number of iterations.  Some of those files have a few lines of import statement at the top of the page and some of those imports are not used anymore.  Is there a way to locate those unused imports besides eyeballing each one of them in each file?All my imports are explicit, I don't usually write  (similar to lint) will give you this information.Use a tool like  which will signal these code defects (among a lot of others).Doing these kinds of 'pre-runtime' checks is hard in a language with dynamic typing, but pylint does a terrific job at catching these typos / leftovers from refactoring etc ...Have a look at . It is a debugging tool and able to find unused variables and modules.If you use the  IDE with  and , it provides automatic checking and highlighting for unused imports, among other things.  It integrates with pylint as well.I have been using  successfully and wished to auto-remove the unused imports.  I recently found :
Python

How does one convert a  from the  to a ? I have yet to find the magical function in  to do this, but one must be there.I like the survival function (upper tail probability) of the normal distribution a bit better, because the function name is more informative:normal distribution \"norm\"  is one of around 90 distributions in scipy.statsnorm.sf also calls the corresponding function in scipy.special as in gotgenes examplesmall advantage of survival function, sf: numerical precision should better for quantiles close to 1 than using the cdfAha! I found it: ! This also appears to be under  as well (which is just a pointer to ).Specifically, given a one-dimensional  instance , one can obtain the p-values asor alternativelyI think the cumulative distribution function (cdf) is preferred to the survivor function. The survivor function is defined as 1-cdf, and may communicate improperly the assumptions the language model uses for directional percentiles. Also, the percentage point function (ppf) is the inverse of the cdf, which is very convenient. from formula
Python

I'm trying to get the links from a page with xpath. The problem is that I only want the links inside a table, but if I apply the xpath expression on the whole page I'll capture links which I don't want.For example:The problem is that applies the expression to the whole document. I located the element I want, for example:But that seems to be performing the query in the whole document as well, as I still am capturing the links outside of the table.  says that \"When xpath() is used on an Element, the XPath expression is evaluated against the element (if relative) or against the root tree (if absolute):\". So, what I using is an absolute expression and I need to make it relative? Is that it?Basically, how can I go about filtering only elements that exist inside of this table?Your xpath starts with a slash () and is therefore absolute. Add a dot () in front to make it relative to the current element i.e.
Python

I understand Django can only be run on Python 2.7 or below.  When will it run on Python 3.1 or above?  I see that Django 1.3 is coming out, does that support Python 3.x?It might run on Python 3 by the end of summer.  I don't know if that means \"officially\" or not, but it doesn't sounds like it, so official support is probably slightly later.The question is why you want to know? You can't run it on Python 3 today. That's all that matters. The day you can run it on python 3, then it matters. Before that it doesn't. [Except to those doing the porting, of course ;-) ].Predicting the future is easy. It's making the predictions come true that is the hard part. :-)Currently Django has passed py3k test.\nThe last port has been made available at \nCheck also news at And, finally, news from PyCon 2012:.Maybe targeting up to python 3.3 as both will be released in the same period (python 3.3 is scheduled for august 2012)    loewis has been working on a port of django to python 3 for a while.On Sept 9th, 2011 jacob (on of the core devs) started the py3k feature branch and pulled these changes in.AFAIK, no official release number or date has been set for when django will support python 3. More info on this thread:, but it is still experimental: The official FAQ mentions it might take , but I don't know when was that last revised. I've been trying hard to find exactly where I've read their exact policies on Python support, but based on Django's , you can understand that it will take some considerable time as it will likely happen through a major release only. Even if they'd decide to provide Py3k support , it could take anything from 1 to 4 major releases to deprecate support from Python 2.4 up to Python 2.7.Django 1.3 will not run on Python3k.Alex Gaynor thinks about making the port a google summer of code project:New version has been come out with Python 3 support (but still experimental). Check it out: 
Python

Is there a way of telling pyplot.text() a location like you can with pyplot.legend()?Something like the legend argument would be excellent:I am trying to label subplots with different axes using letters (e.g. \"A\",\"B\"). I figure there's got to be a better way than manually estimating the position.ThanksJust use  and specify axis coordinates. For example, \"upper left\" would be: You could also get fancier and specify a constant offset in points:For more explanation see the examples  and the more detailed examples .I'm not sure if this was available when I originally posted the question but using the loc parameter can now actually be used. Below is an example:
Python

Just trying to test out very simple Python json commands, but having some trouble.should outputbut I get that same string, with a 'b' in front:Subsequently, when I try to runit gives me the error message, \"TypeError: can't use a string pattern on a bytes-like object\", which I'm assuming has something to do with the 'b'?I imported urlopen from urllib.request, and am running Python 3.Any ideas?The content from read() is of type  so you need to convert it to a string before trying to decode it into a json object.To convert  to a string, change your code to:\nIt worked well :You need to examine the charset specified in the  header and decode by that before passing it to .urllib is returning a byte array, which I assume is the default in py3, and json is expecting a string. Try wrapping the return value in a str() call before invoking the json callLooks like a .  Investigate how you get the data with http,  or how the API returns the data in the headers.
Python

I currently try to use the mock library to write some basic nose unittests in python.After finishing some basic example I now tried to use  and now I have the mock package and the package I tried to 'mock away' are shown in the coverage report. Is there a possibility to exclude these?Here is the class I want to test:And the testcase:\n    from mock import patchI now get the following output for Is there any way to exclude the mock package and the imaplib package  having to manually whitelisting all but those packages by Thanks to Ned Batchelder I now know about the .coveragerc file, thanks for that!I created a .coveragerc file with the following content:Now my output for mock in the coverage report is:It does not cover the mock package any longer but still shows it in the report.I use Coverage.py, version 3.5.2 if this is any help.Create a .coveragerc file that excludes what you don't want in the report: In your .coveragerc move your  entry from the  section to the  section.I had a similar situation testing a series of sub-packages within my main package directory.  I was running  from within the top directory of my module and  and other libraries were included in the coverage report.  I tried using  in nosetests, but then the subpackages were not included.Running the following solved my problem:So,  all the code that you want to test is in the same directory,  you can get coverage for it alone by specifying the module path to .  This avoids the need to whitelist each of the submodules individually.(Python 2.7.6, coverage 4.0.3, nose 1.3.7)
Python

Is there any method to replace values with  in Pandas in Python?You can use  and can replace a value with another, but this can't be done if you want to replace with  value, which if you try, you get a strange result.So here's an example:which returns a successful result.But,which returns a following result:Why does such a strange result be returned?Since I want to pour this data frame into MySQL database, I can't put  values into any element in my data frame and instead want to put . Surely, you can first change  to  and then convert  to , but I want to know why the dataframe acts in such a terrible way.Actually in later versions of pandas this will give a TypeError:You can do it by passing either a list or a dictionary:But I recommend using NaNs rather than None: is probably what you're looking for. SoFrom the : 
Python

I have two dataframes with the following column names:I would like to get a dataframe with the following columns by joining (left) on :I cannot figure out how to do it if the columns on which I want to join are not the index. What's the easiest way? Thanks!you can use the left_on and right_on options as follows:I was not sure from the question if you only wanted to merge if the key was in the left hand dataframe. If that is the case then the following will do that (the above will in effect do a many to many merge)you need to make  as index for the right frame:for your information, in pandas left join breaks when the right frame has non unique values on the joining column. see this .so you need to verify integrity before joining by 
Python

I have a DataFrame like this one:In here, I want to ask how to get column name which has maximum value for each row, the desired output is like this:You can use  to find the column with the greatest value on each row:To create the new column use .You could  on dataframe and get  of each row via Here's a benchmark to compare how slow  method is to  for And if you want to produce a column containing the name of the column with the maximum value but considering only a subset of columns then you use a variation of @ajcr's answer:
Python

On the , an elbow method is described for determining the number of clusters in k-means.  provides an implementation but I am not sure I understand how the distortion as they call it, is calculated. Assuming that I have the following points with their associated centroids, what is a good way of calculating this measure? I am specifically looking at computing the 0.94.. measure given just the points and the centroids. I am not sure if any of the inbuilt methods of scipy can be used or I have to write my own. Any suggestions on how to do this efficiently for large number of points? In short, my questions (all related) are the following:The output for the first set of points is accurate. However, when I try a different set:I guess the last value does not match because  seems to be diving the value by the total number of points in the dataset.My code so far (should be added to Denis's K-means implementation):And following is the output for k=2:On my real dataset (does not look right to me!):The distortion, as far as  is concerned, is used as a stopping criterion (if the change between two iterations is less than some threshold, we assume convergence)If you want to calculate it from a set of points and the centroids, you can do the following (the code is in MATLAB using  function, but it should be straightforward to rewrite in Python/Numpy/Scipy):the result:I had some time to play around with this.. Here is an example of KMeans clustering applied on the  (4 features, 150 instances). We iterate over , plot the elbow curve, pick  as number of clusters, and show a scatter plot of the result.Note that I included a number of ways to compute the within-cluster variances (distortions), given the points and the centroids. The  function returns this measure by default (computed with Euclidean as a distance measure). You can also use the  function to calculate the distances with the function of your choice (provided you obtained the cluster centroids using the same distance measure:  have a solution for that), then compute the distortion from that.\nIn response to the comments, I give below another complete example using the : it has 1797 images of digits from 0 to 9, each of size 8-by-8 pixels. I repeat the experiment above slightly modified:  is applied to reduce the dimensionality from 64 down to 2:\n\nYou can see how some clusters actually correspond to distinguishable digits, while others don't match a single number.Note: An implementation of  is included in  (as well as many other clustering algorithms and various ).  is another similar example.A simple cluster measure:\n1) draw \"sunburst\" rays from each point to its nearest cluster centre,\n2) look at the lengths \u2014 distance( point, centre, metric=... ) \u2014 of all the rays.  For  and 1 cluster,\nthe average length-squared is the total variance ; for 2 clusters, it's less ... down to N clusters, lengths all 0.\n\"Percent of variance explained\" is 100 % - this average.Code for this, under :Like any long list of numbers, these distances can be looked at in various ways: np.mean(), np.histogram() ... Plotting, visualization, is not easy.\nSee also , in particular\n
Python

I know to never use built-in function names as variable identifiers. But are there any reasons not to use them as attribute or method identifiers?For example, is it safe to write , or define an instance method  in my own class?It won't confuse the interpreter but it may confuse people reading your code.  Unnecessary use of builtin names for attributes and methods should be avoided.Another ill-effect is that shadowing builtins confuses syntax highlighters in most python-aware editors (vi, emacs, pydev, idle, etc.)  Also, some of the lint tools will warn about this practice. No, that's fine. Since an object reference is required there is no way to have them shadow the built-in.Yes it's bad practice. It might not immediately break anything for you, but it still hurts readability of the code.To selectively quote from PEP20:Seeing a call to  it would be natural to assume that it's going to return , or that  returns the same thing as It's possible for them to find out that they're wrong; but that will take time and effort and probably lead to some mistakes while they figure it out. Calling your attribute  is much longer, but makes it clearer that it's different to 
Python

Is that possible to add more static paths for my local dev Flask instance?\nI want to have default  folder for storing js/css/images files for the site and another folder, e.g.  to keep my specific assets. I don't want to place  folder inside  if there is a better solution exists.I have been using following approach:The  variable is defined in my configuration.And in templates: - I'm not really sure whether it's secure ;)You can use a Blueprint with its own static dir\nBlueprintTemplate
Python

Ruby's regular expressions have a feature called atomic grouping , described , is there any equivalent in Python's  module?Python does not directly support this feature, but you can emulate it by using a zero-width lookahead assert (), which matches from the current point with the same semantics you want, putting a named group () inside the lookahead, and then using a named backreference () to match exactly whatever the zero-width assertion matched. Combined together, this gives you the same semantics, at the cost of creating an additional matching group, and a lot of syntax.For example, the link you provided gives the Ruby example ofWe can emulate that in Python as such:We can show that I'm doing something useful and not just spewing line noise, because if we change it so that the inner group doesn't eat the final , it still matches:You can also use anonymous groups and numeric backreferences, but this gets awfully full of line-noise:(Full disclosure: I learned this trick from perl's  documentation, which mentions it under the documentation for .)In addition to having the right semantics, this also has the appropriate performance properties. If we port an example out of :We see a dramatic improvement:Which only gets more dramatic as we extend the length of the search string.According to , the answer is no. A  was created to add it to Python 3, but was declined in favor of the new  module, which supports it:Note:  is also available for Python 2.It would seem not.You can emulate the non-capturing-ness of them by using non-capturing groups, , but if I'm reading it right, that still won't give you the optimization benefits.from (?P<name>...)Similar to regular parentheses, but the substring matched by the group is accessible within the rest of the regular expression via the symbolic group name name. Group names must be valid Python identifiers, and each group name must be defined only once within a regular expression. A symbolic group is also a numbered group, just as if the group were not named. So the group named id in the example below can also be referenced as the numbered group 1.For example, if the pattern is (?P[a-zA-Z_]\\w*), the group can be referenced by its name in arguments to methods of match objects, such as m.group('id') or m.end('id'), and also by name in the regular expression itself (using (?P=id)) and replacement text given to .sub() (using \\g).(?P=name)
Python

I connected to a mysql database using python \nThe program that I wrote takes a lot of time in full execution i.e. around 10 hours. Actually, I am trying to read distinct words from a corpus. \nAfter reading was finished there was a timeout error.I checked Mysql default timeouts which were:How can I change the default timeout ?Do:You change default value in MySQL configuration file (option  in  section) -If this file is not accessible for you, then you can set this value using this statement -I know this is an old question but just for the record this can also be done by passing appropriate connection options as arguments to the  call. For example,Notice the use of keyword parameters (host, passwd, etc.). They improve the readability of your code.For detail about different arguments that you can pass to , see open phpmyadmin>setting>Feature then incress \"Login cookie validity\" by default its 1440 second
Python

I am doing some scripts in python. I create a string that I save in a file. This string got lot of data, coming from the arborescence and filenames of a directory.\nAccording to convmv, all my arborescence is in UTF-8.I want to keep everything in UTF-8 because I will save it in MySQL after.\nFor now, in MySQL, which is in UTF-8, I got some problem with some characters (like \u00e9 or \u00e8 - I'am French).I want that python always use string as UTF-8. I read some informations on the internet and i did like this.My script begin with this :And when I execute, here is the answer : Edit:\nI see, in my file, the accent are nicely written. After creating this file, I read it and I write it into MySQL.\nBut I dont understand why, but I got problem with encoding.\nMy MySQL database is in utf8, or seems to be SQL query  returns me only utf8 or binary.My function looks like this : And artiste who are nicely displayed in the file writes bad into the BDD.\nWhat is the problem ?You don't need to encode data that is  encoded. When you try to do that, Python will first try to  it to  before it can encode it back to UTF-8. That is what is failing here:Just write your data directly to the file, there is  need to encode already-encoded data.If you instead build up  values instead, you would indeed have to encode those to be writable to a file. You'd want to use  instead, which returns a file object that will encode unicode values to UTF-8 for you.You also  don't want to write out the UTF-8 BOM,  you  to support Microsoft tools that cannot read UTF-8 otherwise (such as MS Notepad).For your MySQL insert problem, you need to do two things:It may actually work better if you used  to decode the contents automatically instead:You may want to brush up on Unicode and UTF-8 and encodings. I can recommend the following articles:Unfortunately, the string.encode() method is not always reliable. Check out this thread for more information: 
Python

Is it possible to mock a return value of a function called within another function I am trying to test? I would like the mocked method (which will be called in many methods I'm testing) to returned my specified variables each time it is called. For example: and in the unit test, I would like to use mock to change the return value of  so that any time is is called in , it will return what I defined in There are two ways you can do this; with patch and with patch.objectPatch assumes that you are not directly importing the object but that it is being used by the object you are testing as in the followingIf you are directly importing the module to be tested, you can use patch.object as follows:In both cases some_fn will be 'un-mocked' after the test function is complete.Edit:\nIn order to mock multiple functions, just add more decorators to the function and add arguments to take in the extra parametersNote that the closer the decorator is to the function definition, the earlier it is in the parameter list.It can be done with something like this:Here's a source that you can read: Let me clarify what you're talking about: you want to test  in a testcase, which calls external method . Instead of calling the actual method, you want to mock the return value.Okay, suppose the above code is in ,  is defined in module . Here is the unittest:If you want to change the return value every time you passed in different arguements,  provides .
Python

Difference between setUpClass vs. setUp in python Unittest framework, why not do set up part in setUp instead of setUpClass?I want to understand what part of setup is done in setUp and setUpClass functions as well with tearDown and tearDownClass.The difference manifests itself when you have more than one test method in your class.  and  are run once for the whole class;  and  are run before and after each test method.For example:When you run this test, it prints:(The dots () are 's default output when a test passes.) Observe that  and  appear before and after   , whereas  and  appear only once, at the beginning and end of the whole test case.
Python

How do I install a .whl file?  I have the Wheel library but I don't know how to use it to install those files.  I have the .whl file but I don't know how to run it.  Please help.You normally use a tool like  to install wheels. Leave it to the tool to discover and download the file if this is for a project hosted on PyPI.For this to work, you do need to install the  package:You can then tell  to install the project (and it'll download the wheel if available), or the wheel file directly:The  module, once installed, also is runnable from the command line, you can use this to install already-downloaded wheels:Also see the .
Python

I'm speaking of this module:\nFrom the article:I'm not sure I understand the benefit or purpose of this module.Possibly the most popular usage is operator.itemgetter.  Given a list  of tuples, you can sort by the ith element by: Certainly, you could do the same thing without operator by defining your own key function, but the operator module makes it slightly neater.As to the rest, python allows a functional style of programming, and so it can come up -- for instance, Greg's reduce example.You might argue: \"Why do I need  when I can just do: ?\" The answers are:One example is in the use of the  function:
Python

So I knocked up some test code to see how the multiprocessing module would scale on cpu bound work compared to threading. On linux I get the performance increase that I'd expect:My dual core macbook pro shows the same behavior:I then went and tried it on a windows machine and got some very different results.Why oh why, is the multiprocessing approach so much slower on windows?Here's the test code:Processes are much more  lightweight under UNIX variants. Windows processes are heavy and take much more time to start up. Threads are the recommended way of doing multiprocessing on windows.The  blames the lack of os.fork() for the problems in Windows. It may be applicable here.See what happens when you import psyco. First, easy_install it:Add this to the top of your python script:I get these results without:I get these results with:Parallel is still slow, but the others burn rubber.Edit: also, try it with the multiprocessing pool. (This is my first time trying this and it is so fast, I figure I must be missing something.)Results:It's been said that creating processes on Windows is more expensive than on linux.  If you search around the site you will find some information. Here's  I found easily.Currently, your counter() function is not modifying much state.  Try changing counter() so that it modifies many pages of memory.  Then run a cpu bound loop.  See if there is still a large disparity between linux and windows.I'm not running python 2.6 right now, so I can't try it myself.Just starting the pool takes a long time. I have found in 'real world' programs if I can keep a pool open and reuse it for many different processes,passing the reference down through method calls (usually using map.async) then on Linux I can save a few percent but on Windows I can often halve the time taken. Linux is always quicker for my particular problems but even on Windows I get net benefits from multiprocessing.
Python

I need to create a diff file using standard UNIX  command with python  module. The problem is that I must compare file and stream without creating tempopary file. I thought about using named pipes via  method, but didn't reach any good result. Please, can you write a simple example on how to solve this stuff? I tried like so:but it seems like  doesn't see the second argument.You can use \"-\" as an argument to  to mean .You could perhaps consider using the  python module (I've linked to an example here) and create something that generates and prints the diff directly rather than relying on . The various function methods inside difflib can receive character buffers which can be processed into diffs of various types. Alternatively, you can construct a shell pipeline and use process substitution like soFor details, check out 
Python

I'm interested in subclassing the built-in  type in Python (I'm using v. 2.5), but having some trouble getting the initialization working.Here's some example code, which should be fairly obvious.However, when I try to use this I get:where I'd expect the result to be .What am I doing wrong? Google, so far, hasn't been very helpful, but I'm not really sure what I should be searching for is immutable so you can't modify it after they are created, use  instead
Python

when I use the Django shell, it shows an error; this is the error:What can I do?The model definition must come in an application - the error you're seeing there is that it tries to take the   - which should be something like  for  - and get the app name, . In the interactive console, the module's  is  - so it fails.To get around this, you'll need to specify the  yourself in the  class;For explanation of why you can do that, look at that file mentioned in the traceback, :(Where  is the  class, see just above in that file.)That other answer definitely works for the interactive prompt, however, I don't think that the intention of the first block of code was intended to actually be run. Immediately following that code in , you are expected to put the next codes into your models.py file created during the previous tutorial... I guess that's why they subtly labeled that section \"Quick Example.\" What a headache for me too!I ran into this problem using Eclipse, Django and PyDev. I needed to have the application (instead of some .py file for example) selected in the PyDev Package Explorer (left panel) before clicking Run for everything to work properly.
Python

I'm working on a classification problem with unbalanced classes (5% 1's). I want to predict the class, not the probability.In a binary classification problem, is scikit's  using  by default?\nIf it doesn't, what's the default method? If it does, how do I change it?In scikit some classifiers have the  option, but not all do. With , would  use the actual population proportion as a threshold?What would be the way to do this in a classifier like  that doesn't support ? Other than using  and then calculation the classes myself.In probabilistic classifiers, yes. It's the only sensible threshold from a mathematical viewpoint, as others have explained.You can set the , which is the prior probability P() per class . That effectively shifts the decision boundary. E.g.The threshold in scikit learn is 0.5 for binary classification and whichever class has the greatest probability for multiclass classification. In many problems a much better result may be obtained by adjusting the threshold. However, this must be done with care and NOT on the holdout test data but by cross validation on the training data. If you do any adjustment of the threshold on your test data you are just overfitting the test data.Most methods of adjusting the threshold is based on the  and  but it can also be done by other methods such as a search with a genetic algorithm.Here is a peer review journal article describing doing this in medicine: So far as I know there is no package for doing it in Python but it is relatively simple (but inefficient) to find it with a brute force search in Python.This is some R code that does it. You seem to be confusing concepts here. Threshold is not a concept for a \"generic classifier\" - the most basic approaches are based on some tunable threshold, but most of the existing methods create complex rules for classification which cannot (or at least shouldn't) be seen as a thresholding.So first - one cannot answer your question for scikit's classifier default threshold because there is no such thing.Second - class weighting is not about threshold, is about classifier ability to deal with imbalanced classes, and it is something dependent on a particular classifier. For example - in SVM case it is the way of weighting the slack variables in the optimization problem, or if you prefer - the upper bounds for the lagrange multipliers values connected with particular classes. Setting this to 'auto' means using some default heuristic, but once again - it cannot be simply translated into some thresholding.Naive Bayes on the other hand  estimates the classes probability from the training set. It is called \"class prior\" and you can set it in the constructor with \"class_prior\" variable.From the :0.5 is not related to the population proportion in any way. Its a probability output. There is no \"threshold\", if one class has a probability of 0.51, then it appears to be the most likely class. 0.5 if always the what should be used*, and no package uses a different \"threshold\". If your probability scores are a*ccurate and truly representative*, then you . To do otherwise can only reduce your accuracy. Since we are using various algorithms that make assumptions, we don't know that the probability is true - but you would be going against the assumptions made by your model. You  confused on what class_weight does. Changing the class weight increase the weights for data points in the less represented classes (/ decreasing for the over represented class) so that the \"weight\" of each class is equal - as if they had the same number of positive and negative examples. This is a common trick for trying to avoid a classifier that always votes for the most common class. Because this way, both classes are equally common from the learning algorithm's view. 
Python

Let's say I have a dictionary:It has a method :... which has a  attribute:... which is callable:So why can't I hash it? I know that  objects are unhashable \u2013 I'm curious as to why this restriction extends to their methods, even though, as noted above, they appear to claim otherwise?It is a bound method, and bound methods have a reference to , e.g. the dictionary. This makes the method un-hashable.You  hash the unbound  method:Methods on instances that  hashable will themselves be hashable, so the object type for built-in bound methods implements a  method but raises  when the  attribute is not hashable. This is consistent with the  method documentation; if you can set it to  or not implement it at all then that is preferable but for these cases where the hashability is only known at runtime raising a  is the only option available.Martijn is right as he very often is. If you have a  subclass that does implement the  method, even the bound methods become hashableOutput:
Python

I have a fresh install (started with a wiped drive) of Snow Leopard with the developer tools installed during the Snow Leopard installation.I then installed Python 2.6.2, replacing the Snow Leopard default python 2.6.1. I've tried to install PIL by:All yield the same error (link to  log: ). I've seen others have had success installing PIL using the Snow Leopard default python 2.6.1, so I'm not sure why I'm having so much trouble getting it to work with 2.6.2.The python.org Python was built with an earlier gcc. Try using gcc-4.0 instead of SL's default of 4.2:See similar problem .That gets past the stdarg problem.  You may then run into later build problems with various dependent libraries.BTW, gcc-4.0 and gcc-4.2 are both included with Snow Leopard's Xcode  so no additional installs are needed.UPDATED 2011-05:  Note, that the newer Xcode , released for experimental use with 10.6 and expected to be standard with 10.7, no longer includes PPC support so, if you install Xcode 4, this suggestion will not work.  Options include using the newer 64-bit/32-bin Python 2.7.x installers from python.org or installing a newer Python 2.6 and PIL and the various 3rd-party libs using MacPorts, Homebrew, or Fink.The problem I ran into was that PIL was being compiled against PowerPC architecture (-arch ppc).Do this before setup/build/compile:(Assuming you're on i386)Here are the steps that I took to successfully install PIL on Mac OS X 10.6 (without using MacPorts or Fink).: I was not able to install PIL using , so I installed from the URL as shown above.From what I can see in your  file it appears that you installed Python 2.6.2 using the  from Python.org released on April 16, 2009. Can you confirm this?From the pip log, gcc failed with exit status 1. The offending  command from your pip log is as follows:This appears to be a problem related to Snow Leopard changing the default value for the -arch flag from  to  according to Ronald Oussoren in  of . There is a patch available Python 2.6.2, but it has not been integrated into the Mac Installer Disk Image.Your best solution that doesn't involve MacPorts or Fink would probably be to compile and install Python from the 2.6 release branch from either the  or the . According to  of , Ronald Oussoren fixed this in . I've been seeing similar errors using Python 2.6.2 installed from the Mac Disk Image while trying to then install Fabric in a virtualenv, so I plan to compile and install from the 2.6 release maintenance branch. If you want, I'll update when successful.10.6 Snow Leopard install PIL without the hassle and without keeping MacPorts :)\n\nStep 1: Install MacPorts\nStep 2: sudo port install py26-pil\nStep 3: mv /opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/* /Library/Python/2.6/site-packages/\nStep 4: Uninstall MacPorts\n\nBest of both worlds?Following steps worked for me:IT seems to me that the \"No such file\" is conjunction with stdarg.h is the most interesting error. There seems to be a header file missing. I don't know how to make sure it's installed on OS X, so this only half an answer, sorry about that, but maybe it pushes you in the right direction.May be you should try pre-build universal binaries from pythonmac siteThese are for python2.5 , with python2.5 included(so may or may not be usable for you), I have been using it since I had problem using self build PIL with py2app.I found a simpler method.\nsudo port install python26\nsudo port install python_selectThen use python_select set python26 as default.Then just install PIL as normal.I was able to get PIP installed with SL's Python using these instructions:Do you have  (comes on the Snow Leopard disc) installed? There are some key components (most notably ) that need to be installed which XCode handles for you. Uninstalled and Installed Xcode, suggested here:\nto remove Xcode properlly follow this answer:\nuse the install Xcode.app after you restart your mac after xcode was reinstalled, the installation failed to resolve that i followed this post:\nGood luck!On OS X Lion with current XCode and no gcc-4.0 I'm able to get around the missing stdard.h error by setting the follow environment variables:I can't say I understand why this works.By the way this works for the Pillow fork of PIL too.
Python

I need to create a fake helper class to be used in unit tests (injected into tested classes). Is there some way to use TestCase assertions in such class?I would like to use the assertions for some common checks performed by the Fake class. Something like:You can create a instance of  and call the methods on that, provided you pass in the name of an  method on the class.  will do in this case:However, you are probably looking for a good  instead.  would be a good choice.
Python

Is there a standard way (without installing third party libraries) to do cross platform filesystem mocking in python? If I have to go with a third party library, which library is the standard?The standard mocking framework in Python 3.3+ is ; you can use this for the filesystem or anything else.You could also simply hand roll it by mocking via monkey patching:A trivial example:A bit more full (untested):In this example, the actual mocks are trivial, but you could back them with something that has state so that can represent filesystem actions, such as save and delete. Yes, this is all a bit ugly since it entails replicating/simulating basic filesystem in code.Note that you can't monkey patch python builtins. That being said...For earlier versions, if at all possible use a third party library, I'd go with Michael Foord's awesome , which is now  in the standard library since 3.3+ thanks to , and you can get it on  for Python 2.5+. And, it can mock builtins! () does what you want \u2013 a  filesystem; it\u2019s third-party, though that party is Google. See  for discussion of use.For ,  is the standard library for Python 3.3+ (); for earlier version see  (for Python 2.5+) ().Terminology in testing and mocking is inconsistent; using the  terminology of Gerard Meszaros, you\u2019re asking for a \u201cfake\u201d: something that behaves like a filesystem (you can create, open, and delete files), but isn\u2019t the actual file system (in this case it\u2019s in-memory), so you don\u2019t need to have test files or a temporary directory.In classic mocking, you would instead  out the system calls (in Python, mock out functions in the  module, like   and ), but that\u2019s much more fiddly. is gaining a lot of traction, and it can do all of this using  and  (mocking).You can use the  function argument which will provide a temporary directory unique to the test invocation, created in the base temporary directory (which are by default created as sub-directories of the system temporary directory).The  function argument helps you to safely set/delete an attribute, dictionary item or environment variable or to modify  for importing. You can also pass it a function instead of using lambda.If your application has a lot of interaction with the file system, then it might be easier to use something like , as mocking would become tedious and repetitive. allows you to create a fake file system, write and read files, set permissions and more without ever touching your real disk.It also contains a practical example and tutorial showing you how to apply it to unittest and doctest.Personally, I find that there are a lot of edge cases in filesystem things (like opening the file with the right permissions, string-vs-binary, read/write mode, etc), and using an accurate fake filesystem can find a lot of bugs that you might not find by mocking. In this case, I would check out the  module of  (it has various concrete implementations of the same interface, so you can swap them out in your code).That said, if you really want to mock, you can do that easily with Python's  library:The above example only demonstrates creating and writing to files via mocking the  method, but you could just as easily mock any method.
Python

Does anyone know of a good platform agnostic example or library that does Facebook authentication and Graph API access via Python?The official  is tied to Google App Engine and  is deeply woven with Django. I just want to be able to mess around in terminal and go through the process of authenticating a user and then doing simple requests from the Facebook API.Thanks.I ran across same problem some time ago and later found out that PyFacebook isn't deeply tied up with Django. It just uses a few utils from django.My recommendation is that you setup PyFacebook alongwith django and then play around with it using command line. To use PyFacebook you won't have to go through or even know anything about django at all.Here's an example:You might need to get an infinite session key which you can get from here: Use this code to get convert the code from above URL into infinite session key:A new library that is available is:\nIt currently support authentication and the dialog API.  Planned in the near future(currently being worked on) is a wrapper around the graph API.The project goal is to be platform agnostic, single file, and use only standard Python libraries.How about taking the Facebook Python SDk itself and stripping off the GAE part from it and using the other API calls only?
Python

I would like to compute the following using numpy or scipy:where  is a  matrix,  is the transpose of  and  is an  diagonal matrix.Since  is a diagonal matrix I store only its diagonal elements as a vector.Currently I can think of two ways of how to calculate :Clearly option 2 is better than option 1 since no real matrix has to be created with  (if this is what numpy really does...)\nHowever, both methods suffer from the defect of having to allocate more memory than there really is necessary since  and  have to be stored along with  in order to calculate .Is there a method in numpy/scipy that would eliminate the unnecessary allocation of extra memory where you would only pass two matrices  and  (in my case  is ) and a weighting vector  along with it?(w/r/t the last sentence of the OP: i am  aware of such a numpy/scipy method but w/r/t the Question in the OP Title (i.e., improving NumPy dot performance) what's below should be of some help. In other words, my answer is directed to improving performance of most of the  your function for Y).\nFirst, this should give you a noticeable boost over the vanilla NumPy  method:Note that the two arrays, v1, v2 are  in C_FORTRAN orderYou can access the byte order of a NumPy array through an array's  attribute like so:to change the order of one of the arrays so both are aligned, just call the NumPy array constructor, pass in the array and set the appropriate  flag to TrueYou can further optimize by exploiting array-order alignment to .But why are the arrays copied before being passed to ?The dot product relies on BLAS operations. These operations require arrays stored in C-contiguous order--it's this constraint that causes the arrays to be copied.On the other hand, the  does  effect a copy, though unfortunately returns the result in :Therefore, to remove the performance bottleneck, you need to ; to do that just requires passing both arrays to  in C-contiguous order*.So to calculate   making an extra copy:In sum, the expression just above (along with the predicate import statement) can substitute for dot, to supply the same functionality but better performanceyou can bind that expression to a function like so:I just wanted to put that up on SO, but this pull request should be helpful and remove the need for a separate function for numpy.dot\n\nThis should be available in numpy 1.7In the meantime, I used the example above to write a function that can replace numpy dot, whatever the order of your arrays are, and make the right call to fblas.dgemm.\nHope this helps, is what you're looking for:This shall not need any additional memory (though usually einsum works slowlier than BLAS operations)
Python

This question is not a duplicate. It pertains not just to  a virtual environment, but to actually  it to a different directory, including, potentially, a different user's directory. This is not the same as merely renaming a virtual environment, especially to people unfamiliar with virtualenvs.If I create a virtualenv, and I move it to a different folder, will it still work? ...later that day, the virtual environment MOVED...  Question: Will this work? I mean this as less of a question about the wisdom of trying this (unless that wisdom is humorous, of course), and more about whether it's possible. I really want to know whether it's possible to do in Python 3, or whether I just have to  and clone it. Can I just  a  like that without sadness? I do want to avoid sadness.Yes. It is possible to move it on the same platform. You can use  on an existing environment.From :HOWEVER, this does NOT seem to change the  script, and rather only changes the  and  scripts.  In the  script, the   environment variable hardcoded as the original . The  variable is used to set the  of your active environment too, so it must be changed based on the new location in order to call  and  etc. without absolute path.To fix this issue, you can change the  environment variable in the  script (for example using ), and everything should be good to go.An example of usage:Hooray, now you can install things and load them into your newly located virtual environment.The  argument to  appears to allow you to do this.Yes, this should be possible if you haven't done anything that depends on the current directory of the virtualenv.However, if you have the choice, the best thing to do is to create new virtualenv and start using the new virtualenv instead. This is the safest choice and least likely to cause issues later.The documentation :For example, if you have run  then it won't be able to switch to the right directory after you run  so in that case you'd need to fix that manually.In general a virtualenv is little more than a directory with the necessary Python interpreter files plus packages that you need.// , BUT ALAS: ... presses  a lot in frustration, and the following worksExcept it is not from , ergo sadness. Want to  your  and use it, otherwise unmodified?  Well, ya .
Python

I'm trying to run a very simple code that outputs a .png file in a cluster. Here's the code:If I run this code with the command  in my system which has matplotlib 1.2.1 installed I get the warning:The .png image is still produced so I have no problems here. But if I use the same command and code in a cluster which has matplotlib 1.3.0 installed it fails with the error:What is happening here?Add, this is the script I use to login into the cluster:Your problem is in ssh command. What you need to do is to write it this way:
Python

Is there a function for drawing a caption box underneath a figure/graph using matplotlib? I have searched google and haven't found any such function.something like what is shown in the image would be great.Use .  Here is some sample code:It produces this:\nIf you want automatic word-wrapping, have a look at .I'm not sure I can help you get it full-justified.You can use the  function (). If you want it outside the axes, you can pass to it a specific location ( keyword argument). The legend function takes a  argument, which might help getting what you want. However, for a caption without any legend, Paul's answer is more suited.
Python

My code is:but the scriptlib is in some other directory, so I will have to include that directory in environment variable \"PYTHONPATH\".Is there anyway in which I can first add the scriptlib directory in environment variable \"PYTHONPATH\" before import statement getting executed like :If so, is the value only for that command prompt or is it global ?Thanks in advanceThis will add a path to your Python process / instance (i.e. the running executable). The path will not be modified for any other Python processes. Another running Python program will not have its path modified, and if you exit your program and run again the path will not include what you added before. What are you are doing is generally correct.set.py:loop.pyrun: This will run loop.py, connected to your STDOUT, and it will continue to run in the background. You can then run . Each has a different set of environment variables. Observe that the output from  does not change because  does not change 's environment.Python imports are dynamic, like the rest of the language. There is no static linking going on. The import is an executable line, just like .As also noted in the docs .\nGo to  and add these lines to the  there,This changes your  so that on every load, it will have that value in it..  As stated  about ,  For other possible methods of adding some path to  see 
Python

Python provides a convenient method long() to convert string to long:; converts '234' into a longIf user keys in 234.89 then python will raise an error message:How should we a python programmer handles scenarios where a string with a decimal value ? Thank you =)can only take string convertibles which can end in a base 10 numeral. So, the decimal is causing the harm. What you can do is,  the value before calling the . If your program is on Python 2.x where int and long difference matters, and you are sure you are not using large integers, you could have just been fine with using  to provide the key as well.So, the answer is  or it could just be  if you are not using large integers. Also note that this difference does not arise in Python 3, because int is upgraded to long by default. All integers are long in python3 and call to covert is just Well, longs can't hold anything but integers. One option is to use a float:  The other option is to truncate or round.  Converting from a float to a long will truncate for you:  
Python

I work in an psudo-operational environment where we make new imagery on receipt of data.  Sometimes when new data comes in, we need to re-open an image and update that image in order to create composites, add overlays, etc.  In addition to adding to the image, this requires modification of titles, legends, etc.  Is there something built into matplotlib that would let me store and reload my matplotlib.pyplot object for later use?  It would need to maintain access to all associated objects including figures, lines, legends, etc.  Maybe pickle is what I'm looking for, but I doubt it.  As of 1.2 matplotlib ships with experimental pickling support. If you come across any issues with it, please let us know on the mpl mailing list or by opening an issue on github.com/matplotlib/matplotlibHTH: Added a simple exampleThen in a separate session:A small modification to Pelson's answer for people working on a JupyterhubUse  before loading the pickle.  Using  did not work for me in either jupyterhub or jupyter notebook. and gives a traceback ending in \nAttributeError: 'module' object has no attribute 'new_figure_manager_given_figure'.Then in a separate session:I produced figures for a number of papers using matplotlib. Rather than thinking of saving the figure (as in MATLAB), I would write a script that plotted the data then formatted and saved the figure. In cases where I wanted to keep a local copy of the data (especially if I wanted to be able to play with it again) I found  and  to be very useful.At first I missed the shrink-wrapped feel of saving a figure in MATLAB, but after a while I have come to prefer this approach because it includes the data in a format that is available for further analysis.Did you try the pickle module?  It serialises an object, dumps it to a file, and can reload it from the file later.
Python

I have a sequence of new objects. They all look like similar to this:Foo(pk_col1=x, pk_col2=y, val='bar')Some of those are Foo that exist (i.e. only val differs from the row in the db)\nand should generate update queries. The others should generate inserts.I can think of a few ways of doing this, the best being:Is there an easier way?I think you are after . This will merge an object in a detached state into the session if the primary keys match and will make a new one otherwise. So  will work for both insert and update.
Python

Is there a good wxpython GUI builder that does not require much coding, like in the case of the form builder in MS visual studio ?There is . Here is a screenshot:and Also, have a look here for more alternatives: I've tried a few, and the only one I seem to have any luck with is In addition to those, some people really like the XRCed application that's included with wxPython. Basically you create your GUI in XML. There's also the defunct Boa Constructor that I see people still using on the wxPython user's list.In a long ago day, I tried them all and found  to be the most professional of the bunch.  Along with that goes the fact that it is commercial software.It's by Julian Smart, the creator of wxWidgets, so I suppose it's not too surprising that it's a quality product.  At $90, it's a bit expensive but not outrageous.
Python

Assuming I have two Python modules and path_b is in the import path:Is it possible to see where the module is imported from? I want an output like \"I was imported from path_a/app.py\", if I start app.py (because I need the file name).\nFor better understanding; I could write:So the output would be:There may be an easier way to do this, but this works:Note that the path will be printed relative to the current working directory if it's a parent directory of the script location.Try this: In that case write into the  file of your module:Try  to find out where it is from. If you get an , it is probably not a Python source (.py) file.Also, if you have a function/class  from a module  you can get the path of the module using the module I've written a simple script so I have the command \nthat allows me to find where a Python module comes from.\nIt doesn't work for some builtins like sys which doesn't have a  attribute.This can be run from a Linux command line to find where a python script run in the current environment will get a module from, for example:Other answers are OK, but if you want to tell it from  the imported module then do
Python

Is there a way in matplotlib to partially specify the color of a string?Example:How can I show \"today\" as red, \"is\" as green and \"cloudy.\" as blue?Thanks.here's the interactive version (same one I posted to )I only know how to do this non-interactively, and even then only with the 'PS' backend.To do this, I would use Latex to format the text. Then I would include the 'color' package, and set your colors as you wish. Here is an example of doing this:This results in (converted from ps to png using ImageMagick, so I could post it here):\nExtending Yann's answer, LaTeX coloring now :Note that this python script sometimes fails with  errors in the first attempt. Running it again is then successful.
Python

I'm writing a program in which I would like to have arguments like this:Is there a way to get argparse to do this for me?I'm using Python 3.2.Since there seems to be no way to do this, I'm opting for this idea instead...IMHO, not quite as elegant, but it works.I figured out a reasonably nice solution involving deriving my own class derived from  that I've detailed in an .Well, none of the answers so far are quite satisfactory for a variety of reasons. So here is my own answer:And an example of use:Unfortunately, the  member function isn't documented, so this isn't 'official' in terms of being supported by the API. Also,  is mainly a holder class. It has very little behavior on its own. It would be nice if it were possible to use it to customize the help message a bit more. For example saying  at the beginning. But that part is auto-generated by stuff outside the  class.Does the  of  help?Here's how it looks when run:This is different from the following in the mutually exclusive group allows  option in your program (and I'm assuming that you want  because of the  syntax).  This implies one or the other:If these are required (non-optional), maybe using  is what you're looking for.Logically different, but maybe cleaner:And running it:Write your own subclass.For fun, here's a full implementation of :Here's the output:I modified the solution of @Omnifarious to make it more like the standard actions:You can add the Yes/No argument as you would add any standard option. You just need to pass  class in the  argument:Now when you call it:Extending  's answerThis yields help output like so:\n    usage: myscript.py [-h] [--flaga] [--flabb]Gist version here, pull requests welcome :)\nBefore seeing this question and the answers I wrote my own function to deal with this:It can be used like this:Help output looks like this:I prefer the approach of subclassing  that the other answers are suggesting over my plain function because it makes the code using it cleaner, and easier to read.This code has the advantage of having a standard default help, but also a  and  to reconfigure the rather stupid defaults.Maybe someone can integrate.
Python

I can't seem to be able to get the python ldap module installed on my OS X Mavericks 10.9.1 machine.Kernel details:\nuname -a\nDarwin  13.0.0 Darwin Kernel Version 13.0.0: Thu Sep 19 22:22:27 PDT 2013; root:xnu-2422.1.72~6/RELEASE_X86_64 x86_64I tried what was suggested here:\nBut when I try to use pip I get a different error Modules/LDAPObject.c:18:10: fatal error: 'sasl.h' file not found*#include sasl.hI also tried what was suggested here:\nBut with the same error.I am hoping someone could help me out here. \n/usr/include appears to have movedNow run pip install!using pieces from both @hharnisc and @mick-t answers.In my particular case, I couldn't simply use the  arguments noted in other answers because I'm using it with  to install dependencies from a requirements.txt file, and I need my tox.ini to remain compatible with non-Mac environments.I was able to resolve this in much simpler fashion: exporting  such that it adds an include path to the sasl headers already installed by Xcode:Depending on whether or not you use any userspace-friendly Python tools (I use ), you may have to prefix your pip commands with .I had the same problem. I'm using Macports on my Mac and I have cyrus-sasl2 installed which provides sasl.h in  /opt/local/include/sasl/. You can pass options to build_ext using pip's global-option argument. To pass the include PATH to /opt/local/include/sasl/sasl.h run pip like this:Alternatively you could point it to whatever the output from  provides. On my box that's:\n Then you need to determine the PATH to the sasl header files. For me that's:Let me know if that helps or you need a hand.I used a combination of posts I found about this problem (including this one) to eventually come up with this (copied from a larger script):You can test it with The main reason I didn't follow the advice of @hharnisc was that on my local machine /usr/local had not moved, so I just temporarily put $XC_SDK before it on the path, and that seems to work. some sources:\n
Python

I've read the manual for pseudo-randomness in Python, and to my knowledge, you can only generate numbers up to a given maximum value, i.e. 0-1, 0-30, 0-1000, etc.  I want to:I've looked around, and I can't find anywhere that explains this.Create an integer random between e.g.  and multiply it by . Simple math.produces e.g.should work in any Python >= 2.If you don't want to do it all by yourself, you can use the  function.For example  prints a number that is between 10 and 25 (10 included, 25 excluded) and is a multiple of 5. So it would print 10, 15, or 20.The simplest way is to generate a random nuber between 0-1 then strech it by multiplying,  and shifting it.\nSo yo would multiply by (x-y)  so the result is in the range of 0 to x-y,\nThen add x and you get the random number between x and y.   To get a five multiplier use rounding. If this is unclear let me know and I'll add code snippets. 
Python

Could someone please tell me what I'm doing wrong with this code? It is just printing 'count' anyway.  I just want a very simple prime generator (nothing fancy). There are some problems:Here's your code with a few fixes, it prints out only primes:For much more efficient prime generation, see the Sieve of Erastothenes, as others have suggested. Here's a nice, optimized implementation with many comments:Note that it returns a generator.We will get all the prime numbers upto 20 in a list.\nI could have used Sieve of Eratosthenes but you said\nyou want something very simple. ;)To test if a number is prime:Here's a  (Python 2.6.2) solution... which is in-line with the OP's original request (now six-months old); and should be a perfectly acceptable solution in any \"programming 101\" course... Hence this post.This simple \"brute force\" method is \"fast enough\" for numbers upto about about 16,000 on modern PC's (took about 8 seconds on my 2GHz box).Obviously, this could be done much more efficiently, by not recalculating the primeness of every even number, or every multiple of 3, 5, 7, etc for every single number... See the  (see eliben's implementation above), or even the  if you're feeling particularly brave and/or crazy.Caveat Emptor: I'm a python noob. Please don't take anything I say as gospel.To my opinion it is always best to take the functional approach,So I create a function first to find out if the number is prime or not then use it in loop or other place as necessary.Then run a simple list comprehension or generator expression to get your list of prime,This seems homework-y, so I'll give a hint rather than a detailed explanation. Correct me if I've assumed wrong.You're doing fine as far as bailing out when you see an even divisor. But you're printing 'count' as soon as you see even  number that doesn't divide into it. 2, for instance, does not divide evenly into 9.  But that doesn't make 9 a prime. You might want to keep going until you're sure  number in the range matches.(as others have replied, a Sieve is a much more efficient way to go... just trying to help you understand why this specific code isn't doing what you want)How about this if you want to compute the prime directly:Another simple example, with a simple optimization of only considering odd numbers. Everything done with lazy streams (python generators).Usage: primes = list(create_prime_iterator(1, 30))re is powerful:You need to make sure that all possible divisors don't evenly divide the number you're checking.  In this case you'll print the number you're checking any time just one of the  possible divisors doesn't evenly divide the number.Also you don't want to use a continue statement because a continue will just cause it to check the next possible divisor when you've already found out that the number is not a prime.Here is what I have:It's pretty fast for large numbers, as it only checks against already prime numbers for divisors of a number.Now if you want to generate a list of primes, you can do:using generators here might be desired for efficiency.And just for reference, instead of saying:you can simply say:You can create a list of primes using list comprehensions in a fairly elegant manner. Taken from Similar to user107745, but using 'all' instead of double negation (a little bit more readable, but I think same performance):Basically it iterates over the x in range of (2, 100) and picking only those that do not have mod == 0 for all t in range(2,x)Another way is probably just populating the prime numbers as we go: is a Python library for symbolic mathematics. It provides several functions to generate prime numbers.Here are some examples.For me, the below solution looks simple and easy to follow. 
Python

I'm trying to make a script that gets data out from an sqlite3 database, but I have run in to a problem.The field in the database is of type text and the contains a html formated text. see the text belowand the python code that try to extract the data is as follows.Does anybody have any idea of how to print/write this to a file. Yes I know that this is printed to stdout, but I get the same UnicodeEncodeError when I try to write to a file. I tried both write method of a file object and .When you open the file you want to write to, open it with a specific encoding that can handle all the characters.Maybe a little late to reply. I happen to run into the same problem today. I find that on Windows you can change the console encoder to  or other encoder that can represent your data. Then you can print it to .First, run following code in the console:Then, start  do anything you want.While Python 3 deals in Unicode, the Windows console or POSIX tty that you're running inside does not. So, whenever you , or otherwise send Unicode strings to , and it's attached to a console/tty, Python has to encode it.The error message indirectly tells you what character set Python was trying to use:This means the charset is .You can test or yourself that this charset doesn't have the appropriate character just by doing . Or you can look up cp850 online (e.g., at ).It's possible that Python is guessing wrong, and your console is really set for, say UTF-8. (In that case, just manually set .) It's also possible that you intended your console to be set for UTF-8 but did something wrong. (In that case, you probably want to follow up at superuser.com.)But if nothing is wrong, you just can't print that character. You will have to manually encode it with one of the non-strict error-handlers. For example:So, how do you print a string that won't print on your console?You  replace every  function with something like this:\u2026 but that's going to get pretty tedious pretty fast.The simple thing to do is to just set the error handler on :For printing to a file, things are pretty much the same, except that you don't have to set  after the fact, you can set it at construction time. Instead of this:Do this:\u2026 Or, of course, if you can use UTF-8 files, just do that, as Mark Ransom's answer shows:
Python

I've always used dictionaries. I write in Python.A dictionary is a general concept that maps keys to values.  There are many ways to implement such a mapping.A hashtable is a specific way to implement a dictionary.Besides hashtables, another common way to implement dictionaries is .Each method has it's own pros and cons.  A red-black tree can always perform a lookup in O(log N).  A hashtable can perform a lookup in O(1) time although that can degrade to O(N) depending on the input.A dictionary is a data structure that maps keys to values.A hash table is a data structure that maps keys to values by taking the hash value of the key (by applying some hash function to it) and mapping that to a bucket where one or more values are stored.IMO this is analogous to asking the difference between a list and a linked list.For clarity it may be important to note that it MAY be the case that Python currently implements their dictionaries using hash tables, and it MAY be the case in the future that Python changes that fact without causing their dictionaries to stop being dictionaries.\"A dictionary\" has a few different meanings in programming, as  will tell you -- \"associative array\", the sense in which Python uses the term (also known as \"a mapping\"), is one of those meanings (but \"data dictionary\", and \"dictionary attacks\" in password guess attempts, are also important).Hash tables are important data structures; Python uses them to implement two important built-in data types,  and .So, even in Python, you can't consider \"hash table\" to be a synonym for \"dictionary\"... since a similar data structure is also used to implement \"sets\"!-)A Python dictionary is internally implemented with a hashtable.A hash table always uses some function operating on a value to determine where a value will be stored. A Dictionary (as I believe you intend it) is a more general term, and simply indicates a lookup mechanism, which might be a hash table or might be implemented by a simpler structure which does not consider the value itself in determining its storage location.Dictionary is implemented using hash tables. In my opinion the difference between the 2 can be thought of as the difference between Stacks and Arrays where we would be using arrays to implement Stacks.
Python

I've been using Boost::Python for a while, and everything always turned out ok. However yesterday I was trying to find out why a particular type I thought I had registered (a tuple) was giving me errors when I was trying to access it from Python.Turns out that while the tuple was actually registered, when trying to access it through an  wrapped via the  this is not enough anymore.I was wondering, why is it not working? Is there any way to make this work? Should I try to wrap the vector by hand?Below is my MVE:Accessing the resulting  via Python results in:EDIT:\nI've realized that the error does not happen if the  is used with the  parameter set to true. However, I'd prefer if this wasn't necessary, as it makes the exported classes unintuitive in Python. registers C++-to-Python converters and Python-to-C++ converters. This is fine.On the other hand, you want your vector elements to be returned by reference. But there's nothing on the Python side that can serve as a reference to your tuple. A converted-to-Python tuple may hold the same values, but it is completely detached from the original C++ tuple.It looks like in order to export a tuple by reference, one would need to create an indexing suite for it, rather than to/from-Python converters. I have never done that and cannot guarantee it will work.Here's how one could expose a tuple as a minimal tuple-like Python object (with only len() and indexing). First define some helper functions:Then expose specific tuples:Note these quasi-tuples, unlike real Python tuples, are mutable (via C++). Because of tuple immutability, exporting via converters and  looks like a viable alternative to this.
Python

To read data from a socket in python, you call , which has this signature:The  vaguely state:: What does \"\" mean?  What is the  impact of setting bufsize to a non-power-of-two?I've seen    to make this read a power of 2.  I'm also well aware of reasons when it is often useful to have array lengths as powers of two (bitshift/masking operations on the length, optimal FFT array size, etc), but these are application dependent.  I just am not seeing the general reason for it with .  Certainly not to the point of the  in the python documentation.  I also don't see any power-of-two optimizations in the  to make it a python-specific recommendationFor example... if you have a protocol where the incoming packet length is exactly known, it is obviously preferrable to only read \"at most\" what is needed for the packet you are dealing with, otherwise you could potentially eat into the next packet and that would be irritating.  If the packet I'm currently processing only has 42 bytes pending, I'm only going to set bufsize to 42.What am I missing?  When I have to choose an arbitrary buffer/array size I usually (always?) make the length a power of two, just in case.  This is just a habit developed over many years.  Are the python docs also just a victim of habit?This isn't exclusive to python, but since I'm specifically referencing the python docs I'll tag it as such.: I just checked the size of the buffer at the kernel level on my system (or at least I think I did... I did ) and it was 124928.  Not a power of two.   was 131071, also clearly not a power of two.In looking into this more I really cannot see any benefit in the power of two recommendation(s) yet.  I'm about ready to call it as a bogus recommendation...I also added  and  tags since they are also relevant.In regards to: \"if you have a protocol where the incoming packet length is exactly known, it is obviously preferrable to only read \"at most\" what is needed for the packet you are dealing with, otherwise you could potentially eat into the next packet and that would be irritating.\"This may be preferable for the application developer, but is probably inefficient for the underlying network stack.  First, it ties up socket buffer space that can be used for additional network I/Os.  Second, each recv() you make means dipping into a system call/kernel space and there is a performance penalty for the transition.  It is always preferable to get as much data as you can out of kernel space and into user space with as few system calls as possible and do your message parsing there.  This adds more complexity to the application code and message handling but is probably the most efficient.That said, given the speed of today's processors and amount of available memory, this may not be an issue for most applications, but this was a common recommendation for network applications back in the \"old days\".I am not sure about the power of 2 recommendation from a user-space application.  I have seen these types requirements for drivers due to alignment and page size issues, etc.  but its not clear what effect this has from user space unless it somehow aids in copying data out of kernel buffers into user buffers.  Maybe somebody with more OS development knowledge could comment.Have a look at the answers on . It deals with  too and the answers may be helpfull for a more complete understanding. It won't answer the question but will provide a bit more insight.
Python

What is the the time complexity of each of python's set operations in  notation?I am using Python's  for an operation on a large number of items. I want to know how each operation's performance will be affected by the size of the set. For example, , and the test for membership:Googling around hasn't turned up any resources, but it seems reasonable that the time complexity for Python's set implementation would have been carefully considered.If it exists, a link to something like  would be great. If nothing like this is out there, then perhaps we can work it out?Extra marks for finding the time complexity of  set operations.The operation  should be independent from he size of the container, ie.  -- given an optimal hash function. This should be  true for Python strings. Hashing strings is always critical, Python should be clever there and thus you can expect near-optimal results.According to ,  is implemented as a . So you can expect to lookup/insert/delete in  average. Unless your hash table's load factor is too high, then you face collisions and O(n).P.S. for some reason they claim O(n) for delete operation which looks like a mistype.P.P.S. This is true for CPython, pypy is a .
Python

Is there an established approach to embed gettext  in a ? Specifically to have Gtks automatic widget translation pick them up  the ZIP archive.For other embedded resources  or / work well enough. But system  Python  depend on  being supplied a plain old ; no resources or strings etc.So I couldn't contrive a workable or even remotely practical workaround:Is there a more dependable approach perhaps? This my example Glade/GtkBuilder/Gtk application. I've defined a function  which transparently translates glade xml files and passes to  instance as a string.  I've archived my locale directories into  which is included in the  bundle.\nThis is contents of   To make the locale.zip as a filesystem I use ZipFS from .  Fortunately Python  is not GNU gettext.  is pure Python it doesn't use GNU gettext but mimics it.  has two core functions  and . I've redefined these two in a seperate module named  to make them use files from the .   uses  , and  to find files and open them which I replace with the equivalent ones form  module.  This is contents of my application.  Because  files have text, usually a shebang, prepended to it, I skip this line after opening the  file in binary mode. Other modules in the application that want to use the  function, should import  instead from  and make it an alias to .  Here goes .  The following two shouldn't be called because  doesn't use Python .  
Python

We have a distributed architecture based on  and .\nWe can launch in parallel multiple tasks without any issue. The scalability is good. Now we need to control the task remotely: PAUSE, RESUME, CANCEL.\nThe only solution we found is to make in the Celery task a RPC call to another task that replies the command after a DB request. The Celery task and RPC task are not on the same machine and only the RPC task has access to the DB.Do you have any advice how to improve it and easily communicate with an ongoing task?\nThank you\nIn fact we would like to do something like in the picture below. It's easy to do the  configuration or the , but we don't know how to do both simultaneously.\n\nWorkers are subscribing to a common  and each worker has its own  declared on an exchange. \nIF this is not possible with , I'am open to a solution with other frameworks like .It look like the .For a better scalability and in order to reduce the RPC call, I recommend to reverse the logic. The  command are push to the Celery tasks through a control bus when the state change occurs. The Celery app will store the current state of the Celery app in a store (could be in memory, on the filesystem..). If task states must be kept even after a stop/start of the app, It will involve more work in order to keep both app synchronized (eg. synchronization at startup).
Python

I am running socket.io on an Apache server through Python Flask. We're integrating it into an iOS app (using the  library) and we're having a weird issue.From the client side code in the app (written in Swift), I can view the actual connection log (client-side in XCode) and see the connection established from the client's IP and the requests being made. The client never receives the information back (or any information back; even when using a global event response handler) from the socket server.I wrote a very simple test script in Javascript on an HTML page and sent requests that way and received the proper responses back. With that said, it seems to likely be an issue with iOS. I've found these articles (but none of them helped fix the problem):\nMy next thought is to extend the logging of socket.io to find out exact what data is being POSTed to the socket namespace. Is there a way to log exactly what data is coming into the server (bear in mind that the 'on' hook on the server side that I've set up is not getting any data; I've tried to log it from there but it doesn't appear to even get that far).I found mod_dumpio for Linux to log all POST requests but I'm not sure how well it will play with multi-threading and a socket server.Any ideas on how to get the exact data being posted so we can at least troubleshoot the syntax and make sure the data isn't being malformed when it's sent to the server?Thanks!When testing locally, we got it working (it was a setting in the Swift code where the namespace wasn't being declared properly). This works fine now on localhost but we are having the exact same issues when emitting to the Apache server.We are not using mod_wsgi (as far as I know; I'm relatively new to mod_wsgi, apologies for any ignorance). We used to have a .wsgi file that called the main app script to run but we had to change that because mod_wsgi is not compatible with Flask SocketIO (as stated in the uWSGI Web Server section ). The way I am running the script now is by using  to run the .py file as a daemon (using that specifically so it will autostart in the event of a server crash).Locally, it worked great once we installed the eventlet module through pip. When I ran  on my virtual environment on the server, eventlet was installed. I uninstalled and reinstalled it just to see if that cleared anything up and that did nothing. No other Python modules that are on my local copy seem to be something that would affect this.One other thing to keep in mind is that in the function that initializes the app, we change the port to port 80:because we have other API functions that run through a domain that is pointing to the server in this app. I'm not sure if that would affect anything but it doesn't seem to matter on the local version.I'm at a dead end again and am trying to find anything that could help. Thanks for your assistance!I'm not exactly sure what was happening yet but we went ahead and rewrote some of the code, making sure to pay extra special attention to the namespace declarations within each socket event  function. It's working fine now. As I get more details, I will post them here as I figure this will be something useful for other who have the same problem. This thread also has some really valuable information on how to go about debugging/logging these types of issues although we never actually fully figured out the answer to the original question.I assume you have verified that Apache does get the POST requests. That should be your first test, if Apache does not log the POST requests coming from iOS, then you have a different kind of problem.If you do get the POST requests, then you can add some custom code in the middleware used by Flask-SocketIO and print the request data forwarded by Apache's mod_wsgi. The this is in file . The relevant portion is this:You can find out what's in  in the . In particular, the body of the request is available in , which is a file-like object you read from.Keep in mind that once you read the payload, this file will be consumed, so the WSGI server will not be able to read from it again. Seeking the file back to the position it was before the read may work on some WSGI implementations. A safer hack I've seen people do to avoid this problem is to read the whole payload into a buffer, then replace  with a brand new  or  object.Are you using flask-socketio on the server side? If you are, there is a lot of debugging available in the constructor. socketio = SocketIO(app, async_mode=async_mode, logger=True, engineio_logger=True)
Python

I've recently switched entirely to Vim for all my Python/Django development. It took me a lot of time to customize it to the point it is today, and God knows how hard it was for me to find help regarding the best vim plugins out there suited for Python/Django development.I decided to ask this question so people like me could benefit directly from your experience:\nYou've built the perfect Python/Djangoish Vim editor? Describe it for us (plugins, scripts, customized .vimrc, colorschemes ..etc).ThanksOk, this is my own configuration. actually I've chosen to create a simple Vim configuration so I can master the little number of plugins I've chosen to install instead of make a big stack of plugins that I'll never master nor use. This is the list of the plugins I use the most:Also I've created a python.vim file in $HOME/.vim/ftplugin/ containing this script so I can run python code from Vim just by running Shift+e:Also I've collected some useful .vimrc customizations:I don't really have much Django specific mods, although I have given the jinja2 syntax a higher priority than the django template syntax.I am not going to post my whole .vimrc file here, but I have a similiar setup as you. This is less Python/Django specific though, except for some custom snippets for snipMate and python-mode. Here the vim plugins I am using:Some custom python snippets I use quite frequently:
Python

I would like to roll my own login system for my python Google App Engine application (rather than using Google's ).I am using webapp2, and I noticed that there is a  module and an .Does anyone know how I can use this API to create:Once I have the email and password, where do I store it? In the AuthStore?\nAnd how do I authenticate against the AuthStore?How and where you store user credentials and information is entirely up to you; the webapp2 module you reference merely provides an interface you must conform to if you want to use its features. An obvious (perhaps the only sensible) choice would be the datastore.I'd strongly, strongly recommend using the built in  instead of rolling your own, though. By doing so, you're forcing users to create yet another username and password, and you're taking on a whole set of password storage and security hassles for yourself.New answer to an old question: Anyone looking to add own authentication and login to webapp2 on Google App Engine should consider .Signup, login, logout, password reset, federated login (Google, Twitter, Facebook, etc), user profiles, etc are implemented.Technologies leveraged include, Python 2.7, NDB, Jinja2, WTForms, unittest, webtest, pyquery, OpenID (Google App Engine), and OAuth2 (for federated login providers that do not support OpenID).Online demo is .
Python

Python 3 has  and  but no . So, why a number representing the infinite set of integers is missing in the language? Is  unreasonable?Taken from here: That is, the representation of  and  can store these special values. However, there is nothing within the basic type  that can store the same. As you exceed the limit of 2^32 in an unsigned 32-bit int, you simply roll over to 0 again.If you want, you could create a class containing an integer which could feature the possibility of infinite values.For python 2.\nIt is sometimes the case that you need a very large integer. For example, I may want to produce a subarray with x[:n] and, I may wish to sometimes set n to a value such that the whole array will be produced. Since you can't use a float for n (python wants an integer), you need a \"large integer\". A good way of doing this is to use the largest integer available: sys.maxint.\nHere is an example:So, while testing, I could use a smaller sources array but use the full array in production.You are right that an integer infinity is possible, and none has been added to Python standard.  This is probably because  supplants it in almost all cases.
Python

I need to walk through folders with long file names in Windows.I tried using , but it crashes with long pathnames, which is bad.I tried using , but it ignores the pathnames longer than ~256, which is worse.I tried the magic word workaround described , but it only works with mapped drives, not with .Here is an example with short pathnames, that shows that UNC pathnames don't work with the magic word trick.Any idea on how to deal with long pathnames or with unicode UNC pathnames?Edit:Following the suggestion of the comments below, I created some test functions to compare Python 2.7 and 3.3, and I added the test of  and  after . The  didn't help as expected (see this ).The  is the only one that in Python 3.3 works better, but only in one condition: using the magic word and with the drive name.Here is the code I used (it works on both 2.7 and 3.3). I am learning Python now, and I hope these tests make sense:And here is the result:-Use the 8.3 fallback to avoid the long pathname,  browsing in Win7 explorer this seems to be what windows itself does, ie every long paths has a shorter 'true name':but you can use win32api (pywin32) to 'build' up a shorter version, ieclearly you can just fold the win32api.GetShortPathName call into you dir exploration rather than nesting as in my example.\nI've done it like this with 3 calls because if you've already got a 'too long' path then win32api.GetShortPathName wont cope with it either,  but you can do it per dir and stay below the limit.To locate files on UNC paths, the the magic prefix is  rather than just .Reference: So to access , you'd need toResulting unicode string: I've only experimented a little (much less than @stenci did) but with Python 2.7 it seems to work OK with , and to fail with .In my previous comment I said that the nested recursive call of  is not required. I found it is not required most of the times, but once in a while it crashes. I wasn't able to figure out when, so I made this little function that has been working smoothly for some time:This is the function that I use now:
Python

I've been following the saga of Python 3.x and have watched the 3.x features gradually getting back-ported to the 2.x line.  Most of the libraries I use haven't been ported and some (e.g. Twisted) seem covertly or overtly hostile to 3.x to varying degrees.  At any rate, there has been very little movement towards compatible versions of many of them.  Expecially the larger ones.So, my question is, with all the features that have been backported, what is still available in 3.x that's NOT been back-ported?  It's pretty easy to find what  been backported, but not .Right now, porting to 3.x just seems like all pain, and I can't see the gain; maybe an \"Only in 3.x\" list would let me see the light...Thanks,Stu The most important thing is probably unicode throughout. So there is no need anymore to fiddle around with str/unicode. This sounds small but has huge (positive) implications when you think of OS interaction - for example everyone has to try hard to give you 'usable' strings instead of 'a binary thing that might be an error message'.There's also a lot of stuff in the interpreter itself that was improved. One example is the global interpreter lock (GIL) which did not vanish but it way better in py3k: Speed might be a feature worth mentioning.The speed imporovements of project \"Unladen Swallow\" have been approved to be merged into Python. But as far as I know only to Python 3. See  for details.
Python

This is tricking me out.\nI understand elem is the lists inside of the list from \nI don't quite understand the usage of  and  in the beginning and the end.How does python interpret this?\nWhat's the order it looks at?Lets break it down.A simple list-comprehension:This is easy to understand if we break it into parts: In this way, one could write:In order to convert all words in a list to lowercase.It is when we complicate this with another list like so:Here, something special happens. We want our final list to include  items, and  items are found inside  items, so we have to tell the list-comprehension that.This logic is similar to the normal for loop:To expand on this, and give a great example + explanation, imagine that there is a train.The train engine (the front) is always going to be there (the result of the list-comprehension) Then, there are any number of train cars, each train car is in the form: A list comprehension could look like this:Which would be like having this regular for-loop:In other words, instead of going down a line and indenting, in a list-comprehension you just add the next loop on to the end. To go back to the train analogy: -  -  -  ... What is the tail? The tail is a special thing in list-comprehensions. You don't  one, but if you have a tail, the tail is a condition, look at this example:This would give you every line in a file as long as the line didn't start with a hashtag (), others are just skipped.The trick to using the \"tail\" of the train is that it is checked for True/False at the same time as you have your final 'Engine' or 'result' from all the loops, the above example in a regular for-loop would look like this: Though in my analogy of a train there is only a 'tail' at the end of the train, the condition or 'tail' can be after  'car' or loop...for example:In regular for-loop:Your code equals:From the :In other words, pretend that the  loops are nested. Reading from left to right your list comprehension can be nested as:where the list comprehension will use that last, innermost block as the values of the resulting list.
Python

I would like to know how to pass a variable to all my templates, without repeating the same code on every method in my views.py file? In the example below I would like to make categories (an array of category objects) available to all templates in the web app.What you want It's a  and it's very easy to create one for example assuming you have got an app named  you have to follow the next steps to create one.And now  you can use  in all the templates :DTo add a , in the settings you must add the next code:
Python

How can I test whether two JSON objects are equal in python, disregarding the order of lists?For example ...JSON document :JSON document : and  should compare equal, even though the order of the  lists are different.If you want two objects with the same elements but in a different order to compare equal, then the obvious thing to do is compare sorted copies of them - for instance, for the dictionaries represented by your JSON strings  and :... but that doesn't work, because in each case, the  item of the top-level dict is a list with the same elements in a different order, and  doesn't try to sort anything except the \"top\" level of an iterable.To fix that, we can define an  function which will recursively sort any lists it finds (and convert dictionaries to lists of  pairs so that they're orderable):If we apply this function to  and , the results compare equal:Another way could be to use  option:This works for nested dictionaries and lists.Decode them and compare them as mgilson comment.Order does not matter for dictionary as long as the keys, and values matches. (Dictionary has no order in Python)But order is important in list; sorting will solve the problem for the lists.Above example will work for the JSON in the question. For general solution, see Zero Piraeus's answer.
Python

I want to connect too and execute a process on a remote server using python.  I want to be able to get the return code and stderr(if any) of the process.  Has anyone ever done anything like this before.  I have done it with ssh, but I want to do it from python script.Cheers.Well, you can call ssh from python...Use the  which was created for this purpose instead of using . Here's an example below:UPDATE: The example used to use the  module, but that is now deprecated and  is the up-to-date module that provides ssh functionality in python.Maybe if you want to wrap the nuts and bolts of the ssh calls you could use \nThis library is geared towards deployment and server management, but it could also be useful for these kind of problems.Also have a look at . This implements a task queue for Python/Django on various brokers. Maybe an overkill for your problem, but if you are going to call more functions on multiple machines it will save you a lot of headache managing your connections. 
Python

I'm trying to dump a list of all active threads including the current stack of each. I can get a list of all threads using threading.enumerate(), but i can't figure out a way to get to the stack from there. Background: A Zope/Plone app freaks out from time to time, consuming 100% of cpu and needs to be restarted. I have a feeling it's a loop which doesn't terminate properly, but i cannot reproduce it in the test-environemt for verification. I managed to register a signal handler which can be triggered from the outside, so i can trigger some code as soon as the situation occurs again. If I could dump the stacktrace for all active threads, that would give me a clue what goes wrong. The hole thing runs on python 2.4...Any ideas on how to trace down situations like these are appreciated :)Cheers,\n   ChrissWhen using Zope, you want to install  or ; these were designed for just this purpose!Send a USR1 signal to your Zope server and it'll immediately dump stack traces for all threads to the console. It'll do this even if all Zope threads are locked up.Under the hood these packages indirectly use ; for Python versions 2.5 and up, when  using Zope, you can build the same functionality using the  function to access per-thread stack frames.As of  this functionality is integrated into Zope itself, and there is no need to install additional packages anymore.As jitter points out in an earlier answer  gives you what you need for v2.5+. For the lazy the following code snippet worked for me and may help you:For Python 3.3 and later, there is .The code below produces similar output, but includes the thread name and could be enhanced to print more information.2.4. Too bad. From Python 2.5 on there is .But you could try . And if the makefile gives you trouble you could try this Just for completeness sake,  is super helpful to identify bottlenecks, and to do so it dumps stacktraces at specific intervals.There is an applicable recipe on . You can use  to get all the tids, then just call _async_raise() with some suitable exception to force a stack trace.
Python

Given an RFC822 message in Python 2.6, how can I get the  text/plain content part?  Basically, the algorithm I want is this:Of these things, I have  and  down pat, but I'm not quite sure how to get the decoded text from the MIME part.  I can get the  text using , but if I try to use the  parameter of the  method (see ) I get an error when I call it on the text/plain part:In addition, I don't know how to take HTML and render it to text as closely as possible.In a multipart e-mail,  returns a list with one item for each part. The easiest way is to walk the message and get the payload on each part:For a non-multipart message, no need to do all the walking. You can go straight to get_payload(), regardless of content_type.If the content is encoded, you need to pass  as the first parameter to , followed by True (the decode flag is the second parameter). For example, suppose that my e-mail contains an MS Word document attachment:As for getting a reasonable plain-text approximation of an HTML part, I've found that  works pretty darn well.Flat is better than nested ;)
Python

Which is preferred (\".\" indicating whitespace)?A)B)My intuition would be B (that's also what vim does for me), but I see people using A) all the time. Is it just because most of the editors out there are broken?The  does not seem to be clear on this issue, although the statements about \"blank lines\" could be interpreted in favor of B. The PEP 8 style-checker (pep8.py) prefers B and warns if you use A; however, both variations are legal. My own view is that since Python will successfully interpret the code in either case that this doesn't really matter, and trying to enforce it would be a lot of work for very little gain. I suppose if you are very adamantly in favor of one or the  other you could automatically convert the one to the other. Trying to fix all such lines manually, though, would be a huge undertaking and really not worth the effort, IMHO.If you use , you could copy paste your block in python shell,  will get unexpected indentation error.That empty line belongs to , so I would consider  to be the most natural. But I guess it's just a matter of opinion.Adding proper indentation to blank lines (style  in the question) vastly improves code readability with display whitespace enabled because it makes it easier to see whether code after a blank line is part of the same indentation block or not.For a language like Python, where there is no end statement or close bracket, I'm surprised this is not part of PEP.  Editing Python with display whitespace on is strongly recommended, to avoid both trailing whitespace and mixed indentation.Compare reading the following:A)B)In , it is far clearer that the last two lines are part of .  This is even more useful at higher indentation levels.TextMate breaks block collapsing if you use B, and I prefer A anyway since it's more \"logical\".I wouldn't necessarily call the first example \"broken\", because I know some people hate it when the cursor \"jumps back\" when moving the cursor up or down in code. E.g. Visual Studio (at least 2008) automatically prevents this from happening without using any whitespace characters on those lines.Emacs does B) for me, but I really don't think it matters. A) means that you can add in a line at the correct indentation without any tabbing.My experience in open-source development is that one should never leave whitespace inside blank lines.  Also one should never leave trailing white-space.  It's a matter of coding etiquette.I prefer B since it makes hopping around in vim easier via the { and } commands.It's also a waste of space to write A, albeit minimal. A presumes that the subsequent code will be indented, which is not always the case.
Python

I'm trying to copy  and all its contents (and their contents, etc.) to  in python. Furthermore, I want the copy to overwrite everything in .It  like  might be the right tool for the job, but not sure if there's anything easier/more obvious to use for such a simple task.If it is the right tool, how do I use it? According to the  there are 8 parameters that it takes. Do I have to pass all 8 are just ,  and , and if so, how (I'm brand new to Python).If there's something out there that's better, can someone give me an example and point me in the right direction? Thanks in advance!You can use . It works just fine and you don't have to pass every argument, only  and  are mandatory.However in your case you can't use a similar tool like because it behaves differently: as the destination directory must not exist this function can't be used for overwriting its contents.If you want to use the  tool as suggested in the question comments beware that using the  module is currently the recommended way for spawning new processes as you can see in the .Have a look at the  package, especially  and . You can check if a file / path exists with .Vincent was right about  not working, if dirs already exist. So  is the nicer version. Below is a fixed version of . It's basically copied 1-1, except the first  put behind an if-else-construct:Here's a simple solution to recursively overwrite a destination with a source, creating any necessary directories as it goes.  This does not handle symlinks, but it would be a simple extension (see answer by @Michael above).
Python

I have the following error when I run django allauth example and it tries to send an email:Under OS X 10.9.1From allauth documentation:
Python

Sometimes I download python source code from github and don't know how to install all the dependencies. If there is no requirements.txt file I have to create it by hands. \nThe question is:\nGiven python source code directory is it possible to create requirements.txt automatically from import section?If you use virtual environment,  just fine. If not,  will be a good choice for you.By the way, I do not ensure it will work with 2.6.You can use the following code to generate a requirements.txt file:more info related to pipreqs can be found .Sometimes you come across , but this saves all packages in the environment including those that you don't use in your current project. 
Python

When working with the default global graph, is it possible to remove nodes after they've been added, or alternatively to reset the default graph to empty? When working with TF interactively in IPython, I find myself having to restart the kernel repeatedly. I would like to be able to experiment with graphs more easily if possible.There's , but not part of public API (I think it should be, does someone wants to  on GitHub?)My work-around to reset things is this:By default, a session is constructed around the default graph.\nTo avoid leaving dead nodes in the session, you need to either control the default graph or use an explicit graph.
Python

I have a small multithreaded script running in django and over time its starts using more and more memory. Leaving it for a full day eats about 6GB of RAM and I start to swap.Following  I see this as the most common types (with only 800M of memory used):which doesn't show anything weird. What should I do now to help debug the memory problems? Trying some things people are recommending. I ran the program overnight, and when I work up, 50% * 8G == 4G of RAM used. That doesn't sum to 4G, nor really give me any big data structured to go fix. The unicode is from a set() of \"done\" nodes, and the list's look like just random s. I didn't use guppy since it required a C extension and I didn't have root so it was going to be a pain to build.None of the objectI was using have a  method, and looking through the libraries, it doesn't look like django nor the python-mysqldb do either. Any other ideas?See  . Short answer: if you're running django but not in a web-request-based format, you need to manually run  (and of course have DEBUG=False, as others have mentioned). Django automatically does  after a web request, but in your format, that never happens.Is DEBUG=False in settings.py?If not Django will happily store all the SQL queries you make which adds up.Have you tried  ?You need to ask yourself simple questions:See, the main issue would be a cycle of objects containing  methods:I would really encourage you to flag objects / concepts that are cycling in your application and focus on their lifetime: when you don't need them anymore, do we have anything referencing it?Even for cycles without  methods, we can have an issue:If you have to use \"seen\"-like dictionaries, or history, be careful that you keep only the actual data you need, and no external references to it.I'm a bit disappointed now by , I wish it could be configured to output data somewhere else than to stderr, but hopefully .See  on how they traced down real memory leak in HP's Tabblo. A classic and worth reading.I think you should use different tools. Apparently, the statistics you got is only about GC objects (i.e. objects which may participate in cycles); most notably, it lacks strings.I recommend to use ; this should provide you with more detailed statistics.Do you use any extension? They are a wonderful place for memory leaks, and will not be tracked by python tools.Try .Basicly, you need more information or be able to extract some. Guppy even provides graphical representation of data.
Python

How Do I add a single item to a serialized panda series. I know it's not the most efficient way memory wise, but i still need to do that.Something along:also, how can i add a single row to a pandas DataFrame? How to add single item. This is not very effective but follows what you are asking for:produces x:Obviously there are better ways to generate this series in only one shot.  For your second question check answer and references of SO question . I think the question in its current form is a bit tricky. And the accepted answer does answer the question. But the more I use pandas, the more I understand that it's a bad idea to append items to a Series one by one. I'll try to explain why for pandas beginners.You might think that appending data to a given Series might allow you to reuse some resources, but in reality a Series is just a container that stores a relation between an index and a values array. Each is a numpy.array under the hood, and the index is immutable. When you add to Series an item with a label that is missing in the index, a new index with size n+1 is created, and a new values values array of the same size. That means that when you append items one by one, you create two more arrays of the n+1 size on each step.By the way, you can not append a new item by position (you will get an IndexError) and the label in an index does not have to be unique, that is when you assign a value with a label, you assign the value to all existing items with the the label, and a new row is not appended in this case. This might lead to subtle bugs.The moral of the story is that you should not append data one by one, you should better extend with an ordered collection. The problem is that you can not extend a Series inplace. That is why it is better to organize your code so that you don't need to update a specific instance of a Series by reference.If you create labels yourself and they are increasing, the easiest way is to add new items to a dictionary, then create a new Series from the dictionary (it sorts the keys) and append the Series to an old one. If the keys are not increasing, then you will need to create two separate lists for the new labels and the new values.Below are some code samples:When we update an existing item, the index and the values array stay the same (if you do not change the type of the value)But when you add a new item, a new index and a new values array is generated:That is if you are going to append several items, collect them in a dictionary, create a Series, append it to the old one and save the result:You can use the append function to add another element to it. Only, make a series of the new element, before you append it:If you have an index and value. Then you can add to Series as:this will add a new value to Series (at the end of Series).Adding to joquin's answer the following form might be a bit cleaner (at least nicer to read):which would produce the same outputalso, a bit less orthodox but if you wanted to simply add a single element to the end:
Python

Have a list of python dictionaries in the following format. How would you do a search to find a specific name exists?The following did not work:You'd have to search through all dictionaries in your list; use  with a generator expression:This will short circuit; return  when the  match is found, or return  if none of the dictionaries match.You might also be after:Or possibly more clearly:
Python

Using virtualenv and just trying to install pyodbc. All resources I can find claim this should be extremely straightforward. After all the basic installs of MySQL, etc., just do:However, I am seeing a very strange error. It has nothing (as far as I can tell) to do with missing libraries, and after Googling for this sort of error for a long time, I can't find anything constructive on it at all.So I tried with the \"allow-external\" option and it does not help:But the help documentation makes it appear that I am using this option correctly, e.g. from the output of running :Here's the result in the PIP log file:It makes it seem that if I can just get the  option to work, it will work because it clearly sees the common location for getting pyodbc.But I am puzzled why this is needed at all, when virtually all references to installing pyodbc do not need to go out of the way to enable external links. I've also been installing many packages all day today, with few issues and certainly not encountering this  need in any other case.I am using pip version 1.5 with Python 2.7.3 on Ubuntu 12.04.Running  will work if the PyPI directory structure is correct. Based on the pip.log output when I originally posted this answer, I think that package's website directory structure was broken. You can always work around this type of problem by specifying the URL of the package like , links for different versions are described .I just tried installing pyodbc as well and hit the same wall. I think the problem you and I  both hit is that --allow-external consumes the next argument as well. So you actually need to write:I then hit another error about unverified sources so that command that actually worked for me was:Note that once that was done the permissions on the installed files prevented normal users from access pyodbc. So I went in manually adjusted the permissions on all installed packages (seemed easier than finding just the files needed by pyodbc).As per the suggestion of EMS I have added an issue to the Pip bug tracker. It can be found at:FWIW, on ms windows anything other than installing the binary (windows install) for me was cumbersome in a windows/cygwin hybrid  environment.I opted to use   as it's pure python and didn't require any changes for my windows/linux development. It can be seen as an  with no compilation needed, and of course can be installed easily with .There is an \"easier\" way to install pyodbc on windows in a virualenv using :as used for pywin32 see: I had success when installed withHowever, I also needed the  package in order for pyodbc to actually compile.Both  and  take package name as an argument.So your usage should beor the little confusing: use  when you just want to allow one and not . It kills the whole purpose of putting in the security check.
Python

I'm using the Pandas package and it creates a DataFrame object, which is basically a labeled matrix. Often I have columns that have long string fields, or dataframes with many columns, so the simple print command doesn't work well. I've written some text output functions, but they aren't great.What I'd really love is a simple GUI that lets me interact with a dataframe / matrix / table. Just like you would find in a SQL tool. Basically a window that has a read-only spreadsheet like view into the data. I can expand columns, page up and down through long tables, etc.I would suspect something like this exists, but I must be Googling with the wrong terms. It would be great if it is pandas specific, but I would guess I could use any matrix-accepting tool. (BTW - I'm on Windows.)Any pointers?Or, conversely, if someone knows this space well and knows this probably doesn't exist, any suggestions on if there is a simple GUI framework / widget I could use to roll my own? (But since my needs are limited, I'm reluctant to have to learn a big GUI framework and do a bunch of coding for this one piece.)I use  from PyQt to display a . I create a  and then populate with  created with  values.\nFollowing is the snippet of code that reads a CSV file ,create a , then display in a GUI:I wasn't fully satisfied with some other GUIs, so I created my own, which I'm now maintaining . Example:Apart from the basic table + plot functionality, I wanted to have a specific way to filter data:You could use the to_html() dataframe method to convert the dataframe to html and display it in your browser. Here is an example assuming you have a dataframe called df. You should check the documentation to see what other options are available in the to_html() method.If you want to get the table to be nicely formatted and scrollable then you can use the datatables plug-in for jQuery . Here is the javascript I use to display a table the scrolls in both x and y directiions.Pandas 0.13 provides as an experimental feature:PySide support for the qtpandas  and see you can add this feature usingIn addition to all the valuable answers, I would like to mention that the Spyder IDE () has this feature as you can see in my printscreen below:This is just an objective fact and not advertisement for any IDE :) I don't want to trigger any debate on this question. The question was post in 2012 and other answers may be too old to apply.The answer in 2016 is, we should use Pycharm and it's shipped with  viewer.I've been working on a PyQt GUI for pandas DataFrame you might find useful.  It includes copying, filtering, and sorting.The nicest solution I've found is using  (see , and also mentioned in the ). You can install byand then you need to do a further install (just once) in your  notebookAfterwards, it's as easy as taking your   and runningThe other nice thing is that it renders in  too. See it in action It seems there is no easy solution. So, below is a little function to open a dataframe in Excel. It's probably not production quality code, but it works for me!I use ipython notebooks to drive pandas -- notebooks provide a nice clean way of incrementally building and interacting with pandas data structures, including HTML-ized display of dataframes:  I'm not a Pandas user myself, but a quick search for \"pandas gui\" turns up the Pandas project's :So, there's no GUI, but if you'd write one using Qt or Tk, the project might be interested in your code.There's  for python2.7 and  for python3. You can use GitHub Atom with Hydrogen plugin. In Mac you can use Cmd+Shift keys to execute line by line. Even you can select only the variable and see inside. DataFrames are nicely display and you can even copy. I wrote a blog to show the way to configure these.\n
Python

How can I make the following functionality compatible with versions of Python earlier than Python 2.7?Use:That's the  function with a generator expression producing  pairs.Or, to put it generically, a dict comprehension of the form:can always be made compatible with Python < 2.7 by using:
Python

How can I auto fill the username and password over the link below:After that I really do not know:Notes to your code:Use  method to simulate key typing. in the code (, ) does not match actual  of the elements (, ).Note:
Python

In a iPython notebook, I have a while loop that listens to a Serial port and  the received data in real time.What I want to achieve to only show the latest received data (i.e only one line showing the most recent data. no scrolling in the cell output area)What I need(i think) is to clear the old cell output when I receives new data, and then prints the new data. I am wondering how can I clear old data programmatically ?You can use  to clear the output of a cell.At the end of this loop you will only see one .Without a code example it's not easy to give you working code. Probably buffering the latest n events is a good strategy. Whenever the buffer changes you can clear the cell's output and print the buffer again.
Python

Demo:Why does  call ?  It doesn't seem to use the result for anything obvious.  A  loop doesn't do it.  This isn't mentioned anywhere in the , which just talks about  and .  Is this Python reserving space for the list in advance, or something clever like that?  (CPython 3.6.0 on Linux)See the  that introduced  and offers insight on the motivation:Also see the documentation :So it seems that it's simply the case that  can result in some nice optimizations., , then tries to see if  is available, and, if neither is there, returns a default value of  for lists. , which is called from  as Eli stated in his answer, was modified according to this PEP to offer this optimization for anything that defines either a  or a .  isn't the only one that benefits from this, of course, :so :and  objects which create  populate themselves:If anybody is wandering why exactly  is printed   in class  and not after as happens with class : This is because if the object in hand defines an  , thereby running the  too. The same doesn't happen if it falls back to using . is a list object constructor that will allocate an initial slice of memory for its contents.  The list constructor attempts to figure out a good size for that initial slice of memory by checking the length hint or the length of any object passed into the constructor .  See the call to  in the Python . This place is called from the list constructor -- If your object has no  or , that's OK -- a  is used; it just may be less efficient due to reallocations.
Python

Let's say I have the following classes set up:How can I (if I can at all) use super() in this context to eliminate the duplicate code?In Python >=3.0, like this:Read more here: EDIT: As said in another answer, sometimes just using  can be the better solution. (For instance, when working with certain forms of multiple inheritance.)Assuming you want class Bar to set the value 34 within its constructor, this would work:However,  introduces its own complications. See e.g. . For completeness, here's the equivalent version without .
Python

I'm confused about what the different between  and  is in matplotlib. Could someone please explain in an easy-to-understand way?Axis is the axis of the plot, the thing that gets ticks and tick labels. The axes is the area your plot appears in.This figure from the documentation will answer your question:\"axes\" is the plural of \"axis\".
Python

I have two lists:and I need to create a list of tuples from these lists, as follows:I tried doing it like this:but resulted in:i.e. a list of tuples of every element in x with every element in y... what is the right approach to do what I wanted to do? thank you... The other two duplicates mentioned before the edit is my fault, indented it in another for-loop by mistake...Use the builtin function :You're looking for the  function.\nFrom the docs:You're after the zip function.Taken directly from the question: 
Python

I'm writing a script which will have to work on directories which are modified by hand by Windows and Linux users alike. The Windows users tend to not care at all about case in assigning filenames.Is there a way to handle this on the Linux side in Python, i.e. can I get a case-insensitive, glob-like behaviour? Use case-insensitive regexes instead of glob patterns.  generates a regex from a glob pattern, sogives you a case-insensitive version of a glob pattern as a compiled RE.Keep in mind that, if the filesystem is hosted by a Linux box on a Unix-like filesystem, users will be able to create files ,  and  in the same directory.You can replace each alphabetic character c with [cC], viaIn order to retrieve the files (and files only) of a directory \"path\", with \"globexpression\":with walk:Better also compile the regular expression, so instead of do (before the loop):and then replace in the loop:Depending on your case, you might use  on both file pattern and results from folder listing and only then compare the pattern with the filename
Python

I am making a chart in matplotlib and I have many subplots in it each of them with a different title, but on the top I also want to a put a title to the whole chart. How this can be done?You can use the  command to add a  in addition to sub plot titles.
Python

In WeasyPrint\u2019s public API I accept filenames (among other types) for the HTML inputs. Any filename that works with the built-in  should work, but I need to convert it to an URL in the  scheme that will later be passed to .(Everything is in URL form internally. I need to have a \"base URL\" for documents in order to resolve relative URL references with .) is a start:The emphasis is mine, but I do need a complete URL. So far this seems to work:UTF-8 seems to be recommended by . But in this case (the\u00a0URL is meant for urllib, eventually) maybe I should use ?However, based on  I should prepend not just  but  ... except when I should not: On Windows the results from  already start with three slashes.So the question is: is there a better way to do this and make it cross-platform?For completeness, in Python 3.4+, you should do:I'm not sure the docs are rigorous enough to guarantee it, but I think this works in practice:Credit to comment from  above.For Python3, the following code will work:Does the following work for you?
Python

I am trying to use selenium from python to scrape some dynamics pages with javascript. However, I cannot call firefox after I followed the instruction of selenium on the pypi page(http://pypi.python.org/pypi/selenium). I installed firefox on AWS ubuntu 12.04. The error message I got is:I did search on the web and found that this problem happened with other people (https://groups.google.com/forum/?fromgroups=#!topic/selenium-users/21sJrOJULZY). But I don't understand the solution, if it is. Can anyone help me please? Thanks!The problem is Firefox requires a display. I've used  in my example to simulate a display. The solution is:This should resolve your issue.I too had faced same problem.I was on Firefox 47 and Selenium 2.53. So what I did was downgraded Firefox to 45. This worked.1) Remove Firefox 47 first :2) Check for available versions:It will show available firefox versions like:3) Tell which build to download4) Next you have to not upgrade to the newer version again.5) If you want to upgrade later\nHope this helps.
Python

I am using  from  to do binary classification.  I am using its predict_proba() function to get probability estimates.  Can anyone tell me how predict_proba() internally calculates the probability?Scikit-learn uses LibSVM internally, and this in turn uses , as detailed in , to calibrate the SVM to produce probabilities in addition to class predictions.Platt scaling requires first training the SVM as usual, then optimizing parameter vectors  and  such thatwhere  is the signed distance of a sample from the hyperplane (scikit-learn's  method). You may recognize the  in this definition, the same function that logistic regression and neural nets use for turning decision functions into probability estimates.Mind you: the  parameter, the \"intercept\" or \"bias\" or whatever you like to call it, can cause predictions based on probability estimates from this model to be inconsistent with the ones you get from the SVM decision function . E.g. suppose that , then the prediction for  is positive; but if  and , then . I'm pulling these numbers out of thin air, but you've noticed that this can occur in practice.Effectively, Platt scaling trains a probability model on top of the SVM's outputs under a cross-entropy loss function. To prevent this model from overfitting, it uses an internal five-fold cross validation, meaning that training SVMs with  can be quite a lot more expensive than a vanilla, non-probabilistic SVM.Actually I found a slightly different answer that they used this code to convert decision value to probabilityHere A and B values can be found in the model file (probA and probB).\nIt offers a way to convert probability to decision value and thus to hinge loss.Use that ln(0) = -200.
Python

Looking to store usernames and passwords in a database, and am wondering what the safest way to do so is.  I know I have to use a salt somewhere, but am not sure how to generate it securely or how to apply it to encrypt the password.  Some sample Python code would be greatly appreciated.  Thanks.Store the password+salt as a hash and the salt. Take a look at how Django does it:  and .\nIn the db they store   in a single char field. You can also store the three parts in separate fields.The function to set the password:The get_hexdigest is just a thin wrapper around some hashing algorithms. You can use hashlib for that. Something like And the function to check the password:I think it is best to use a package dedicated to hashing passwords for this like passlib:  for reasons as I explained here: I answered this here: , and so did @Koffie.I don't know how to emphasize enough that the accepted answer is NOT secure. It is better than plain text, and better than an unsalted hash, but it is still  to dictionary and even brute-force attacks. Instead, please  like bcrypt (or  PBKDF2 with 10,000 iterations)If you have enough control over both endpoints of the application, the absolute best way is using .Here is a simpler way (taken from effbot), provided passwords with a length greater than 8 will not be a problem*:for generate the password :*: A password with a length greater than 8 is stripped from the right down to 8 chars long
Python

I'm looking for the equivalent of  in Google App Engine and Python.Thanks!I slapped a quick and dirty example together based on the tutorial. It's been tested on my local appengine sdk. You should be able to adapt it to your needs:Try with:or with the :
Python

I have a quirk(?) with Django queryset filtering:orandso, how to use values_list()? (to produce):or is python list comprehension the 'way to go'?Try .  That returns a list of ids instead of a list of single id tuples.One thing to note is that there is a difference in the behaviour of values/values_list from a list comprehension: Choosing the wrong one will either result in unnecessary database hits, or unnecessary faffing around, depending on what you are trying to do.
Python

Consider this snippet:Where  is the dict I'm after that would contain ,  and , among other things.I'd like to basically be able to reference all the variables that are currently in scope inside the string. Hence the expected output would be:I can achieve this by passing  to . Is this always correct or are there some corner cases that this expression would handle incorrectly?Best way to merge two dicts as you're doing (with locals overriding globals) is .What the approach of merging globals and locals is missing is (a) builtins (I imagine that's deliberate, i.e. you don't think of builtins as \"variables\"... but, they COULD be, if you so choose!-), and (b) if you're in a  function, any variables that are local to enclosing functions (no really good way to get a dict with all of , plus -- only those explicitly accessed in the nested function, i.e. \"free variables\" thereof, survive as cells in a closure, anyway).I imagine these issues are no big deal for your intended use, but you did mention \"corner cases\";-).  If you need to cover them, there are ways to get the built-ins (that's easy) and (not so easy) all the cells (variables from enclosing functions that you explicitly mention in the nested function --  to get the names,  to get the cells,  on each cell to get its value). (But, remember, those will only be variables from enclosing functions that are  in your nested function's code!).Does this do what you intended?If I read the documentation correctly, you create a copy of the  dict, then you overwrite any duplicates  insert new entries from the  dict (since the  should have preference within your scope, anyway).I haven't had  luck in getting a proper function to return the full dictionary of variables in scope of the   function.  Here's the code (I only used pprint to format the output nicely for SO):and the output:Note that in the second output, we have overwritten , and x is present; the first output only included the local vars within the scope of .So if you want to access the full variable scope, you cannot put locals() inside another function.I had suspected there was some sort of frame object, I just didn't (know where to) look for it.This works to your spec, I believe:-->You could make your own:or combine the first two lines:Interpolation into strings works in the simplest possible way.  Just list your variables.  Python checks locals and globals for you.
Python

I'm currently trying to automate django tests using hudson, and am struggling to find an option that will automatically destroy the test database if it already exists (typically it will ask for confirmation to destroy it, which the automatic testing obviously cannot provide for).Any suggestions would be much appreciated!Cheers,\nRUse --help to see the docs of the test command:And use --noinput which defaults to destroying the test db;)
Python

I came across this sample of code from a :What does the '' do in Python? is the integer division operator.In Python 3 the ordinary  division operator returns floating point values even if both operands are integers, so a different operator is needed for integer division. This is different from Python 2 where  performed integer division if both operands were integers and floating point division if at least one of the operands was a floating point value.The  operator was first introduced for forward-compatibility in Python 2.2 when it was decided that Python 3 should have this new ability. Together with the ability to enable the Python 3 behavior via  (also introduced in Python 2.2), this enables you to write Python 3-compatible code in Python 2.You can just try it:This should be self-explanatory. (This is in Python 2.7.)
Python

I saw a python example today and it used -> for example this was what I saw:What is that code doing? I'm not quite sure I've never seen code like that I don't really get what is doing either, can someone explain this for me? I googled, \"what does -> do in python\" but no good searches came up that I found.It is function annotation for a return type.  do nothing inside the code, they are there to help a user with code completion (in my experience).Here is the  for it.Let me demonstrate, what I mean by \"annotations do nothing inside the code\". Here is an example:The above code will run without any errors. but as you can see the first parameter  be a , and the second an . But, this only is a problem in my IDE, the code runs just fine:They're . They don't really do anything by themselves, but they can be used for documentation or in combination with metaprogramming.
Python

Usage of relative imports in Python has one drawback, you will not be able to run the modules as standalones anymore because you will get an exception: How should I modify the sample code in order to be able to execute all: ,  and I'm looking for a solution that works with python 2.6+ (including 3.x).First, I assume you realize what you've written would lead to a circular import issue, because foo imports bar and viceversa; try adding to test.py, and you'll see it fails. The example must be changed in order to work.So, what you're asking is really to fallback to absolute import when relative import fails; in fact, if you're executing foo.py or bar.py as the main module, the other modules will just lie at the root level, and if they share the name with another module on the system which one will be picked depends on the order in sys.path. Since the current dir is usually the first, local modules will be picked if available - i.e., if you've got an 'os.py' file in the current working dir, it'll be picked instead of the builtin one.A possibile suggestion is:foo.pybar.py:By the way calling scripts from the proper position is usually  better.Is probably the best way to go.You could just start 'to run the modules as standalones' in a bit a different way:Instead of:Use:Of course, the  file must be present.Please also note, that you have a circular dependency between  and  \u2013 this won't work. I guess it is just a mistake in your example.Update: it seems it also works perfectly well to use this as the first line of the :Then you can execute the script directly in POSIX systems.Ditch relative imports: you should think of your package namespace as a global one, anyway.The trick to making this palatable is editing  appropriately. Here is some food for thought:You need  in each folder.Relative import works only when you do:test.py imports foo.py and foo.py can relative import anything from the folder of test.py and above.You can't do:It will never work.You can try the sys.path.append or sys.path.insert solution but you gonna screw up the paths and you'll have problems with the f=open(filename).Why not just put the \"main\" in a different .py file?So far the only solution I found was not to use relative imports at all. Due to current limitation, I'm wondering when someone is supposed to use relative imports in python.On all configurations that I used the  contained the current directory as first argument so just use  instead of  because it will do the same.
Python

When information about a type is needed you can use:gets:or:gets:Now, in the documentation of Python information can be found about these functions, but I would like to get info about these functions in the terminal/command-line.\nHow should this be done?In python:  for example, will give you the docstring of the function.Tryto get built-in help messages.Orif you're generally poking around.
Python

I have a property in a Django Model that I'd like to expose via a TastyPie ModelResource. My Model isMy ModelResource isHowever all I'm currently getting out of the tastypie api is:I have tried playing with the fields property in the ModelResource, but that hasn't helped. Would love to understand what is going on here.You should be able to define it as a  try:You also have to include:  on your , or TastyPie will try to set its value on insertion or update.A full example with dehydrate:
Python

When considering design, in which cases does it make sense to use class versus dict? Pros & Cons would be useful too.For example,versusI would say the first and most important criteria to distinguish whether to use a class or a  dictionary is whether you just want to have some data storage or you also want to have some logic (i.e., methods).If you only need to keep together several data, then a dictionary might be the way to go. On the other hand, if you need operations performed on that data, and there is a very tight relationship between the data and the operations (forming a kind of entity), then that really calls for using a class.As @Ben is suggesting, you may start using just a dictionary when you have a bunch of related data, and if at some point your realize that you also need some logic for that data, you can turn the dictionary into a class.You may also have a look at the  and its  to get a better feeling on how to use classes. If you are just doing some scripting or programming a small application you may not need to use UML, but if you are designing a bigger and more complex system, it can really help you to decide what and how many classes do you need beforehand.A  can use any hashable value as a key, while a  instance needs to have strings that are legal identifiers as its \"keys\".  So you can bundle together arbitrary data in a .It's pretty common to use a trivial class as a more-convenient  when your key values will all be valid identifier strings anyway:As soon as you start to do proper object oriented design, and you have method functions that go along with the data, you want to have the data in a proper class so you can bundle the method functions in.  It's legal to just have a dict and a handful of global functions that operate on it, but if they are all related, it just makes sense to bundle them up into a .And finally, note that a  is a building-block that is used to implement a .  If you store values in a class, they are actually stored inside an internal  and there is just some convenient syntax to access them.
Python

I'd like to reference a previously-documented function parameter elsewhere in a Python docstring.  Consider the following (admittedly completely artificial) example:Is there a simple way to embed a parameter reference using Sphinx markup, or will this happen automagically?(I'm a complete Sphinx newbie.  I've been scanning the Sphinx docs and haven't found an answer to this question, or an example demonstrating proper markup.)I've just built an extension to accomplish this task.  So far it seems to be working with standalone HTML build and additionally with readthedocs (after some more tweaks).  the extension is available at: .I'm rolling it out right now for the Alembic and SQLAlchemy projects.  ().I take disagreement with the suggestion that linking to params means the docs are too lengthy.  The Python standard library is a poor example here as stdlib functions are necessarily granular and simple.  Software that is accomplishing a more coarse-grained task, where a single function rides on top of a complex problem to be solved, will often have parameters that require a lot more explanation; this explanation is often quite valuable as the solution to a particular problem elsewhere, and therefore being able to link to it is very important.There is no simple way to get a direct reference to a parameter of a function with  and I don't know an extension for this problem.The  explains which objects can be cross referenced.A possible way to give the user a reference to parameter  of function  would beMaybe a direct reference would be possible by writing an extension.If you are looking for a way to link directly to the  definition of  then your documentation is too lengthy or you are asking your reader to ignore the forest for one tree or some combination of the two.Taking an example from :if I can't be bothered to read five sentences into  to find the meaning of  I probably don't deserve to be lead there. Note that the attribute reference syntax is the same as in the section above:but it looks like Sphinx doesn't reach out of the current section scope and so renders the later reference as styled text rather than as an anchor. It would not surprise me if this was intentional.
Python

I have unittest code like the following:When I try to run this code, I get an error like this:  be a class method. From the :Your version is missing the  decorator:The error is thrown because  is called on the , not on an instance, but you didn't mark your method as a classmethod and thus it was not passed in the automatic  argument.
Python

Celery doesn't seem to be handling exceptions properly.  If I have task:and then I callAnd it will hang like this indefinitely.  Going and checking the logs shows that the error IS getting thrown in the task (and if you want the message, ask), and I know that the backend and everything is set up properly because other tasks just work and return results correctly.  Is there something funky that I need to do to catch exceptions in Celery?/Celery version is 3.0.13, broker is RabbitMQ running on my local machineYou can define an  function in your  subclass to handle them correctly.  If you're just looking to find out what happened you can setup  that will send you the stack trace in your celery config.If you are running Celery with the CELERY_ALWAYS_EAGER set to True, then make sure you include this line in your settings too:Going to make @primalpython's answer more explicit.  This will fail:Input/Output:This will succeed:Input/Output:
Python

Using algorithms like leveinstein ( leveinstein or difflib) , it is easy to find approximate matches.eg.The fuzzy matches can be detected by deciding a threshold as needed.Current requirement : To find fuzzy substring based on a threshold in a bigger string.eg. One brute force solution is to generate all substrings of length N-1 to N+1 ( or other matching length),where N is length of query_string, and use levenstein on them one by one and see the threshold.Is there better solution available in python , preferably an included module in python 2.7 , or an externally available module .The new regex library that's soon supposed to replace re includes fuzzy matching.The fuzzy matching syntax looks fairly expressive, but this would give you a match with one or fewer insertions/additions/deletions.How about using ?Above code print: Recently I've written an alignment library for Python: Using it, you can perform both global and local alignments with arbitrary scoring strategies on any pair of sequences. Actually, in your case, you need semi-local alignments as you don't care for the substrings of . I've simulated semi-local algorithm using local alignment and some heuristics in the following code but it is easy to extend the library for a proper implementation.Here is the example code in the README file modified for your case.The output for  is as follows.If you remove the  argument, you will get only the best scoring matches.Note that all algorithms in the library have  time complexity,  and  being the lengths of the sequences.I use  to fuzzy match based on threshold and  to fuzzy extract words from the match.   takes a query, list of words and a cutoff score and returns a list of tuples of match and score above the cutoff score.   takes the result of  and returns the start and end indices of words. I use the indices to build the words and use the built word to find the index in the large string.  of  is 'Levenshtein distance' which has to be adjusted to suit the needs.Test;  Output;\nquery: manhattan\nstring: thelargemanhatanproject is a great project in themanhattincity\nmatch: manhatan\nindex: 8\nmatch: manhattin\nindex: 49  query: citi\nstring: thelargemanhatanproject is a great project in themanhattincity\nmatch: city\nindex: 58  query: greet\nstring: thelargemanhatanproject is a great project in themanhattincity\nmatch: great\nindex: 29  The approaches above are good, but I needed to find a small needle in lots of hay, and ended up approaching it like this:Yields:
Python

Then we are given the sample code:We create a memoryview object to expose the internal data of a buffer object without\ncopying, however, in order to do anything useful with the object (by calling the methods\nprovided by the object), we have to create a copy!Usually memoryview (or the old buffer object) would be needed when we have a large object,\nand the slices can be large too. The need for a better efficiency would be present\nif we are making large slices, or making small slices but a large number of times.With the above scheme, I don't see how it can be useful for either situation, unless\nsomeone can explain to me what I'm missing here.We have a large chunk of data, we want to process it by advancing through it from start to \nend, for example extracting tokens from the start of a string buffer until the buffer is consumed.In C term, this is advancing a pointer through the buffer, and the pointer can be passed\nto any function expecting the buffer type. How can something similar be done in python?People suggest workarounds, for example many string and regex functions take position \narguments that can be used to emulate advancing a pointer. There're two issues with this: first \nit's a work around, you are forced to change your coding style to overcome the shortcomings, and\nsecond: not all functions have position arguments, for example regex functions and  do, / don't. Others might suggest to load the data in chunks, or processing the buffer in small\nsegments larger than the max token.  Okay so we are aware of these possible\nworkarounds, but we are supposed to work in a more natural way in python without\ntrying to bend the coding style to fit the language - aren't we?A code sample would make things clearer. This is what I want to do, and what I assumed memoryview would allow me to do at first glance. Lets use pmview (proper memory view) for the functionality I'm looking for: objects are great when you need subsets of binary data that only need to support indexing. Instead of having to take slices (and create new, potentially large) objects to pass to  you can just take a  object.One such API example would be the  module. Instead of passing in a slice of the large  object to parse out packed C values, you pass in a  of just the region you need to extract values from. objects, in fact, support  unpacking natively; you can target a region of the underlying  object with a slice, then use  to 'interpret' the underlying bytes as long integers, or floating point values, or n-dimensional lists of integers. This makes for very efficient binary file format interpretations, without having to create more copies of the bytes.One reason  are useful is because they can be sliced without copying the underlying data, unlike /.For example, take the following toy example.On my computer, I getYou can clearly see quadratic complexity of the repeated string slicing. Even with only 400000 iterations, it's already unmangeable. Meanwhile, the memoryview version has linear complexity and is lightning fast.Edit: Note that this was done in CPython. 
Python

I am fairly new to python, and noticed these posts:\n and \nAfter playing around with it, however, I noticed that these two classes give apparently equivalent results-(from ) and Is there any real difference between these two? Or, more generally, does  change anything inherently about the attributes of a class? In  it is mentioned that  is called when the instance is created. Does this mean that  in class  is established before instantiation? Yeah, check this out:and now try:and this:Yes, it's a class attribute (it is shared between instances). While in class A it's an instance attribute. It just happens that strings are immutable, thus there is no real difference in your scenario (except that class B uses less memory, because it defines only one string for all instances). But there is a huge one in my example.In the first exemple you have the variable of the instance of the class. This variable is only accessible through an instance (self required).In the second exemple you have a static variable. You can access to this variable thanks to the name of the class AIn fact you can have a static variable and an instance variable with the same name:The static value is shared between all the instancesYou have a good article here:\nAs others have stated, it's the difference between a variable on a class and a variable on a class . See the following example.For immutable objects like tuples, strings, etc. it's harder to notice the difference, but for mutables, it changes \u2014the changes applied are shared between ALL instances of that class.Note also that the same behavior happens for keyword argument defaults!This behavior bites a lot of new Python programmers. Good for you in discovering these distinctions early on!you use init you dont have to use it in your case you can justand if you want use init try it
Python

Does anyone know an algorithm to either calculate the moon phase or age on a given date or find the dates for new/full moons in a given year?Googling tells me the answer is in some Astronomy book, but I don't really want to buy a whole book when I only need a single page.I should have qualified my statement about googling a little better. I did find solutions that only worked over some subset of time (like the 1900's); and the trig based solutions that would be more computationally expensive than I'd like. S Lott in his Python book has several algorithms for calculating Easter on a given year, most are less than ten lines of code and some work for all days in the Gregorian calendar. Finding the full moon in March is a key piece of finding Easter so I figured there should be an algorithm that doesn't require trig and works for all dates in the Gregorian calendar.I ported some code to Python for this a while back.  I was going to just link to it, but it turns out that it fell off the web in the meantime, so I had to go dust it off and upload it again.  See  which is derived from .I can't find a reference for this for what time spans it's accurate for either, but seems like the authors were pretty rigorous.  Which means yes, it does use trig, but I can't imagine what the heck you would be using this for that would make it computationally prohibitive.  Python function call overhead is probably more than the cost of the trig operations.  Computers are pretty fast at computing.The algorithms used in the code are drawn from the following sources:A must-have; if you only buy one book, make sure it's this one. Algorithms are presented mathematically, not as computer programs, but source code implementing many of the algorithms in the book can be ordered separately from the publisher in either QuickBasic, Turbo Pascal, or C. Meeus provides many worked examples of calculations which are essential to debugging your code, and frequently presents several algorithms with different tradeoffs among accuracy, speed, complexity, and long-term (century and millennia) validity.Despite the word Calculator in the title; this is a valuable reference if you're interested in developing software which calculates planetary positions, orbits, eclipses, and the like. More background information is given than in Meeus, which helps those not already versed in astronomy learn the often-confusing terminology. The algorithms given are simpler and less accurate than those provided by Meeus, but are suitable for most practical work.I think you searched on wrong google:If you're like me, you try to be a careful programmer. So it makes you nervous when you see random code scattered across the internet that purports to solve a complex astronomical problem, but doesn't explain why the solution is correct.You believe that there must be authoritative sources such as  which contain careful, and complete, solutions. For instance:You place your trust in widely-used, well-tested, open source libraries which can have their errors corrected (unlike static web pages). Here then, is a Python solution to your question based on the  library, using the  interface.This returnsAlso,  [], which is a Python package but has the , and that  sayPyephem by default uses coordinated universal (UTC) time. I wanted a program that would generate a list of full moons that would be accurate in the pacific time zone. The code below will calculate the full moons for a given year and then adjust that using the ephem.localtime() method to calibrate to the desired time zone. It also appears to properly account for daylight savings time as well. Thank you to Richard, this code is similar to what he had written.The code above will return:I know that you're looking for Python but if you can understand C# there's an open source project out there called  which does this very well.A quick google revealed .If you don't need high accuracy, you can always (ab)use a lunar (or lunisolar) calendar class (e.g.,  or  in Microsoft .NET) to calculate the (approximate) moon phase of any date, as the calendar's \"day-of-month\" property, being a lunar (or lunisolar) calendar day,  (e.g., day 1 is the new moon, day 15 is the full moon, etc.)
Python

For the following code:Pylint reported an error: Could anyone give a hint what is happening here? From pylint source code the description is:But I do not have a clue what it means. Could anyone give an example of the problem?The name  in the body of the  will be looked up when the function is actually called, so it will see what ever value  had most recently. Since you are calling  immediately, the value of  will not change before the resulting function object is used, so you can safely ignore the warning. To silence it, you can make  the default value of a parameter to the :
Python

I am trying to use a list comprehension that compares string objects, but one of the strings is utf-8, the byproduct of json.loads.  Scenario:Part one of my question, is why does this return False? :Part two - how can I compare within a list comprehension?EDIT:  I'm using Google App Engine, which uses Python 2.7Here's a more complete example of the problem:You must be looping over the wrong data set; just loop directly over the JSON-loaded dictionary, there is no need to call  first:You may want to use  to avoid implicit conversions between Unicode and byte strings:Both versions :Note that in your first example,  is  a UTF-8 string; it is unicode data, the  library has already decoded it for you. A UTF-8 string on the other hand, is a sequence . You may want to read up on Unicode and Python to understand the difference:On Python 2, your expectation that your test returns  would be correct, you are doing something else wrong:There is  need to encode the strings to UTF-8 to make comparisons; use unicode literals instead:You are trying to compare a string of bytes () with a string of Unicode code points ().  This is an \"apples and oranges\" comparison.  Unfortunately, Python 2 pretends in some cases that this comparison is valid, instead of always returning :It's up to you as the designer/developer to decide what the correct comparison should be.  Here is one possible way:I recommend the above instead of  because all  style strings can be encoded into bytes with UTF-8, except possibly in some bizarre cases, but not all byte-strings can be decoded to Unicode that way.But if you choose to do a UTF-8 encode of the Unicode strings before comparing, that will fail for something like this on a Windows system: .  But if you  instead it would succeed.  That's why it's an apples and oranges comparison.I'm assuming you're using Python 3.  returns  because the  function is :In Python 3, strings are , so the  is superfluous.
Python

Reading through the Python docs I came across .Can someone explain to me (with example) a scenario in which  would be preferred to ?With particular reference to:This is one example where I see the use:Usually I start programming with the Lock and when case 1 or 2 occur, I switch to an RLock.  the RLock should be a bit slower because of the additional code. It uses Lock:within the given thread you can acquire a  as often as you like. Other threads need to wait until this threads releases the resource again. This is different to the  which implies 'function-call ownership'(I would call it this way): Another function call has to wait until the resource is released by the last blocking function even if it is in the same thread = even if it is called by the other function. When you make a call to the outside of the resource which you can not control.The code below has two variables: a and b and the RLock shall be used to make sure a == b * 2In  the Lock would be the right choice although it does block. Or one can enhance it with errors using . Functions like  may occur when you have implemented a Observer pattern or a Publisher-Subscriber and add locking afterwards.A primitive lock (Lock) is a synchronization primitive that is not owned by a particular thread when locked.For the repeatable Lock (RLock) In the locked state, some thread owns the lock; in the unlocked state, no thread owns it.\nWhen invoked if this thread already owns the lock, increment the recursion level by one, and return immediately. if thread doesn't own the lock It waits until owner release lock.\nRelease a lock, decrementing the recursion level. If after the decrement it is zero, reset the lock to unlocked.I don't think there is some performance difference rather conceptual one. Here is another use case for RLock.  Suppose you have a web-facing user interface that supports concurrent access, but you need to manage certain kinds of access to an external resource.  For instance, you have to maintain consistency between objects in memory and objects in a database, and you have a manager class that controls access to the database, with methods that you must ensure get called in a specific order, and never concurrently.What you can do is create an RLock and a guardian thread that controls access to the RLock by constantly acquiring it, and releasing only when signaled to.  Then, you ensure all methods you need to control access to are made to obtain the lock before they run.  Something like this:This way, you're ensured of the following things:
Python

I am trying to run the following Python code to create a Firefox Webdriver window via Selenium:While this code worked fine a few weeks ago, it now produces the following foreboding message:Does anyone know what this means, or what I can do to remedy the error and get the code to run as expected? I've found related error messages through Google searches, but nothing that has allowed me to resolve the issue.For what it's worth, I can open a Chrome Webdriver without issue by changing the second line of the above to .I'm using Python 2.7, Selenium 2.35.0 (I just ran \"pip install selenium --upgrade) and Firefox 26.0 on a Windows 8 machine. Any tips or advice others can offer are most appreciated.Selenium 2.35 is not compatible with Firefox 26.  As the  say, FF 26 support was added in Selenium 2.39.  You need to update to 2.39.  Try  instead.Not sure if it works fine on Windows too, but for me the combination of Firefox 26 and selenium 2.37.0 works fine.I also have this issue in Win8.1 FF28 and python3.4/selenium 2.41. But after I degraded FF to 24, it worked! And I also tested in Win8.1/FF27/Python3.4/Selenium 2.41, it worked too.  I just ran into the same thing with FF36 and selenium 2.44.0. Re-installing FF 32.0 fixed it.selenium-2.45.0  ===works==> FF36(win7)I've experienced the same problem on my Kubuntu 14.04 desktop, I removed the Firefox 47.XX and re-installed Firefox 45.XX and the problem resolved.Download firefox debian package
Python

I've built a few Flask apps, but on my latest project I noticed something a little strange in development mode.  The second line of the usual message in the terminal which always reads:has been replaced by:I don't think I've done anything different, in fact, I started by cloning a starter-kit project that I have used many times, which itself, does not display this behavior.  I also notice that this project consumes about 15% CPU steadily, whereas my other project are barely a blip.Any ideas why this is happening?Check your version of Werkzeug.  Version 0.10 was just released and numerous changes went into the reloader.  One change is that a default polling reloader is used; the old pyinotify reloader was apparently inaccurate.  If you want more efficient polling, install the  package.  You can see the code related to this .When Werkzeug can't find watchdog, it uses the  reloader, otherwise it uses whatever reloader watchdog uses, which can vary by platform.  This message is just so you know which one is in use.
Python

Using Python, how can information such as CPU usage, memory usage (free, used, etc), process count, etc be returned in a generic manner so that the same code can be run on Linux, Windows, BSD, etc?Alternatively, how could this information be returned on all the above systems with the code specific to that OS being run only if that OS is indeed the operating environment?Regarding cross-platform: your best bet is probably to write platform-specific code, and then import it conditionally.  e.g.For specific resources, as Anthony points out you can access  under linux.  For Windows, you could have a poke around at the .  I'm not sure where to get that kind of information on Macs, but I can think of a great website where you could ask :-)In a Linux environment you could read from the /proc file system.I recommend the platform module: should provide what you need:It looks like you want to get a lot more information than the standard Python library offers. If I were you, I would download the source code for 'ps' or 'top', or the Gnome/KDE version of the same, or any number of system monitoring/graphing programs which are more likely to have all the necessary Unix cross platform bits, see what they do, and then make the necessary native calls with ctypes.It's trivial to detect the platform. For example with ctypes you might try to load libc.so, if that throws an exception try to load 'msvcrt.dll' and so on. Not to mention simply checking the operating system's name with os.name. Then just delegate calls to your new cross-platform API to the appropriate platform-specific (sorry) implementation.When you're done, don't forget to upload the resulting package to pypi.take a look at the There's the  (Python System Information) project with that aim, but they don't cover Windows yet.You can probably use PSI and recpies  and create a basic library that meets your needs.
Python

I'm trying to understand how Python's garbage collector detects circular references. When I look at the documentation, all I see is a statement that circular references are detected, except when the objects involved have a  method. If this happens, my understanding (possibly faulty) is that the gc module acts as a failsafe by (I assume) walking through all the allocated memory and freeing any unreachable blocks.How does Python detect & free circular memory references before making use of the gc module?It doesn't. The gc exists only  detect and free circular references. Non-circular references are handled through refcounting.Now, to see  gc determines the set of objects referenced by any given object, take a look at the  function in . The relevant bit is:The major function here is . Each C-level type defines a  function (or in the case of objects which don't hold any references, like , sets it to ).  One example of  is , the traversal function for :You are correct \u2014 Python's cycle detector can detect and collect cycles  they contain objects with a  method, as there is no way for the interpreter to safely delete these objects (to get an intuition on why this is, imagine you've got two objects with  methods that reference each other. In which order should they be freed?).When objects with a  method are involved in a cycle, the garbage collector will stick them in a separate list (accessible through ) so that the programmer can manually \"deal with\" them.Python's garbage collector (not actually the  module, which is just the Python interface to the garbage collector) does this. So, Python  detect and free circular memory references before making use of the garbage collector.Python ordinarily frees most objects as soon as their reference count reaches zero. (I say \"most\" because it never frees, for example, small integers or interned strings.) In the case of circular references, this never happens, so the garbage collector periodically walks memory and frees circularly-referenced objects.This is all CPython-specific, of course. Other Python implementations have different memory management (Jython = Java VM, IronPython = Microsoft .NET CLR).I think I found the answer I'm looking for in some links provided by @SvenMarnich in comments to the original question: Container objects are Python objects that can hold references to other Python objects. Lists, Classes, Tuples etc are container objects; Integers, Strings etc. are not. So, only container objects are at risk for being in a circular reference.Each Python object has a field - *gc_ref*, which is (I believe) set to NULL for non-container objects. For container objects it is set equal to the number of  that reference itAny container object with a *gc_ref* count greater than 1 (? I would've thought 0, but OK for now ?) has references that are not container objects. So they are reachable and are removed from consideration of being unreachable memory islands.Any container object reachable by an object known to be reachable (i.e. those we just recognized as having a *gc_ref* count greater than 1) also does not need to be freed.The remaining container objects are not reachable (except by each other) and should be freed. is a link providing a fuller explanation\n is a link to the source code, which has comments further explaining the thoughts behind the circular reference detection
Python

I came across bizarre eval behavior in Python 3 - local variables aren't picked up when eval is called in a list comprehension.It errors in Python 3:And it works fine in Python 2:Moving it outside of the list comprehension removes the problem.Is this intended behavior, or is it a bug?There is a  issue in the bug tracker for this: .The resolution for this bug is .Some comments from the Issue read:If you want:to work you'll need to capture the locals and globals as the issue is that  is the same has  but as the  appears within the generator function the results of those functions aren't the same as they were when the  didn't have a wrapping function so capture them outside the generator and use them inside:Or better as  are locals and the strings are only variable names:
Python

Following-up from  years ago, is there a canonical \"shift\" function in numpy? I don't see anything from .Here's a simple version of what I'm looking for:Using this is like:So  is much faster than . This version of the function performs a lot better:An even faster version simply pre-allocates the array:Not numpy but scipy provides exactly the shift functionality you want,where default is to bring in a constant value from outside the array with value , set here to . This gives the desired output,and the negative shift works similarly,Provides output There is no single function that does what you want. Your definition of shift is slightly different than what most people are doing. The ways to shift an array are more commonly looped:However, you can do what you want with two functions. Consider :After running cProfile on your given function and the above code you provided, I found that the code you provided makes 42 function calls while  made 14 calls when arr is positive and 16 when it is negative. For those who want to just copy and paste the fastest implementation of shift, there is a benchmark and conclusion(see the end). In addition, I introduce fill_value parameter and fix some bugs.benchmark result:shift5 is winner! It's OP's third solution. 
Python

I read in a string from a GUI textbox entered by the user and process it through . The string contains latex directives for math which have backslash characters. I want to send in the string as a raw string to pandoc for processing. But something like '\\theta' becomes a tab and 'heta'.How can i convert a string literal that contains backslash characters to a raw string...?Edit: Thanks develerx, flying sheep and unutbu. But none of the solutions seem to help me. The reason is that there are other backslashed-characters which do not have any effect in python but do have a meaning in latex. For example '\\lambda'. All the methods suggested produce which does not go through in latex processing -- it should remain as \\lambda.Another edit:If i can get this work, i think i should be through. @Mark: All three methods give answers that i dont desire.Python\u2019s raw strings are just a way to tell the Python interpreter that it should interpret backslashes as literal slashes. If you read strings entered by the user, they are already past the point where they could have been raw. Also, user input is most likely read in literally, i.e. \u201craw\u201d.This means the interpreting happens somewhere else. But if you know that it happens, why not escape the backslashes for whatever is interpreting it?(Note that you can't do  as , but I could have used  as well for the second argument.)If that doesn\u2019t work, your user input is for some arcane reason interpreting the backslashes, so you\u2019ll need a way to tell it to stop that.This shows that there is a single backslash before the ,  and :There is something funky going on with your GUI. Here is a simple example of grabbing some user input through a . Notice that the text retrieved only has a single backslash before the , , and . Thus no extra processing should be necessary:If you type  into the Entry box, the console will (correctly) print:If your GUI is not returning similar results (as your post seems to suggest), then I'd recommend looking into fixing the GUI problem, rather than mucking around with  and string .When you read the string from the GUI control, it is already a \"raw\" string. If you print out the string you might see the backslashes doubled up, but that's an artifact of how Python displays strings; internally there's still only a single backslash.
Python

I'm using python 2.7.2 and windows 7. I searched through internet, helps and other sources but i can't find an answer to my problem. One of my source imports , and this one imports . At this moment it say : I searched _tkinter and i found it in Python27/libs as a lib file.On many sites it says to install  or , but I don't find a separate installation for windows.  Using Windows x86 MSI Installer (2.7) from . In windows 7 64-bit. The python version is 32 bit.I had a similar problem importing Tkinter on Windows 7 64-bit - seems that the 64-bit library was still in the libs folder from a previous 64-bit python install.Uninstalling 64-bit python properly and then repairing with the 32-bit installer fixed the problem for me - you don't need to use 64-bit python.Re-install Python.If this still doesn't work, there is another simple solution:I had the same issue and was able to uninstall Python 2.7 (using the Windows 7 'uninstall' service) and then reinstall it from here:\nAlso, if you're concerned about ensuring 64bit conformance across your python libraries then you may find the following . It has numerous 64bit versions of python libraries.I have a lot of installed python packages on my machine so I did not want to unistall and reinstall the whole python, I did as follow and the problem was solved:Please pay attention to get a backup form your tcl and DLLs folder to recover it in case you face any further problem.
Python

I have Windows Vista 64.I have some projects requiring Python 2.7.3 64 bit and others requiring Python 2.7.3 32 bit (because some extensions do not work in 64 bit).How do I prevent the Python 2.7.3 MSI installer (32 or 64 bot) from deleting the other  version.Side by side worked for me with Python 2.7.2 without problems.This appears to be working for me on Windows 7 64 bit. Choose one version to be your default installation, e.g. 64 bit,  and install it first. Before doing anything else install the other version.Specify a different installation directory and in the  screen select  and select .You can generally install multiple Python Version side by side. When installing in Windows, apart from file installation, registry is also updated so that any subsequent package/tools installation can enumerate all the Python Installation in the current m/c.\nSolutionAs Ruediger Jungbeck pointed out that he can see two different registry keys, I suddenly recollected an important change post Vista. On a 64 bit system in order to enable accessing the registry keys from 32 bit and 64 bit application, Windows splits the registry at important nodes. For 64 bit applications, its the native registry path but for 32 bit applications its the WoW6432Node. So when running a 32 bit Version of Python\\Tools\\extension, it will only see the Wow6432Node. 64 bit applications will only see the native node. There are APIs to access the cross bitness nodes but that is outside the scope of this question. \nSo to summarize, windows intelligently handles 32 and 64 bit applications by splitting the node which will allow 32 bit extensions to transparently access the 32 bit Python Installation.While installing 2nd python, for Register Extensions select \"Entire feature will be unavailable\" option.\nPython 64 Installation path will be in registry \"HKLM:SOFTWARE\\Python\\PythonCore\\2.7\\InstallPath\"Python 64 bit PythonPath will be in \n\"HKLM:SOFTWARE\\Python\\PythonCore\\2.7\\PythonPath\"Python 32 Installation path will be in registry\n\"HKLM:SOFTWARE\\Wow6432Node\\Python\\PythonCore\\2.7\\InstallPath\"Python 32 bit PythonPath will be in \n\"HKLM:SOFTWARE\\Wow6432Node\\Python\\PythonCore\\2.7\\PythonPath\"
Python

I have an event loop that runs some co-routines as part of a command line tool. The user may interrupt the tool with the usual  + , at which point I want to clean up properly after the interrupted event loop.Here's what I tried.Running this and hitting  +  yields:Clearly, I didn't clean up correctly. I thought perhaps calling  on the tasks would be the way to do it.What's the correct way to clean up after an interrupted event loop?When you CTRL+C, the event loop gets stopped, so your calls to  don't actually take effect. For the tasks to be cancelled, you need to start the loop back up again.Here's how you can handle it:Once we catch , we  call  and then start the  up again.  will actually exit as soon as  gets cancelled (note that cancelling the  returned by  also cancels all the  inside of it), because the interrupted  call added a  to  that stops the loop. So, when we cancel , that callback fires, and the loop stops. At that point we call , just to avoid getting a warning about not fetching the exception from the .Based on the other answers and some thinking I arrived at this handy solution that should work almost all use cases and does not depend on you manually keeping track of tasks that need to be cleaned up on +:The above code will obtain all currently tasks from the event loop using  and place them in a single combined future using . All tasks in that future (which are all currently running tasks) are then canceled using the future's  method. The  then ensures that all the received  exceptions are stored instead of causing the future to become errored.The above code will override the default exception handler to prevent Unless you are on Windows, set up event-loop based signal handlers for SIGINT (and also SIGTERM so you can run it as a service). In these handlers, you may either exit the event loop immediately, or initiate some kind of cleanup sequence and exit later.Example in official Python documentation: 
Python

Is it possible to parse a file line by line, and edit a line in-place while going through the lines?It can be simulated using a backup file as stdlib's  does.Here's an example script that removes lines that do not satisfy  from files given on the command line or :Example: On completion  and  files will contain only lines that satisfy  predicate.No. You cannot safely write to a file you are also reading, as any changes you make to the file could overwrite content you have not read yet. To do it safely you'd have to read the file into a buffer, updating any lines as required, and then re-write the file.If you're replacing byte-for-byte the content in the file (i.e. if the text you are replacing is the same length as the new string you are replacing it with), then you can get away with it, but it's a hornets nest, so I'd save yourself the hassle and just read the full file, replace content in memory (or via a temporary file), and write it out again.If you only intend to perform localized changes that do not change the length of the part of the file that is modified (e.g. changing all characters to lower case), then you can actually overwrite the old contents of the file dynamically.To do that, you can use random file access with the  method of a  object.Alternatively, you may be able to use an  object to treat the whole file as a mutable string. Keep in mind that  objects may impose a maximum file-size limit in the 2-4 GB range on a 32-bit CPU, depending on your operating system and its configuration.You have to back up by the size of the line in characters.  Assuming you used , then you can get the length of the line and back up using:Set whence to , set offset to .See  or look at the manpage for .
Python

I'd like to embed an IPython qt console widget in a PyQt application I am working on. The code provided below (and adapted from ) Accomplishes this for IPython v0.12. However, this crashes in IPython v0.13 at the line  with . Commenting out this line brings up the widget, but doesn't respond to user input.Does anyone know how to achieve the equivalent functionality for IPython v0.13?Traceback for v0.13Ok, this code seems to do the trick (i.e. it puts a non-blocking ipython interpreter in a Qt widget, which can be embedded into other widgets). Keywords passed to  get added to the namespace of the widgetThe accepted answer by @ChrisB is fine for IPython version 0.13, but it doesn't work with newer versions. From the  of the IPython kernel repository on github,  is the way to do it in v1.x+ (currently tested with 4.0.1), which has the feature that the console and kernel are in the same process.Here is an example, based on the official one, which gives a convenience class that can be easily plugged into an application. It's setup to work with pyqt4 and IPython 4.0.1 on Python 2.7:IPython 0.13 version with some cleanups:pberkes was kind enough to update this example for me:I have it working on the latest 1.0-dev in a separate window, now I just need to figure out how to get access to all my program variables and stick it in my main window.Possibly helping others researching this: I came across this example:Tested and works with PySide, IPython 2.1.0, Python 3.4.1. It appears I can even use matplotlib directly. Have you tried some of the most recent examples provided in the ipython source code?  I recently came across the following from fperez (I'd like to buy that man a beer) and they seem to illustrate a nice way of capturing variables embedded in your GUI.A 2016 update working in PyQt5:
Python

I'm working with Python itertools and using groupby to sort a bunch of pairs by the last element. I've gotten it to sort and I can iterate through the groups just fine, but I would really love to be able to get the length of each group without having to iterate through each one, incrementing a counter.The project is cluster some data points. I'm working with pairs of (numpy.array, int) where the numpy array is a data point and the integer is a cluster labelHere's my relevant code:On the last line, 'if len(clusterList) < minLen:', I get an error that object of type 'itertools._grouper' has no len().I've looked up the operations available for _groupers, but can't find anything that seems to provide the length of a group.Just because you call it  doesn't make it a list! It's basically a lazy iterator, returning each item as it's needed. You can convert it to a list like this, though:Or do that and get its length in one step:If you don't want to take up the memory of making it a list, you can do this instead:Be aware that the original iterator will be consumed entirely by either converting it to a list or using the  formulation. is  but it is not a .  This can be a little confusing sometimes.  You can do a  loop over  but you can't do other list things over it (slice, len, etc).Fix: assign the result of  to .
Python

When i try to follow python wiki page example related to URL encoding:An error is raised on the second line:What i am missing? has been split up in Python 3.  The  function is now , and the  function is now .You use the Python 2 docs but write your program in Python 3.
Python

Why can't I perform an action like the following:I would expect it to print  since we're overwriting the instance with it, but instead it doesn't do anything at all. Doesn't even throw an error. Just ignores the assignment.I understand that there would be hardly any situations where one would want to do that, but it still seems odd that you can't. I now understand  it doesn't work, but I'd still like to know if there is any way of replacing an instance from within the instance. simple assignment to  argument of  function behaves exactly the same way in Python: binds that name to a different value, and does nothing else whatsoever. \"No special case is special enough to break the rules\", as the Zen of Python says!-)So, far from it being odd (that simply=assigning to a specific argument in a specific function has no externally visible effect whatsoever), it would be utterly  if this specific case worked in any other way, just because of the names of the function and argument in question.Should you ever want to make a class that constructs an object of a different type than itself, such behavior is of course quite possible -- but it's obtained by overriding the special method ,  :This  emit .  The  /  behavior in Python is an example of the \"two-step construction\" design pattern: the \"constructor\" proper is  (it builds and returns a (normally uninitialized) object (normally a new one of the type/class in question);  is the \"initializer\" which properly initializes the new object.This allows, for example, the construction of objects that are immutable once constructed: in this case everything must be done in , before the immutable object is constructed, since, given that the object is immutable,  cannot mutate it in order to initialize it.It doesnt \"ignore\" the assignment. The assignment works just fine, you created a local name that points to the data 5.If you  want to do what you are doing...I just ran a quick test, and you can assign to self.  Inside your () method, print out the value of self.  You'll see that it's 5.What you're missing here is that parameters are passed by value in Python.  So, changing the value of a variable in a function or method won't change it for the outside world.All that being said, I would strongly advise against ever changing self.Sometimes you want to do this, though not with immutable types like :Dr. Egon Spengler: It would be bad.\nDr. Peter Venkman: I'm fuzzy on the whole good/bad thing. What do you mean, \"bad\"?\nDr. Egon Spengler: Try to imagine all life as you know it stopping instantaneously and every molecule in your body exploding at the speed of light.is like having this PHP (only other lang i know, sorry)I don't see how it makes sense. replacing the instance with a value?
Python

I was unable to upload to an AppEngine as  was telling me :I was only a developer on the AppEngine, so as I was just testing I created a new AppEngine where I was the owner but I still get the same message on a newly created AppEngine.The fix I found was to add the parameter :This can happen when you upload AppEngine applications from different Google accounts on the same computer.You have to log in in your gae account and create an application before you upload it, and your app_id has to have the same name as you app. You can't just upload it.So go , create your app, for example \"example_app\" and set the app_id=example_app and everything should work :)The same problem occurs with the Java/Eclipse plugin version of App Engine. The 404 happens when you're logged in to the wrong Google account from within the plugin. In that case, look at the bottom-left of Eclipse to see what account you're currently using.Regarding the Python command line updater, if your cookies indicate that you're logged in to a Google account that doesn't have access to the application you're updating, then that would explain why ignoring those cookies by using \"appcfg.py update --nocookies\" fixes it.This is really old, so I wouldn't be surprised if this isn't picked up by the poster, but I wanted to ensure that I have a reference for the next time I have the issue.I had this issue. My problem ended up being that I had not invited the user that I was authenticating as to be a developer on the project. In fact I had just created the user and not even logged on yet.I logged on to the google infrastructure as the new user, then added the new user as a developer on the application. I was then able to upload the app.Tried to upload to the app this morning (first time i've tried since Friday) and it just worked (first time...!) No idea what the issue was as I haven't done any work on this over the weekend so everything should have been the same as it was on Friday.I got the same error message trying to make the first deployment of a Python Application using a Google Apps account.In my case the problem was caused by the fact that my 2-way authentication is enabled.With 2-way authentication enabled you need to generate an authentication password in your Google Account Management Application and use it to do the deployments.this way worked:I fixed this problem by editing my app.yaml file to have the correct application name. In the app.yaml file where it says 'application:[insert app name here]', I had to change the [insert app name here] part. I'm not sure why the name was wrong, but I do remember toying around with it before while attempting to fix a different bug. The way I figured out the proper name was to go to my applications in my GAE admin console and look to see what the app's name was there. Hope this helps anyone else that runs into this same problem :)If you are using  make sure that you are logged into the correct account when generating the token.I navigated to my app engine directory folder and ran the above command. This deployed it successfully from the command line for me (Mac OSX terminal)--although I still couldn't deploy from app engine launcher. I believe Launcher still thinks I'm running off port 8080. However, running doesn't fix this issue for me-- what ended up solving it was just removing the directory from the app engine launcher then just re-adding it.What worked for me is to use the project id from the google app engine console instead of the project name in app.yamlPosting Ric Moore's comment in the selected answer because that is a valid answer and it worked in my case (and hopefully it helps someone else having the same issue spot it quickly).   I had this issue and I simply needed to run 'gcloud app create' for this project within the console console. Previously I don't think this step was needed.
Python

Using python2.7, I'm trying to print to screen tabular data.This is roughly what my code looks like:The problem is that, depending on the length of  or  the data won't be aligned.This is what I'm getting:What I want to get:Are there any modules that permit doing this?It's not really hard to roll your own formatting function:There is a nice module for this in pypi, PrettyTable.For more beautiful table use the tabulate module:Here reported an example:It seems like you want your columns left-justified, but I haven't seen any answers mention the  string method, so I'll demonstrate that in Python 2.7:For your reference, running  gives you this:It looks like the  method takes your specified width and subtracts the length of the string from that, and pads the right side of your string with that many characters. You can try .\nHere's an example:
Python

For instance, I've tried things like , which, doesn't work.. Is there some kind of structure with this kind of functionality? I realize that I could obviously do this just as easily with a bunch of def statements:  But the number of statements I need is getting pretty unwieldy and tough to remember. It would be nice to wrap them nicely in a dictionary that I could examine the keys of now and again. Functions are first class objects in Python and so you can dispatch using a dictionary. For example, if  and  are functions, and  is a dictionary like so. Note that the values are  and  which are the function objects, and NOT  and .To call , you can just do EDIT: If you want to run  functions stored in a list, you can possibly do something like this.
Python

First thing I have to mention here, I'm new to python.Now I have a file located in:I want to copy to my home directory with a new folder created:My expected result is:Is there any existing library to do that? If no, how can I achieve that?To create all intermediate-level destination directories you could use  before copying:take a look at .  will copy a file to another file.Note that  will not create directories that do not already exist.  for that, use 
Python

My Python version is 2.6.I would like execute the setUp method only once since I'm doing there things which are needed for every test.My idea was to create a boolean var which will be set to 'true' after the first execution.The output:why is this not working? \nDid I missed something?You can use  to define methods that only run once per testsuite.Daniel's answer is correct but better with an example to avoid some common mistakes I found, like not calling super in setUpClass.The documentation  don't states the need to call super and you will get an error if you don't, solved here .Don't try to dedupe the calls to setUp, just call it once.For example:This will call _set_up() when the module's first loaded. I've defined it to be a module-level function, but you could equally make it a class method of MyClass.Place all code you want set up once outside the mySelTest.Another possibility is having a Singleton class that you instantiate in , which will only run the  code once and return the object instance for the rest of the calls.\nSee: Your way works too though.
Python

I'd like to make a scatter plot where each point is colored by the spatial density of nearby points.  I've come across a very similar question, which shows an example of this using R:What's the best way to accomplish something similar in python using matplotlib?In addition to  or  as @askewchan suggested, you can use the same method that the accepted answer in the question you linked to uses.If you want to do that:If you'd like the points to be plotted in order of density so that the densest points are always on top (similar to the linked example), just sort them by the z-values.  I'm also going to use a smaller marker size here as it looks a bit better:You could make a histogram:
Python

Using a python flask server, I want to be able to throw an http error response with the abort command and use a custom response string and a custom message in the bodyBut the error.message variable comes up as an empty string.  I can't seem to find documentation on how to get access to the second variable of the abort function with a custom error handlerIf you look at  you will see that  is actually imported from .  Looking at the , we can see that when called with a numeric code, the particular  subclass is looked up and called with all of the arguments provided to the  instance.  Looking at , paying particular attention to  we can see that the second argument passed to  is stored in the  property, as @dirn pointed out.You can either access the message from the  property:or just pass the description in by itself:People rely on  too much. The truth is that there are much better ways to handle errors.For example, you can write this helper function:Then from your view function you can return an error with:If the error occurs deeper in your call stack in a place where returning a response isn't possible then you can use a custom exception. For example:Then in the function that needs to issue the error you just raise the exception:I hope this helps.
Python

What would be the best way in Python to parse out chunks of text contained in matching brackets?should initially return:putting that as an input should return:which should return:Pseudocode:Or this pyparsing version:I'm kind of new to Python, so go easy on me, but here is an implementation that works:Parse using  (installable via ):Output:You could also parse them all at once, though I find the  to mean  rather than  slightly weird.  If I've understood the format correctly:If you want to use a parser (lepl in this case), but still want the intermediate results rather than a final parsed list, then I think this is the kind of thing you were looking for:That might look opaque at first, but it's fairly simple really :o) is a recursive definition of a matcher for nested brackets (the \"+\" and [...] in the definition keep everything as a single string after it has been matched).  Then  says match as many as possible (\"[:]\") of something that is surrounded by \"{\" ... \"}\" (which we discard with \"Drop\") and contains either a nested expression or any letter.Finally, here's a lepl version of the \"all in one\" parser that gives a result in the same format as the pyparsing example above, but which (I believe) is more flexible about how spaces appear in the input:Cleaner solution.  This will find return the string enclosed in the outermost bracket.  If None is returned, there was no match.Using :Here is a solution I came up with for a similar use case. This was loosely based on the accepted psuedo code answer. I didn't want to add any dependencies for external libraries:
Python

Is there a generic \"form sanitizer\" that I can use to ensure all html/scripting is stripped off the submitted form? form.clean() doesn't seem to do any of that - html tags are all still in cleaned_data. Or actually doing this all manually (and override the clean() method for the form) is my only option?Django comes with a template filter called , which you can use in a template:It uses the function  which lives in . You can utilize it also to clean your form data:strip_tags actually removes the tags from the input, which may not be what you want.To convert a string to a \"safe string\" with angle brackets, ampersands and quotes converted to the corresponding HTML entities, you can use the  filter:Alternatively, there is a Python library called :Example:
Python

With Sqlite, a \"select..from\" command returns the results \"output\", which prints (in python):It seems to be a list of tuples. I would like to either convert \"output\" in a simple 1D array (=list in Python I guess):or a 2x3 matrix:to be read via \"output[i][j]\"The flatten command does not do the job for the 1st option, and I have no idea for the second one... :)Could you please give me a hint?  Some thing fast would be great as real data are much bigger (here is just a simple example).Thank you.By far the fastest (and shortest) solution posted:About 50% faster than the  solution, and about 70% faster than the  solution.use  chain:Or you can flatten the list like this:For the 2 by 3 matrix, there's nothing special to do:In Python 3 you can use the  syntax to flatten a list of iterables:you could easily move from list of tuple to single list as shown above.In case of arbitrary nested lists(just in case):
Python

I am trying to write a list comprehension statement that will only add an item if it's not currently contained in the list. Is there a way to check the current items in the list that is currently being constructed? Here is a brief example:You can use  and set comprehension:As , we don't use the  here, so we can use  instead:If you really need a list as the result, you can do this (but notice that usually you can work with sets without any problem):As  suggests: you can use a uniqueness filter:and call with:I would implement the  separately since a design rule says . Furthermore you can simply reuse this method if necessary.Another advantage is - as is written at the  - that the  of the items is preserved. For some applications, this might be necessary.sets and dictionaries are your friends here:There's another way of writing this that is a bit more descriptive of what you're actually doing, and doesn't require a nested (double ) comprehension:This becomes even nicer when you'd represent the input to be more conceptually sound, i.e. use sets for the hobbies of each person (since there shouldn't be repetitions there either):If you really really want a listcomp and only a list-comp, you can doHere,  is a result of a side effect and  is your original dictionary. The unique advantage here is that .A list comprehension is not well-suited for this problem. I think a set comprehension would be better, but since that was already shown in another answer, I'll show a way of solving this problem with a compact one-liner:Another interesting solution using bitwise or operator which serves as a union operator for sets:Or (unintentional pun, I swear), instead of using bitwise or operator, just use  and pass it the unpacked set-mapping of your values. No need to import  and ! This idea is inspired by .Use a set:How about this:Or more nicely:you can apply the  function to list_ like  to return a list rather than a set.
Python

I am looking to do some tinkering with openGL and Python and haven't been able to find good reasons for using PyOpenGl versus pygletWhich would you recommend and why?As Tony said, this is really going to depend on your goals.  If you're \"tinkering\" to try to learn about OpenGL or 3D rendering in general that I would dispense with all pleasantries and start working with PyOpenGL, which is as close are you're going to get to \"raw\" 3D programming using Python.On the other hand, if you're \"tinkering\" by way of mocking up a game or multimedia application, or trying to learn about programming practices in general than Pyglet will save you lots of up-front development time by providing hooks for input events, sounds, text/billboarding, etc. Often, this up-front investment is what prevents people from completing their projects, so having it done for you is not something to be ignored.  (It is also very Pythonic to avoid reinventing the wheel.)If you are looking to do any sort of heavy-duty lifting (which normally falls outside my definition of \"tinkering\", but maybe not if you're tinkering with 3D engine design) then you might want to take a look at , which wraps the  full-featured and robust  graphics engine.Start with pyglet. It contains the best high-level API, which contains all you need to get started, from opening a window to drawing sprites and OpenGL primitives using their friendly and powerful Sprite and Batch classes.Later, you might also want to write your own lower-level code, that makes calls directly to OpenGL functions such as glDrawArrays, etc. You can do this using pyglet's OpenGL bindings, or using PyOpenGL's. The good news is that whichever you use, you can insert such calls right into the middle of your existing pyglet application, and they will 'just work'. Transitioning your code from Pyglet to PyOpenGL is fairly easy, so this is not a decision you need to worry about too much upfront. The trades-off between the two are:PyOpenGL's bindings make the OpenGL interface more friendly and pythonic. For example, you can pass vertex arrays in many different forms, ctypes arrays, numpy arrays, plain lists, etc, and PyOpenGL will convert them into something OpenGL can use. Things like this make PyOpenGL really easy and convenient.pyglet's OpenGL bindings are automatically generated, and are not as friendly to use as PyOpenGL. For example, sometimes you will have to manually create ctypes objects, in order to pass 'C pointer' kinds of args to OpenGL. This can be fiddly. The plus side though, is pyglet's bindings tends to be significantly faster.This implies that there is an optimal middle ground: Use pyglet for windowing, mouse events, sound, etc. Then use PyOpenGL's friendly API when you want to make direct OpenGL function calls. Then when optimising, replace just the small percentage of performance-critical PyOpenGL calls that lie within your inner render loop with the pyglet equivalents. For me, this gives me between 2 and 4 times faster framerates, with PyOpenGL's convenience for 90% of my code.I'd say that Pyglet is actually more evolved than PyOpenGL. It has a nice API of it's own, and it has a full wrapper around OpenGL accessed through the pyglet.gl module! PyOpenGL doesn't even wrap all the functions OpenGL has.\nPyglet also has a great library for rendering 2D with hardware acceleration through OpenGL, and it's really well made.If you want a powerful ready made 3D engine you've got  and suchpyglet has a lot of nice extras included with it (like image loading and sound).  If you're starting out, I'd try pyglet first, and then switch to PyOpenGL if you feel like you want to get closer to the metal.The real important question though is: what are you trying to accomplish?  I promote pyglet because it has the nicest API I've yet seen on stuff like this.Pyglet has opengl API as well. But it's often nicer to use the recently added vertex list support.pyglet.glHmm, i would suggest pyglet, it really provides everything needed by a game or application.  Mind you, you can do a lot of things pyglet does with PyOpenGL, for example to create a window all you need to do is:\nglutInitWindow(title)Although i think glutInitDisplayMode has to be called before that.  Simple summary: if you don't wanna code until you cry, choose pyglet, but if you want to be a master, choose PyOpenGL. Goto  to read the docs on PyOpenGL and to  to read the docs on pyglet. Hope this was helpful!I would recommend Pyglet because it is very easy to get started and have something basic running, and then you can add more advanced techniques at your own pace.pyglet's GL API is nowhere near as nice as PyOpenGL's - pyglet's is at the raw ctypes layer which means you'll need to learn ctypes as well. If you're planning on doing a bunch of OpenGL programming you'll want to use PyOpenGL. The nice thing is you can mix the two just fine. Use pyglet to provide the GL context, sounds, events, image loading and texture management, text rendering, etc, etc. Use PyOpenGL for the actual OpenGL programming you need to do.Try .In ModernGL you can create a simple vertex shader with a single call:With ModernGL you have full control over the OpenGL API.
Python

I'm writing a class in python and I have an attribute that will take a relatively long time to compute, so .  Also, it will not be needed by every instance of the class, so  in .  I'm new to Python, but not to programming.  I can come up with a way to do this pretty easily, but I've found over and over again that the 'Pythonic' way of doing something is often much simpler than what I come up with using my experience in other languages.Is there a 'right' way to do this in Python?The usual way would be to make the attribute a  and store the value the first time it is calculatedI used to do this how gnibbler suggested, but I eventually got tired of the little housekeeping steps.So I built my own descriptor:Here's how you'd use it:You should use both  and  decorators: has more detailed examples and also mentions a backport for previous Python versions.The Python wiki has a  (MIT licensed) that can be used like this:Or any implementation mentioned in the others answers that fits your needs.\nOr the above mentioned backport.You could try looking into memoization. The way it works is that if you pass in a function the same arguments, it will return the cached result. You can find more information on .Also, depending on how your code is set up (you say that it is not needed by all instances) you could try to use some sort of flyweight pattern, or lazy-loading.The most simple way of doing this would probably be to just write a method (instead of using an attribute) that wraps around the attribute (getter method). On the first call, this methods calculates, saves and returns the value; later it just returns the saved value.
Python

The best I can come up with for now is this monstrosity:I.e., in English, get the current time (in UTC), convert it to some other timezone, set the time to midnight, then convert back to UTC.I'm not just using now() or localtime() as that would use the server's timezone, not the user's timezone.I can't help feeling I'm missing something, any ideas?I think you can shave off a few method calls if you do it like this:BUT\u2026 there is a bigger problem than aesthetics in your code: it will give the wrong result on the day of the switch to or from Daylight Saving Time.The reason for this is that neither the datetime constructors nor  take DST changes into account.For example:However, the documentation for  states:Thus, your problem is solved like so:No guarantees for dates before 1582, though. is wrong on the day of transition from Daylight Saving Time (DST) e.g., Apr 1, 2012. To fix it  could be used:The same with comments:Setting the TZ environment variable modifies what timezone Python's date and time functions work with.Each time zone has a number, eg US/Central = -6. This is defined as the offset in hours from UTC. Since 0000 is midnight, you can simply use this offset to find the time in any time zone when it is midnight UTC. To access that, I believe you can use According to , time.timezone actually gives the negative value of this number:So you would simply use that number for the time in hours if it's positive (i.e., if it's midnight in Chicago (which has a +6 timezone value), then it's 6000 = 6am UTC).If the number is negative, subtract from 24. For example, Berlin would give -1, so 24 - 1 => 2300 = 11pm.
Python

Is there any way to modify the bound value of one of the variables inside a closure? Look at the example to understand it better.I don't think there is any way to do that in Python. When the closure is defined, the current state of variables in the enclosing scope is captured and no longer has a directly referenceable name (from outside the closure). If you were to call  again, the new closure would have a different set of variables from the enclosing scope.In your simple example, you might be better off using a class:If you do use this technique I would no longer use the name  because it is no longer actually a closure. However, it works the same as one.It is quite possible in python 3 thanks to the magic of .I've found an alternate answer answer to Greg's, slightly less verbose because it uses Python 2.1's custom function attributes (which conveniently enough can be accessed from inside their own function).Thought I'd post it for completeness. Cheers anyways.We've done the following.  I think it's simpler than other solutions here.I worked around a similar limitation by using one-item lists instead of a plain variable.  It's ugly but it works because modifying a list item doesn't get treated as a binding operation by the interpreter. For example:Why not make var_a and var_b arguments of the function foo?
Python

In , the votes clearly show that the  function is preferred over the simple  string manipulation. Does anyone have a moment to explain exactly why that is? Is it faster, or more accurate, or what? I'm willing to accept that there's something better about it, but I can't immediately see what it might be. Might importing a whole module to do this be overkill, at least in simple cases?EDIT: The OS specificity is a big win that's not immediately obvious; but even I should've seen the \"what if there isn't a dot\" case! And thanks to everybody for the general comments on library usage.Well, there are separate implementations for separate operating systems. This means that if the logic to extract the extension of a file differs on Mac from that on Linux, this distinction will be handled by those things. I don't know of any such distinction so there might be none.:  comments that an example like  would of course not work with a simple  call, and you would have to know both that directories can use extensions, as well as the fact that on some operating systems, forward slash is a valid directory separator.This just emphasizes the  part of my answer.Thanks .Additionally, where a file doesn't have an extension, you would have to build in logic to handle that case. And what if the thing you try to split is a directory name ending with a backslash? No filename nor an extension.The rule should be that unless you have a specific reason not to use a library function that does what you want, use it. This will avoid you having to maintain and bugfix code others have perfectly good solutions to.os.path.splitext will correctly handle the situation where the file has no extension and return an empty string. .split will return the name of the file. does a reverse search for '.' and returns the extension portion as soon as it finds it.  will do a forward search for all '.' characters and is therefore almost always slower. In other words  is specifically written for returning the extension unlike .(see posixpath.py in the Python source if you want to examine the implementation).There exist operating systems that do not use \u2018.\u2019 as an extension separator.(Notably, RISC OS by convention uses \u2018/\u2019, since \u2018.\u2019 is used there as a path separator.)The only reason to worry about importing the module is concern for overhead - that's not likely to be a concern in the vast majority of cases, and if it is that tight then it's likely other overhead in Python will be a bigger problem before that.A clearly defined and documented method to get the file extension would always be preferred over splitting a string willy nilly because that method would be more fragile for various reasons.Edit: This is not language specific.The first and most obvious difference is that the split call has no logic in it to default when there is no extension.This can also be accomplished by a regex, in order to get it to behave as a 1 liner without extra includes, but still return, empty string if the extension isn't there.Also, the path library can handle different contexts for paths having different seperators for folders.In the comment to the answer that provided this solution:Not every file has an extension.Besides being standard and therefore guaranteed to be available, : - like that of a missing extension.\n - Besides correctly returning the extension if one exists, it guarantees that  +  will always return the full path.\n - in the Python source there are actually three different version of os.path, and they are called based on which operating system Python thinks you are on.\n - consider that your version requires users to know that arrays can be indexed with negative numbers.  btw, it should not be any faster. 1) simple split('.')[-1] won't work correctly for the path as C:\\foo.bar\\Makefile so you need to extract basename first with os.path.basename(), and even in this case it will fail to split file without extension correctly. os.path.splitext do this under the hood.2) Despite the fact os.path.splitext is cross-platform solution it's not ideal. Let's looking at the special files with leading dot, e.g. .cvsignore, .bzrignore, .hgignore (they are very popular in some VCS as special files). os.path.splitext will return entire file name as extension, although it does not seems right for me. Because in this case name without extension is empty string. Although this is intended behavior of Python standard library, it's may be not what user wants actually.
Python

You know how django passwords are stored like this: and that is the \"hashtype $salt $hash\".  My question is, how do they get the $hash?  Is it the password and salt combined and then hashed or is something else entirely?As always, use the source:As we can see, the password digests are made by concatenating the salt with the password using the selected hashing algorithm.  then the algorithm name, the original salt, and password hash are concatenated, separated by \"$\"s to form the digest.  To validate passwords django just verifies that the same salt and same password result in the same digest.:According to the code of :As the documentation describes, the hash is the salt, algorithm, and password, hashed.For a long time, until version 1.3, Django indeed followed the irresponsible practice of using a plain single iteration of SHA1, with a salt that was too short, to store password information.  That approach has been .  Any passwords still stored that way are highly vulnerable to brute force attack.  For reasons why, see Since version 1.4 in 2012, Django has a default hashing algorithm based on a good, standard key derivation function, PBKDF2, with a configurable number of iterations, whose default increases with each release (20000 in version 1.7).  It also provides bcrypt support, and is backwards compatible with earlier releases, automatically upgrading password hashes when users log in.  See more at 
Python

If I have a list of dictionaries, say:and I would like to remove the dictionary with  of 2 (or name john), what is the most efficient way to go about this programmatically (that is to say, I don't know the index of the entry in the list so it can't simply be popped).: as some doubts have been expressed in a comment about the performance of this code (some based on misunderstanding Python's performance characteristics, some on assuming beyond the given specs that there is exactly one dict in the list with a value of 2 for key 'id'), I wish to offer reassurance on this point.On an old Linux box, measuring this code:of which about 57 microseconds for the random.shuffle (needed to ensure that the element to remove is not ALWAYS at the same spot;-) and 0.65 microseconds for the initial copy (whoever worries about performance impact of shallow copies of Python lists is most obviously out to lunch;-), needed to avoid altering the original list in the loop (so each leg of the loop does have something to delete;-).When it is known that there is exactly one item to remove, it's possible to locate and remove it even more expeditiously:(use the  builtin rather than the  method if you're on Python 2.6 or better, of course) -- but this code breaks down if the number of dicts that satisfy the removal condition is not exactly one. Generalizing this, we have:where the shuffling can be removed because there are already three equispaced dicts to remove, as we know. And the listcomp, unchanged, fares well:totally neck and neck, with even just 3 elements of 99 to be removed. With longer lists and more repetitions, this holds even more of course:All in all, it's obviously not worth deploying the subtlety of making and reversing the list of indices to remove, vs the perfectly simple and obvious list comprehension, to possibly gain 100 nanoseconds in one small case -- and lose 113 microseconds in a larger one;-). Avoiding or criticizing simple, straightforward, and perfectly performance-adequate solutions (like list comprehensions for this general class of \"remove some items from a list\" problems) is a particularly nasty example of Knuth's and Hoare's well-known thesis that \"premature optimization is the root of all evil in programming\"!-)This is not properly an anwser (as I think you already have some quite good of them), but... have you considered of having a dictionary of  instead of a list of dictionaries?Here's a way to do it with a list comprehension (assuming you name your list 'foo'):Substitute  or whatever as appropriate. also works:And if you want a generator you can use itertools:However, as of Python 3,  will return an iterator anyway, so the list comprehension is really the best choice, as Alex suggested.list.pop() is a good choice:You can develop other ways of tracking done  dictionary you want to eliminate, so long as it resolves to an integer. Here is one of those ways:Another possibility is to use del:Will probably be faster than the list comprehension methods on average because it doesn't traverse the whole list if it finds the item in question early on.You could try something along the following lines:Unless you build something akin to an index over your data, I\ndon't think that you can do better than doing a brute-force \"table\nscan\" over the entire list. If your data is sorted by the key you\nare using, you might be able to employ the  module to\nfind the object you are looking for somewhat faster.You can try the following: If You can't pop from the beginning - pop from the end, it won't ruin the for loop.
Python

Can someone please explain how you can write a url pattern and view that allows optional parameters? I've done this successfully, but I always break the url template tag.Here's what I have currently:If I use the url template tag in this example providing both arguments, it works just fine; however, if I omit the optional argument, I get a reversing error.How can I accomplish this?Thanks,\nPeteI generally make two patterns with a :Django urls are polymorphic:its obious that you have to make your views like this:so you can call it with the same name and it would work work url resolver fine. However be aware that you cant pass None as the required argument and expect that it will get you to the regexp without argument: I dont know whether this is documented anywhere - I have discovered it by accident - I forgot to rewrite the url names and it was working anyway :)Others have demonstrated the way to handle this with two separate named URL patterns. If the repetition of part of the URL pattern bothers you, it's possible to get rid of it by using include():And then add a required_urls.py file with:Normally I wouldn't consider this worth it unless there's a common prefix for quite a number of URLs (certainly more than two).Why not have two patterns:For anyone who is still having this problem.\nI use Django 1.5 (updated: using 1.8) and it's still working fine. I use:Then when I want to have the two urlsandI use:This will create the urlsIf you create a url manually you have to keep the / in mind.I hoop this helps anyone!in views.py you do simple thing.And when you dont get  param in url string it will be None in your code. Simple and elegant :)Depending on your use case, you may simply want to pass a url parameter like so:call this in your view:this will return 'foo'
Python

I have a file where the first byte contains encoded information.  In Matlab I can read the byte bit by bit with var=fread(file,8, 'ubit1') then retrieve each bit by var(1),var(2), etc.Is there any equivalent bit reader in python?Read the bits from a file, low bits first.The smallest unit you'll be able to work with is a byte.  To work at the bit level you need to use .You won't be able to read each bit one by one - you have to read it byte by byte. You can easily extract the bits out, though:With  it is easy like this:More info here:\nThere are two possible ways to return the i-th bit of a byte.  The \"first bit\" could refer to the high-order bit or it could refer to the lower order bit.Here is a function that takes a string and index as parameters and returns the value of the bit at that location.  As written, it treats the low-order bit as the first bit.  If you want the high order bit first, just uncomment the indicated line.The indexing starts at 0.  If you want the indexing to start at 1, you can adjust index in the function before calling .Example usage:Now, for how it works:A string is composed of 8-bit bytes, so first we use divmod() to break the index into to parts: We use the  function to convert the character at  into an integer type.  Then,  computes the value of the j-th bit by left-shifting 1 by .  Finally, we use bitwise-and to test if that bit is set.  If so return 1, otherwise return 0.To read a byte from a file: . Note: the file is opened in the  mode.To get bits, convert the bytestring into an integer:  (Python 3) or  (Python 2) and extract the desired bit: :Joining some of the previous answers I would use:For each byte read from the file. The results for an 0x88 byte example is:You can assign it to a variable and work as per your initial request.\nThe \"{0.08}\" is to guarantee the full byte lengthThis is pretty fast I would think:Supposing you have a file called bloom_filter.bin which contains an array of bits and you want to read the entire file and use those bits in an array.First create the array where the bits will be stored after reading,Open the file,\nusing open or with, anything is fine...I am sticking with open here,Now load all the bits into the array 'a' at one shot using,'a' is now a bitarray containing all the bits
Python

I'm writing a doctest for a function that outputs a dictionary. The doctest looks likeWhen I run it, it fails withMy best guess as to the cause of this failure is that doctest isn't checking dictionary equality, but  equality.  indicates that there's some way to trick doctest into checking dictionary equality. How can I do this?Doctest doesn't check  equality, per se, it just checks that the output is exactly the same. You have to ensure that whatever is printed will be the same for the same dictionary. You can do that with this one-liner:Although this variation on your solution might be cleaner:Another good way is to use  (in the standard library).According to its source code, it's sorting dicts for you:I ended up using this. Hacky, but it works.turn it into a list via dict.items() and then sort it ...You can create an instance of  class inside your doctests, and use it to compare dictionaries:Note: this approach is better than simply checking if dictionaries are equal, because it will show diff between the two dictionaries.Most of it has been already said here.. anyway JSYK: there is a dedicated section in doctest documentation:
Python

I have a very long and complicated json object but I only want to get the items/keys in the first level!Example:I want to get  as result!I found this code:But it prints all keys (also )Just do a simple If you need a sorted list:
Python

I can create a new conda environment, with program  with this:What if I do not want to install any program? It seems I can not do that:You can give a package name of just \"python\" to get a base, empty install. 
Python

I have the following problem. How do I accomplish this in Python? With a buffer object somehow?Slicing lists does not generate copies of the objects in the list; it just copies the references to them. That is the answer to the question as asked.First, let's test the basic claim. We can show that even in the case of immutable objects like integers, only the reference is copied. Here are three different integer objects, each with the same value:They have the same value, but you can see they are three distinct objects because they have different s:When you slice them, the references remain the same. No new objects have been created:Using different objects with the same value shows that the copy process doesn't bother with  -- it just directly copies the references.Testing with mutable values gives the same result:Of course the references  are copied. Each one costs 8 bytes on a 64-bit machine. And each list has its own memory overhead of 72 bytes:As Joe Pinsonault , that overhead adds up. And integer objects themselves are not very large -- they are three times larger than references. So this saves you some memory in an absolute sense, but asymptotically, it might be nice to be able to have multiple lists that are \"views\" into the same memory.Unfortunately, Python provides no easy way to produce objects that are \"views\" into lists. Or perhaps I should say \"fortunately\"! It means you don't have to worry about where a slice comes from; changes to the original won't affect the slice. Overall, that makes reasoning about a program's behavior much easier. If you really want to save memory by working with views, consider using  arrays. When you slice a  array, the memory is shared between the slice and the original: What happens when we modify  and look again at ?But this means you have to be sure that when you modify one object, you aren't inadvertently modifying another. That's the trade-off when you use : less work for the computer, and more work for the programmer!Depending on what you're doing, you might be able to use .Since it operates via iteration, it won't make new lists, but instead will simply create iterators that  elements from the original list as requested for their ranges.
Python

I am trying to parse a JSON object into a Python . I've never done this before. When I googled this particular error, (), other posts have said that the string being loaded is not actually a JSON string.  I'm pretty sure this is, though.In this case,  works fine, but I'm wondering if there is a more appropriate way? This string comes directly from Twitter, via ptt tools.That's definitely not JSON - not as printed above anyhow.  It's already been parsed into a Python object - JSON would have , not , and wouldn't show strings as  for unicode (all JSON strings are unicode).  Are you sure you're not getting your json string turned into a Python object for free somewhere in the chain already, and thus loading it into json.loads() is obviously wrong because in fact it's not a string?Sometimes you can have this error because your string values are not well recognized by python. As an example: I've spent quite a lot of time searching for the origin of this kind of error. Here is what I found. Sometimes a language recognizes a kind of quotes and not another one:\nbtw, to parse a string in to json in JavaScript all quotes have to be in the ' formatto parse a string into json in JavaScript all quotes have to be in the \" format which is not really logic.Hopefully you can use the replace function. For Python:Hope it will save you the time I've spent hunting this bug! I got this error when I had a hanging comma at the end of a list of properties. Because of the comma it was expecting another property name but there was none. 
Python

how can I change the values of the diagonal of a matrix in numpy?I checked , but the function there is not implemented in numpy v 1.3.0.lets say we have a np.array X and I want to set all values of the diagonal to 0.Did you try ? See the following  and this . Or the following from the documentation (although currently broken):If you're using a version of numpy that doesn't have  (the  to set the diagonal to a constant) or , you can do this pretty easily with array slicing:This is much faster than an explicit loop in Python, because the looping happens in C and is potentially vectorized.One nice thing about this is that you can also fill a diagonal with a list of elements, rather than a constant value (like , but for modifying an existing matrix rather than making a new one). For example, this will set the diagonal of your matrix to 0, 1, 2, ...:If you need to support more array shapes, this is more complicated (which is why fill_diagonal is nice...):(The  call is only necessary in Python 3, where  returns an iterator.)Here's another good way to do this. If you want a one-dimensional view of the array's main diagonal use:For the i'th superdiagonal use:For the i'th subdiagonal use:Or in general, for the i'th diagonal where the main diagonal is 0, the subdiagonals are negative and the superdiagonals are positive, use:These are  and not copies, so they will run faster for extracting a diagonal, but any changes made to the new array object will apply to the original array.\nOn my machine these run faster than the fill_diagonal function when setting the main diagonal to a constant, but that may not always be the case. They can also be used to assign an array of values to a diagonal instead of just a constant.Notes: for small arrays it may be faster to use the  attribute of the NumPy array.\nIf speed is a major issue it could be worth it to make  a local variable.\nAlso, if the array is not contiguous,  will return a copy, so, in order to assign values to a strided slice, it will be necessary to creatively slice the original array used to generate the strided slice (if it is contiguous) or to use the  attribute.Also, it was originally planned that in NumPy 1.10 and later the 'diagonal' method of arrays will return a view instead of a copy.\nThat change hasn't yet been made though, but hopefully at some point this trick to get a view will no longer be necessary.\nSee Where size is n in an n x n matrix.Minimal. Code.You can do the following.Assuming your matrix is 4 * 4 matrix.
Python

How can I declare a bit array of a very large size, say 6 million bits?You can check out more info about this module at The  module may help:This will take less than a megabyte of memory, and it's easy to set, read, slice and interpret bits. Unlike the bitarray module it's pure Python, plus it works for Python 3.See  for more details.Get the bitarray module using Then, this code will create a bit array of size 6 million,You can initialize all the bits to zero usingTo set a particular bit, say bit number 25, to 1, do this:This is one-liner converts bytes to a list of True/False bit values. Might be not performant for 6M but for small flags it should be fine and does not need additional dependencies.
Python

I have a directory with a bunch of files inside: ,  ... and .I want to exclude all files that start with  with the  function.How can I do it?You can't exclude patterns with the  function, globs only allow for  patterns.  is very limited (even a  character class  match a character).You'll have to do your own filtering; a list comprehension usually works nicely here:The pattern rules for glob are not regular expressions. Instead, they follow standard Unix path expansion rules. There are only a few special characters: two different wild-cards, and character ranges are supported [from ].  So you can exclude some files with patterns.\nFor example to exclude manifests files (files starting with ) with glob, you can use:  You can deduct sets:More generally, to exclude files that don't comply with some shell regexp, you could use module :    The above will first generate a list from a given path and next pop out the files that won't satisfy the regular expression with the desired constraint.Late to the game but you could alternatively just apply a python  to the result of a :or replacing the lambda with an appropriate regex search, etc...EDIT: I just realized that if you're using full paths the  won't work, so you'd need a regex As mentioned by the accepted answer, you can't exclude patterns with glob, so the following is a method to filter your glob result.The accepted answer is probably the best pythonic way to do things but if you think list comprehensions look a bit ugly and want to make your code maximally numpythonic anyway (like I did) then you can do this (but note that this is probably less efficient than the list comprehension method): (In my case, I had some image frames, bias frames, and flat frames all in one directory and I just wanted the image frames)
Python

Environment:django debug toolbar breaking while using to get sql stats else it's working fine on the other pages, breaking only on the pages which have sql queries.sqlparse latest version was released today and it's not compatible with django-debug-toolbar version 1.4, Django version 1.9workaround is force pip to install the latest version of  is not compatible with .  Your choices are:@Rex Salisbury\nThat's not correct.You have to installorTested on Cloud9, with django 1.9.2Sorry,but for me, with Django 1.8.11, it only worked with this:
Python

How can I turn the minor ticks only on y axis on a linear vs linear plot?When I use the function to turn minor ticks on, they appear on both x and y axis.nevermind, I figured it out.Here's another way I found in the :This will place minor ticks on  the y-axis, since minor ticks are off by default.Also, if you only want minor ticks on the actual y-axis, rather than on both the left and right-hand sides of the graph, you can follow the  with , like so:
Python

I am working on python and selenium. I want to download file from clicking event using selenium. I wrote following code.  I want to download both files from links with name \"Export Data\" from given url. How can I achieve it as it works with click event only.ThanksFind the link using , then call  method.Added profile manipulation code to prevent download dialog.I'll admit this solution is a little more \"hacky\" than the Firefox Profile saveToDisk alternative, but it works across both Chrome and Firefox, and doesn't rely on a browser-specific feature which could change at any time. And if nothing else, maybe this will give someone a little different perspective on how to solve future challenges.: Ensure you have selenium and pyvirtualdisplay installed...We first load a URL on the domain we're targeting a file download from. This allows us to perform an AJAX request on that domain, without running into  issues.Next, we're injecting some javascript into the DOM which fires off an AJAX request. Once the AJAX request returns a response, we take the response and load it into a FileReader object. From there we can extract the base64 encoded content of the file by calling readAsDataUrl(). We're then taking the base64 encoded content and appending it to , a gobally accessible variable.Finally, because the AJAX request is asynchronous, we enter  a Python while loop waiting for the content to be appended to the window. Once it's appended, we decode the base64 content retrieved from the window and save it to a file.This solution should work across all modern browsers supported by Selenium, and works whether text or binary, and across all mime types.While I haven't tested this, Selenium does afford you the ability to wait until an element is present in the DOM. Rather than looping until a globally accessible variable is populated, you could create an element with a particular ID in the DOM and use the binding of that element as the trigger to retrieve the downloaded file.In chrome what I do is downloading the files by clicking on the links, then I open  page and then retrieve the downloaded files list from shadow DOM like this:This solution is restrained to chrome, the data also contains information like file path and download date. (note this code is from JS, may not be the correct python syntax)
Python

I'm making a simple login app in django 1.6 (and python 2.7) and I get an error at the beggining that is not letting me continue.This is the site's url.pyAnd this is login/urls.py:This is login/views,pyI have a form that has this as action:And that's where the problem is, when I try to load the page, I get:But if I set the url pattern toit works fine, only it sets the action as '/'.I've been looking all around for an answer and I don't understand why it doesn't work.I tried changing the login url pattern to url(r'^login/$', include('login.urls', namespace='login')), and it didn't change anything.The problem is in the way you include the auth URLs in the main one.\n Because you use both ^ and $, only the empty string matches. Drop the $.
Python

As I know, %debug magic can do debug within one cell.However, I have function calls across multiple cells.For example,What I tried:     What is the right way to set a break point within ipython notebook?Use  Install it via Usage: For executing line by line use  and for step into a function use  and to exit from debugging prompt use .For complete list of available commands: You can use  inside jupyter with:: the functions above are deprecated since IPython 5.1. This is the new approach:Add  where you need a breakpoint. Type  for  commands when the input field appears.You can always add this in any cell:and the debugger will stop on that line.  For example:Your return function is in line of def function(main function), you must give one tab to it.\nAnd Use instead ofto debug the whole cell not only line. Hope, maybe this will help you.
Python

I am trying to implement , which requires to 'freeze' one or the other part of the graph during alternating training minibatches. I.e. there two sub-networks: G and D.where loss function of  depends on .First I need to train parameters in D with all G parameters fixed, and then parameters in G with parameters in D fixed. Loss function in first case will be negative loss function in the second case and the update will have to apply to the parameters of whether first or second subnetwork.I saw that tensorflow has  function. For purpose of training the D (downstream) subnetwork I can use this function to block the gradient flow to The  is very succinctly annotated with no in-line example (and example  is too long and not that easy to read), but looks like it must be called during the graph creation.  Also it seems that As an alternative I saw that one can pass the list of variables to the optimizer call as , which would be an easy solution if one could get all variables in the scopes of each subnetwork. The easiest way to achieve this, as you mention in your question, is to create two optimizer operations using separate calls to . By default, the optimizer will use all of the variables in . If you want to filter the variables to a particular scope, you can use the optional  argument to  as follows:Another option you might want to consider is you can set trainable=False on a variable. Which means it will not be modified by training.@mrry's answer is completely right and perhaps more general than what I'm about to suggest. But I think a simpler way to accomplish it is to just pass the python reference directly to : I have a self-contained example here:  I don't know if my approach has down sides, but I solved this issue for myself with this construct:So if , the values and gradients will flow through just fine, but if , then the values will only flow through the stop_gradient op, which will stop the gradients flowing back.For my scenario, hooking do_gradient up to an index of a random_shuffle tensor let me randomly train different pieces of my network.
Python

I've read some about .egg files and I've noticed them in my lib directory but what are the advantages/disadvantages of using then as a developer?From the :-AdamOne egg by itself is not better than a proper source release. The good part is the dependency handling. Like debian or rpm packages, you can say you depend on other eggs and they'll be installed automatically (through ).A second comment: the egg format itself is a binary packaged format. Normal python packages that consist of just python code are best distributed as \"source releases\", so \"python setup.py sdist\" which result in a .tar.gz. These are also commonly called \"eggs\" when uploaded to pypi.Where you need binary eggs: when you're bundling some C code extension. You'll need several binary eggs (a 32bit unix one, a windows one, etc.) then.Eggs are a pretty good way to distribute python apps.  Think of it as a platform independent .deb file that will install all dependencies and whatnot.  The advantage is that it's easy to use for the end user.  The disadvantage are that it can be cumbersome to package your app up as a .egg file.You should also offer an alternative means of installation in addition to .eggs.  There are some people who don't like using eggs because they don't like the idea of a software program installing whatever software it wants.  These usually tend to be sysadmin types..egg files are basically a nice way to deploy your python application. You can think of it as something like .jar files for Java. More info .Whatever you do, do not stop distributing your application, also, as a tarball, as that is the easiest packagable format for operating systems with a package sysetem.For simple Python programs, you probably don't need to use eggs. Distributing the raw .py files should suffice; it's like distributing source files for GNU/Linux. You can also use the various OS \"packagers\" (like py2exe or py2app) to create .exe, .dmg, or other files for different operating systems.More complex programs, e.g. Django, pretty much require eggs due to the various modules and dependencies required.
Python

I've been using virtualenv lately while developing in python. I like the idea of a segregated development environment using the --no-site-packages option, but doing this while developing a PyGTK app can be a bit tricky. The PyGTK modules are installed on Ubuntu by default, and I would like to make a virtualenv (with --no-site-packages) aware of specific modules that are located elsewhere on the system.What's the best way to do this? Or should I just suck it up and drop the --no-site-packages option?One way is to add the paths to your code using sys.path.Another way is to use site, which processes .pth files in addition to adding to sys.path.But you probably don't want to add this to all your related code.  I've seen mention of sitecustomize.py being used to perform something like this, but after some testing I couldn't get it to work as might be expected. Here it mentions that auto-import of sitecustomize.py ended in 2.5, if your not on 2.5 try it out.  (just add one of the path add methods above to the file and drop it in the directory your program is run)\nA work around method is mentioned in the post for users of 2.5 and up. I find in this situation, symlinks, or even copying specific files (packages, modules, extensions) works really well.It allows the program to emulate being run in the target environment, rather than changing the application to suit the development environment.Same deal for something like AppEngine.Check out the postmkvirtualenv hook script here: In that case, he's using it to import PyQt and SIP after a new Virtualenv is created, but you can add the packages that you need to LIBS. And vote that script up because it's fantastic :)If you want to include the links to the relevant system's python gtk-2.0 in the virtualenv, you can just use pip to install :pip install ruamel.venvgtk\nYou don't have import anything, the links are setup during installation.This is especially handy if you are using , in that case you only need to include the dependency (for tox):and a newly setup python2.7 environment will have the relevant links included before the tests are run.More detailed information on how the links are setup can be found in 
Python

How would I go about using Python to read the frequency peaks from a WAV PCM file and then be able to generate an image of it, for spectogram analysis?I'm trying to make a program that allows you to read any audio file, converting it to WAV PCM, and then finding the peaks and frequency cutoffs. will let you import the audio. After that, you can  of the audio.Then,  makes very nice charts and graphs - absolutely comparable to MATLAB.It's old as dirt, but  would probably get you started on almost exactly the problem you're describing (article in Python of course).Loading WAV files is easy using :or for reading any general audio format and converting to WAV:The spectrogram is built into PyLab:Specifically, it's part of .  is the easiest. Also quite handy in this context:But be warned: Matplotlib is very slow but it creates beautiful images. You should not use it for demanding animation, even less when you are dealing with 3DIf you need to convert from PCM format to integers, you'll want to use struct.unpack.
Python

 -Quote suggests it is incorrect to call  as a  because the object is already constructed by the time  is called. But! I have always been under the impression that the  is called only after the object is constructed because it is essentially used  to initialized the data members of the instance which wouldn't make sense if the object didn't exist by the time  was called? (coming from C++/Java background)If you have a class  then:Construction of a Python object is simply allocation of a new instance followed by initialization of said instance.Personally, I find \" is not a constructor\" to be pretty fine hair-splitting. is called when a new object is requested. It is supposed to use its arguments to assign attributes on the new object, such that the required invariants for normal operation of the object are set up. The object is already a valid pre-existing place to store attributes by the time the code in  begins running.  (other than the ones that all objects possess).A C++ constructor is called when a new object is requested. It is supposed to use its arguments to assign to fields on the new object, such that the required invariants for normal operation of the object are set up. The object is already a valid pre-existing place to store fields by the time the code in the constructor begins running. A Java constructor is called when a new object is requested. It is supposed to use its arguments to assign to fields on the new object, such that the required invariants for normal operation of the object are set up. The object is already a valid pre-existing place to store fields by the time the code in the constructor begins running. The major difference between an  method and a C++/Java constructor is in that last sentence I've highlighted, and that's just the difference between the static nature of Java/C++ and the dynamic nature of Python. I don't think this warrants calling them fundamentally different concepts that must not be referred to by the same word.I think the main reason Pythonistas don't like to refer to  as a constructor is that people  of C++/Java constructors as \"making a new object\", because that's what they seem to do when you call them. But there's really two things going on when you call a constructor; a new object is created and then the constructor is called to initialise it. In C++/Java the \"create a new object\" part of that is invisible, whereas that can be exposed/customised in Python (via the  method).So while the role of the  method is extremely similar to the role of a C++/Java constructor, some people prefer to emphasise the fact that this isn't the whole process by saying that \" is not a constructor\".Constructor  an instance and can fail. But  does not return an instance. Even when  raises and exception,  is called to delete the instance.This can be seen here: on the other hand, returns an instance. In \"Programming Python : Introduction to Computer Science\" from John Zelle says,\n\". Python calls this method to initialize a new object. The role of  is to provide initial values for the instance variables of an object.\"From  Regarding the answert given by Ben, I would argue here, that most languages don't follow that defintion (completely).Furthermore:Bottomline (for me):  appears to be the constructor, not  although -by all practical means  does part of what most people think a constructor will do.  is not a constructor, but for reasons that won't matter to you as you're learning Python. It behaves the way you're used to constructors behaving in C++ and Java.
Python

I'm writing some test cases for my application using Python's . Now I need to compare a list of objects with a list of another objects to check if the objects from the first list are what I'm expecting.How can I write a custom  method? What should it do? Should it raise an exception on failure? If yes, which exception? And how to pass the error message? Should the error message be a unicode string or a bytestring?Unfortunately, the  doesn't explain how to write custom assertion methods.If you need a real-world example for this, continue reading.The code I'm writing is somewhat like this:This approach makes it extremely easy to describe the expected values of each object in a very compact way, and without needing to actually create full objects.However... When one object fails the assertion, no further objects are compared, and this makes debugging a bit more difficult. I would like to write a custom method that would unconditionally compare all objects, and then would display all objects that failed, instead of just the first one.I use the multiple inheritance in these cases. For example:First. I define a class with methods that will incorporate.Now I define a class that inherits from unittest.TestCase and CustomAssertionYou should create your own TestCase class, derived from unittest.TestCase.  Then put your custom assert method into that test case class.  If your test fails, raise an AssertionError.  Your message should be a string.  If you want to test all objects in the list rather than stop on a failure, then collect a list of failing indexes, and after the loop over all the objects, build an assert message that summarizes your findings.
Python

I have an array of distances  and I need the indices of the sorted array (for example , for ). Is there a function in Numpy to do that?Yes, there's the  function or  method. It does exactly what you're asking for. You can also call  as a method on an  object like so: .Here's a link to the documentation: 
Python

I have written many scrapers but I am not really sure how to handle infinite scrollers. These days most website etc, Facebook, Pinterest has infinite scrollers.You can use selenium to scrap the infinite scrolling website like twitter or facebook. Step 1 : Install Selenium using pip Step 2 : use the code below to automate infinite scroll and extract the source codeStep 3 : Print the data if required.Most sites that have infinite scrolling do (as Lattyware notes) have a proper API as well, and you will likely be better served by using this rather than scraping.But if you must scrape...Such sites are using JavaScript to request additional content from the site when you reach the bottom of the page. All you need to do is figure out the URL of that additional content and you can retrieve it. Figuring out the required URL can be done by inspecting the script, by using the Firefox Web console, or by using a .For example, open the Firefox Web Console, turn off all the filter buttons except Net, and load the site you wish to scrape. You'll see all the files as they are loaded. Scroll the page while watching the Web Console and you'll see the URLs being used for the additional requests. Then you can request that URL yourself and see what format the data is in (probably JSON) and get it into your Python script.Finding the url of the ajax source will be the best option but it can be cumbersome for certain sites. Alternatively you could use a headless browser like  from  and send keyboard events while reading the data from the DOM tree.  has a nice and simple api.
Python

I'd like to have a child class modify a class variable that it inherits from its parent.I would like to do something along the lines of:and ideally have:I could do:but then every time I instantiate an instance of Child, \"world\" gets appended to the list, which is undesired.  I could modify it further to:but this is still a hack because I must instantiate an instance of Child before it works.Is there a better way?Assuming you want to have a separate list in the subclass, not modify the parent class's list (which seems pointless since you could just modify it in place, or put the expected values there to begin with):Note that this works independently of inheritance, which is probably a good thing.You should not use mutable values in your class variables. Set such values on the  instead, using the  instance initializer:Otherwise what happens in that the  list is shared among not only the instances, but with the subclasses as well.In any case, you'll have to avoid modifying mutables of parent classes even if you do desire to share state among instances through a mutable class variable; only  to a name would create a new variable:where a   variable is created for the  class. By using assignment, you've created a new list instance and the  mutable is unaffected.Do take care with nested mutables in such cases; use the  module to create deep copies if necessary.
Python

How can you  the parent loop of say two nested loops in Python?I know you can avoid this in the majority of cases but can it be done in Python?I would go with 5 every time.Here's a bunch of hacky ways to do it:You use  to break out of the inner loop and continue with the parent
Python

Are there functions for conversion between different coordinate systems?For example, Matlab has  for conversion from cartesian to polar coordinates. Seems like it should be in numpy or scipy.Using numpy, you can define the following:The existing answers can be simplified:Or even:Note these also work on arrays!If your coordinates are stored as complex numbers you can use If you can't find it in numpy or scipy, here are a couple of quick functions and a point class:There is a better way to write polar(), here it is: Thinking about it in general, I would strongly consider hiding coordinate system behind well-designed abstraction. Quoting Uncle Bob and his book:With interface like that any user of Point class may choose convenient representation, no explicit conversions will be performed. All this ugly sines, cosines etc. will be hidden in one place. Point class. Only place where you should care which representation is used in computer memory.
Python

I have been trying to understand python metaclasses, and so have been going through some sample code. As far as I understand it, a Python metaclass can be any callable. So, I can have my metaclass likeHowever, I have seen a lot of people write their metaclasses in the following way:As far as I can see, these would both do the same thing. Is there any reason to use the base class instead? Is it customary?There are subtle differences, mostly relating to inheritance.  When using a\nfunction as a metaclass, the resulting class is really an instance of ,\nand can be inherited from without restriction; however, the metaclass function\nwill never be called for such subclasses.  When using a subclass of  as a\nmetaclass, the resulting class will be an instance of that metaclass, as will\nany of its subclasses; however, multiple inheritance will be restricted.Illustrating the differences:Note that when defining sub1 and sub2, no metaclass functions were called.\nThey will be created exactly as if c1 and c2 had no metaclasses, but instead\nhad been manipulated after creation.Note the differences already: M1 was called when creating Sub1, and both\nclasses are instances of M1.  I'm using  for the actual creation here,\nfor reasons which will become clear later.This is the major restriction on multiple inheritance with metaclasses.\nPython doesn't know whether M1 and M2 are compatible metaclasses,\nso it forces you to create a new one to guarantee that it does what you need.This is why I used  in the metaclass  functions: so each one\ncan call the next one in the MRO.Certain use cases might need your classes to be of type , or might want\nto avoid the inheritance issues, in which case a metaclass function is probably\nthe way to go.  In other cases, the type of the class might be truly important,\nor you might want to operate on all subclasses, in which case subclassing\n would be a better idea.  Feel free to use the style that fits best in\nany given situation.
Python

In Python, and in general - does a  operation on a file object imply a  operation?Yes. It uses the underlying  function which does that for you ().NB:  and  won't ensure that the data is actually secure on the disk. It just ensures that the OS has the data == that it isn't buffered inside the process.You can try sync or fsync to get the data written to the disk.filehandle.close does not necessarily flush. Surprisingly, filehandle.flush doesn't help either---it still can get stuck in the OS buffers when Python is running. Observe this session where I wrote to a file, closed it and Ctrl-Z to the shell command prompt and examined the file:Subsequently I can reopen the file, and that necessarily syncs the file (because, in this case, I open it in the append mode). As the others have said, the sync syscall (available from the os package) should flush all buffers to disk but it has possible system-wide performance implications (it syncs all files on the system).
Python

I have a raw image where each pixel corresponds to a 16 bits unsigned integer. I am trying to read using the PIL Image.fromstring() function as in the following code:The PIL documentation informs that the first argument of the fromstring() function is 'mode'. However, looking at the documentation and googling I wasn't able to find details about what that argument really means (I believe that it is related to the color space or something like that). Does anyone knows where I can find a more detailed reference about the fromstring() function and what the mode argument means?The specific documentation is at :I'm not sure what \"L\" stands for, but \"RGBA\" stands for Red-Green-Blue-Alpha, so I presume RGBX is equivalent to RGB (edit: upon testing this isn't the case)? CMYK is Cyan-Magenta-Yellow-Kelvin, which is another type of colorspace. Of course I assume that if you know about PIL you also know about colorspaces. If not,  has a great article.As for what it really means (if that's not enough): pixel values will be encoded differently for each colorspace. In regular RGB you have 3 bytes per pixel - 0-254, 0-254, 0-254. For Alpha you add another byte to each pixel. If you decode an RGB image as RGBA, you'll end out reading the R pixel to the right of the first pixel as your alpha, which means you'll get the G pixel as your R value. This will be magnified depending on how large your image, but it will really make your colors go wonky. Similarly, trying to read a CMYK encoded image as RGB  (or RGBA) will make your image look very much not like it's supposed to. For instance, try this with an image:And you'll see what the different modes do - try it with a variety of input images: png with alpha, png without alpha, bmp, gif, and jpeg. It's kinda a fun experiment, actually.If all else fails, you can always read the source code. For PIL, the downloads are .You never said exactly what format the pixel data in the 16 bits unsigned integers was in, but I'd guess it's something like RRRRRGGGGGGBBBBBB, (5-bits Red, 6-bits Green, 5-bits Blue), or RRRRRGGGGGBBBBBA (5-bits Red, 5-bits Green, 5-bits Blue, 1-bit Alpha or Transparency). I didn't see support for those formats after a very quick peek at the some of the sources myself, but can't say one way or the other for sure. On the same web page where the PIL downloads are, they mention that one can send questions to the Python Image SIG mailing list and provide a link for it. That might be a better source than asking here.Hope this helps.This is an old question, but this might help someone in the future. One of the problems with the original code snippet is that in , the  part works for  mode.This works for me:
Python

Is there anything similar to Python  for Java or JVM Languages?From what I understand, virtualenv enables you to have separate library installation paths, effectively separate \"virtual\" Python installations.Java doesn't have the concept of a \"system-wide installed\" library: It always searches the classpath for the libraries to be loaded. Since the classpath can be (and needs to be!) defined for each application, each application can pick-and-choose which libraries and which versions it wants to load.If you go down one level deeper and have a single application that somehow needs two different versions of the same library at the same time, then you can do even that with some classpath trickery. It can get complicated, but it's definitely possible (OSGi is one example where this is supported, even Tomcat with two separate webapplications does this).I've seens some references to security in the virtualenv description: Java has a pretty thorough security system built in. In server applications it's often turned off because it's just easier to configure this way, but you can easily configure what exactly a Java application is allowed to do.Build tools like Ant, Maven, and gradle are the the closest thing to  or .The concept of virtualenv is done by the classpath. So there is no real need of virtualenv for JavaI know this may be a little late , but Groovy/Java has gvm  which is the Groovy version of Ruby's renv.I would respectfully agree with Gautam K, luthur. Dependency and package version management for projects is not the  same as an isolated self-contained virtual environment to maintain different project.My 2 cents\n-WI have also been looking for a similar solution to simplify switching context between projects that use different Maven versions/settings and/or Java SDKs without having to modify  and  settings every time.To this end, I developed a solution that helps execute  commands with the appropriate configuration based on  settings (stored in a  folder). See: Be aware that this only helps if you're using Maven to build and/or run your project.Maven, you can explicitly specify which packages you would use in a java projectI'm confused by the assertion that \"Java doesn't have the concept of a 'system-wide installed' library\". What would you call the jar files in $JAVA_HOME/jre/lib and $JAVA_HOME/jre/lib/ext?Regardless of whether or not Java \"needs\" a tool like virtualenv, it seems that something that allowed you to quickly switch between different Java environments (e.g. Java 6 with such-and-such security extensions, Java 7, etc.) would be handy - even if all it was actually doing under the covers was manipulating the PATH, JAVA_HOME, and CLASSPATH env variables.Java as a language does not need the sandboxing features of virtualenv but a JVM Language like Jython can have VirtualEnv to use different environments without any conflict.It is outlined in  Quote:So when using Jython different frameworks and packages can be used without any conflict with global packages.
Python

So I have a dict passed from a web page.  I want to build the query dynamically based on the dict.  I know I can do:However, that only works when the values are an exact match.  I need to do 'like' filtering.  My best attempt using the  attribute:Not sure how to build the query from there.  Any help would be awesome.You're on the right track!First thing you want to do different is access attributes using , not ;  will always do the right thing, even when (as may be the case for more convoluted models) a mapped attribute isn't a column property.The other missing piece is that you can specify  more than once, and just replace the old query object with the result of that method call.  So basically:
Python

I have a matrix  and I want 2 matrices  and  such that  contains the upper triangular elements of A (all elements above and not including diagonal) and similarly for (all elements below and not including diagonal). Is there a  method to do this?e.g Try  (triangle-upper) and  (triangle-lower).Use the  of  and  to return a copy of a matrix with the elements above or below the k-th diagonal zeroed.In case that you want to extract the upper triangle values to a flat vector,\nyou can do something like:
Python

Why does first line prints True, but second prints False? And neither enters operator ?I am using Python 2.6You need to define  too. For exampleWill work as expected.As a general rule, any time you implement  you should implement a  such that for all  and  such that , .Set __contains__ makes checks in the following order:The relevant C source code is in Objects/setobject.c::set_lookkey() and in Objects/object.c::PyObject_RichCompareBool().Sets and dictionaries gain their speed by using  as a fast approximation of full equality checking. If you want to redefine equality, you usually need to redefine the hash algorithm so that it is consistent.The default hash function uses the identity of the object, which is pretty useless as a fast approximation of full equality, but at least allows you to use an arbitrary class instance as a dictionary key and retrieve the value stored with it if you pass exactly the same object as a key. But it means if you redefine equality and  redefine the hash function, your objects will go into a dictionary/set without complaining about not being hashable, but still won't actually work the way you expect them to.See  for more details.A tangential answer, but your question and my testing made me curious. If you ignore the set operator which is the source of your  problem, it turns out your question is still interesting.Thanks to the help I got on , I was able to chase the in operator through the source code to it's root. Near the bottom I found the PyObject_RichCompareBool function which indeed tests for identity (see the comment about \"Quick result\") before testing for equality.So unless I misunderstand the way things work, the technical answer to your question is first identity and then equality, through the equality test itself. Just to reiterate, that is not the source of the behavior you were seeing but just the technical answer to your question.If I misunderstood the source, somebody please set me straight.Sets seem to use hash codes, then identity, before comparing for equality. The following code:outputs:What happens seems to be:
Python

I have a rather big program, where I use functions from the  module in different files. I would like to be able to set the random seed once, at one place, to make the program always return the same results. Can that even be achieved in ?The main python module that is run should  and call  - this is shared between all other imports of  as long as somewhere else doesn't reset the seed.In the beginning of your application call  making sure x is always the same. This will ensure the sequence of pseudo random numbers will be the same during each run of the application.Jon Clements pretty much answers my question. However it wasn't the real problem:\nIt turns out, that the reason for my code's randomness was the numpy.linalg SVD because it does not always produce the same results for badly conditioned matrices !!So be sure to check for that in your code, if you have the same problems!You can guarantee this pretty easily by using your own random number generator.Just pick three largish primes (assuming this isn't a cryptography application), and plug them into a, b and c:\na = ((a * b) % c)\nThis gives a feedback system that produces pretty random data.  Note that not all primes work equally well, but if you're just doing a simulation, it shouldn't matter - all you really need for most simulations is a jumble of numbers with a pattern (pseudo-random, remember) complex enough that it doesn't match up in some way with your application.Knuth talks about this.
Python

Alright, I know how to print variables and strings.  But how can I print something like \"My string\" card.price (it is my variable). I mean, here is my code:\n.By printing multiple values separated by a comma:The  will output each expression separated by spaces, followed by a newline.If you need more complex formatting, use the :or by using the older and semi-deprecated .Assuming you use Python 2.7 (not 3): (as mentioned above). (using ) (by joining lists)There are a lot of ways to do the same, actually. I would prefer the second one.Something that (surprisingly) hasn't been mentioned here is simple concatenation.Example:Result:Additionally, as of Python 3, the  method is deprecated. Don't use that.
Python

I have some escaped strings that need to be unescaped. I'd like to do this in Python.For example, in python2.7 I can do this:How do I do it in Python3?  This doesn't work:My goal is to be abel to take a string like this:And turn it into:After I do the conversion, I'll probe to see if the string I have is encoded in UTF-8 or UTF-16.You'll have to use  instead:If you  with a  object instead (equivalent to the python 2.7 unicode) you'll need to encode to bytes first, then decode with .If you need bytes as end result, you'll have to encode again to a suitable encoding ( for example, if you need to preserve literal byte values; the first 255 unicode code points map 1-on-1).Your example is actually UTF-16 data with escapes. Decode from , back to  to preserve the bytes, then from  (UTF 16 little endian without BOM):The old \"string-escape\" codec maps bytestrings to bytestrings, and there's been a lot of debate about what to do with such codecs, so it isn't currently available through the standard encode/decode interfaces.BUT, the code is still there in the C-API (as ), and this is still exposed to Python via the undocumented  and .These functions return the transformed  object, plus a number indicating how many bytes were processed... you can just ignore the latter.You can't use  on byte strings (or rather, you can, but it doesn't always return the same thing as  does on Python 2) \u2013 beware!This function implements  using a regular expression and custom replacement logic.
Python

I'd like to make a migration for a Flask app. I am using Alembic.However, I receive the following error.Online, I read that it has something to do with this. \nUnfortunately, I don't quite understand how to get the database up to date and where/how I should write the code given in the link. If you have experience with migrations, can you please explain this for meThanksAfter creating a migration, either manually or as , you must apply it with .  If you used  from a shell, you can use  to indicate that the current state of the database represents the application of all migrations.I had to delete some of my migration files for some reason. Not sure why. But that fixed the problem, kind of.One issue is that the database ends up getting updated properly, with all the new tables, etc, but the migration files themselves don't show any changes when I use automigrate.If someone has a better solution, please let me know, as right now my solution is kind of hacky.
Python

I want to print the whole dataframe, but I don't want to print the indexBesides, one column is datetime type, I just want to print time, not date.The dataframe looks like:I want it print asOr possibly:
Python

Are there any Mixed Integer Linear Programming(MILP) solver for Python?Can GLPK python solve MILP problem? I read that it can solve Mixed integer problem.\nI am very new to linear programming problem. So i am rather confused and cant really differentiate if Mixed Integer Programming is different from Mixed Integer Linear programming(MILP).  is a python modeling interface that hooks up to solvers like the open source , , ,  and (open source).You can also use  to model the optimization problem and then call an external solver, namely CPLEX, Gurobim GLPK and the AMPL solver library.You can also call GLPK from ,  or .Yet another modelling language is , which has a python interface for MIP solvers (for linear programs only).All the above solvers solve , while some of them (CPLEX, GUROBI and XRESS-MP for sure) can solve  and  (and also conic programs but this probably goes beyond the scope of this question). MIP refers to Mixed integer programs, but it is commonly used to refer to linear programs only. To make the terminology more precise, one should always refer to MILP or MINLP (Mixed integer non-linear programming).Note that CPLEX and GUROBI have their own python APIs as well, but they (and also) XPRESS-MP are commercial products, but free for academic research.  is similar to Pulp above but interfaces with the COIN-OR solvers CBC and CGL and CLP.Note that : the latter are falling behind the former by a large margin.  is . Its python interface, PySCIPOpt, is .Also, have a look at .Finally, if you are interested at a simple constraint solver (not optimization) then have a look at .I hope this helps! Two more solvers and python interfaces that fell into my radar: , which appears to be one of the fastest non-commercial MIP solvers, has a  that has quite . Note, however, that the Python API does not include the advanced functionality that comes together with the native . I particularly like the , which demonstrates an array of models used in Operations Management, on top of some small-scale implementations. It is a very interesting introductory manual in its own right, regardless of which solver/API one may want to make use of., which include a multitude of functionalities, such as It has extensive documentation of several traditional OR problems and simple implementations. I could not find a complete Python API documentation, although there exist some examples . It is somewhat unclear to me how other solvers hook up on the interface and whether methods of these solvers are available.
Python

I'm trying to plot a ROC curve using seaborn (python).\nWith matplotlib I simply use the function :where  and  are two lists of paired values.Is there a simple counterparts of the plot function in seaborn? I had a look at the gallery but I didn't find any straightforward method.Since seaborn also uses matplotlib to do its plotting you can easily combine the two. If you only want to adopt the styling of seaborn the  function should get you started:Result:
Python

This is sort of a follow-up to  thread.Sample input strings:Desired outputs:The number of -like items is .Currently, I'm doing it through :Would it be possible to combine these two  calls into a single one?In other words, I want to replace something at the beginning of the string and then multiple similar things after, all of that in one go.I've looked into  - it's ability to  looks very promising, tried using  but failed to make it work.You can indeed use the regex module and repeated captures. The main interest is that you can check the structure of the matched string:Please do not do this in any code I have to maintain.You are trying to parse syntactically valid Python.  Use  for that.  It's more readable, easier to extend to new syntax, and won't fall apart on some weird corner case. Working sample:Prints:You could do this.  Though I don't think it's very readable.  And doing it this way could get unruly if you start adding more patterns to replace.  It takes advantage of the fact that the replacement string can also be a function.You can use  and a simple string formatting:
Python

For my program I have a lot of places where an object can be either a string or a list containing strings and other similar lists. These are generally read from a JSON file. They both need to be treated differently. Right now, I am just using isinstance, but that does not feel like the most pythonic way of doing it, so does anyone have a better way of doing it? No need to import modules, ,   and  (versions before 3 -- there's no  in 3!) will do the job for you.From :Since Python3 no longer has  or , in this case ( where you are expecting either a list or a string) it's better to test against as that is compatible with both Python2 and Python3Using :On Python>=2.3 a string may be a  or  type. To check both cases:From Python 3 only one string type exists, so instead of  you should use :Another method, using the practice of \"It's better to ask forgiveness than permission,\" duck-typing being generally preferred in Python, you could try to do what you want first, e.g.:As I like to keep things simple, here is the shortest form that is compatible with both 2.x and 3.x:You can use types module:
Python

Can this Python code be shortened and still be readable using itertools and sets?I can think of this only:An alternative to  is to use the  method of standard dictionaries:This relies on the fact that lists are mutable, so what is returned from setdefault is the same list as the one in the dictionary, therefore you can append to it.You can use a .may be a bit slow but works
Python

In Python, I have a list:I want to identify the item that occurred the highest number of times. I am able to solve it but I need the fastest way to do so. I know there is a nice Pythonic answer to this.  Here is a  solution that will work with Python versions 2.5 and above:Note if \nthen there are six 4s and six 7s.   However, the result will be   i.e. six 4s.For older Python versions (< 2.7), you can use  to get the  class.In your question, you asked for the fastest way to do it.  As has been demonstrated repeatedly, particularly with Python, intuition is not a reliable guide: you need to measure.  Here's a simple test of several different implementations:The results on my machine:So it appears that the  solution is not the fastest.  And, in this case at least,  is faster.  is good but you pay a little bit for its convenience;  it's slightly faster to use a regular  with a .What happens if the list is much bigger?  Adding  to the test above and reducing the repeat count to 200:Now  is the clear winner. So perhaps the cost of the 'get' method and the loss of the inplace add adds up (an examination of the generated code is left as an exercise).But with the modified test data, the number of unique item values did not change so presumably  and  have an advantage there over the other implementations.  So what happens if we use the bigger list but substantially increase the number of unique items?  Replacing the initialization of L with:So now  is clearly faster than the  solutions but still slower than the  versions of  and .The point of these examples isn't to produce an optimal solution.  The point is that there often isn't  optimal general solution.  Plus there are other performance criteria.  The memory requirements will differ substantially among the solutions and, as the size of the input goes up, memory requirements may become the overriding factor in algorithm selection.Bottom line: it all depends and you need to measure.I am surprised no-one has mentioned the simplest solution, with the key :Example:This works in Python 3 or 2, but note that it only returns the most frequent item and not also the frequency. Also, in the case of a  (i.e. joint most frequent item) only a single item is returned.I find the  approach is about twice as fast as :Perhaps the  methodI obtained the best results with  from  module with this function using Python 3.5.2:Output:Test with  from  module.I used this script for my test with :Output (The best one):I want to throw in another solution that looks nice and is fast for  lists.You can benchmark this with the code provided by Ned Deily which will give you these results for the smallest test case:But beware, it is inefficient and thus gets  slow for large lists!
Python

I have a model some thing like thisNow I would like to do a calculation  on the database level. Using Django Aggregation I can have the sum for each field but not the summation of multiplication of fields.  for  please follow the answer provided by @kmmbvnrit's possible using Django ORM:here's what you should do:Note: if the two fields are of different types, say  & , the type you want to return should be passed as the first parameter of It's a late answer, but I guess it'll help someone looking for the same.With Django 1.8 and above you can now pass an expression to your aggregate:Constants are also available, and everything is combinable:The solution depends on Django version.Do you have several options:Overwriting:
Python

I want to play my song (mp3) from python, can you give me a simplest command to do that?This is not correct:You may try this, simplistic but not the best method maybe.Please note that the support for  is limited ()For installation instructions, visit Grab the , vlc.py, which provides full support for libVLC and pop that in site-packages.  Then:And you can stop it with:That module offers plenty beyond that (like pretty much anything the VLC media player can do), but that's the simplest and most effective means of playing one MP3.You could play with os.path a bit to get it to find the path to the MP3 for you, given the filename and possibly limiting the search directories.Full documentation and pre-prepared modules are available .  Current versions are Python 3 compatible.You are trying to play a  as if it were a .You could try using  to convert it to  format, and then feed that into pyAudio.Alternatively, use , as mentioned in the other answer.As it wasn't already suggested here, but is probably one of the easiest solutions:It depends on any mpg123 compliant player, which you get e.g. for Debian using:or A simple solution:cheers...See also Another quick and simple option...Now you might need to make some slight changes to make it work. For example, if the player needs extra arguments or you don't need to specify the full path. But this is a simple way of doing it.If you're working in the Jupyter (formerly IPython) notebook, you canAt this point, why not mentioning :It's the best solution I found.(I needed to install , on Raspbian)Code excerpt loosely based on:\n
Python

I have: I essentially want to input  and return  but I keep getting  to return instead.  Not sure what's wrong! like demented hedgehog said. But you said you can't ...Your problem is your code searches only for the first character of your search string which(the first one) is at index 2.You are basically saying if  is in , increment  until  which returned 3 when I tested it but it was still wrong. Here's a way to do it.It produced the following output:There's a builtin method on string objects to do this in python you know?Python is a \"batteries included language\" there's code written to do most of what you want already (whatever you want).. unless this is homework :)Edit:  returns -1 if the string cannot be found.
Python

I need some guidance in working out how to plot a block of histograms from grouped data in a pandas dataframe. Here's an example to illustrate my question:In my ignorance I tried this code command:which failed with the error message \"TypeError: cannot concatenate 'str' and 'float' objects\"Any help most appreciated.I'm on a roll, just found an even simpler way to do it using the  keyword in the hist method:That's a very handy little shortcut for quickly scanning your grouped data!For future visitors, the product of this call is the following chart:\nYour function is failing because the groupby dataframe you end up with has a hierarchical index and two columns (Letter and N) so when you do  it's trying to make a histogram of both columns hence the str error.This is the default behavior of pandas plotting functions (one plot per column) so if you reshape your data frame so that each letter is a column you will get exactly what you want.The  is just to shove the current index into a column called .  Then  will take your data frame, collect all of the values  for each  and make them a column.  The resulting data frame as 400 rows (fills missing values with ) and three columns ().   will then produce one histogram per column and you get format the plots as needed.One solution is to use matplotlib histogram directly on each grouped data frame.  You can loop through the groups obtained in a loop.  Each group is a dataframe.  And you can create a histogram for each one.
Python

I'm learning python and I'm not sure of understanding the following statement : \"The function (including its name) can capture .\"It's the part that is in bold that I don't understand the meaning in terms of programming. The quote comes from How to think like a computer scientist, 3 edition.Thank you !Abstraction is a core concept in all of computer science. Without abstraction, we would still be programming in machine code or worse not have computers in the first place. So IMHO that's a really good question. something means to  to things, so that the name captures the core of what a function or a whole program does.One example is given in the book you reference, where it says Forget about the turtles for a moment and just think of drawing a square. If I tell you to draw a square (on paper), you immediately know what to do: You can do this without further questions because you know by heart what a  is, without me telling you step by step. Here, the word  is the  of \"draw a rectangle with all sides of the same length\".But wait, how do you know what a  is? Well, that's another abstraction for the following:Of course it goes on and on - , , ,  are all  of well-known concepts.Now, imagine each time you want a rectangle or a square to be drawn you have to give the full definition of a rectangle, or explain lines, parallel lines, perpendicular lines and connecting lines -- it would take far too long to do so.That's the first  they make talking and getting things done much easier. The second power of abstractions comes from the nice property of : once you have defined abstractions, you can  two or more abstractions to form a new, larger abstraction: say you are tired of drawing squares, but you really want to draw a . Assume we have already defined the , so then we can define:Next, you want a village:Oh wait, we want a city -- and we have a new concept :and so on...If in the course of planning your program (a process known as ), you find good abstractions to the problem you are trying to solve, your programs become shorter, hence easier to write and - maybe more importantly - easier to read. The way to do this is to try and grasp the major concepts that define your problems -- as in the (simplified) example of drawing a , this was  and , to draw a  it was . In programming, we define abstractions as functions (and some other constructs like classes and modules, but let's focus on functions for now). A function essentially  a set of single statements, so a function essentially is an abstraction -- see the examples in your book for details.In programming, abstractions can make or break productivity. That's why often times, commonly used functions are collected into  which can be reused by others. This means you don't have to worry about the details, you only need to understand how to use the ready-made abstractions. Obviously that should make things easier for you, so you can work faster and thus be more productive::Imagine there is a graphics library called \"nicepic\" that contains pre-defined    functions for all abstractions discussed above: rectangles, squares, triangles, house, village. Say you want to create a program based on the above abstractions that paints a nice picture of a house, all you have to write is this:So that's just two lines of code to get something much more elaborate. Isn't that just wonderful?Hope this helps.A great way to understand abstraction is through abstract classes.Say we are writing a program which models a house. The house is going to have several different rooms, which we will represent as objects. We define a class for a Bathroom, Kitchen, Living Room, Dining Room, etc.However, all of these are Rooms, and thus share several properties (# of doors/windows, square feet, etc.) BUT, a Room can never exist on it's own...it's always going to be some  of room.It then makes sense to create an abstract class called Room, which will contain the properties all rooms share, and then have the classes of Kitchen, Living Room, etc, inherit the abstract class Room.The concept of a room is  and only exists in our head, because any room that  exists isn't just a room; it's a bedroom or a living room or a classroom.We want our code to thus represent our \"mental chunking\". It makes everything a lot neater and easier to deal with.The best way to to describe something is to use examples:A function is nothing more than a series of commands to get stuff done. Basically you can organize a chunk of code that does a single thing. That single thing can get re-used over and over and over through your program.Now that your function does this thing, you should name it so that it's instantly  identifiable as to what it does. Once you have named it you can re-use it all over the place by simply calling it's name.Then to use that function you can just do something like:What happens if we wanted this to bark 4 times? Well you could write bark(); 4 times.Or you could modify your function to accept some type of input, to change how it works.Then we could just call it once:When we start talking about Object Oriented Programming (OOP) abstraction means something different. You'll discover that part later :) As defined on Basically it is removing the details of the problem. For example, to draw a square requires several steps, but I just want a function that draws a square.Let's say you write a function which receives a bunch of text as parameter, then reads credentials in a config file, then connects to a SMTP server using those credentials and sends a mail using that text. The function should be named , not  because it is more easy to represent what it does this way, to yourself and when presenting the API to coworkers or users... even though the 2nd name is more accurate, the first is a better abstraction. is a very important concept both in hardware and software.  We the human can not remember all the things all the times. For example, if your friend speaks 30 random numbers quickly and asks you to add them all, it won't be possible for you. Reason? You might not be able to keep all those numbers in mind. You might write those numbers on a paper even then you will be adding right most digits one by one ignoring the left digits at one time and then ignoring the right most digits at the other time having added the right most ones.It shows that at one time we the human can  at some particular issue while ignoring those which are already solved and moving focus towards what are left to be solved.Here is how abstraction works in programming.Below is the world's famous hello world program in C language:This is the simplest and usually the first computer program a programmer writes. When you compile and run this program on command prompt, the output may appear like this: gcc -o hello hello.cAnd it converted your English like C language code to binary code and you could run that code by giving command:./helloSo, for writing an application in C program, you never need to know how C compiler converts C language code to binary code. So you used GCC compiler as an abstraction.I did not expand the answer to abstraction of operating system, kernel, firmware and hardware for the sake of simplicity.While doing programming, you can use abstraction in a variety of ways to make your program simple and easy.Example 1: You can use a  to abstract value of PI 3.14159 in your program because PI is easy to remember than 3.14159 for the rest of programExample 2: You can write a  which returns square of a given number and then anyone, including you, can use that function by giving it input as parameters and getting a return value from it.Example 3: In an Object-oriented programming (OOP), like Java, you may define an  which encapsulates data and methods and you can use that object by invoking its methods. Example 4: Many applications provide you  which you use to interact with that application. When you use API methods, you never need to know how they are implemented. So abstraction is there.Through all the examples, you can realize the importance of abstraction and how it is implemented in programming. One key thing to remember is that abstraction is contextual i.e. keeps on changing as per context
Python

Following on from my previous question, , I have now come across a problem regarding the timezone, and it turns out that it's not always going to be \"+0200\". So when strptime tries to parse it as such, it throws up an exception.I thought about just chopping off the +0200 with [:-6] or whatever, but is there a real way to do this with strptime?I am using Python 2.5.2 if it matters.It looks like this is implemented only in >= 2.6, and I think you have to manually parse it.I can't see another solution than to remove the time zone data:No, but since your format appears to be an RFC822-family date, you can read it much more easily using the  library instead:(7200 = timezone offset from UTC in seconds)You can use the  library which is very useful:As far as I know,  doesn't recognize numeric time zone codes. If you know that the string is always going to end with a time zone specification of that form (+ or - followed by 4 digits), just chopping it off and parsing it manually seems like a perfectly reasonable thing to do.It seems that %Z corresponds to time zone names, not offsets.For example, given:I can parse:Although it seems that it doesn't do anything with the time zone, merely observing that it exists and is valid:I suppose if you wished, you could locate a mapping of offsets to names, convert your input, and then parse it.  It might be simpler to just truncate your input, though.
Python

I'm writing Python code. I want to check if numpy and wxpython are installed on machine. How to do that??You can try importing them and then handle the ImportError if the module doesn't exist.I think you also may use thisThe traditional method for checking for packages in Python is \"it's better to beg forgiveness than ask permission\", or rather, \"it's better to catch an exception than test a condition.\"In the numpy README.txt file, it saysThis should be a sufficient test for proper installation. If you use eclipse, you simply type \"import numpy\" and eclipse will \"complain\" if doesn't find. 
Python

I'm trying to perform an element wise divide in python, but if a zero is encountered, I need the quotient to just be zero.For example:I could always just use a for-loop through my data, but to really utilize numpy's optimizations, I need the divide function to return 0 upon divide by zero errors instead of ignoring the error.Unless I'm missing something, it doesn't seem  can return values upon errors. Does anyone have any other suggestions on how I could get the best out of numpy while setting my own divide by zero error handling?Building on @Franck Dernoncourt's answer, fixing -1 / 0:Building on the other answers, and improving on:Code:Output:In numpy v1.7+, you can take advantage of the \"where\" option for .  You can do things in one line and you don't have to deal with the errstate context manager.In this case, it does the divide calculation anywhere 'where' b does not equal zero.  When b does equal zero, then it remains unchanged from whatever value you originally gave it in the 'out' argument.Try doing it in two steps. Division first, then replace.The  line is optional, and just prevents numpy from telling you about the \"error\" of dividing by zero, since you're already intending to do so, and handling that case.This is a neat trick  more than they hate warnings:You can also replace based on , only if the array dtypes are floats, as per :One answer I found searching a related question was to manipulate the output based upon whether the denominator was zero or not.Suppose  and  have been initialized, but  has some zeros. We could do the following if we want to compute  safely.In this case, whenever I have a divide by zero in one of the cells, I set the cell to be equal to , which in this case would be zeroFootnote: In retrospect, this line is unnecessary anyways, since  is instantiated to zero. But if were the case that , this operation would do something.
Python

I'm new to Python and programming in general (a couple of weeks at most).Concerning Python and using modules, I realise that functions can imported using .So instead of typingI can saywhich I find simplifies things a great deal. Now, say I have a bunch of  that I want to use across modules and I have them all defined in one python module. How can I, using a similar method as mentioned above or an equally simple one, import these variables. I don't want to use  and then be required to prefix all my variables with .The following situation would by ideal:a.pyb.pyOutput:You gave the solution yourself:  will work just fine. Python does not differentiate between functions and variables in this respect.Just for some context, most linters will flag  with a warning, because it's prone to namespace collisions that will cause headaches down the road.Nobody has noted yet that, as an alternative, you can use theform and then use  and  directly (without the  prefix). The  form is more future proof because you can easily see when one import will be overriding another.Also note that \"variables\" aren't different from functions in Python in terms of how they're addressed -- every identifier like  or  is pointing at some kind of object. The identifier  is pointing at a string object,  is pointing at a function object, and  is pointing at an integer object. When you tell Python:you're saying \"take those objects pointed at by  and  within module  and point at them in the current scope with the same identifiers\".Similarly, if you want to point at them with different identifiers on import, you can use theform. The same function object gets pointed at, except in the current scope the identifier pointing at it is  whereas in module  the identifier pointing at it is .Like others have said,will also import the modules variables.However, you need to understand that you are  importing variables, just references to objects. Assigning something else to the imported names in the importing module  affect the other modules.Example: assume you have a module  containing the following code:Then you have two other modules,  and  which both do the following:In each module, two names,  and  are created, pointing to the objects  and , respectively.Now, if somewhere in  you assign something else to the global name :the name  in  and the name  in  will still point to the object .So  will work if you want read-only globals, but it won't work if you want read-write globals. If the latter, you're better off just importing  and then either getting the value () or setting the value () prefixed by the module.You didn't say this directly, but I'm assuming you're having trouble with manipulating these global variables.If you manipulate global variables from inside a function, you must declare them globalIf you don't do that, then  will just create a local variable and assign it 15, while the global a stays 10
Python

I was having trouble implementing , so I copied the code right off of the documentation:and I got:instead of:as is shown in the doc.I'm using Python 2.6 on Windows 7What's going on?Yes it does, it works exactly as documented.  a new namedtuple, it does not modify the original, so you need to write this:See here:  for more information.A tuple is immutable.  returns a new tuple with your modifications: returns a new tuple; the original is unchanged.It looks to me as if namedtuple is immutable, like its forebear, tuple. returns a new  of the same type but with values changed.
Python

How do I access a private attribute of a parent class from a subclass (without making it public)?My understanding of Python convention isOptions for if you control the parent classIf you don't control itSome language designers subscribe to the following assumption:These language designers will feel tempted to protect programmers from each other by introducing a  specifier into their language.\nShortly later they recognize that this is often too inflexible and introduce  as well.Language designers such as Python's Guido van Rossum, in contrast, assume that programmers are responsible adults and capable of good judgment (perhaps not always, but typically).\nThey find that everybody should be able to access the elements of a program if there is a need to do that, so that the language does not get in the way of doing the right thing.\n(The only programming language that can successfully get in the way of doing the  thing is the  language)Therefore,  in Python means something like \"The designer of this module is doing some non-obvious stuff with this attribute, so please do not modify it and stay away from even reading it if you can -- suitable ways to access relevant information have been provided.\"In case you are not able to stay away from accessing  (such as in special cases in a subclass), you simply access it.Using  and    to do what you wante.gif the variable name is \"__secret\" and the class name is \"MyClass\" you can access it like this on an instance named \"var\"var._MyClass__secretThe convention to suggest/emulate protection is to name it with a leading underscore: self._protected_variable = 10Of course, anybody can modify it if it really wants.Make an accessor method, unless I am missing something:
Python

I'm trying to get this Python MYSQL update statement correct(With Variables):Any ideas where I'm going wrong?It :You can  do it with basic string manipulation,but . As it's so easy (and similar) to do it the . Do it correctly. The only thing you should be careful, is that some database backends don't follow the same convention for string replacement (SQLite comes to mind).You've got the syntax all wrong:For more, .This is the right way\uff1aP.S. Don't forget , or it won't workNeither of them worked for me for some reason.I figured it out that for some reason python doesn't read %s. So use (?) instead of %S in you SQL Code.And finally this worked for me.
Python

I can't find the correct way to install a local directory as a python package using pip.As you can see pip just copied over the package to site-packages. How can I avoid this, and use the package directly from its source folder?I'm trying to integrate django-pipeline into my Django project, but I want to add support for Django 1.4 first, so I forked and cloned my fork. works by installing packages to your .  If you just want to  your module regularly, all you have to do is add the directory path to your  environmental variable.I can also just use:orIf you're working in a venv, you can do this:env/bin/pip install git+file:///path/to/your/git/repoOr with a branch:env/bin/pip install git+file:///path/to/your/git/repo@mybranch
Python

I've got mssql 2005 running on my personal computer with a database I'd like to run some python scripts on. I'm looking for a way to do some really simple access on the data. I'd like to run some select statements, process the data and maybe have python save a text file with the results.Unfortunately, even though I know a bit about python and a bit about databases, it's very difficult for me to tell, just from reading, if a library does what I want. Ideally, I'd like something that works for other versions of mssql, is free of charge and licensed to allow commercial use, is simple to use, and possibly works with ironpython.I use  with cPython (I don't know if it'll work with IronPython though).  It'll be pretty familiar to you if you've used Hibernate/nHibernate.  If that's a bit too verbose for you, you can use , which is a thin layer on top of SQL Alchemy.  To use either one of those, you'll need , but that's a pretty simple install.Of course, if you want to write straight SQL and not use an ORM, you just need pyodbc.Everyone else seems to have the cPython -> SQL Server side covered. If you want to use IronPython, you can use the standard ADO.NET API to talk to the database:If you've already got IronPython, you don't need to install anything else.Lots of docs available  and .pyodbc comes with Activestate Python, which can be downloaded from .  A minimal odbc script to connect to a SQL Server 2005 database looks like this:I also successfully use  with CPython. (With and without SQLAlchemy). can be used with either CPython or IronPython. I have been very pleased with it. () works under PyPy, Ironpython and CPython. shows a Hello World sample of accessing mssql in Python.PyPyODBC has almostly same usage as pyodbc, as it can been seen as a re-implemenation of the pyodbc moudle. Because it's written in pure Python, it can also run on IronPython and PyPy.Actually, when switch to pypyodbc in your existing script, you can do this:I've used  with standard python and liked it. Probably easier than the alternatives mentioned if you're  looking for basic database access.Sample .If you are want the quick and dirty way with CPython (also works for 3.X python):Install PYWIN32 after you install python Import the following library:\nimport odbcI created the following method for getting the SQL Server odbc driver (it is slightly different in naming depending on your version of Windows, so this will get it regardless):Note: if you use the above function, you'll need to also import these two libraries: winreg and reThen you use the odbc API 1 information as defined here: Your connection interface string should look something like this (assuming you are using my above method for getting the ODBC driver name, and it is a trusted connection):This method has many down sides.  It is clumsy because of only supporting ODBC API 1, and there are a couple minor bugs in either the API or the ODBC driver that I've run across, but it does get the job done in all versions of CPython in Windows.
Python

I know Django 1.1 has some new aggregation methods. However I couldn't figure out equivalent of the following query:Is it possible with Django 1.1's Model Query API or should I just use plain SQL?If you are using Django 1.1 beta (trunk):Django 1.1 does support aggregation methods like count. You can find .To answer your question, you can use something along the lines of:This will need slight tweaking depending on your actual model.Edit: The above snippet generates aggregations on a per-object basis. If you want aggregation on a particular field in the model, you can use the  method: is needed because fields that are in the default ordering are automatically selected even if they are not explicitly passed to . This call to  clears any ordering and makes the query behave as expected.Also, if you want to count the field that is used for grouping (equivalent to ), you can use:
Python

I'm trying to find a way to lazily load a module-level variable.Specifically, I've written a tiny Python library to talk to iTunes, and I want to have a  module variable. Unfortunately, iTunes won't tell you where its download folder is, so I've written a function that grabs the filepath of a few podcast tracks and climbs back up the directory tree until it finds the \"Downloads\" directory.This takes a second or two, so I'd like to have it evaluated lazily, rather than at module import time.Is there any way to lazily assign a module variable when it's first accessed or will I have to rely on a function?You can't do it with modules, but you can disguise a class \"as if\" it was a module, e.g., in , code...:Now anybody can ... and get in fact your  instance. The  is there to let you access anything else in  that may be more convenient for you to code as a top-level module object, than inside !_)I used Alex' implementation on Python 3.3, but this crashes miserably:\nThe codeis not correct because an  should be raised, not a .\nThis crashed immediately under Python 3.3, because a lot of introspection is done\nduring the import, looking for attributes like ,  etc.Here is  the version that we use now in our project to allow for lazy imports\nin a module. The  of the module is delayed until the first attribute access\nthat has not a special name:The module now needs to define an  function. This function can be used\nto import modules that might import ourselves:The code can be put into another module, and it can be extended with properties\nas in the examples above.Maybe that is useful for somebody.I think you are correct in saying that a function is the best solution to your problem here. \nI will give you a brief example to illustrate.The expensive operation will be executed on import if it is at module level. There is not a way to stop this, short of lazily importing the entire module!!You will be following best practice by using this method.Recently I came across the same problem, and have found a way to do it.With this , You can define a  method for the object, and the object will be initialized lazily, example code looks like:the  object above will have exactly the same methods whatever  object have, for example, you can do:complete code with tests (works in 2.7) can be found here:If that variable lived in a class rather than a module, then you could overload getattr, or better yet, populate it in init.
Python

I have been learning a bit of Python 2 and Python 3 and it seems like Python 2 is overall better than Python 3. So that's where my question comes in. Are there any good reasons to actually switch over to python 3?On the whole, and even in most details, Python3 is better than Python2.The only area where  is .  What makes Python great is not only its intrinsic characteristics as a language and its rather extensive standard library, but also the existence of a whole \"\" of libraries which support so many specific applications of the language.\nSeveral such libraries are, at the moment not fully ported to Python 3.x and this sometimes results in keeping people developing under Python 2.x.: Application developers won't move to 3.x till the libraries \"get there\", libraries developers would rather only maintain one branch and are waiting in an attempt to time the porting to Py3k in a way that they can put the their Py2.x branches in maintenance shortly thereafter.This situation is somewhat of a testimony the satisfaction people have of Python 2.x (or phrased more negatively, to the lack of truly  incentives for a move to 3.x; while Py3k is better and poised for better things yet, as-is, it doesn't have any features that would prompt a move to 3.x \"\".)  This said,  I believe . \nTo back this up, I was about to mention the likelihood that  be only ported to Py3k-only, providing some strong incentive for the move.  But Alex Martelli has started answering this question, and is using this example.  Obviously Alex speaks first-hand of these roadmap questions, please get it from the Master!:  Be sure to use the  version (currently 3.1.2,  soon 3.2.x will replace it as the most recent  version).  Beware that some folks (like me) occasionally use the expression  to reference the generic name for all Py3k (or even for the current version thereof).  The short lived 3.0 version  is now \"defunct\" and of no interest but maybe forensic specialists ;-)As other answers mention, the only real (and crucial) current advantage of Python 2 over Python 3 is that the former already has a huge wealth of third-party extensions (and auxiliary tools, such as IDEs and the like), which the latter is only gradually moving towards.  This is a situation that's gradually improving, as existing extensions are ported to support Python 3; sooner or later somebody will release a Py3-only extension or tool that's important to you, and that might tip you over to actually using Py3 for a new project (and that will happen for many different values of \"you\";-).Python core development has mostly shifted to the Python 3 area -- while Python 2.7 will be out soon, I'm not sure how many future important enhancements, if any, will keep getting backported to Python 2 versions.  In particular, I doubt that Unladen Swallow will be -- if that's the case, then at some point CPython 3 will gain an important speed advantage over CPython 2, which will be the tipping-over factor for other new projects (and ports of existing projects) yet.Not sure what gives you the impression that \"Python 2 is over all better than Python 3\", in terms, of course, of just \"Python proper\", i.e., the parts that the Python Software Foundation is releasing (core code, libraries, docs...): I strongly disagree with this assessment.  Python 3 is better in terms of simplicity (cruft removal) and in having a few features that enable future third-party extensions and tools (such as better metaclass interaction, and syntax for parameter annoutation); I cannot find, in fact, any advantages for Python 2 in terms of \"Python proper\".  The \"ecosystem\" around Python, as already discussed, is another thing, but that's already progressing (at its own pace, of course, which is definitely  under the control of the Python Software Foundation, but rather of many external groups of developers and a few firms).For example, PyQt is already available for Python 3 (as well as 2), and you can use PostgreSQL (a splendid open-source SQL database engine, much more standard than MySql) via . So, if the third party extensions you're pining for are (say) wxpython and mysqldb, perhaps you can try these alternatives (I'm biased, of course, since I've long preferred Qt to wxWidgets, and PostgreSQL to MySQL, on purely technical grounds -- but the prompt porting of the related Python extensions to Python 3 does also hint that these extensions are being more actively and vigorously developed, so that might be another nudge to try them;-).Python 3 is going to be the new standard going forward. As no major sweeping changes are planned to Python 3 anytime soon, more people will eventually be moving to it. So... although there are many Python 2 applications around now, eventually  many of these applications will be migrated up. There is even at tool for this, .Also, what makes you say that python 2 is better than 3? There were many language improvements made in Python 3, and even IDLE is improved. The main thing holding Python 3.x back right now is the lack of third-party libraries.  I'll be converting my code as soon as SciPy gets ported.More iterators (in things like ) will be a big boost for web applications.The core team will put more work into the new version. New books might focus on python 3 (see Dive into Python), but the real work is still done in python 2.Sooner or later, the big libraries (numpy, wx, django) will be ported. Until those big three switch, I can't see many people using python 3. But those aren't impossible projects to port.Once the big libraries are ported, the community will face a real choice. That's when it will start to catch on.
Python

I'm trying to create a histogram with argument normed=1For instance:I expected that the sum of the bins would be 1. But instead, one of the bin is bigger then 1. What this normalization did? And how to create a histogram with such normalization that the integral of the histogram would be equal 1?See my other post for how to make the sum of all bins in a histogram equal to one:\nCopy & Paste:where myarray contains your dataAccording to   This is from numpy doc, but should be the same for pylab.So simply normalization is done according to the documentation like:I think you are confusing bin heights with bin contents. You need to add the contents of each bin, i.e. height*width for all bins. That should = 1.I had the same problem, and while solving it another problem came up: how to plot the the normalised bin frequences as percentages with ticks on  values. I'm posting it here in case it is useful for anyone. In my example I chose 10% (0.1) as the maximum value for the y axis, and 10 steps (one from 0% to 1%, one from 1% to 2%, and so on). The trick is to set the ticks at the  counts (which are the output list  of the ) that will next be transformed into percentages using the  class. Here's what I did:Before normalisation: the y axis unit is number of samples within the bin intervals in the x axis:\nAfter normalisation: the y axis unit is frequency of the bin values as a percentage over all the samples\nIn order to normalize a sequence, you have to take into account the bin size.\nAccording to the  , the default number of bin is 10. Consequently, the bin size is , that is 0.41.\nIf , then the heights of the bar is such that the sum, multiplied by 0.41, gives 1. This is what happens when you integrate.I think that you want the sum of the histogram, not its integral, to be equal to 1. In this case the quickest way seems:There is also an analogue in numpy - : \nOne of the parameters is \"density\", If you set , the output will be normalised.
Python

I'm going through Zed Shaw's Learn Python The Hard Way and I'm on lesson 26. In this lesson we have to fix some code, and the code calls functions from another script. He says that we don't have to import them to pass the test, but I'm curious as to how we would do so. | And here are the particular lines of code that call on a previous script:It depends on how the code in the first file is structured.If it's just a bunch of functions, like:Then you could import it and use the functions as follows:oror, to import  the symbols defined in first.py:Note: This assumes the two files are in the same directory.It gets a bit more complicated when you want to import symbols (functions, classes, etc) in other directories or inside modules.It's worth mentioning that (at least in python 3), in order for this to work, you must have a file named  in the same directory.
Python

How can I insert some seed data in my first migration? If the migration is not the best place for this, then what is the best practice?Alembic has, as one of its operation, . The documentation gives the following example (with some fixes I've included):Note too that the alembic has an  operation, which is just like the normal  function in SQLAlchemy: you can run any SQL you wish, as the documentation example shows:Notice that the table that is being used to create the metadata that is used in the  statement is defined directly in the schema. This might seem like it breaks  (isn't the table already defined in your application), but is actually quite necessary. If you were to try to use the table or model definition that is part of your application, you would break this migration when you make changes to your table/model in your application. Your migration scripts should be set in stone: a change to a future version of your models should not change migrations scripts. Using the application models will mean that the definitions will change depending on what version of the models you have checked out (most likely the latest). Therefore, you need the table definition to be self-contained in the migration script.Another thing to talk about is whether you should put your seed data into a script that runs as its own command (such as using a Flask-Script command, as shown in the other answer). This can be used, but you should be careful about it. If the data you're loading is test data, then that's one thing. But I've understood \"seed data\" to mean data that is required for the application to work correctly. For example, if you need to set up records for \"admin\" and \"user\" in the \"roles\" table. This data SHOULD be inserted as part of the migrations. Remember that a script will only work with the latest version of your database, whereas a migration will work with the specific version that you are migrating to or from. If you wanted a script to load the roles info, you could need a script for every version of the database with a different schema for the \"roles\" table. Also, by relying on a script, you would make it more difficult for you to run the script between migrations (say migration 3->4 requires that the seed data in the initial migration to be in the database). You now need to modify Alembic's default way of running to run these scripts. And that's still not ignoring the problems with the fact that these scripts would have to change over time, and who knows what version of your application you have checked out from source control.Migrations should be limited to schema changes only, and not only that, it is important that when a migration up or down is applied that data that existed in the database from before is preserved as much as possible. Inserting seed data as part of a migration may mess up pre-existing data.As most things with Flask, you can implement this in many ways. Adding a new command to Flask-Script is a good way to do this, in my opinion. For example:So then you run:MarkHildreth has supplied an excellent explanation of how alembic can handle this. However, the OP was specifically about how to modify a flask-migration migration script. I'm going to post an answer to that below to save people the time of having to look into alembic at all.\nMiguel's answer is accurate with respect to normal database information. That is to say, one should follow his advice and absolutely not use this approach to populate a database with \"normal\" rows. This approach is specifically for database rows which are required for the application to function, a kind of data which I think of as \"seed\" data.Flask migrate generates migration scripts at . These scripts are run in order on a database in order to bring it up to the latest version. The OP includes an example of one of these auto-generated migration scripts. In order to add seed data, one must manually modify the appropriate auto-generated migration file. The code I have posted above is an example of that. Very little. You will note that in the new file I am storing the table returned from  for  in a variable called . We then operate on that table using  to create a few example rows.
Python

What's the easiest way to determine which version of  is installed?As of flask 0.7 (June 28th, 2011), a  attribute can be found on the flask module.Keep in mind that because prior to flask 0.7 there was no  attribute, the preceding code will result in an attribute error on those older versions.For versions older than flask 0.7, you might be able to determine it using pkg_resources as shown below:This won't work 100% though. It depends on the user having the pkg_resources library installed (it might come by default with a Linux distribution's python installation, but since it's not part of the standard library you can't be positive), and also that the user installed flask in a way that pkg_resources can find it (for example, just copying the full flask source code into your directory puts it out of the range of pkg_resources).Via the python interpreter.If flask was installed via pip or easy_install, you can always use the 'pip freeze' command.More general way of doing it is :It will list all installed python packages and their versions.\nIf you want to see just flask then try :      using dpkg:output:
Python

I am following a previous thread on how to plot confusion matrix in Matplotlib. The script is as follows:I would like to change the axis to show string of letters, say (A, B, C,...) rather than integers (0,1,2,3, ..10). How can one do that. Thanks.musaHere's what I'm guessing you want:\nJust use  and .E.g.
Python

Guys, I just started python recently and get confused with the optional parameters, say I have the program like this:If I create A twiceand print their buildsI found they are using the exactly same object,But it is not what I want, since if  changed some internal state of builds, the one in  object will also be changed.Is it possible to recreate this optional parameters each time by using this optional parameters syntax?You need to understand how default values work in order to use them effectively.Functions are objects.  As such, they have attributes.  So, if I create this function:I've created an object.  Here are its attributes:One of them is .  That sounds promising, what's in there?That's a tuple that contains the function's default values.  If a default value is an object, the tuple contains an instance of that object.  This leads to some fairly counterintuitive behavior if you're thinking that  adds an item to a list, returning a list containing only that item if no list is provided:But if you know that the default value is an object instance that's stored in one of the function's attributes, it's much less counterintuitive:Knowing this, it's clear that if you want a default value of a function's parameter to be a new list (or any new object), you can't simply stash an instance of the object in .  You have to create a new one every time the function is called:you need to do the following:it's a very wide-spread error, using mutable parameters as a default arguments. there are plenty of dupes probably on SO.Yes; default parameters are evaluated only at the time when the function is defined.One possible solution would be to have the parameter be a  rather than an instance, a la
Python

I'm making a game link site, where users can post links to their \nfavorite web game. \nWhen people post games they are supposed to check what category the \ngame falls into. \nI decided to allow many categories for each game since some games can \nfall into many categories. \nSo the question is, how do I handle this in my view? \nAnd how can I show it as Checkboxes, where at least one has to be \nchecked? \nAnd how can I show this as checkboxes in the Admin as well? Thanks! that should fix your view, but i'm not sure about the admin. still looking... will edit if i find anything.Here is how I solved it (Edit: and the admin thing)(It was the queryset part I couldn't find..)And that's all the code needed to save the data.Edit:\nhere is a solution for the adminIt's kind of quirky in looks, but works!\nIf someone finds a way to make it more \"clean\" please post!Cheers!+1 for the admin part in the answer @Gr\u00e9tar J\u00f3nsson. Just a minor correction:In the \"Models:\" section you also need to import models:(A bit silly that you need reputation to comment directly on other peoples posts)
Python

Has anyone had issues setting up a debug configuration for Django project in PyCharm Community Edition?\nCommunity Edition of the IDE is lacking the project type option on project setup and then when I am setting up Debug or Run config it asks me for a script it should run. What script would it be for Django, manage.py?\nThanks in advanceYes you can.
Python

I have the following code:this will printwhile I'd like it to printIs any way there to do this without having to writePS: img.size is a PIL image. Dunno if that matters anything in this case.Might be a nicer way, but this should workThe  way would be using a list comprehension:Another way could be:Solution:Explanation:  make direct scalar multiplication possible. Hence the  called  here is converted to an . I assume you wish to keep using the , hence we convert the  back to a .This solution is to avoid the explicit and verbose  loop. I do not know whether it is faster or whether the exact same thing happens in both cases.There is probably a simpler way than this, butWill do nearly what you want, although it prints as a list rather than a tuple. Wrap the  call inside  if you want it to print as a tuple (parentheses rather than square brackets).If you have this problem more often and with larger tuples or lists then you might want to use the  library, which allows you to do all kinds of mathematical operations on arrays. However, in this simple situation this would be complete overkill.You can try something like this:It will give you a new list with all the elements you have in the tuple multiplied by 10In line with the previous answers but using numpy:adding nothing but variety..
Python

Is it preferred to do:orSame thing for \"is not\"  is different than . is true if and only if  -- that is,   and  have to be one and the same object (with the same s).For all built-in Python objects (like strings, lists, dicts, functions, etc.), if ,  then  is also True. However, this is not guaranteed in general. Strictly speaking,  is true if and only if  returns True. It is possible to define an object  with a  method which always returns False, for example, and this would cause  to return False, even if . So the bottom line is,   and   are completely different tests.Consider this for example:PS. Instead ofit is more Pythonic to writeAnd similarly,can be replaced with compares the identities of the two objects, and is asking  It is equivalent to . uses the equality operator and asks the looser question  For user defined types it is equivalent to .The  special method should represent 'equalness' for the objects, for example a class representing fractions would want 1/2 to equal 2/4, even though the 'one half' object couldn't have the same identity as the 'two quarters' object.Note that it is not only the case that  does not imply , but also the reverse is true. One is not in general a more stringent requirement than the other. Yes, this means that you can have  return  if you really want to, for example:In practice though  is  always a more specific comparison than .as others have already said,  (and ) are only when you actually  that a pair of variables are referring to exactly the same object. in most cases, you really don't care at all, so you would use  and .however, what you may start to notice, if you look at a lot of Python code, is that  (and ) are more likely to be used when comparing against , , and . the main reason for this is that those objects are singletons, meaning there is exactly one instance of each of those values. why does that matter? well, this leads to another reason... speed.with  and , the interpreter has to pull up both referred objects in order to make a comparison (of whether they're the same or not), while  and  simply just check the values of the objects they're referring to. with this said, you can see that  the latter pair will perform faster because you don't have to fetch the objects themselves in order to make the comparison. here's a speed test from a couple of years back where we concluded that for one-offs, it's not a big deal, but if it's called a gazillion times in a tight loop, well, it will start to add up.bottom line is that you can use object identity comparisons for checking against , , and , and everything else should use straight-up equality operators. we won't get into interned integers nor bound instance methods, or anything like that here. :-)Depends.  and  do identity comparison, which is good for , , or making sure that two objects are the same. Otherwise, use  or .
Python

Is there a better way to print the + sign of a digit on positive numbers?0 should return 0 without +.Here is .** Update** If for whatever reason you can't use the  operator, you don't need a function:Use the It's recommended over the  operator
Python

on my computerbut I get into problems when I run some python programs. my guess is (or at least I want to try this) that there is some backward compatibility issues, and I want to run those python scripts with which is also installed on my system but I do not know how to make it as the (temporary) default python. The python script starts withand I am using arch linux.You can use Enjoy!Just call the script using something like python2.7 or python2 instead of just python.So:instead of:What you could alternatively do is to replace the symbolic link \"python\" in /usr/bin which currently links to python3 with a link to the required python2/2.x executable. Then you could just call it as you would with python 3.You don't want a \"temporary default Python\"You want the 2.7 scripts to start withAnd you want the 3.2 scripts to begin with There's really no use for a \"default\" Python.  And the idea of a \"temporary default\" is just a road to absolute confusion.Remember.You could use :To stop using python2,  or .Use python command to launch scripts, not shell directly. E.g.AFAIK this is the recommended method to workaround scripts with bad env interpreter line.
Python

I cannot seem to find a good simple explanation of what python does differently when running with the -O or optimize flag.  statements are completely eliminated, as are statement blocks of the form  (so you can put your debug code in such statements blocks and just run with  to avoid that debug code).With , in addition, docstrings are also eliminated.From :So in other words, almost nothing.From As answered in :python -O does the following currently:and when called as python -OOI don't know why everyone forgets to mention the  issue; perhaps it is because I'm the only one using it :) An  construct creates no bytecode at all when running under , and I find that very useful.
Python

If you happen to havein the middle of your program (or module), you would get the warning:I understand why  is discouraged in general (namespace invisibility),\nbut there are many situations where it would prove convenient, especially where\ncode is not shared with anyone.So, can anyone explain precisely in detail why  should\nbe prohibited in all possible cases?I believe by \"in the middle of your program\" you are talking about an import  a function definition:This is not allowed because it would make optimizing the body of the function too hard.  The Python implementation wants to know all of the names of function-local variables when it byte-compiles a function, so that it can optimize variable references into operations on the (CPython) virtual machine's operand stack, or at least to local variable-slot operations rather than lookups in outer namespaces.  If you could dump the entire contents of a module into a function's local namespace, then the compiler would have to assume that  name in the function might possibly refer to a module global, because the list of names brought in by  is only known at runtime.Putting   top-level declarations is poor style, but it's allowed: While looking into something else, I discovered that this restriction was introduced in Python 2.1, as a consequence of the  ().  Quoting from the link:This clarifies the Python 3.x vs 2.x behavior discussed in the comments.  It is always contrary to the language specification, but CPython 2.1 through 2.7 only issue an error for  within a function if it might affect the compiler's ability to know whether a variable binds locally or in a containing scope.  In 3.x it has been promoted to an unconditional error. ... and apparently flashk pointed this out years ago in another answer, quoting the same paragraph of \"What's New in Python 2.1\" yet.  Y'all go upvote that now.At any lexical level,  is a \"seemed a good idea at the time\" design decision that has proven a real disaster in real life, with the  exception of handy exploration at the interactive interpreter prompt (even then, I'm not too hot on it --  forces only two extra characters to use qualified names instead [[just an  prefix]],  qualified names are always sharper and more flexible than barenames, not to mention the great usefulness in exploratory interactive situations of having  available for , , and the like!).This bedraggled construct makes it very hard, for the poor person reading the code (often in a doomed attempt to help debug it) to understand where mysteriously-appearing names are coming from -- impossible, if the construct is used more than once on a lexical level; but even when used just once, it forces laborious re-reading of the whole module every time before one can convince oneself that, yep, that bedraggled barename must come from the module.Plus, module authors usually don't go to the extreme trouble needed to \"support\" the horrid construct in question.  If somewhere in your code you have, say, a use of  (and an  at the very top of your module, of course), how do you  that  is the module it should be... or some completely different one (or a non-module) coming from the ?!  Multiply that by all the qualified names you're using, and misery is the only end result -- that, and mysterious bugs requiring long, laborious debugging (usually with the reluctant help of somebody who  \"get\" Python...!-)., a way to add and override arbitrary local names would be even worse.  As an elementary but crucial optimization, the Python compiler looks around the function's body for any assignment or other binding statements on each barename, and deems \"local\" those names it sees thus assigned (the others must be globals or built-ins).  With an  (just like with an  without explicit dicts to use as namespaces), suddenly it becomes a total mystery which names are local, which names are global -- so the poor compiler would have to resort to the slowest possible strategy for each name lookup, using a dict for local variables (instead of the compact \"vector\" it normally uses) and performing up to three dict look-ups for each barename referenced, over and over.Go to any Python interactive prompt.  Type .  What do you see?  The Zen of Python.  What's the last and probably greatest bit of wisdom in that text...?By forcing the use of barenames where qualified names are  vastly preferable, you're essentially doing the very  of this wise recommendation: instead of admiring the greatness and honkingtude of namespaces, and doing more of those, you're  two perfectly good and ready-to-use namespaces (that of the module you're importing, and that of the lexical scope you're importing it in) to make a single, unholy, buggy, slow, rigid, unusable mess.If I could go back and change  early design decision in Python (it's a hard choice, because the use of  and especially  for what Javascript so much more readably calls  is a close second;-), I would retroactively wipe out the  idea from Guido's mind.  No amount of  convenience for exploration at the interactive prompt can balance the amount of evil it's wrought...!-)The  seem to explain why this limitation exists:... it's handy for quick scripts and shell exploring. It's not prohibited at all. It works fine, but you get a warning because it's generally a bad idea (for reasons others have gone into). You can, if you like, suppress the warning; the warnings module is what you want for that.others have given in-depth answers, I'll give a short overview answer of my understanding.. when using from you are making it so you can directly call any function in that module you imported without doing modulename.functioname (you can just call \"functionname\") this creates problems if you have 2 functions of the same name in different modules and also can create confusion when dealing with a lot of functions as you don't know what object/module it belongs to (from point of view of someone looking over already written code that isn't familiar with it)
Python

What are the new commands & or equivalents of:I know they have changed to , ,  but there doesn't seem to be an example of how to properly use each one. For example, if I use  I get the following: To list:To show:To select:
Python

Is it possible to have missing values in scikit-learn ? How should they be represented? I couldn't find any documentation about that.The above answer is outdated; the latest release of scikit-learn has a class  that does simple, per-feature missing value imputation. You can feed it arrays containing NaNs to have those replaced by the mean, median or mode of the corresponding feature.I have come across very similar issue, when running the  on data. The presence of NA values were throwing out \"nan\" for predictions. From scrolling around several discussions, the Documentation by Breiman recommends two solutions for continuous and categorical data respectively.According to Breiman the random nature of the algorithm and the number of trees will allow for the correction without too much effect on the accuracy of the prediction. This I feel would be the case if the presence of NA values is sparse, a feature containing many NA values I think will most likely have an affect.I wish I could provide a simple example, but I have found that RandomForestRegressor does  handle nan's gracefully. Performance gets steadily worse when adding features with increasing percentages of nan's. Features that have \"too many\" nan's are completely ignored, even when the nan's indicate very useful information.AFAIK the algorithm will never create a split on the decision \"isnan\" or \"ismissing\". The algorithm will ignore the feature at a particular level of the tree if the feature has only one known value and the rest of the feature's values are nan/unknown.My solution: replace nan's with a single \"clearly out-of-range\" value (like -1.0). This enables the tree to split on the criteria \"known values vs unknown values\". I  tried more advanced imputation techniques (replace with mean/median, predict missing value's \"true\" value, etc.), but the results were mixed. However, there is a problem with replacing with such out-of-range values: known values could get lumped together with the out-of-range value when the algorithm tries to find a good place to split. For example, the minimum known value could get lumped with your out-of-range value (your known 0's get lumped with the -1's that you used to replace your nan values). So your model could change depending on if your out-of-range value is less than the minimum or if it's greater than the maximum (it could get lumped in with the minimum value or maximum value, respectively).Replacing a missing value with a mean/median/other stat may not solve the problem as the fact that the value is missing may be significant. For example in a survey on physical characteristics a respondent may not put their height if they were embarrassed about being abnormally tall or small. This would imply that missing values indicate the respondent was unusually tall or small - the opposite of the median value.What is necessary is a model that has a separate rule for missing values, any attempt to guess the missing value will likely reduce the predictive power of the model. is another python machine learning library that has facilities dedicated to imputation. I have not had a chance to use them, but might be soon, since the simple methods of replacing nan's with zeros, averages, or medians all have significant problems.
Python

I'm trying to figure out a way of deleting (dynamically) subplots in matplotlib. I see they have a  method, but I get the errorI'm surprised that I can't find this anywhere.  Does anyone know how to do this?Wow, ok well I feel really stupid :PIn case anyone else needs it.
Python

In Python 2 there was an error when return was together with yield in function definition. But for this code in Python 3.3there is no error that return is used in function with yield. However when the function  is called then there is thrown exception StopIteration. Why there is not just returned value ? Is this return somehow ignored?This is a new feature in Python 3.3 (as a comment notes, it doesn't even work in 3.2). Much like  in a generator has long been equivalent to ,  in a generator is now equivalent to . For that reason, the exception you're seeing should be printed as , and the value is accessible through the attribute  on the exception object. If the generator is delegated to using the (also new)  syntax, it is the result. See  for details.This prints , but not .The return value is not ignored, but generators only  values, a  just ends the generator, in this case early. Advancing the generator never reaches the  statement in that case.Whenever a iterator reaches the 'end' of the values to yield, a   be raised. Generators are no exception. As of Python 3.3 however, any  expression becomes the value of the exception:Use the  function to advance iterators, instead of calling  directly:
Python

I can not save the image in this ImageField.You seem to be missing the  argument to the serializer constructor in the your  and  handlers.I think you can use  instead after . The usage of  and  is now pending deprecation in favor of a single  attribute that contains all the parsed data.You can check it from Uploading image files with Django Rest Framework:Hope it helps someone.Following should work if you are posting the image\nas base64 string and your serializer set accordingly and it inherits serializer.Serializer 
Python

I want to implement a function that gives information about all the tables (and their column names) that are present in a database (not only those created with SQLAlchemy). While reading the documentation it seems to me that this is done via reflection but I didn't manage to get something working. Any suggestions or examples on how to do this?start with an engine:quick path to all table /column names, use an inspector:docs: alternatively, use MetaData / Tables:docs: Hey I created a small module that helps easily reflecting all tables in a database you connect to with SQLAlchemy, give it a look: 
Python

What would be an easy expression to process command line arguments if I'm expecting anything like 001 or 999 (let's limit expectations to 001...999 range for this time), and few other arguments passed, and would like to ignore any unexpected?I understand if for example I need to find out if \"debug\" was passed among parameters it'll be something like that:How to find out if 009 or 575 was passed?All those are expected calls:At this point I don't care about calls like that:...first one - because of more than one \"numeric\" argument; second - because of... well, unexpected arguments; third and fourth - because of non-3-digits arguments.As others answered, optparse is the best option, but if you just want quick code try something like this:: Here's an optparse example because so many people are answering optparse without really explaining why, or explaining what you have to change to make it work.The primary reason to use optparse is it gives you more flexibility for expansion later, and gives you more flexibility on the command line.  In other words, your options can appear in any order and usage messages are generated automatically.  However to make it work with optparse you need to change your specifications to put '-' or '--' in front of the optional arguments and you need to allow all the arguments to be in any order.So here's an example using optparse:The differences here with optparse and your spec is that now you can have command lines like:and you can easily add new options by calling parser.add_option()Have a look at the  module.  Dealing with sys.argv yourself is fine for really simple stuff, but it gets out of hand quickly.Note that you may find optparse easier to use if you can change your argument format a little; e.g. replace  with  and  with  or . is your best friend for parsing the command line. Also look into ; it's not in the standard library, though.If you want to implement actual command line switches, give  a look. It's incredibly simple to use, too.Van Gale is largely correct in using the regular expression against the argument.  However, it is NOT absolutely necessary to make everything an option when using optparse, which splits sys.argv into options and arguments, based on whether a \"-\" or \"--\" is in front or not.  Some example code to go through just the arguments:Yes, the args array is parsed much the same way as sys.argv would be, but the ability to easily add options if needed has been added.  For more about optparse, check out the  .
Python

My deployment script overwrites the media and source directories which means I have to move the uploads directory out of the media directory, and replace it after the upload has been extracted.How can I instruct django to upload to /uploads/ instead of /media/?So far I keep getting django Suspicious Operation errors! :(I suppose another solution might be a symlink?Many thanks,\nToby.I did the following: is defined in my  file: 
Python

There is a snippet of code that I would like to copy and paste into my Python interpreter. Unfortunately due to Python's sensitivity to whitespace it is not straightforward to copy and paste it a way that makes sense. (I think the whitespace gets mangled) Is there a better way? Maybe I can load the snippet from a file. This is just an small example but if there is a lot of code I would like to avoid typing everything from the definition of the function or copy and pasting line by line. You can call execfile(filename). More or less the same as importing a module, except that it skips the module administration part and doesn't require you to add a folder to sys.path.EDIT: To address the original question: copy-pasted code can be executed by calling exec(codestring).You can usually easily and safely do copy-pasting with , through the commands  and .  This is very handy for testing code that you copy from web pages, for instance, or from your editor.  IPython also has a  command that runs a program and leaves you in a Python shell with all the variables that were defined in the program, so that you can play with them.In order to get help on these functions: , etc.You can just import the file into the python interpreter. This will load the class in, and allow you to run the code.For instance, create a file named \"bgcolors.py\" and copy and paste your code inside. Then using the python interpreter, you just type \"import bgcolors\" and you should be able to run it.You can read more here:You can use  which is much better python repl. It has command for getting input from  by using %edit command.  allows you to copy and paste code with proper indentation.The  interface does go to effort to preserve the proper indentation of pasted text. You can simply convert all tabs to spaces and remove  empty lines.\nSo you will be able to paste any code to python console (e.g.: python2.6)There is an inbuilt method call \"indent region & dedent region\" and you can just use it. After you paste a lot of code at once you can select them all and adjust the whitespace.My answer is specifically about copy-pasting into the standard python shell (only tested on linux).Depending on where the code comes from and how it is originally formatted  may or may not matter. In particular about your example snippet - copy-pasted from SO's code-formatted section - it doesn't matter (assuming the code is properly indented to be executable)., however, does cause trouble in the standard python interpreter because it normally is . In your snippet's case the empty line preceeding the  function definition ends/exits the class definition prematurely, so when the  definition line comes in an indentation error is detected:So you just need to pay attention at those empty lines. Your snippet needs just 2 multi-line copy-paste ops to work around that empty line.The only other thing I needed - for copy-pasting just sections of already indented code (say functions from inside classes) - one extra level of indentation to not need to re-do the indentation of the copied code. For that a leading  line prior to pasting the snippet and an  (i.e. empty line) after do the trick:I had this problem recently and ultimately just needed to change my editor's indentation setting from tabs to spaces. (I was running the interpreter using the OSX Terminal.) Once I did this, copy & paste worked fine.
Python

Say I have a dictionary like so:Is there a way that I can switch the keys and values to get:If you are using python 2.7 or 3.x you can use a dictionary comprehension instead:EditAs noted in the comments by JBernardo, for python 3.x you need to use  instead of Use this code (trivially modified) from the accepted answer at :Note that this assumes that the values in the original dictionary are unique.  Otherwise you'd end up with duplicate keys in the resulting dictionary, and that is not allowed.  And, as @wim points out, it also assumes the values are hashable.  See  if you're not sure what is and isn't hashable.Try this:maybe:Sometimes, the condition that the values are all unique will not hold, in which case, the answers above will destroy any duplicate values.The following rolls the values that might be duplicates up into a list:I'm sure there's a better (non-list-comp) method, but I had a problem with the earlier answers, so thought I'd provide my solution in case others have a similar use-case. P.S. Don't expect the dict to remain neatly arranged after any changes to the original! This method is a one-time use only on a static dict - you have been warned!
Python

This should be easy but I have just started toying with matplotlib and python. I can do a line or a scatter plot but i am not sure how to do a simple step function. Any help is much appreciated.It seems like you want .E.g. If you have non-uniformly spaced data points, you can use the  keyword argument for :Also available are  and .Just draw two lines, one at y=0, and one at y=1, cutting off at whatever  your step function is for?e.g. if you want to step from 0 to 1 at  and plot from  to :I think you want  or equally 's bar method. if not checkout the  for the many styles of plots you can do. Each image comes with example code showing you how to make it using matplotlib.In case someone just wants to  rather than actually plot it:
Python

Is it somehow possible to have certain output appear in a different color in the IPython Notebook?\nFor example, something along the lines of:The notebook has, of course, its own syntax highlighting. So I would be careful when using colour elsewhere, just to avoid making things harder to read for yourself or someone else (e.g., output should simply be in black, but you get parts in red if there is an exception).But (to my surprise), it appears that you can use ANSI escape codes (even in the browser). At least, I could:On the default Python prompt:In the notebook:(Obviously, I cheated here with the syntax highlighting of SO so that \"red\" is printed in the colour red in both examples. I don't think SO allows a user to set a colour for text.)I wouldn't really know another way to get colours.For more on ANSI escape codes, I'd suggest the . And if you find the above to verbose, you can of course write a wrapper function around this.Not with raw Python print. You will have to define a  on an object and return it  or call . I guess you could overwrite the built-in print to do it automatically...You could inspire from , code , ML discussion .you can use this library  and you can get all other official libraries of python in pypiSee the documentation in pypi.python.org or follow these steps\n1. pip install termcolor\n2. then goto ipython\ntypeThe first argument is what you want to print on console and second argument use that colorHere's a quick hack:[out]:If you just want a single color:  
Python

If I have 1000+ pdf files need to be merged into one pdf,Execute the above code\uff0cwhen ,An error message\uff1a\nI think this is a bug, If not, What should I do\uff1fI recently came across this exact same problem, so I dug into PyPDF2 to see what's going on, and how to resolve it.Use the  class instead of the  class.  I've tried to provide the following to as closely resemble your content as I could:The way you're using  and  is keeping each file open, and eventually causing Python to generate IOError 24.  To be more specific, when you add a page to the , you are adding references to the page in the open  (hence the noted IO Error if you close the file).  Python detects the file to still be referenced and doesn't do any garbage collection / automatic file closing despite re-using the file handle.  They remain open until  no longer needs access to them, which is at  in your code.To solve this, create copies in memory of the content, and allow the file to be closed.  I noticed in my adventures through the PyPDF2 code that the  class already has this functionality, so instead of re-inventing the wheel, I opted to use it instead.  I learned, though, that my initial look at  wasn't close enough, and that it only created copies .My initial attempts looked like the following, and were resulting in the same IO Problems:Looking at the PyPDF2 source code, we see that  requires  to be passed, and then uses the  function, passing in it's last page as the new files position.  does the following with  (before opening it with :We can see that the  option does accept a string, and when doing so, assumes it's a file path and creates a file object at that location.  The end result is the exact same thing we're trying to avoid.  A  object holding open a file until the file is eventually written!However, if we either make a file object of the file path string  a  object of the path string  it gets passed into , it will automatically create a copy for us as a  object, allowing Python to close the file.I would recommend the simpler , as others have reported that a  object may stay open in memory, even after calling .Hope this helped! I assumed you were using , not .  If you aren't, I highly recommend switching, as PyPDF is no longer maintained with the author giving his official blessings to Phaseit in developing PyPDF2.  If for some reason you cannot swap to PyPDF2 (licensing, system restrictions, etc.) than  won't be available to you.  In that situation you can re-use the code from PyPDF2's  function (provided above) to create a copy of the file as a  object, and use that in your code in place of the file object.  Previous recommendation of using  changed based on comments .The pdfrw package reads each file all in one go, so will not suffer from the problem of too many open files.   is an example concatenation script.The relevant part -- assumes  is a list of input filenames, and  is an output file name:Disclaimer:  I am the primary pdfrw author.It maybe just what it says, you are opening to many files.\nYou may explicitly use  in the loop, or use the  statement. So that each opened file is properly closed. The problem is that you are only allowed to have a certain number of files open at any given time. There are ways to change this (), but I don't think you need this.What you could try is closing the files in the for loop:
Python

If I catch a , how can I tell what lookup failed?Take the current exception (I used it  in this case); then for a  the first argument is the key that raised the exception. Therefore we can do:With that, you have the offending key stored in .It should be noted that  works in Python 2 but not Python 3, so it shouldn't be used.Not sure if you're using any modules to assist you - if the JSON is coming in as a dict, one can use  towards a useful end. takes two arguments - the first being the  you want, the second being the value to return if that key does not exist.If you import the  module you can get exception info with like this:
Python

I have a pandas dataframe with mixed type columns, and I'd like to apply sklearn's min_max_scaler to some of the columns.  Ideally, I'd like to do these transformations in place, but haven't figured out a way to do that yet.  I've written the following code that works:I'm curious if this is the preferred/most efficient way to do this transformation.  Is there a way I could use df.apply that would be better?  I'm also surprised I can't get the following code to work:If I pass an entire dataframe to the scaler it works:I'm confused why passing a series to the scaler fails.  In my full working code above I had hoped to just pass a series to the scaler then set the dataframe column = to the scaled series.  I've seen this question asked a few other places, but haven't found a good answer.  Any help understanding what's going on here would be greatly appreciated!I am not sure if previous versions of  prevented this but now the following snippet works perfectly for me and produces exactly what you want without having to use Like this?As it is being mentioned in pir's comment - the  method will produce the following warning:Converting your columns to numpy arrays should do the job (I prefer StandardScaler):You can do it using   only:
Python

I am trying to use some AOP in my Python programming, but I do not have any experience of the various libraries that exist. So my question are:I've found some, but I don't know how they compare:In which context will I use these? I have two applications, written in Python, which have typically methods which compute taxes and other money things. I'd like to be able to write a \"skeleton\" of a functionality, and customize it at runtime, for example changing the way local taxes are applied (by country, or state, or city, etc.) without having to overload the full stack.Another AOP library for python would be . It is currently the most powerful (as far as I know).Its features are:It also has other goodies such as some special descriptors (see the documentation)See S.Lott's link about Python decorators for some great examples, and see the .Python had AOP since the beginning, it just didn't have an impressive name.\nIn Python 2.4 the decorator syntax was added, which makes applying decorators very nice syntactically.Maybe if you want to apply decorators based on rules you would need a library, but if you're willing to mark the relevant functions/methods when you declare them you probably don't.Here's an example for a simple caching decorator (I wrote it for ):Using annotations is not really AOP, because the weaving process is somewhat hard-coded.There are several AOP frameworks in Python (I counted and compared 8 of them, of which  was the clear winner).I'm going to publish a paper with my findings on one of the next conferences, including a real-life industry use case.In Python, aspect-oriented programming typically consists of dynamically modifying classes and instances at runtime, which is commonly referred to as monkeypatching.  In an answer to another AOP question, I summarized some of these .I'd start with the .  Much of that is AOP kind of stuff.  What about the BSD-licensed ?
Python

How do I set the timezone of a datetime instance that just came out of the datastore?When it first comes out it is in UTC.  I want to change it to EST.I'm trying, for example:When a Book is retrieved, I want to set its tzinfo immediately:Where  for my EST objectHowever I get:I've seen a number of answers that recommend pytz and python-dateutil, but I really want an answer to this question.'s objects are immutable, so you never change any of their attributes -- you make a  object with some attributes the same, and some different, and assign it to whatever you need to assign it to.I.e., in your case, instead ofyou have to codeIf you're receiving a datetime that's  EST, but doesn't have its tzinfo field set, use  to assign a tzinfo without modifying the time.  (Your database should be doing this for you.)If you're receiving a datetime that's in UDT, and you want it in EST, then you need astimezone.  In the vast majority of cases, your database should be storing and returning data in UDT, and you shouldn't need to use replace (except possibly to assign a UDT tzinfo).What you want is right there in the .output:
Python

If I have a string like:and I want:What do the replacement tokens have to be? (I know that my example above is incorrect; I'm just trying to express my goal.)is another true but long answer. Just to show you another viewpoint about the issue ;)Python 3 has exactly that syntax, except the  operator is now the  method.  has also been added to Python 2.6+ to smooth the transition to Python 3. See  for more details.It cannot be done with a tuple in older versions of Python, though. You can get close by using mapping keys enclosed in parentheses. With mapping keys the format values must be passed in as a dict instead of a tuple.From the :
Python

Do I need to add a db_index to \"content\"? Or would that automatically be indexed because it's a foreign key?Unless specified otherwise, an index will be created for a .  Relevant source code:
Python

In Python 2.7, dictionaries have both an  method and a  method (and similar pairs for values and items), giving two different ways to lazily iterate over the keys of the dictionary. The  method provides the principal feature of , with  effectively equivalent to . Additionally, objects returned  have convenient set-like features. There thus are strong reasons to favor  over . What about the other direction? Apart from compatibility with earlier versions of Python, are there any ways in which  would be preferable to ? Would anything be lost by just always using ? No, there's no advantage to  over , in the same way that there's no advantage to  over either of them.  is only around for back compatibility. Indeed, in Python 3,  is the only behaviour that still exists, and it has been renamed to  - the  method is actually a backport of the Python 3 behaviour.A dictionary view updates as the dictionary does, while an iterator does not necessarily do this.This means if you work with the view, change the dictionary, then work with the view again, the view will have changed to reflect the dictionary's new state.Example:When changes are made to the size, an exception will be thrown:It's also worth noting you can only iterate over a keyiterator once:Functionality-wise, as you have observed, views are better. Compatibility-wise, they're worse.Some performance metrics, taken from Python 2.7.2 on a 64-bit Ubuntu machine:Dealing with an empty dictionary:Constructing the view is slightly more expensive, but consuming the view is significantly faster than the iterator (a bit over twice as fast).Dealing with a thousand-element dictionary:Same results, though less marked; constructing the view is very slightly more expensive, but consuming it is quite definitely faster (15% faster).For fair comparison with  and ,  is distinctlyfaster: it's a trade-off; better functionality (which you will rarely use) and performance (which will only  rarely be significant enough to worry you\u2014if you're caring about such performance matters, you're probably already in the region of needing to work with numpy/scipy) versus better compatibility and muscle memory usage.Personally, unless already depending on 2.7-only functionality or unless I am absolutely controlling the runtime environment, I would avoid dictionary views in Python 2 code. Even in these cases, my fingers still want to type  instead of , so I let 'em!As the name (and ) indicate, the ,  and  methods return a  of the current elements in the dictionary meaning that if the dictionary changes, so does the view; views  . In the general case  views are set-like, and  views are only set-like if the values are hashable.In what cases would be better to use the standard methods ,  and  ? You mentioned a very important one: backwards compatibility. Also, when you need to have a simple list of all keys, values or items  (not a set-like, not an iterator), when you need to modify the returned list without modifying the original dictionary and when you need a snapshot of a dictionary's keys, values or items at a moment in time, independent of any posterior modifications over the dictionary.And what about ,  and ? They're a suitable alternative when you need a one-shot, constant-space, lazy iterator snapshot of a dictionary's contents that will tell you if the dictionary got modified while iterating (via a ), also they're very important for backwards compatibility.
Python

The move in recent versions of Python to passing a  function to  from the previous  function is making it trickier for me to perform complex sorts on certain objects.For example, I want to sort a set of objects from newest to oldest, with a set of string tie-breaker fields. So I want the dates in reverse order but the strings in their natural order. With a comparison function I can just reverse the comparison for the date field compared to the string fields. But with a key function I need to find some way to invert/reverse either the dates or the strings.It's easy (although ugly) to do with numbers - just subtract them from something - but do I have to find a similar hack for dates (subtract them from another date and compare the timedeltas?) and strings (...I have no idea how I'd reverse their order in a locale-independent way).I know of the existence of  but it is described as being . This implies that I should be able to do what I want with the key method - but how?The slow-but-elegant way to do this is to create a value wrapper that has reversed ordering:If you don't have , you'd have to implement all 6 comparisons, e.g.:The most generic way to do this is simply to sort separately by each key in turn. Python's sorting is always stable so it is safe to do this:will (assuming the relevant definitions for the key functions) give you the data sorted by descending date and ascending tiebreakers.Note that doing it this way is slower than producing a single composite key function because you will end up doing two complete sorts, so if you can produce a composite key that will be better, but splitting it out into separate sorts gives a lot of flexibility: given a key function for each column you can make any combination of them and specify reverse for any individual column.For a completely generic option:and for completeness, though I really think it should be avoided where possible:The reason I think you should avoid this you go back to having  calls to the comparison function compared with  calls to the key function (or  calls when you do the sorts twice).I think the docs are incomplete.  I interpret the word \"primarily\" to mean that there are still reasons to use cmp_to_key, and this is one of them.   was removed because it was an \"attractive nuisance:\" people would gravitate to it, even though  was a better choice.But your case is clearly better as a  function, so use  to implement it.Sort twice, once on each key and once reversed.(Python  is ; that is, it doesn't change the order of the original list unless it has to.)For String, you can use some commonly acknowledged maximum value (such as 2^16 or 2^32) and use chr(), unicode(), ord() to do the math, just like for integers.In one of my work, I know I deal with strings in utf8 and their ordinals are below 0xffff, so I wrote:x is of type: (string, int), so what I get is, to abuse the SQL:
Python

I'm currently learning Python and Classes and I have a basic question, but I didn't find any answer to it. Let's say I have this dummy classI want to run simultaneously resolve_domain and generate_website_thumbnail and when the threads are finished I want to print the IP and the thumbnail.  I know I should use threads, maybe something like thisBut should I use them outside the Class? Should I write another Class to handle Threads?What is the  to do that?If you call them from the class, it is as simple as:
Python

Before I ask,  will be my last options, this script will be used across Windows and Linux and I'd prefer to have a coded out method of doing this than leaving this to the end user to complete.Is there a library for Python that I can use to schedule tasks? I will need to run a function once every hour, however, over time if I run a script once every hour and use .sleep, \"once every hour\" will run at a different part of the hour from the previous day due to the delay inherent to executing/running the script and/or function.What is the  way to schedule a function to run at a specific time of day (more than once)  using a Cron Job or scheduling it with Task Scheduler?out:(From Animesh Pandey's answer below)Maybe this can help: Here's a small piece of code from their documentation:To run something every 10 minutes past the hour.  For  < 3.0, see .For  > 3.0One option is to write a C/C++ wrapper that executes the python script on a regular basis. Your end-user would run the C/C++ executable, which would remain running in the background, and periodically execute the python script. This may not be the best solution, and may not work if you don't know C/C++ or want to keep this 100% python. But it does seem like the most user-friendly approach, since people are used to clicking on executables. All of this assumes that python is installed on your end user's computer.Another option is to use cron job/Task Scheduler but to put it in the installer as a script so your end user doesn't have to do it.The Python standard library does provide  and  for this task. But this means your scheduler script will have be running all the time instead of leaving its execution to the OS, which may or may not be what you want.On the version posted by sunshinekitty called \"Version < 3.0\" , you may need to specify apscheduler 2.1.2 .  I accidentally had version 3 on my 2.7 install, so I went:It worked correctly after that.  Hope that helps.
Python

I try to extract all files from .zip containing subfolders in one folder.  I want all the files from subfolders extract in only one folder without keeping the original structure. At the moment, I extract all, move the files to a folder, then remove previous subfolders.  The files with same names are overwrited.Is it possible to do it before writing files?Here is a structure for example:At the end I whish this:What can I add to this code ?if I rename files path from zip_file.namelist(), I have this error:This opens file handles of members of the zip archive, extracts the filename and copies it to a target file (that's how  works, without taken care of subdirectories).Just extract to bytes in memory,compute the filename, and write it there yourself,\ninstead of letting the library do it - -mostly, just use the \"read()\" instead of \"extract()\" method:
Python

I'm trying to write a short program that will read in the contents of e-mails within a folder on my exchange/Outlook profile so I can manipulate the data. However I'm having a problem finding much information about python and exchange/Outlook integration. A lot of stuff is either very old/has no docs/not explained. I've tried several snippets but seem to be getting the same errors. I've tried Tim Golden's code:However I get an error:Not sure what my profile name is so I tried with:to be prompted but that didn't work either (same error). Also tried both with Outlook open and closed and neither changed anything.I had the same problem you did - didn't find much that worked. The following code, however, works like a charm.I have created my own iterator to iterate over Outlook objects via python. The issue is that python tries to iterates starting with Index[0], but outlook expects for first item Index[1]...  To make it more Ruby simple, there is below a helper class Oli with following\nmethods:  .items() - yields a tuple(index, Item)... \n.prop() - helping to introspect outlook object exposing available properties (methods and attributes)    \nI had the same issue. Combining various approaches from the internet (and above) come up with the following approach (checkEmails.py)For concistency I include also the code for the FileWriter class (found in FileWrapper.py). I needed this because \ntrying to pipe UTF8 to a file in windows did not work.Enjoy.
Python

I have a Django webapp. I have installed the debug_toolbar middleware and module.\nHowever, my webapps don't have the debug toolbar pull-out.How do I actually see the debug toolbar? Is there something more I need to do?\nDo I need to use a particular template for my webapp? I have followed all the steps in the README, but that is not enough -- there seems to be some other dependency, or something else I'm missing.Also, when looking at the set of URL patterns for my webapp, the  prefix is  found among the recognized patterns. I've put a log in urls.py in debug_toolbar to make sure that modules is getting loaded by the activated debug_toolbar application, and it is.This has me totally mystified, and I can find no Google or README on what to do to make this actually show up, or what the requirements are, so any pointer you can provide would be great!Edit: It turns out, I was testing this with a SSH tunnel from the machine running the browser to the machine running the Django/Apache. In this case, the IP address actually seen for the remote machine was not what I thought it was, so the list of \"good\" IPs did not contain the browser's apparent remote machine. Fixing that fixed the problem!(Edit note: lapis updated the configs above to match the names used by the current (at the time of this update, 1.3.2) version of the Django Debug Toolbar.  Per , the original versions (that used e.g. debug_toolbar.panels.sql.SQLDebugPanel vs debug_toolbar.panels.sql.SQLPanel as in 1.3.2) were correct when this question was original answered.)(note: after Django 1.10,  should be .)
Python

I want to get the directory where the file resides. For example the full path is:I could do it like this:But the example above relies on specific directory separator and is not really pretty. Is there a better way?You are looking for this:Related functions:
Python

I have a 2D array containing integers (both positive or negative). Each row represents the values over time for a particular spatial site, whereas each column represents values for various spatial sites for a given time.So if the array is like:The result should beNote that when there are multiple values for mode, any one (selected randomly) may be set as mode.I can iterate over the columns finding mode one at a time but I was hoping numpy might have some in-built function to do that. Or if there is a trick to find that efficiently without looping.Check  (inspired by @tom10's comment):Output:As you can see, it returns both the mode as well as the counts. You can select the modes directly via :Output:This is a tricky problem, since there is not much out there to calculate mode along an axis.  The solution is straight forward for 1-D arrays, where  is handy, along with  with the  arg as .  The most common n-dimensional function I see is scipy.stats.mode, although it is prohibitively slow- especially for large arrays with many unique values.  As a solution, I've developed this function, and use it heavily:Result:Some benchmarks:EDIT: Provided more of a background and modified the approach to be more memory-efficientExpanding on , applied to finding the mode of the data where you may need the index of the actual array to see how far away the value is from the center of the distribution.Remember to discard the mode when len(np.argmax(counts)) > 1, also to validate if it is actually representative of the central distribution of your data you may check whether it falls inside your standard deviation interval.
Python

I've done some searching and can't figure out how to filter a dataframe by , however I'm wondering if there is a way to do the reverse: filter a dataframe by that set's compliment. eg: to the effect of . Can this be done through a  method?You can use the invert (~) operator (which acts like a not for boolean data):I was having trouble with the not (~) symbol as well, so here's another way from another :I had to get rid of the NULL values before using the command recommended by Andy above. An example:Now running the command:I get the following error:I got rid of the NULL values using dropna() or fillna() first and retried the command with no problem.
Python

 has been released, and I am wondering, if a similar solution is available, or coming for Python?RubyMotion isn't a new cross-platform framework (like Kivy, Papaya, Rhodes, etc.) but rather an implementation of the Ruby programming language ON TOP OF the native iOS language Objective-C. Because of this, a RubyMotion object  an Obj-C Object, but you get to use the dynamic Ruby syntax and idioms to deal with it, instead of the static-oriented Objective-C approaches. You must still learn the Apple SDK, you just talk to it with \"toll-free\" Ruby code. With Titatnium, for example, you learn that platform's APIs which work on multiple OSes, albeit at a cost of UI mismatches and performance penalties.MacRuby is the desktop progenitor of RubyMotion, and the Python analogue to it would be PyObjC. The  for PyObjC looks dormant to me (last updated in late 2009) so someone would have to first revive it, and then make similar modifications (replacing garbage-collection style memory management with some form of automatic reference counting and binary compilation) in order to build a similar Python solution for iOS.I wouldn't expect it to drop out of the sky anytime soon, but surprises are always welcome.Depends what you are after and what for. Papaya do what they call a social engine (for games really). But you can write with Python for that. 
Python

I'm working on a Python script that uses the scissor character (9986 - \u2702) and I'm trying to port my code to Mac, but I'm running into this error.The scissor character shows up fine when run from IDLE (Python 3.2.5 - OS X 10.4.11 iBook G4 PPC) and the code works entirely fine on Ubuntu 13.10, but when I attempt to run this in the terminal I get this error/traceback:and the code that is giving me the problem: Doesn't this signal that the terminal doesn't have the capability to display that character? I know this is an old system, but it is currently the only system I have to use. Could the age of the OS is interfering with the program?I've read over these questions:What's causing this error? Is it the age of the system/OS, the version of Python, or some programming error?:\nThis error crops up later with this duplicate issue (just thought I'd add it as it is within the same program and is the same error): I went into the terminal character settings and it does in fact support that character (as you can see in this screenshot:when I insert it into terminal it prints out this:  and when I press  I get this:  Ran commands as @J.F. Sebastian asked::: Tried the \"hackerish\" solution provided by @PauloBu:As you can see, this caused one (Yay!) scissor, but I am now getting a new error. Traceback/error: Added results of @PauloBu's fix::And his fix for his fix:When Python prints and output, it automatically encodes it to the target medium. If it is a file, UTF-8 will be used as default and everyone will be happy, but if it is a terminal, Python will figure out the encoding the terminal is using and will try to encode the output using that one.This means that if your terminal is using  as encoding, Python is trying to encode  char to ascii. Of course, ascii doesn't support it so you get Unicode decode error.This is why . Explicit is better than implicit remember? To fix your code you may do:This seems a bit hackerish. You can also set PYTHONIOENCODING=utf-8 before executing the script. I'am uncomfortable with both solutions. Probably your console doesn't support utf-8 and you see gibberish. But your program will be behaving correctly.What I strongly recommend if you  need to show correct output on your console is to set your console to use another encoding, one that support  character. (utf-8 perhaps). On Linux, that can be achieve by doing: . On Windows you change the console's code page with . Just figure out how to set utf8 in yours and IMHO that'll be the best solution.I suggest you to take a read at the docs to see what's going on under the hood with  function and with : Hope this helps! output suggests that you should change your  settings e.g., set .The first error might be due to you are trying to decode a string that is already Unicode. Python 2 tries to encode it using a default character encoding ()  decoding it using (possibly) different character encoding. The error happens on the  step:It looks like you are running your script using Python 2 instead of Python 3. You would get:different error otherwise.Just drop the  call:The second issue is due to printing a Unicode string into a pipe:Set appropriate for your purpose  environment variable:If  is a  object then leave the  calls. The fix is the same:My locale is set to de_AT.UTF-8 but these lines in \nwere missing:logout / login and your problem should be solvedTo verify if all locales are set correctly type  in your terminalThe output should be similar to this:in the first line of your file .py you need to add this string, :# --and you can also try this:print (\"|\\t \",unichr(9986),\"PySnipt'd\",unichr(9986),\"\\t|\")
Python

In Python, I know that the value  returns for a given object is supposed to be the same for the lifetime of that object. But, out of curiosity, what happens if it isn't? What sort of havoc would this cause?I know  and  would behave strangely, and dicts and sets would act odd because of that. You also might end up with \"orphaned\" values in the dict/set.What else could happen? Could it crash the interpreter, or corrupt internal structures?Your main problem would indeed be with dicts and sets. If you insert an object into a dict/set, and that object's hash changes, then when you try to retrieve that object you will end up looking in a  spot in the dict/set's underlying array and hence won't find the object. This is precisely why dict keys should always be immutable.Here's a small example: let's say we put  into a dict, and 's initial hash is 3. We would do something like this (a slight simplification but gets the point across):Now let's say the hash of  changes to . If we want to retrieve  from the dict, we'll look at spot , but there's nothing there! This will cause a false negative when querying the data structure. In reality, each element of the array above could have a \"value\" associated with it in the case of a dict, and there could be multiple elements in a single spot (e.g. a ). Also, we'd generally take the hash value modulo the size of the array when deciding where to put the element. Irrespective of all these details, though, the example above still accurately conveys what could go wrong when the hash code of an object changes. No, this won't happen. When we say an object's hash changing is \"dangerous\", we mean dangerous in the sense that it essentially defeats the purpose of hashing and makes the code difficult if not impossible to reason about. We don't mean dangerous in the sense that it could cause crashes.There's a great post on Github about it: . \nFirst, you need to know that Python expects (quoted from the article): Here's the code example which show the problem of a variant hash, with a slightly different class example, but the idea remains the same: but unexpected behavior will happen with dict/set and everything based on object hash.
Python

For example, I may use  or  or just , in which case the default compiler (say, ) will be used. How can I get the compiler name inside my setup.py (e. g. ,  and , respectively)?UPD.: I don't need the default compiler, I need the one that is  going to be used, which is not necessarily the default one. So far I haven't found a better way than to parse  to see if there's a  string there.This is an expanded version of Luper Rouch's answer that worked for me to get an openmp extension to compile using both mingw and msvc on windows. After subclassing build_ext you need to pass it to setup.py in the cmdclass arg. By subclassing build_extensions instead of finalize_options you'll have the actual compiler object to look into, so you can then get more detailed version information. You could eventually set compiler flags on a per-compiler, per-extension basis:You can subclass the  command.Once  method has been called, the compiler type is stored in  as a string (the same as the one passed to the 's  option, e.g. 'mingw32', 'gcc', etc...).import distutils.ccompilercompiler_name = distutils.ccompiler.get_default_compiler()You can use self.distribution.get_command_obj('build_ext') to get build_ext instance,\nand then get the compiler_type
Python

Can anyone suggest any good payment processing libraries for python/django?The most developed Django solution is  with support for Authorize.Net, TrustCommerce, CyberSource, PayPal, Google Checkout, and Protx.The new kid on the Django block is  which looks like only support for PayPal at the moment, and even that may not be complete.For general Python the main player is There is  which currently supports only PayPal. It can be used with any existing application without changing it's code. Basically, it can use  as order.Perhaps you can find some usefull code hints/modules looking at Satchmo: \nDjango paypal is very cool. I've used in on couple of my projects. It is relatively easy to integrate with an existing website. \nSatchmo is good, if you want a full internet store, but if you want to sell just couple items from your website, which is devoted to something else, you will find Satchmo to be very heavy (a lot of dependencies to install, really complicates your admin). You may want to take a look at  which isn't django-specific but works nicely with it or in plain ole python.I created Paython: Supports a few different processors:
Python

I'm trying to generate an XML document with namespaces, currently with Python's xml.dom.minidom:The namespace is saved ( is ), but why is it missing in the output?I expect:or is defined as:so\u2026yields:\u2026not quite there\u2026yields:alternatively:wich produces:It looks like you'd have to do it manually.  shows no indication that namespaces would get any special treatment.EDIT: This answer is targeted at  only, since the OP used it in the question. I do not indicate that it was impossible to use XML namespaces in Python generally. ;-)This feature is already proposed; a patch is . See Tomalak's answer (in short: Manually add the  attribute) for a workaround.
Python

I'm working on several Python projects who run on various versions of Python. I'm hoping to set up my vim environment to use ropevim, pyflakes, and pylint but I've run into some issues caused by using a single vim (compiled for a specific version of Python which doesn't match the project's Python version).I'm hoping to build vim into each of my virtualenv directories but I've run into an issue and I can't get it to work. When I try to build vim from source, despite specifying the Python config folder in my virtualenv, the system-wide Python interpreter is always used.Currently, I have Python 2.6.2 and Python 2.7.1 installed with several virtualenvs created from each version. I'm using Ubuntu 10.04 where the system-default Python is 2.6.5. Every time I compile vim and call  it returns .Results in the following in config.log:It should be . Is there any way to specify the Python interpreter for vim to use?NOTE: I can confirm that /virtualenv/project/bin appears at the front of  environment variable.I'd recommend building vim against the 2 interpreters, then invoking it using the shell script I provided below to point it to a particular virtualenv.I was able to build vim against Python 2.7 using the following command (2.7 is installed under $HOME/root):Your virtualenv is actually a thin wrapper around the Python interpreter it was created with --   is a symlink to .So if you created it with the system interpreter, VIM will probe for this and ultimately link against the real interpreter, using the system  by default, even though configure will show the virtualenv's path:: Since your system vim is most likely compiled against your system python, you don't need to rebuild vim for each virtualenv: you can just drop a shell script named  in your virtualenv's bin directory, which extends the PYTHONPATH before calling system vim:Contents of :When that is invoked, the virtualenv's sys.path is inserted:For what it's worth, and no one seems to have answered this here, I had some luck using a command line like the following:vi_cv_path_python=/usr/bin/python26 ./configure --includedir=/usr/include/python2.6/  --prefix=/home/bcrowder/local --with-features=huge --enable-rubyinterp --enable-pythoninterp --disable-selinux --with-python-config-dir=/usr/lib64/python2.6/configI would like to give a similar solution to crowder's that works quite well for me.Imagine you have Python installed in /opt/Python-2.7.5 and that the structure of that folder isand you would like to build vim with that version of Python. All you need to do isThus, just by explicitly giving  variable to  the script will deduce everything on it's own (even the config-dir).This was tested multiple times on vim 7.4+ and lately with .I was having this same issue with 3 different versions of python on my system.for me the easiest thing was to change my  env variable so that the folder that has the version of python I wanted was (in my case ) was found before another.
Python

Should be a simple question, but I'm unable to find an answer anywhere. The  operator in python is a documented as a bitwise inversion operator.  Fine. I have noticed seemingly schizophrenic behavior though, to wit:In the first 4 examples, I can see that python is implementing (as documented) , with the input treated as an int . Hence, for a scalar boolean,  is not treated as a logical negation. Not that the behavior is identical on a numpy array defined with boolean values by with an int type.Why does  then work as a logical negation operator on a boolean array (Also notice: ?)?It is extremely annoying that I must use  on a scalar, but  won't work to negate an array. Then for an array, I must use , but  won't work to negate a scalar... is implemented through the  special method, which is required to return either  or , so it can't give the required result.  Instead the  operator is used, which is implemented through the  special method.  For the same reason,  and  are used in place of  and . aimed to allow overloading of boolean operators but was rejected because of excessive overhead (it would e.g. complicate  statements).   suggests a general syntax for \"elementwise\" operators, which would provide a more general solution, but has been deferred.  It appears that the current situation, while awkward, is not painful enough to force change. when called on a scalar returns a value of type , not .   is also the type you get when extracting a scalar value from an array of bool dtype.  If you use  and  in place of  and  you will get consistent behaviour under .
Python

How do I transform a directed acyclic graph into a hash value such that any two isomorphic graphs hash to the same value?  It is acceptable, but undesirable for two isomorphic graphs to hash to different values, which is what I have done in the code below.  We can assume that the number of vertices in the graph is at most 11.I am particularly interested in Python code.Here is what I did.  If  is a mapping from node to descendants (not children!), then I relabel the nodes according to a modified topological sort (that prefers to order elements with more descendants first if it can).  Then, I hash the sorted dictionary.  Some isomorphic graphs will hash to different values, especially as the number of nodes grows.I have included all the code to motivate my use case.  I am calculating the number of comparisons required to find the median of 7 numbers.  The more that isomorphic graphs hash to the same value the less work that has to be redone.  I considered putting larger connected components first, but didn't see how to do that quickly.To effectively test for graph isomorphism you will want to use . Specifically for Python there is the wrapper , but I can't attest its quality (to compile it correctly I had to do some simple patching on its ). If this wrapper is doing everything correctly, then it simplifies nauty a lot for the uses you are interested and it is only a matter of hashing  -- which will be the same value for isomorphic graphs.Some quick tests showed that  is giving the same certificate for every graph (with same amount of vertices). But that is only because of a minor issue in the wrapper when converting the graph to nauty's format. After fixing this, it works for me (I also used the graphs at  for comparison). Here is the short patch which also considers the modifications needed in : Therefore there is currently no known (worst case sub-exponential) solution to guarantee that two isomorphic directed acyclic graphs will yield the same hash. Only if the mapping between different graphs is known - for example if all vertices have unique labels - one could efficiently guarantee matching hashes.Okay, let's brute force this for a small number of vertices. We have to find a representation of the graph that is independent of the ordering of the vertices in the input and therefore guarantees that isomorphic graphs yield the same representation. Further this representation must ensure that no two non-isomorphic graphs yield the same representation.The simplest solution is to construct the adjacency matrix for all n! permutations of the vertices and just interpret the adjacency matrix as n bit integer. Then we can just pick the smallest or largest of this numbers as canonical representation. This number completely encodes the graph and therefore ensures that no two non-isomorphic graphs yield the same number - one could consider this function a . And because we choose the smallest or largest number encoding the graph under all possible permutations of the vertices we further ensure that isomorphic graphs yield the same representation.How good or bad is this in the case of 11 vertices? Well, the representation will have 121 bits. We can reduce this by 11 bits because the diagonal representing loops will be all zeros in an acyclic graph and are left with 110 bits. This number could in theory be decreased further; not all 2 remaining graphs are acyclic and for each graph there may be up to 11! - roughly 2 - isomorphic representations but in practice this might be quite hard to do. Does anybody know how to compute the number of distinct directed acyclic graphs with n vertices?How long will it take to find this representation? Naively 11! or 39,916,800 iterations. This is not nothing and probably already impractical but I did not implement and test it. But we can probably speed this up a bit. If we interpret the adjacency matrix as integer by concatenating the rows from top to bottom left to right we want many ones (zeros) at the left of the first row to obtain a large (small) number. Therefore we pick as first vertex the one (or one of the vertices) with largest (smallest) degree (indegree or outdegree depending on the representation) and than vertices connected (not connected) to this vertex in subsequent positions to bring the ones (zeros) to the left.There are likely more possibilities to prune the search space but I am not sure if there are enough to make this a practical solution. Maybe there are or maybe somebody else can at least build something upon this idea.How good does the hash have to be? I assume that you do  want a full serialization of the graph. A hash rarely guarantees that there is no second (but different) element (graph) that evaluates to the same hash. If it is very important to you, that isomorphic graphs (in different representations) have the same hash, then only use values that are invariant under a change of representation. E.g.:All these informations can be gathered in O(#nodes) [assuming that the graph is stored properly]. Concatenate them and you have a hash. If you prefer you can use some well known hash algorithm like  on these concatenated informations. Without additional hashing it is a  (it allows to find similar graphs), with additional hashing it is  and fixed in size if the chosen hash algorithm has these properties.As it is, it is already good enough to register any added or removed connection. It might miss connections that were changed though ( instead of ).This approach is modular and can be extended as far as you like. Any additional property that is being included will reduce the number of collisions but increase the effort necessary to get the hash value. Some more ideas:You requested \"a unique hash value\" and clearly I cannot offer you one. But I see the terms \"hash\" and \"unique to every graph\" as mutually exclusive (not entirely true of course) and decided to answer the \"hash\" part and not the \"unique\" part. A \"unique hash\" () basically needs to be a full serialization of the graph (because the amount of information stored in the hash has to reflect the total amount of information in the graph). If that is really what you want just define some unique order of nodes (eg. sorted by own outdegree, then indegree, then outdegree of children and so on until the order is unambiguous) and serialize the graph in any way (using the position in the formentioned ordering as index to the nodes).Of course this is much more complex though.Imho, If the graph could be topologically sorted, the very straightforward solution  exists.I will describe an algorithm to hash an arbitrary directed graph, not taking into account that the graph is acyclic. In fact even counting the acyclic graphs of a given order is a very complicated task and I believe here this will only make the hashing significantly more complicated and thus slower. A unique representation of the graph can be given by the neighbourhood list. For each vertex create a list with all it's neighbours. Write all the lists one after the other appending the number of neighbours for each list to the front. Also keep the neighbours sorted in ascending order to make the representation unique for each graph. So for example assume you have the graph:What I propose is that you transform this to , here the curly brackets being only to visualize the representation, not part of the python's syntax. So the list is in fact: .Now to compute the unique hash, you need to order these representations somehow and assign a unique number to them. I suggest you do something like a lexicographical sort to do that. Lets assume you have two sequences  and  , Here c and a are the number of neighbours for each vertex and b_i_j and d_k_l are the corresponding neighbours. For the ordering first compare the sequnces  and  and if they are different use this to compare the sequences. If these sequences are different, compare the lists from left to right first comparing lexicographically  to  and so on until the first missmatch.In fact what I propose to use as hash the lexicographical number of a word of size  over the alphabet that is formed by all possible selections of subsets of elements of . The neighbourhood list for a given vertex is a letter over this alphabet e.g.  is the subset consisting of two elements of the set, namely  and .The (set of possible ) for the set  would be(ordered ): First number like above is the number of elements in the given subset and the remaining numbers- the subset itself. So form all the 3  from this alphabet and you will get all the possible directed graphs with 3 vertices.Now the number of subsets of the set  is  and thus the number of  of this alphabet is . Now we code each directed graph of  nodes with a  with exactly   from this  and thus the number of possible hash codes is precisely: . This is to show that the hash code grows  fast with the increase of . Also this is the number of possible different directed graphs with  nodes so what I suggest is optimal hashing in the sense it is bijection and no smaller hash can be unique. There is a linear algorithm to get a given subset number in the the lexicographical ordering of all subsets of a given set, in this case . Here is the code I have written for coding/decoding a subset in number and vice versa. It is written in  but quite easy to understand I hope. For the hashing you will need only the code function but as the hash I propose is reversable I add the decode function - you will be able to reconstruct the graph from the hash which is quite cool I think:Also this code stores the result in  variable,  which is only enough for graphs with less than 64 elements. All possible hashes of graphs with 64 nodes will be . This number has about 1280  so maybe is a big number. Still the algorithm I describe will work really fast and I believe you should be able to hash and 'unhash' graphs with a lot of vertices.Also have a look at .I'm not sure that it's 100% working, but here is an idea:Let's code a graph into a string and then take its hash.To produce the same hash for isomorphic graphs before concatenation in step3 just sort the hashes (e.g. in lexicographical order).For hash of a graph just take hash of its root (or sorted concatenation, if there are several roots). While I hoped that the resulting string will describe graph without collisions,  found that sometimes non-isomorphic graphs will get the same hash. That happens when a vertex has several parents - then it \"duplicated\" for every parent. For example, the algorithm does not differentiate a \"diamond\" {A->B->C,A->D->C} from the case {A->B->C,A->D->E}.I'm not familiar with Python and it's hard for me to understand how graph stored in the example, but here is some code in C++ which is likely convertible to Python easily:I am assuming there are no common labels on vertices or edges, for then you could put the graph in a canonical form, which itself would be a perfect hash.  This proposal is therefore based on isomorphism only.For this, combine hashes for as many simple aggregate characteristics of a DAG as you can imagine, picking those that are quick to compute.  Here is a starter list:\nLet me be more explicit.  For 1, we'd compute a set of triples  (where no two triples have the same , values), signifying that there are  nodes with in-degree  and out-degree .  You'd hash this set of triples or better yet use the whole set arranged in some canonical order e.g. lexicographically sorted.  For 2, we compute a set of quintuples  signifying that there are  edges from nodes with in degree  and out degree , to nodes with  and  respectively.  Again hash these quintuples or else use them in canonical order as-is for another part of the final hash.Starting with this and then looking at collisions that still occur will probably provide insights on how to get better.When I saw the question, I had essentially the same idea as @example. I wrote a function providing a graph tag such that the tag coincides for two isomorphic graphs. This tag consists of the sequence of out-degrees in ascending order. You can hash this tag with the string hash function of your choice to obtain a hash of the graph. I expressed my proposal in the context of @NeilG's original question. The only modification to make to his code is to redefine the  function as:Years ago, I created a simple and flexible algorithm for exactly this problem (finding duplicate structures in a database of chemical structures by hashing them).I named it \"Powerhash\", and to create the algorithm it required two insights. The first is the power iteration graph algorithm, also used in PageRank. The second is the ability to replace power iteration's inside step function with anything that we want. I replaced it with a function that does the following on each step, and for each node:On the first step, a node's hash is affected by its direct neighbors. On the second step, a node's hash is affected by the neighborhood 2-hops away from it. On the Nth step a node's hash will be affected by the neighborhood N-hops around it. So you only need to continue running the Powerhash for N = graph_radius steps. In the end, the graph center node's hash will have been affected by the whole graph.To produce the final hash, sort the final step's node hashes and concatenate them together. After that, you can compare the final hashes to find if two graphs are isomorphic. If you have labels, then add them in the internal hashes that you calculate for each node (and at each step).For more on this you can look at my post here:The algorithm above was implemented inside the \"madIS\" functional relational database. You can find the source code of the algorithm here:With suitable ordering of your descendents (and if you have a single root node, not a given, but with suitable ordering (maybe by including a virtual root node)), the method for hashing a tree ought to work with a slight modification.Example code in , the modification would be to sort children in some deterministic order (increasing hash?) before hashing the parent.Even if you have multiple possible roots, you can create a synthetic single root, with all roots as children.
Python

I managed to override the look of a  Widget in the django admin interface with two different ways:in :This way is a bit of an overkill, since it will change all the TextField for that\nmodel.in :in Both solutions resize the . However in both solutions the actual size of the \ntext area is more than 1 row (actually 2 rows). Here is how the rendered HTML looks like:And here is a screentshot:According to :So, my questions are: This is a browser-specific problem.According to the thread :You can set a  attribute of the textarea:Works for me - tested on Firefox v. 23 and Chrome v. 29.Hope that helps.
Python

I have a dataframe where some cells contain lists of multiple values. Rather than storing multiple\nvalues in a cell, I'd like to expand the dataframe so that each item in the list gets its own row (with the same values in all other columns). So if I have:How do I convert to long form, e.g.:The index is not important, it's OK to set existing\ncolumns as the index and the final ordering isn't\nimportant.A bit longer than I expected:If you want sequential index, you can apply  to the result.:you can also use  and  for this:last, if you need you can sort base on the first the first three columns.Trying to work through Roman Pekar's solution step-by-step to understand it better, I came up with my own solution, which uses  to avoid some of the confusing stacking and index resetting. I can't say that it's obviously a clearer solution though:Output (obviously we can drop the original samples column now):
Python

Dependency analysis programs help us organize code by controlling the dependencies between modules in our code. When one module is a circular dependency of another module, it is a clue to find a way to turn that into a unidirectional dependency or merge two modules into one module.What is the best dependency analysis tool for Python code?I recommend using  for creating graphical dependency graphs of Python projects. It detects dependencies nicely enough to immediately see areas for refactorisation. Its usage is pretty straightforward if you read a little bit of documentation.Of course, you can omit the graph-creation step and receive a dependency dictionary in a file instead.I don't know what is the  dependency analysis tool.  You could look into  \u2013 it's a module in the standard library that determines the set of modules imported by a script.Of course, with python you have problems of conditional imports, and even potentially scripts calling  directly, so it may not find everything.  This is why tools like py2exe need special help to cope with packages like PIL.PyStructure \u2013 Automated Structure and Dependency Analysis of Python CodeThis is used for PyDev's refactoring features. I'm not sure about the best tool, but dependency analysis is best done using extracting and scanning the python files of the project.Here is one such tool using the above technique : 
Python

How can I turn the above into a function where I pass the name of the class?\nIn the above example, Subscriber is a class name. I want to do something like this: Thanks,\nNeal Walters If you pass the class object directly, as in your code between \"like this\" and \"or\",\nyou can get its name as the  attribute.Starting with the name (as in your code  \"or\") makes it REALLY hard (and not unambiguous) to retrieve the class object unless you have some indication about where the class object may be contained -- so why not pass the class object instead?!A slight variation of Ned's code that I used.  This is a web application, \nso I start it by running the get routine via a URL: .  I didn't see the need of the . Output: 
Python

I have tens of millions of rows to transfer from multidimensional array files into a PostgreSQL database. My tools are Python and psycopg2. The most efficient way to bulk instert data is using . However, my data are mostly 32-bit floating point numbers (real or float4), so I'd rather not convert from real \u2192 text \u2192 real. Here is an example database DDL:Here is where I'm at with Python using strings (text):Is there an equivalent that could work using a binary mode? I.e., keep the floating point numbers in binary? Not only would this preserve the floating point precision, but it could be faster.(Note: to see the same precision as the example, use )Here is the binary equivalent of COPY FROM for Python 3:I rewrote the above approach to writing the files for COPY. My data in Python is in NumPy arrays, so it makes sense to use these. Here is some example  with with 1M rows, 7 columns:On my database, I have two tables that look like:and another similar table named .Here are some simple helper functions to prepare the data for COPY (both text and binary formats) by using the information in the NumPy record array:This how I'm using the helper functions to benchmark the two COPY format methods:Here is the output from the last two  commands:So both the NumPy \u2192 file and file \u2192 database steps are way faster with the binary approach. The obvious difference is how Python prepares the COPY file, which is really slow for text. Generally speaking, the binary format loads into the database in 2/3 of the time as the text format for this schema.Lastly, I compared the values in both tables within the database to see if the numbers were different. About 1.46% of the rows have different values for column , and this fraction increases to 6.17% for  (probably related on the random method that I used). The non-zero absolute differences between all 70M 32-bit float values range between 9.3132257e-010 and 7.6293945e-006. These small differences between the text and binary loading methods are due to the loss of precision from the float \u2192 text \u2192 float conversions required for the text format method. is my version. Based on Mike's version. Its very ad-hoc but there are two pros:
Python

I've recently started experimenting with using Python for web development. So far I've had some success using Apache with mod_wsgi and the Django web framework for Python 2.7. However I have run into some issues with having processes constantly running, updating information and such.I have written a script I call \"daemonManager.py\" that can start and stop all or individual python update loops (Should I call them Daemons?). It does that by forking, then loading the module for the specific functions it should run and starting an infinite loop. It saves a PID file in  to keep track of the process. So far so good. The problems I've encountered are:Any useful answer on how to  run infinite Python processes, hopefully also shedding some light on the above problems, I will acceptI'm using Apache 2.2.14 on an Ubuntu machine.\nMy Python version is 2.7.2I'll open by stating that this is  way to manage a long running process (LRP) -- not de facto by any stretch.In my experience, the best possible product comes from concentrating on the specific problem you're dealing with, while delegating supporting tech to other libraries. In this case, I'm referring to the act of backgrounding processes (the art of the double fork), monitoring, and log redirection. My favorite solution is Using a system like supervisord, you basically write a conventional python script that performs a task while stuck in an \"infinite\" loop.Writing your script this way makes it simple and convenient to develop and debug (you can easily start/stop it in a terminal, watching the log output as events unfold). When it comes time to throw into production, you simply define a supervisor config that calls your script (here's the  example for defining a \"program\", much of which is optional: ).Supervisor has  of configuration options so I won't enumerate them, but I will say that it specifically solves the problems you describe:I assume you are running Unix/Linux but you don't really say. I have no direct advice on your issue. So I don't expect to be the \"right\" answer to this question. But there is something to explore here.First, if your daemons are crashing, you should fix that. Only programs with bugs should crash. Perhaps you should launch them under a debugger and see what happens when they crash (if that's possible). Do you have any trace logging in these processes? If not, add them. That might help diagnose your crash.Second, are your daemons providing services (opening pipes and waiting for requests) or are they performing periodic cleanup? If they are periodic cleanup processes you should use cron to launch them periodically rather then have them run in an infinite loop. Cron processes should be preferred over daemon processes. Similarly, if they are services that open ports and service requests, have you considered making them work with INETD? Again, a single daemon (inetd) should be preferred to a bunch of daemon processes.Third, saving a PID in a file is not very effective, as you've discovered. Perhaps a shared IPC, like a semaphore, would work better. I don't have any details here though.Fourth, sometimes I need stuff to run in the context of the website. I use a cron process that calls wget with a maintenance URL. You set a special cookie and include the cookie info in with wget command line. If the special cookie doesn't exist, return 403 rather than performing the maintenance process. The other benefit here is login to the database and other environmental concerns of avoided since the code that serves normal web pages are serving the maintenance process.Hope that gives you ideas. I think avoiding daemons if you can is the best place to start. If you can run your python within mod_wsgi that saves you having to support multiple \"environments\". Debugging a process that fails after running for days at a time is just brutal.You should consider Python processes as able to run \"forever\" assuming you don't have any memory leaks in your program, the Python interpreter, or any of the Python libraries / modules that you are using. (Even in the face of memory leaks, you might be able to run forever if you have sufficient swap space on a 64-bit machine. Decades, if not centuries, should be doable. I've had Python processes survive just fine for nearly two years on limited hardware -- before the hardware needed to be moved.)Ensuring programs restart when they die used to be very simple back when Linux distributions used  -- you just add a new line to the  and  would spawn your program at boot and re-spawn it if it dies. (I know of no mechanism to replicate this functionality with the new  -replacement that many distributions are using these days. I'm not saying it is impossible, I just don't know how to do it.)But even the  mechanism of years gone by wasn't as flexible as some would have liked. The  package by DJB is one example of process control-and-monitoring tools intended to keep daemons living forever. The  suite provides another similar tool, though it might provide too much \"extra\" functionality to be justified for this task.  is another option.
Python

Here is the thing, I have a proxy holding the reference to a remote module, and I put some of these proxies to the  such that I can use it just like local modules. But some other objects are put in the  module at the remote environment (like a magic variable for convenience of debugging or referencing). I don't want to reference these vars like , and I have to either replace the local  (which seems not working for replace  or to hook the global name finding rules.\nHow? For a module you can just overload a  to do this. But in a interactive interpreter like , who is the main module or how to do this?   As pointed out by @Nizam Mohamed, yes I can get the  module, but still I can't modify the name lookup role of it.   For now I just iterate all the  and if there is a name that isn't in the local . I add the name to local's . But it's not so dynamic compare to a name lookup rule say if I can't find the name in local  try the remote one. is a similar discussion.And  question gives a simulation of module by replace it with a object in . But this won't work for  name lookup, I've also tried to replace the  with a custom one that will first use the original lookup followed by a custom one when failed. But global name lookup of  never called into the  even  returns the desired value,  or  never returns one.As @asmeurer said, you can write a simple AST transformer to \"hook\" the variable name lookup. The base class  provide a  method that you can manipulate. You just need to overload this method to redefine those variables existing in the remote module but not locally.The following module can be used as an :testAST.pydummyModule.pyUsage:The benefit of this method is that any modification to the remote module takes effect immediately because the lookup is done in the language level and no object is copied and cached.One drawback of this method is not being able to handle dynamic lookup. If that's important for you, maybe the  hook is more suitable.There is a way to get a list of all names the module will use. Although it does not modify the lookup mechanism, I believe it solves your problem.Here is some code (hopefully understandable enough) you can put in a module, let's call it :You can then import it to do magic:There are two downsides, however. First, dynamic lookups will fails:Although that particular case can be solved by looking at the strings in , it will not work with more advanced dynamic lookups like The second downside is that it will not work in functions:This is because in that case, the name  is in \u00a0instead of the module's .One possible solution would be to modify  to try to find all functions of the module and alter their code, but it won't work with functions defined inside functions, etc.An other solution is to call  in the function:
Python

So I have a few Python C extensions I have previously built for and used in 32 bit Python running in Win7. I have now however switched to 64 bit Python, and I am having issues building the C extension with MinGW-w64.I made the changes to distutils as per , but I am getting some weird errors suggesting something is wrong:I have googled around quite a bit to find information, but it's not easy to find a definite answer. Could someone shed some light on this? What further changes should I do to be able to successfully build C extensions for 64 bit Python in Win7?EDIT:After some helpful pointers in cgohlke's comments below I managed to generate . However after following the advice on  (2nd to last) I still had a the  error. After some serious Google-fu I managed to trip over  telling me to rename the  line to . After that everything worked swimmingly.This worked for me with Python 3.3 :voila!
Python

Experimenting with some code and doing some microbenchmarks I just found out that using the  function on a string containing an integer number is a factor 2 faster than using  on the same string.It gets even stranger when testing  which runtime is shorter than the bare .I tested the code under Windows 7 running cPython 2.7.6 and Linux Mint 16 with cPython 2.7.6. I have to add that only Python 2 is affected, Python 3 shows a way smaller (not remarkable) difference between the runtimes.I know that the information I get by such microbenchmarks are easy to misuse, but I'm curious why there is such a difference in the functions' runtime.I tried to find the implementations of  and  but I can not find it in the sources. has lots of bases.*, 0*, 0x*, 0b*, 0o* and it can be long, it takes time to determine the base and other thingsif the base is set, it saves a lot of timeas @Martijn Pieters metions the code the  and 
Python

The setuptools documentation only states:In practical terms, what is the performance benefit gained? Is it worth investigating if my projects are zip-safe, or are the benefits generally minimal?Zip files take up less space on disk, which also means they're more quickly read from disk. Since most things are I/O bound, the overhead in decompressing the packaging may be less than the overhead in reading a larger file from disk. Moreover, it's likely that a single, small-ish zip file is stored sequentially on disk, while  a collection of smaller files may be more spread out. On rotational media, this also increases read performance by cutting down the number of seeks. So you generally optimize your disk usage at the cost of some CPU time, which may dramatically improve your  and load times.There are several advantages, in addition to the ones already mentioned.Reading a  large .egg file (and unzipping it) may be significantly faster than loading multiple (potentially a lot of) smaller .py files, depending on the storage medium/filesystem on which it resides.Some filesystem have a large block size (e.g., 1MB), which means that dealing with small files can be expensive. Even though your files are small (say, 10KB), you may actually be loading a 1MB block from disk when reading it. Typically, filesystems combine multiple small files in a large block to mitigate this a bit.On filesystems where access to file metadata is slow (which sometimes happens with shared filesystems, like NFS), accessing a large amount of files may be very expensive too.Of course, zipping the whole bunch also helps, since that means that less data will have to be read in total.Long story short: it may matter a lot if your filesystem is more suited for a small amount of large files.
Python

Is there a way to use  to organize multiple files into a ?Reason:  Modules are easier to use than packages, because they don't have as many layers of namespace.Normally it makes a package, this I get.  Problem is with a package, 'import thepackage' gives me an empty namespace.  Users must then either use \"from thepackage import *\" (frowned upon) or know exactly what is contained and manually pull it out into a usable namespace.What I want to have is the user do 'import thepackage' and have nice clean namespaces that look like this, exposing functions and classes relevant to the project for use.The maintainer's job would be to avoid defining the same name in different files, which should be easy when the project is small like mine is.It would also be nice if people can do  and have it retrieve the class, rather than a module containing the class.This is easy if all my code is in one gigantic file, but I like to organize when things start getting big. What I have on disk looks sort of like this:I only separate them so my files aren't huge and unnavigable.  They are all related, though someone (possible me) may want to use the classes by themselves without importing everything.I've read a number of suggestions in various threads, here's what happens for each suggestion I can find for how to do this:If I , I cannot import anything because Python doesn't descend into the folder from sys.path.If I , when I  it's an empty namespace with nothing in it. None of my files imported, which makes it more difficult to use.If I , I can use the (frowned upon?)  syntax, but all of my classes are behind unnecessary namespace barriers again. The user has to (1) know they should use  instead of , (2) manually reshuffle classes until they can reasonably obey line width style constraints.If I , I get closer but I have namespace conflicts (?) and extra namespaces for things I didn't want to be in there.  In the below example, you'll see that:.Also someone importing just the data abstraction class would get something different than they expect when they do 'from doit_tools import JobInfo':So, is this just a wrong way to organize Python code? If not, what is a correct way to split related code up but still collect it in a module-like way?Maybe the best case scenario is that doing 'from doit_tools import JobInfo' is a little confusing for someone using the package?Maybe a python file called 'api' so that people using the code do the following?:============================================Examples in response to comments:Take the following package contents, inside folder 'foo' which is in python path.Do this: and  are there cluttering things up, and also have extra copies of e.g. doit() underneath their namespaces.If I have a class named Data inside a file named Data.py, when I do 'from Data import Data' then I get a namespace conflict because Data is a class in the current namespace that is inside module Data, somehow is also in the current namespace.  (But Python seems to be able to handle this.)You can sort of do it, but it's not really a good idea and you're fighting against the way Python modules/packages are supposed to work. By importing appropriate names in  you can make them accessible in the package namespace.  By deleting module names you can make them inaccessible.  (For why you need to delete them, see ).  So you can get close to what you want with something like this (in ):However, this will break subsequent attempts to .  In general, you can't import anything from a  without making  accessible as an importable reference to that module (although with the  you can block ).More generally, by splitting up your code by class/function you are working against the Python package/module system.  A Python module should generally contain stuff you want to import as a unit.  It's not uncommon to import submodule components directly in the top-level package namespace for convenience, but the reverse --- trying to hide the submodules and allow access to their contents  through the top-level package namespace --- is going to lead to problems.  In addition, there is nothing to be gained by trying to \"cleanse\" the package namespace of the modules.  Those modules are supposed to be in the package namespace; that's where they belong.Define  in the  e.g.:Real-world example: .You have some misconception about how Python packages work:You need  file in Python versions older than Python 3.3 to mark a directory as containing a Python package.It doesn't prevent the import:It works as expected.(1) Your users (in most cases) should  use  outside an interactive Python shell.(2) you could use  to break a long import line:It is upto you to resolve namespace conflicts (different objects with the same name). The name can refer to any object: integer, string, package, module, class, functions, etc. Python can't know what object you might prefer and even if it could it would be inconsistent to ignore some name bindings in this particular case with respect to the usage of name bindings in all other cases.To mark names as non-public you could prefix them with  e.g., .python is not java. Module file name does not need to be the same as class name. In fact python recommend using all lower case for module file name.Also \"from math import sqrt\" will only add sqrt to namespace, not math.There are perfectly valid reasons to hide the sub-structure of a package (not only when debugging). Amongst them are  and . When trying to do a rapid prototype with a package it is extremely annoying having to interrupt the train of thought just to look up the utterly useless information what the exact sub-module for a specific function or class might be.When everything is available at the top level of a package, The idiom:displays the , not just some measly module names.You can always turn off sub-module imports for production code, or to clean up the package modules after development.The following is the best way I have come up with so far. It maximizes convenience while trying not to suppress valid errors. See also the .Define package name and sub-modules to be imported to avoid error-prone duplication:Use relative imports when available (this is imperative, see ):Try importing the package, including .\nThis happens when executing a module file as script with the\npackage in the search path (e.g. )As a last resort, try importing the sub-modules directly.\nThis happens when executing a module file as script inside the\npackage directory without the package in the search path\n(e.g. ).Construct  (leaving out modules), unless it has been imported\nbefore:Here is the function :
Python

On Ubuntu 16.04 with virtualenv 15.0.1 and Python 3.5.2 (both installed with ) when I create and activate new Python virtual environment withI get the following output:Indeed  lists these 4 packages:Though, I'd expect  (without ) to omit these implicitly installed packages. It does omit some of them, but not :(Same btw. for )While this is consistent with the help texthaving  in the  output doesn't seem very useful and might even be harmful. (I suspect it's why running  from  uninstalls pkg-resources from the virtual environment, subtly breaking the environment thereby.)  As far as I remember, it didn't list it on Ubuntu 14.04 (with Python 3.4).According to , this is a bug resulting from Ubuntu providing incorrect metadata to pip. So, no there does not seem to be a good reason for this behaviour. I filed a follow-up bug with Ubuntu. I had the same problem.\nwith commands It just worked.
Python

I have two zip files, both of them open well with Windows Explorer and 7-zip. However when i open them with Python's zipfile module [ zipfile.ZipFile(\"filex.zip\") ], one of them gets opened but the other one gives error \"\".I've made sure that the latter one is a valid Zip File by opening it with 7-Zip and looking at its properties (says 7Zip.ZIP). When I open the file with a text editor, the first two characters are \"PK\", showing that it is indeed a zip file.I'm using Python 2.5 and really don't have any clue how to go about for this. I've tried it both with Windows as well as Ubuntu and problem exists on both platforms. Traceback from Python 2.5.4 on Windows:Basically when the  function is called for getting data from End of Central Directory\" record, the comment length checkout fails [ endrec[7] == len(comment) ]. The values of locals in the  function are as following:files named file can confuse python - try naming it something else. if it  wont work, try this code:I run into the same issue. My problem was that it was a gzip instead of a zip file. I switched to the class  and it worked like a charm.astronautlevel's solution works for most cases, but the compressed data and CRCs in the Zip can also contain the same 4 bytes. You should do an  (not ), seek to pos+20 and then add write  to the end of the file (tell zip applications that the length of the 'comments' section is 0 bytes long).Show the full traceback that you got from Python -- this may give a hint as to what the specific problem is.  What software produced the bad file, and on what platform?Update: Traceback indicates having problem detecting the \"End of Central Directory\" record in the file -- see function _EndRecData starting at line 128 of C:\\Python25\\Lib\\zipfile.pySuggestions:\n(1) Trace through the above function\n(2) Try it on the latest Python\n(3) Answer the question above.\n(4) Read  and anything else found by  that appears to be relevantI had the same problem and was able to solve this issue for my files, see my answer at \nHave you tried a newer python, or if that is too much trouble, simply a newer zipfile.py? I have successfully used a copy of zipfile.py from Python 2.6.2 (latest at the time) with Python 2.5 in order to open some zip files that weren't supported by Py2.5s zipfile module.
Python

I would like to put some logging statements within test function to examine some state variables.I have the following code snippet:I get the following output:Notice that only the logging messages from the  block get transmitted to the console.Is there a way to force pytest to emit logging to console from test methods as well?Works for me, here's the output I get: [snip -> example was incorrect]Edit: It seems that you have to pass the  option to py.test so it won't capture stdout. Here (py.test not installed), it was enough to use  .For your code, all you need is to pass  in  to :See the py.test documentation on .
Python

I noticed Pandas now has .  Currently, I create s like this:Is there a way to create a  with a  or ? Converting to dense format kills RAM badly. Thanks!A direct conversion is not supported ATM. Contributions are welcome!Try this, should be ok on memory as the SpareSeries is much like a csc_matrix (for 1 column)\nand pretty space efficientAs of pandas v 0.20.0 you can use the  constructor.An example from :A much shorter version:
Python

Python is a \"whitespace delimited\" language.  However, the use of semicolons  allowed.  For example, the following works but is frowned upon:I've been using python for several years now, and the only time I have ever used semicolons is in generating one-time command-line scripts with python:or adding code in comments on SO (i.e. \"you should try \")I also noticed in  that the semicolon can also be used to make one line  blocks, as inwhich is convenient for the two usage examples I gave (command-line scripts and comments).The above examples are for communicating code in paragraph form or making short snippets, but not something I would expect in a production codebase.  Here is my question: in python, is there ever a reason to use the semicolon in a production code?  I imagine that they were added to the language solely for the reasons I have cited, but its always possible that Guido had a grander scheme in mind.  No opinions please; I'm looking either for examples from existing code where the semicolon was useful, or some kind of statement from the python docs or from Guido about the use of the semicolon. is the official style guide and says:(See also the examples just after this in the PEP.)While I don't agree with everything PEP 8 says, if you're looking for an authoritative source, that's it.  You should use multi-statement lines only as a last resort.  ( is a good example of such a last resort, because you have no way to use actual linebreaks in that case.)I use semicolons in code all of the time. Our code folds across lines quite frequently, and a semicolon is a definitive assertion that a statement is ending.See? They're quite helpful to readability.
Python

model example)If 72 and '2011-08-07' is already storedraises the question is why  raises the , thats the idea of using \n.Not sure if this is a bug, I opened a ticket It appears your problem is with there being more columns you're not including in your , see i.e.  on a Django mailing list.You need to use the  parameter of  as described in the , or specify values for all columns, for  to match correctly.
Python

I've started working on a project with loads of unused legacy code in it.  I was wondering if it might be possible to use a tool like coverage in combination with a crawler (like the django-test-utils one) to help me locate code which isn't getting hit which we can mark with deprecation warnings.  I realise that something like this won't be foolproof but thought it might help.I've tried running coverage.py with the django debug server but it doesn't work correctly (it seems to just profile the runserver machinery rather than my views, etc).We're improving our test coverage all the time but there's a way to go and I thought there might be a quicker way.Any thoughts?Thanks.You can run the development server under coverage if you use the --noreload switch: is great tool for static code analysis (among others things it will detect unused imports, variables or arguments).
Python

I'm familiar with  C function. I've been using this function for many purpouses. Most of them, if not all, for reading and writting to pipes, files, etc... I must say that I've never used the error list, but this is not involved in the key question.Does python  behaves as the following?It turns out to me that  on python behaves a different way despite the  interface to C . It seems that  returns the very first time a file is ready for reading. If you read the file letting being bytes on its queue, calling  will block. But, if you call  again after a previous call to  was returned without any read call between these two calls,  will return as expected. For example:If this is the behaviour of  in python, I'm okay with that, I could handle it. Not what I expected though, but it's fine, I know what I can do with it.But, if this is not the behaviour of  I would appreciate someone to tell me what I'm doing wrong. What I read about  is what the python doc says: \"select() returns if any file in the read|write|error list is ready for read|write|error.\". That's ok, no lies there. Maybe the questions should be: Python's  gets passed through as a  system call as you are expecting, but the problem you have with it blocking is a different issue, probably relating to buffering.  Just to satify yourself that  is doing the right thing, try reading/writing a file on the file system rather than using a special device such as a joystick.You probably want to change your  call.  Pythons  call will by default use buffered reads, so even if you do a  it will likely read more data from the input file and buffer the results.  You need to set the  option to  so that the joystick device is opened unbuffered.Suggestions for you to try:Can I ask a stupid question - are you sure there are really 8 bytes left?Device nodes don't necessarily behave like normal files.  It might be that you have to read the entire struct input_event in a single read() system call.  (And if you don't read enough, the rest gets thrown away).  A bit like recvmsg() on datagram sockets.
Python

There are lots of questions about using numpy in cython on this site, a particularly useful one being .However, the cython/numpy interface api , in particular with ensuring the passing of memory-contiguous arrays.What is the best way to write a wrapper function in cython that:My try is below:This code compiles but is not necessarily optimal. Do you have any suggestions on improving the snippet above?You've basically got it right. First, hopefully optimization shouldn't be a big deal. Ideally, most of the time is spent inside your C++ kernel, not in the cythnon wrapper code.There are a few stylistic changes you can make that will simplify your code. (1) Reshaping between 1D and 2D arrays is not necessary. When you know the memory layout of your data (C-order vs. fortran order, striding, etc), you can see the array as just a chunk of memory that you're going to index yourself in C++, so numpy's ndim doesn't matter on the C++ side -- it's just seeing that pointer. (2) Using cython's address-of operator , you can get the pointer to the start of the array in a little cleaner way -- no explicit cast necessary -- using .So this is my edited version of your original snippet:
Python

All the docs I've seen imply that you  be able to do that, but there isn't anything official w/r/t ulong64/uint64 fields. There are a few off-the-shelf options that look quite promising in this arena:... all of which  like they  store a number like that. Except NONE OF THEM WILL COMMIT, much like every single rom-com character portrayed by Hugh Grant. My primary criterion is that it works with Django's supported backends, without any  type of special-case nonsense. After that, there is the need for speed -- this is for a model field in an visual-database application that will index image-derived data (e.g. perceptual hashes and extracted keypoint features), allowing ordering and grouping by the content of those images.So: is there a good Django extension or app that furnishes some kind of  that will suit my purposes?And, barring that: If there is a simple and reliable way to use Django's stock ORM to store unsigned 64-bit ints, I'd like to know it. Look, I'm no binary whiz; I have to do two's complement on paper -- so if this method of yours involves some bit-shifting trickery, don't hesitate to explain what it is, even if it strikes you as obvious. Thanks in advance.Although I did not test it, but you may wish to just subclass . The original  looks like that ():Derived  may looks like this:Although you should test it thoroughly, before using it. If you do, please share the results :):I missed one thing - internal database representation. This is based on value returned by  and the definition of the column type is stored eg.  in case of MySQL backend and determined . It looks like overwriting  will give you control over how the field is represented in the database. However, you will need to find a way to return DBMS-specific value in  by checking  argument.
Python

It seems common practice in Flask to start like this:And then import and use  and  everywhere.  But when you create  like this, it grabs configuration from the app, and it seems that this configuration can't ever be overridden once it happens.  There are some pages on Flask's website about making application factories, but it's not clear how I would be able to still use  and  everywhere if I did that.How do I write a script to test my Flask application with a different database?  How should I structure my application to make this possible?  Do I have to use s ?Your instinct to use environment variables is correct. However, there is some danger of running unit tests with the wrong db. Also, you may not want to  with every request and everywhere you want to use . You can use a config directory and environment variables which you set explicitly. This is the best I've come up with so far.so, the config files may be:andSo, I can explicitly set the db in my base TestCase:Then, the , for me:Then, in the other files, where I know what config I want to run, potentially:andMaybe .. best so far :P.You won't want to make connecting to the db happen at import time.  Go ahead and configure your app at import time because you can always tweak the configuration in your tests before attempting to test or run your app.  In the example below you'll have your db connection behind some functions that use the application config so in a unittest you can actually change the db connection to point to a different file and then go ahead and connect explicitly in your setup.Say you have a myapp package containing myapp.py which looks like:Your test file myapp/test_myapp.py will look like this:Of course if you'd like to use SQLAlchemy you'll have to update the connect_db and init_db functions appropriately but hopefully you get the idea.First, instead of instantiating Flask app directly in your script, you use an . It means you create a function that takes your config file as parameter, and return the instantiated app object. Then, you create the global SQLAlchemy object without parameter, and you configure it when creating the app, .To run the app, you simply do something like:To run unittests, you can do something like:In my case, I'm using SQLAlchemy directly with scoped_session instead of Flask-SQLAlchemy.\nI did the same, but with .
Python

I often find myself doing this:Is there a more concise way to do this in Python? I am thinking of something along the lines ofYou can use :If you've got  as a dependency already,  will do the trick ...Use :From the docs:It depends on what is inside the loop.  If dealing with lists, you may be able to use a For the more general case, see  on itertools. 
Python

I'm probably doing something very stupid, but I'm stumped.I have a dataframe and I want to replace the values in a particular column that exceed a value with zero. I had thought this was a way of achieving this:If I copy the channel into a new data frame it's simple:this does exactly what I want, but seems not to work with the channel as part of the original dataframe.Thanks is advance.BenTry indexer works okay for pandas version prior to 0.20.0, but since pandas 0.20.0, the  indexer is , so you should avoid using it. Instead, you can use  or  indexers. In this case you can solve your problem by: helps you to select the rows in which  is , while  sets the value 0 to the selected rows where holds in the column which name is .
Python

Is there a standard body or a specific normative way how time-related things should be  (like ICU for Unicode-related tasks) or is this currently a \"best-effort\", depending on how much effort, time and money language and library implementers want to spend?Is there a specific and complete implementation which could serve as a example for how time-related things should be handled?Which existing library would you consider as a bad, a decent or a good example?These classes are a complete rewrite of JodaTime trying to fix the design flaws of / as well as JodaTime.JSR 310 tries to provide a comprehensive model for date and time, which is type-safe and self-documenting. It is interoperable with existing classes, but also considers XML- and DBMS-based use-cases.\nThe classes are final, immutable, thread-safe and cannot be modified after construction. Instances are created via a rich set of Factory methods which can cache things in the background.The API has some \"machine-oriented\" classes and some \"human-oriented\" classes:For a point of time comparable to an Unix or Java timestamp. Actually there are ,  and  which enable people to exactly choose which definition of time they need i. e. \"day-based\", \"linear, without leap seconds\" etc.A time range not necessarily associated with a specific Date or Calendar.There is a rich collection of classes handling different use-cases like Date-only, Time-only, Time and Date, with and without Timezones, with and without DST.,  (,  compatibility),  (,  compatibility), ,  (,  compatibility), ,  (,  compatibility)Periods represent a time span like \"5 days\" that can be added and subtracted from a date/time.Matchers enable queries like \"is this date in the year 2006?\" or \"is this day the last day of this year\".Adjusters come to the rescue if you have want to make more complex changes, like \"Give me the last day of the month!\" or \"The second Tuesday after Christmas, please!\".Resolvers allow users to define what should happen if a certain date is not valid, like February 31st 2010:It is possible to serialize these classes and deserialize them using either the current timezone data or the timezone data when they were serialized.\nAdditionally, rules from different timezones can be compared: It is possible to find out if DST rules have changed, e. g. between version 2010e and 2010f for Dates in London or Moscow and decide what should be done if a Time is in a gap or overlap.Although everything is based on , simple calendars for Hebrew, Hijrah, Japanese, ThaiBuddist, etc. time systems are provided. returns ISO8601 and patterns like those in  and more advanced are supported.\nThe first problem is that dates are not linked to time but to astronomical position of Earh, Moon, etc. + regularity/periodicity of human activity. The time is also subjective and relative or even relativistic and measured either astronomically or or atomically.    \n [4] has issued   which, like other international standards,  is recommendation and is based on already established practices.\nIt is (subjectively) based only on Gregorian Calendar [5] and on proleptic one (projected backwards to well before it was actually invented so is of limited use in dealing with historic dates) [5a].   The World Calendar Association [1d] initiated the introduction of new World Calendar since 2012 [1b-1d] which would make useless already existing date libraries. Again, the same main problem, see on it further on.    The most covering, I ever saw, date-time-related comparison in IT systems is [2] between BIG8 DBMS (IBM DB2, Informix, Ingres, InterBase, Microsoft SQL Server, MySQL, Oracle, and Sybase).\nThis and all other surveys show that     in all-all systems, frameworks is that their date/time datatypes do not permit to include .\nWithout which they are mainly half- useless - what is the sense of milliseconds in SQL Server datetime2 values in 7th century? At that time there was even no clocks measuring time with accuracy of minutes (Galileo Galilei used, for ex., his heart beats to measure intervals of time in his experiments) as well as Gregorian Calendar was not even invented.          Just fast illustrations:   ==== Cited:\n[1] New World Calendar\n[1a]\n\n[1b] \n[1c] \n[1d] [2] Peter Gulutzan,Trudy Pelzer. SQL Performance Tuning: Dates in SQL\n[3] SqlDateTime.MinValue != C# DateTime.MinValue, why?\n  [4]\nInternational Organization for Standardization\n\n[4a] ISO 8601 Data elements and interchange formats \u2014 Information interchange \u2014 Representation of dates and times\n   [5]\nGregorian Calendar\n\n[5a] Proleptic Gregorian calendar\n\n[5b] Gregorian Calendar Adoption\n\n[6]\n  I don't think there's a single standard to such things at the moment, however there are multiple standards which such things may conform to: ISO 8601 for example.'s own date/time handling is a cross-language (C/C++ and Java) and multi-platform library.It handles dates and times internally, typically, using for a single time a UDate (C/C++) or a java.util.Date/long (Java), as number of milliseconds since 1-1-1970, or a Calendar object which is specific to the type of calendar (Gregorian vs Hijri, etc).   Durations are available for formatting.   Leap years are calculated as part of calendar systems, and leap seconds are assumed to be handled by the underlying operating system.   DST/Timezone data is kept up to date with 'the tz database' sometimes referred to by its author's surname, Olson.Hope this has answered your question some as regards ICU.I haven't used it in a while, but from past experience I'd say that  is a pretty good example.While probably not the first choice for many fast paced projects today, the expressive power of C++ still seems to be a very good match for a complex problem domain like date/time, so combined with the high quality peer review process to pass for becoming an official Boost C++ library I'd hope that the library at hand could , albeit not as a , see below.The library is documented  well, so I could probably assemble the entire answer from quotes, but I'll try to extract some fragments according to the template suggested by  instead - nonetheless I'm going to start with an entire quote:The library supports 3 basic temporal types:You can get a pretty intuitive overview on how the domain concepts relate to each other in section .An important part of my original decision to evaluate the library has been the available documentation of design goals and necessary tradeoffs in light of the complex problem domain, which seems to outline the real world expertise that has been put into the library - you can read more about it in the following two sections:There is full support for all kind of calculations and conversions one could think of, as far as I'm concerned - see the headings in section  for an initial impression.This is definitely the weak spot concerning your specification, despite the library being specifically designed with extensibility in mind:However, I'm not aware of any implementations of other calendar/time systems than the ones included, see  for the current implementations of:This is fully supported and one of the strong points of the library due to the respective power of the underlying C++ I/O system, see  - the stream oriented C++ I/O has both merit and issues depending on your needs and expectations, but this topic is discussed elsewhere on this site.This is  via compatibility with , which is  oriented though, usually meaning a  or so; i.e. databases are not explicitly supported as in your  example.You mention Python in an earlier comment.  Python's builtin  support  is pretty practical, but you have to use a third-party timezone database such as   to make it close to complete.  And, as the pytz docs mention, you may still have problems with adding deltas to times right around DST transitions if you aren't careful.It was once the case that eGenix's  was the way to go if datetime didn't do it for your application, particularly for string to timestamp conversions, but  seems to be popular these days (I haven't used it though).To answer your \"Good Example\" question, take a look at  - 's port of the  libraries for Java to .Net
Python

I am creating a program for analyzing and generating queries.  I was curious if there currently exists a method within SQLite such that I could query the time taken for a query to process?  I am unable to modify my install in any way, so this method needs to work out of the box.  I am writing my tool in python, and although I guess I could use the timer class to time execution -this method will not work when I am connecting to remote machines (and return a consistent timing.) From within the sqlite3 command-line program you can do:This will print the CPU time taken for the query.
Python

I use Python 2.7 and matplotlib. I have a *.txt data file :first column of my file (numbers) should be on axis Y in my bar chart, and the second column from my file (dates) should be on axis OX in my histogram. I only know how to read the file:I did read a matplotlib docs but it still doesn't help me. I would also like to add dates I read to my bar chart, to make it look likeCould someone please help me?You're talking about histograms, but this doesn't quite make sense. Histograms and bar charts are different things. An histogram would be a bar chart representing the sum of values per year, for example. Here, you just seem to be after bars.Here is a complete example from your data that shows a bar of for each required value at each date:You need to parse the date with  and set the x-axis to use dates (as described in ).If you're not interested in having the x-axis show a linear time scale, but just want bars with labels, you can do this instead:EDIT: Following comments, for all the ticks, and for them to be centred, pass the range to  (and move them by half the bar width):This code will do what you're looking for. It's based on examples found  and .The  call is particularly useful for making the x-axis labels readable.First, what you are looking for is a  or , not really a histogram. A histogram is made from a frequency distribution of a continuous variable that is separated into bins. Here you have a column against separate labels.To make a bar diagram with matplotlib, use the  method. Have a look at  of the matplotlib documentation that explains very well with examples and  how to do it.If it is possible though, I would just suggest that for a simple task like this if you could avoid writing code that would be better. If you have any spreadsheet program this should be a piece of cake because that's exactly what they are for, and you won't have to 'reinvent the wheel'. The following is the plot of your data in Excel:I just copied your data from the question, used the text import wizard to put it in two columns, then I inserted a column diagram.
Python

I need to create a symlink for every item of dir1 (file or directory) inside dir2. dir2 already exists and is not a symlink. In Bash I can easily achieve this by: But in python using os.symlink I get an error:I know I can use  and run  command. I don't want that solution. I'm also aware that workarounds using  or  are possible, but I want to know if it is possible to do this using . creates a single symlink. creates multiple symlinks (if its last argument is a directory, and there's more than one source). The Python equivalent is something like:So, how does it work when you do ? Your  makes that work, by turning the wildcard into multiple arguments. If you were to just  the  command with a wildcard, it would look for a single source literally named  in , not all files in that directory.The Python equivalent is something like (if you don't mind mixing two levels together and ignoring a lot of other cases\u2014tildes, env variables, command substitution, etc. that are possible at the shell):You can't do that with  alone\u2014either part of it\u2014because it doesn't do that. It's like saying \"I want to do the equivalent of  using  without filtering on the name.\" Or, for that matter, I want to do the equivalent of  without the shell globbing for me.\"The right answer is to use , or , or  plus a regex, or whatever you prefer.Do  use , because that does a  filesystem walk, so it's not even close to shell  expansion. is a shell extension pattern, which in your case designates \"all files starting with \". But it's your  to the files it matches. Not the  command's.But  is not a shell, it's an OS call - hence, it doesn't support shell extension patterns. You'll have to do that work in your script. To do so, you can use , or . As indicated in the other answer, the appropriate call will depend on what you want to do. ( wouldn't be the equivalent of )To convince yourself: run this command on an Unix machine in your terminal: . You'll see that it's the shell that's doing the matching.  As suggested by @abarnert it's the shell that recognizes  and replaces it with all the items insside dir1. Therefore I think using  is the best choice:
Python

I have the following problem, I want to create my own colormap (red-mix-violet-mix-blue) that maps to values between -2 and +2 and want to use it to color points in my plot.\nThe plot should then have the colorscale to the right.\n\nThat is how I create the map so far. But I am not really sure if it mixes the colors.That way I map the colors to the values.Then I plot it:\nMy problems are:\n1. I can't plot the color scale.\n2. I am not completely sure if my scale is creating a continues (smooth) colorscale.There is an illustrative example of .\nThe docstring is essential for understanding the meaning of\n. Once you get that under your belt, you might use a  like this:Although the  format gives you a lot of flexibility, I find for simple\ngradients its format is rather unintuitive. Here is a utility function to help\ngenerate simple LinearSegmentedColormaps:By the way, the plots one point for every call to . This will work for a small number of points, but will become extremely slow for many points.  can only draw in one color, but  can assign a different color to each dot. Thus,  is the way to go.If you want to automate the creating of a custom divergent colormap commonly used for , this module combined with @unutbu method worked well for me.The high and low values can be either string color names or rgb tuples.  This is the result using the :\n
Python

I would like my default display for IPython notebook code cells to include line numbers. I learned from  that I can toggle this with ctrl-M L, which is great, but manual. In order to include line numbers by default, I would need to add something to my ipython_notebook_config.py file. Unless I've missed something, there is not an explanation of how to do this in the documentation. In your  file (location depends on your OS) put If you can't find custom.js, you can just search for it, but generally it will be in your profile_default folder. If it doesn't exist, create the file at If for whatever reason that doesn't work, you can always edit the  file in the  in the same way. In the latest Jupyter versions, they have  the place to make config changes. So basically, in the Jupyter update, they've removed the concept of profiles, so the  file location is now , depending on where your  folder is. So if you don't have a  folder or the  file, just create them, then put these lines into the newly created file:The above is for setting line numbers to  at the same time. Code, Markdown and Raw cells will all get line numbers if you do this. If you want line numbers , there is a simpler approach. Select a code cell, open the Chrome/Firefox JavaScript console, type the following lines:Then reload the page. These changes persist because Jupyter will create a json config file in  to store them. This method is from  of the documentation, so read the docs for more config changes that you can make.In the latest version of IPython Notebook (v3.1.0), go to  and add these lines:The  line alone will not work as it needs to load the IPython.Cell object before it tries this. Adding this line alone will cause an undefined error in the console. You need to encase it in the event handler as shown.@William-Denman's code might have worked for an earlier version, but now you will need to do this.Also, in the latest IPython/Jupyter, which I'm running using the , I couldn't find the  file within the profile folder. I found it (after  searching) in . I don't know if this is a WinPython thing or a Jupyter thing. If someone has Jupyter (latest version) installed normally (using pip or whatever) and can still find the  file in the profile folder, please comment.
Python

With  when a log scale is specified for an axis, the default method of labeling that axis is with numbers that are 10 to a power eg. 10^6. Is there an easy way to change all of these labels to be their full numerical representation? eg. 1, 10, 100, etc.Note that I do not know what the range of powers will be and want to support an arbitrary range (negatives included).Sure, just change the formatter.For example, if we have this plot:You could set the tick labels manually, but then the tick locations and labels would be fixed when you zoom/pan/etc.  Therefore, it's best to change the formatter:I've found that using  is great if all your tick values are greater than or equal to 1. However, if you have a tick at a number , the  prints the tick label as .I've used this  function with  to set numbers  to their integer value, and numbers  to their decimal value, with the minimum number of decimal places required (i.e. , etc). It assumes that you are only setting ticks on the  values.For clarity, here's that lambda function written out in a more verbose, but also more understandable, way:regarding these questionsyou can solve those issue like this with MINOR formatter:in my application I'm using this format scheme, which I think solves most issues related to log scalar formatting; the same could be done for data > 1.0 or x axis formatting: which yields:then to create a general use machine:yields:
Python

I would like to make a decorator which could be used with or without a parameter :\nSomething like this :In my code, only the use of decorator with parameter is working: How to proceed to have both working (with and without parameter)?I found an example, you can use  or : nice!If you want to take parameters to your decorator, you need to  call it as a function:Otherwise, you need to try to detect the difference in parameters--in other words, you need to magically guess what the caller means.  Don't create an API that needs to guess; consistently say what you mean to begin with.In other words, a function should either be a decorator, or a decorator factory; it shouldn't be both.Note that if all you want to do is store a value, you don't need to write a class.If you don't mind relying on using named arguments, I made something similar to what you need:This works because only one non keyword argument, the function decorated is passed to the decorator.Notice that I also used the arguments passed to the decorated function, in this case 'self'.You have to detect if the argument to the decorator is a function, and use a simple decorator in that case. And then you need to hope that you never need to pass only a function to the parametrized decorator.This would work.If a decorator function @invocation isn't passed any explicit arguments, it is called with the function defined in the following  . If it  passed arguments, then it is first called with them and then the result of  preliminary call (which must itself also be a callable) is called with the function being defined. Either way, the return value of the last or only call is bound to the defined function name.
Python

I have a NumPy array of  values. I want to count how many of these values are in a specific range say x<100 and x>25. I have read about the counter, but it seems to only be valid for specif values not ranges of values. I have searched, but have not found anything regarding my specific problem. If someone could point me towards the proper documentation I would appreciate it. Thank youI have tried thisBut it just gives me the numbers in between 25 and 99. \nThe data I am using was created by another program. I then used a script to read the data and store it as a list. I then took the list and turned it in to an array using array(r).The result of running If your array is called , the number of elements fulfilling  isThe expression  results in a Boolean array with the same shape as  with the value  for all elements that satisfy the condition.  Summing over this Boolean array treats  values as  and  values as .You could use . Here's a basic usage example:In your particular case, it would look something like this:Additionally, when you have a list of strings, you have to explicitly specify the type, so that  knows to produce an array of floats instead of a list of strings.Building on Sven's good approach, you can also do the more direct:This first creates an array of booleans with one boolean for each input number in array , and then count the number of non-False (i.e. True) values (which gives the number of matching numbers).Note, however, that this approach is twice as slow as Sven's  approach, on an array of 100k numbers (NumPy 1.6.1, Python 2.7.3)\u2013about 300\u00a0\u00b5s versus 150\u00a0\u00b5s.Sven's answer is the way to do it if you don't wish to further process matching values.\nThe following two examples return copies with only the matching values:Or: Example interpreter session:The above examples use a \"bit-wise and\" (&) to do an element-wise computation along the two boolean arrays which you create for comparison purposes.\nAnother way to write Sven's excellent answer, for example, is:  The boolean arrays contain  values when the condition matches, and  when it doesn't.\nA bonus aspect of boolean values is that  is equivalent to 1 and  to 0.  I think @Sven Marnach answer is quite nice, because it operates in on the numpy array itself which will be fast and efficient (C implementation).  I like to put the test into one condition like , so I would probably do it something like this:
Python

I need to convert time value strings given in the following format to seconds.I am using eg:Do I need to use regex to do this ?I tried to use time module,but   threw Can someone tell me how this can be solved?Edit:I thinkgives the correct value..I was using the wrong moduleFor Python 2.7:A little more pythonic way I think would be:Output is 263Sec.I would be interested to see if anyone could simplify it further.It looks like you're willing to strip fractions of a second... the problem is you can't use '00' as the hour with There is always parsing by handTo get the , you should subtract : above implies the input is less than a day, to support the time difference more than a day:To emulate  on Python 2.6:without imports
Python

I recently switch to Celery 3.0. Before that I was using  in order to integrate Celery with Flask. Although it had many issues like hiding some powerful Celery functionalities but it allowed me to use the full context of Flask app and especially Flask-SQLAlchemy.In my background tasks I am processing data and the SQLAlchemy ORM to store the data. The maintainer of Flask-Celery has dropped support of the plugin. The plugin was pickling the Flask instance in the task so I could have full access to SQLAlchemy.I am trying to replicate this behavior in my tasks.py file but with no success. Do you have any hints on how to achieve this?extensions.pyapp.pyOnce you've set up your app this way, you can run and use celery without having to explicitly run it from within an application context, as all your tasks will automatically be run in an application context if necessary, and you don't have to explicitly worry about post-task teardown, which is an important issue to manage (see other responses below).I prefer to run all of celery within the application context by creating a separate file that invokes celery.start() with the application's context.  This means your tasks file doesn't have to be littered with context setup and teardowns.  It also lends itself well to the flask 'application factory' pattern.extensions.pytasks.pyapp.pyRunCelery.pyIn your tasks.py file do the following:Nevermind that didn't work. I ended up having an argument in my Flask app factory to not run db.init_app(app) if Celery was calling it. Instead the workers will call it after Celery forks them. I now see several connections in my MySQL processlist. By doing this, we are able to maintain database connection per-worker.If you want to run your task under flask context, you can subclass :
Python

I have two classes,  and . They look a little bit like this:This error is pointing to Field's :I expected Background () to be called first.  To pass \"a, b\" to Fields (), Field to assign a and b then to assign a list with three 0's in it to field.  Then for Background's () to continue, to then call its own buildField() and override self.field with a list containing c.It seems I don't fully understand super(), however i was unable to find a solution to my issue after looking at similar inheritance problems on the web and around here.I expected behavior like c++ where a class can override a method that was inherited.  How can i achieve this or something similar.Most issues I found related to this were people using double underscores.  My experience with inheritance with super is using the inherited class () to just pass different variables to the super class.  Nothing involving overwriting anything.Coming from a C++ perspective, there might be two misconceptions here.First, overriding a method with a different signature does not overload it like in C++. If one of your Background objects tries to call buildField with no arguments, the original version from Field will not be called -- it has been completely hidden.The second issue is that if a method defined in the superclass calls buildField, the subclass version will be called. In python,  methods are bound dynamically, like a C++  method.Field's  expected to be dealing with an object that had a buildField method taking  no arguments. You used the method with an object that has a buildField method taking one argument.The thing with  is that it doesnt change the type of the object, so you shouldn't change the signature of any methods that the superclass' methods might call.So far, so good.Ah. This is where we get the error. Even though this line occurs within ,  is an instance of . so  finds 's  method, not 's.Since  expects 2 arguments instead of 1, raises an error.So how do we tell Python to call 's  method instead of 's?The purpose of  (naming an attribute with double underscores) is to solve this exact problem.The method name  is \"mangled\" to  inside  so inside ,calls , which is 's  method. While similarly, inside  calls 's  method.Actually  is getting called.. But So, the first statement of  is invoking the  init method.. and passing the  as argument.. Now this  is actually a reference of .. Your  method is actually invoking the one in the Background class.. This is because, the  here is instance of  class(Try printing  in your  method of ).. As you passed it while invoking the  method, from  class.. As you are not passing any value.. So, only value passed is the implicit .The  will invoke:in . However,  here refers to the  instance, and  is in fact calling  of , which is why you get that error.It seems to be that your code should be better written as:If you can't allow the base constructor to finish then it signals that the design is flawed. It is therefore much better to separate  to belong to the class by using  or , if you  call these methods in your constructor. However, if your base class constructor does not invoke any instance method from within, you can then safely overwrite any method of this base class. is talked about but it sounds like to me And also it sounds like  properties:Let me explain:I do not know your business logic but sometimes by-passing super class's  method gave me more control:Has more clean syntax.
Python

How would I take an RGB image in Python and convert it to black OR white? Not grayscale, I want each pixel to be either fully black (0, 0, 0) or fully white (255, 255, 255).Is there any built-in functionality for this in the popular Python image processing libraries? If not, would the best way be just to loop through each pixel, see if it's closer to white or black, and if it's closer to white set it to white, if it's closer to black set it to black?Convert to grayscale and then scale to white or black (whichever is closest).Original:Result:Install  if you haven't already: (or PIL) can help you work with images effectively.Alternatively, you can use  with . You'll need to install numpy:Numpy needs a copy of the array to operate on, but the result is the same.Using  you can convert it directly to black and white. It will look like it has shades of grey but your brain is tricking you! (Black and white near each other look like grey)Original:Converted:I would suggest converting to grayscale, then simply applying a threshold (halfway, or mean or meadian, if you so choose) to it.Using  you can convert it directly to black and white. It will look like it has shades of grey but your brain is tricking you! (Black and white near each other look like grey)Original:Converted:And you can use  (in the standard library) to convert rgb to  and use the lightness value to determine black/white:
Python

I have access to numpy and scipy and want to create a simple FFT of a dataset. I have two lists one that is y values and the other is timestamps for those y values. What is the simplest way to feed these lists into a scipy or numpy method and plot the resulting FFT?I have looked up examples, but they all rely on creating a set of fake data with some certain number of data points, and frequency, etc. and doesn't really show how to do it with just a set of data and the corresponding timestamps.I have tried the following example:But when i change the argument of fft to my data set and plot it i get extremely odd results, it appears the scaling for the frequency may be off. i am unsure.Here is a pastebin of the data i am attempting to FFT\nWhen i do an fft on the whole thing it just has a huge spike at zero and nothing elseHere is my code:spacing is just equal to  So I run a functionally equivalent form of your code in an IPython notebook:I get what I believe to be very reasonable output.It's been longer than I care to admit since I was in engineering school thinking about signal processing, but spikes at 50 and 80 are exactly what I would expect. So what's the issue?The problem here is that you don't have periodic data. You should always inspect the data that you feed into  algorithm to make sure that it's appropriate.The important thing about fft is that it can only be applied to data in which the timestamp is uniform. i.e. uniform sampling in time (like what oyu have shown above). In case of non-uniform sampling\nIf that is not the case, please use a function for fitting the data. There are several tutorials and functions to choose from:\n   If fitting is not an option, you can directly use some form of interpolation to interpolate data to a uniform sampling. When you have uniform samples, you will only have to wory about the time delta () of your samples. In this case, you can directly use the fft functionsThis should solve your problem. The high spike that you have is due to the DC (non-varying, i.e. freq = 0) portion of your signal. It's an issue of scale. If you want to see non-DC frequency content, for visualization, you may need to plot from the offset 1 not from offset 0 of the FFT of the signal.Modifying the example given above by @PaulHThe output plots:\nAnother way, is to visualize the data in log scale:Using:Will show:\nJust as a complement to the answers already given, I would like to point out that often it is important to play with the size of the bins for the FFT. It would make sense to test a bunch of values and pick the one that makes more sense to your application. Often, it is in the same magnitude of the number of samples. This was as assumed by most of the answers given, and produces great and reasonable results. In case one wants to explore that, here is my code version:the output plots:\n
Python

I wonder what is the time complexity of pop method of list objects in Python (in CPython particulary). Also does the value of N for list.pop(N) affects the complexity? Pop() for the last element ought to be O(1) since you only need to return the element referred to by the last element in the array and update the index of the last element.  I would expect pop(N) to be O(N) and require on average N/2 operations since you would need to move any elements beyond the Nth one, one position up in the array of pointers.Yes, it is O(1) to pop the last element of a Python list, and O(N) to pop an arbitrary element (since the whole rest of the list has to be shifted).Here's a great article on how Python lists are stored and manipulated: 
Python

I need to load an XML file and put the contents into an object-oriented structure. I want to take this:and turn it into something like this:It'll have a more complicated structure than that and I can't hard code the element names. The names need to be collected when parsing and used as the object properties.Any thoughts on what would be the best way to go about this?It's worth to have a look at Or the other way around to build xml structures:I've been recommending this more than once today, but try  (easy_install BeautifulSoup).David Mertz's  would seem to do this for you. Documentation's a bit hard to come by, but there are a few IBM articles on it, including .Creating xml from objects in this way is a different matter, though.How about this#outputIf googling around for a code-generator doesn't work, you could write your own that uses XML as input and outputs objects in your language of choice.It's not terribly difficult, however the three step process of Parse XML, Generate Code, Compile/Execute Script does making debugging a bit harder.There are three common XML parsers for python: xml.dom.minidom, elementree, and BeautifulSoup.IMO, BeautifulSoup is by far the best.  
Python

I would like to automate the response for some question prompted by some programs, like mysql  prompting for a password, or apt asking for a 'yes' or ... when I want to rebuild my haystack index with a ./manage.py rebuild_index.For MySQL, I can use the --password= switch, and I'm sure that apt has a 'quiet' like option. But how can I pass the response to other programs ?Why can't you just use ?For example, for an automated auto accept, just use , that just outputs a neverending stream of .If you are looking for a user to confirm an operation, use the confrim method.Or if you are looking for a way to get input from the user, use the prompt method.The development version of Fabric (1.0a) now supports interaction with remote programs.\nThose both methods are valid and works.I choose the first one, because I didn't want to have any interaction with my deployment system.So here is the solution I used:WARNING: This will irreparably remove EVERYTHING from your search index.\nYour choices after this are to restore from backups or rebuild via the  command.\nAre you sure you wish to continue? [y/N] \nRemoving all documents from your index because you said so.\nAll documents removed.\nIndexing 27 Items.\n
Python

I have just started to look at the  which is coming in the imminent  release. Those familiar with the library from 2.7 will notice that the library, from a usage perspective, has changed little. For example......would work in either versions. : in fact it's fantastic. However, those previously unfamiliar with Scala and  now have to make sense of method signatures like:For such simple functionality, this is a daunting signature and one which I find myself struggling to understand.  (or /C/C++/C#) - I don't believe its creators were aiming it at that market - but I think it is/was certainly feasible for Scala to become the next Ruby or Python (i.e. to gain a significant commercial user-base)  (mistakenly in my opinion) for what he saw as its overcomplicated type-system. I worry that someone is going to have a field day spreading  with this API (similarly to how Josh Bloch scared the  out of adding closures to Java). - Despite whatever my wife and coworkers keep telling me, I don't think I'm an idiot: I have a good degree in mathematics from the , and I've been programming commercially for almost 12 years and in  for about a year (also commercially).. This question is subjective but it is a genuine question, I've made it CW and I'd like some opinions on the matter.I hope it's not a \"suicide note\", but I can see your point. You hit on what is at the same time both a strength and a problem of Scala: its . This lets us implement most major functionality in libraries. In some other languages, sequences with something like  or  would be built in, and nobody has to see all the hoops the compiler has to go through to make them work smoothly. In Scala, it's all in a library, and therefore out in the open.In fact the functionality of  that's supported by its complicated type is pretty advanced. Consider this:See how you always get the best possible type? If you map s to s you get again a , but if you map s to s, you get a general . Both the static type and the runtime representation of map's result depend on the result type of the function that's passed to it. And this works even if the set is empty, so the function is never applied! As far as I know there is no other collection framework with an equivalent functionality. Yet from a user perspective this is how things are  to work.The problem we have is that all the clever technology that makes this happen leaks into the type signatures which become large and scary. But maybe a user should not be shown by default the full type signature of ? How about if she looked up  in  she got:The docs would not lie in that case, because from a user perspective indeed map has the type . But  also has a more general type which can be inspected by clicking on another link.We have not yet implemented functionality like this in our tools. But I believe we need to do this, to avoid scaring people off and to give more useful info. With tools like that, hopefully smart frameworks and libraries will not become suicide notes. I do not have a PhD, nor any other kind of degree neither in CS nor math nor indeed any other field. I have no prior experience with Scala nor any other similar language. I have no experience with even remotely comparable type systems. In fact, the only language that I have more than just a superficial knowledge of which even  a type system is Pascal, not exactly known for its sophisticated type system. (Although it  have range types, which AFAIK pretty much no other language has, but that isn't really relevant here.) The other three languages I know are BASIC, Smalltalk and Ruby, none of which even have a type system.And yet, I have no trouble at all understanding the signature of the  function you posted. It looks to me like pretty much the same signature that  has in every other language I have ever seen. The difference is that this version is more generic. It looks more like a C++ STL thing than, say, Haskell. In particular, it abstracts away from the concrete collection type by only requiring that the argument is , and also abstracts away from the concrete return type by only requiring that an implicit conversion  function exists which can build  out of that collection of result values. Yes, that is quite complex, but it really is only an expression of the general paradigm of generic programming: do not assume anything that you don't actually have to.In this case,  does not actually  the collection to be a list, or being ordered or being sortable or anything like that. The only thing that  cares about is that it can get access to all elements of the collection, one after the other, but in no particular order. And it does not need to know what the resulting collection is, it only needs to know how to build it. So, that is what its type signature requires.So, instead ofwhich is the traditional type signature for , it is generalized to not require a concrete  but rather just an  data structurewhich is then further generalized by only requiring that a function exists that can  the result to whatever data structure the user wants:I admit that the syntax is a bit clunkier, but the semantics are the same. Basically, it starts from which is the traditional signature for . (Note how due to the object-oriented nature of Scala, the input list parameter vanishes, because it is now the implicit receiver parameter that every method in a single-dispatch OO system has.) Then it generalized from a concrete  to a more general Now, it replaces the  result collection with a function that , well, really just about anything.Which I really believe is not  hard to understand. There's really only a couple of intellectual tools you need:None of these three should give any professional or even hobbyist programmer a serious headache.  has been a standard function in pretty much every language designed in the last 50 years, the fact that different languages have different syntax should be obvious to anyone who has designed a website with HTML and CSS and you can't subscribe to an even remotely programming related mailinglist without some annoying C++ fanboy from the church of St. Stepanov explaining the virtues of generic programming.Yes, Scala  complex. Yes, Scala has one of the most sophisticated type systems known to man, rivaling and even surpassing languages like Haskell, Miranda, Clean or Cyclone. But if complexity were an argument against success of a programming language, C++ would have died long ago and we would all be writing Scheme. There are lots of reasons why Scala will very likely not be successful, but the fact that programmers can't be bothered to turn on their brains before sitting down in front of the keyboard is probably not going to be the main one.Same thing in C++:Well, I can understand your pain, but, quite frankly, people like you and I -- or pretty much any regular Stack Overflow user -- are not the rule.What I mean by that is that... most programmers won't care about that type signature, because ! They don't read documentation.As long as they saw some example of how the code works, and the code doesn't fail them in producing the result they , they won't ever look at the documentation. When that fails, they'll look at the documentation and expect to see  at the top.With these things in mind, I think that:Alas, Java programmers are much into power tools, so, in answering that, I have just revised my expectation of mainstream Scala adoption. I have no doubt at all that Scala will become a mainstream language. Not C-mainstream, but perhaps Perl-mainstream or PHP-mainstream.Speaking of Java, did you ever replace the class loader? Have you ever looked into what that involves? Java can be scary, if you look at the places framework writers do. It's just that most people don't. The same thing applies to Scala, IMHO, but early adopters have a tendency to look under each rock they encounter, to see if there's something hiding there.Yes, but it will also prevent people from being put off.  I've considered the lack of collections that use higher-kinded types to be a major weakness ever since Scala gained support for higher-kinded types.  It make the API docs more complicated, but it really makes usage more natural.Some probably will.  I don't think Scala is accessible to many \"professional\" developers, partially due to the complexity of Scala and partly due to the unwillingness of many developers to learn.  The CTOs who employ such developers will rightly be scared off.Absolutely.  It makes collections fit much better with the rest of the language and the type system, even if it still has some rough edges.I'm not using it commercially.  I'll probably wait until at least a couple revs into the 2.8.x series before even trying to introduce it so that the bugs can be flushed out.  I'll also wait to see how much success EPFL has in improving its development a release processes.  What I'm seeing looks hopeful, but I work for a conservative company.One the more general topic of \"is Scala too complicated for mainstream developers?\"...Most developers, mainstream or otherwise, are maintaining or extending existing systems.  This means that most of what they use is dictated by decisions made long ago.  There are still plenty of people writing COBOL.Tomorrow's mainstream developer will work maintaining and extending the applications that are being built today.  Many of these applications are not being built by mainstream developers.  Tomorrow's mainstream developers will use the language that is being used by today's most successful developers of new applications.One way that the Scala community can help ease the fear of programmers new to Scala is to focus on practice and to teach by example--a lot of examples that start small and grow gradually larger.  Here are a few sites that take this approach:After spending some time on these sites, one quickly realizes that Scala and its libraries, though perhaps difficult to design and implement, are not so difficult to use, especially in the common cases.I have an undergraduate degree from a cheap \"mass market\" US university, so I'd say I fall into the middle of the user intelligence (or at least education) scale :) I've been dabbling with Scala for just a few months and have worked on two or three non-trivial apps.Especially now that IntelliJ has released their fine IDE with what IMHO is currently the best Scala plugin, Scala development is relatively painless: As a newbie, I continue to struggle with the terse and idiomatic syntax. Method calls without parameters don't need parentheses except where they do; cases in the match statement need a fat arrow (  ), but there are also places where you need a thin arrow (  ). Many methods have short but rather cryptic names like  or  - I can get my stuff done if I flip enough manual pages, but some of my code ends up looking like Perl or line noise. Ironically, one of the most popular bits of syntactic shorthand is missing in action: I keep getting bitten by the fact that  doesn't define a  method.This is just my opinion: I feel like Scala has the power of C++ combined with the complexity and readability of C++. The syntactic complexity of the language also makes the API documentation hard to read.Scala is very  and brilliant in many respects. I suspect many an academic would love to program in it. However, it's also full of cleverness and gotchas, it has a much higher learning curve than Java and is harder to read. If I scan the fora and see how many developers are still struggling with the finer points of Java, . No company will be able to justify sending its developers on a 3 week Scala course when formerly they only needed a 1 week Java course.I think primary problem with that method is that the  goes without any explanation.  Even though I know what implicit arguments are there's nothing indicating how this affects the call.  Chasing through the scaladoc only leaves me more confused (few of the classes related to  even have documentation).I think a simple \"there must be an implicit object in scope for  that provides a builder for objects of type  into the return type \" would help somewhat, but it's kind of a heady concept when all you really want to do is map 's to 's.  In fact, I'm not sure that's right, because I don't know what the type  means, and the documentation for  certainly gives no clue at all.So, I'm left with two options, neither of them pleasant:I get that Scala is essentially exposing the guts of how these things work and that ultimately this is provide a way to do what oxbow_lakes is describing.  But it's a distraction in the signature.I'm a Scala beginner and I honestly don't see a problem with that type signature. The parameter is the function to map and the implicit parameter the builder to return the correct collection. Clear and readable.The whole thing's quite elegant, actually. The builder type parameters let the compiler choose the correct return type while the implicit parameter mechanism hides this extra parameter from the class user. I tried this:That's polymorphism done right. Now, granted, it's not a mainstream paradigm and it will scare away many. But, it will also attract many who value its expressiveness and elegance.Unfortunately the signature for map that you gave is an incorrect one for map and there is indeed legitimate criticism.The first criticism is that by subverting the signature for map, we have something that is more general. It is a common error to believe that this is a virtue by default. It isn't. The map function is very well defined as a covariant functor Fx -> (x -> y) -> Fy with adherence to the two laws of composition and identity. Anything else attributed to \"map\" is a travesty.The given signature is something else, but it is not map. What I suspect it is trying to be is a specialised and slightly altered version of the \"traverse\" signature from the paper, The Essence of the Iterator Pattern. Here is its signature:I shall convert it to Scala:Of course it fails -- it is not general enough! Also, it is slightly different (note that you can get map by running traverse through the Identity functor). However, I suspect that if the library writers were more aware of library generalisations that are well documented (Applicative Programming with Effects precedes the aforementioned), then we wouldn't see this error.Second, the map function is a special-case in Scala because of its use in for-comprehensions. This unfortunately means that a library designer who is better equipped cannot ignore this error without also sacrificing the syntactic sugar of comprehensions. In other words, if the Scala library designers were to destroy a method, then this is easily ignored, but please not map!I hope someone speaks up about it, because as it is, it will become harder to workaround the errors that Scala insists on making, apparently for reasons that I have strong objections to. That is, the solution to \"the irresponsible objections from the average programmer (i.e. too hard!)\" is not \"appease them to make it easier for them\" but instead, provide pointers and assistance to become better programmers. Myself and Scala's objectives are in contention on this issue, but back to your point.You were probably making your point, predicting specific responses from \"the average programmer.\" That is, the people who will claim \"but it is too complicated!\" or some such. These are the Yegges or Blochs that you refer to. My response to these people of the anti-intellectualism/pragmatism movement is quite harsh and I'm already anticipating a barrage of responses, so I will omit it.I truly hope the Scala libraries improve, or at least, the errors can be safely tucked away in a corner. Java is a language where \"trying to do anything useful\" is so incredibly costly, that it is often not worth it because the overwhelming amount of errors simply cannot be avoided. I implore Scala to not go down the same path.I totally agree with both the question and Martin's answer :). Even in Java, reading javadoc with generics is much harder than it should be due to the extra noise. This is compounded in Scala where implicit parameters are used as in the questions's example code (while the implicits do very useful collection-morphing stuff).I don't think its a problem with the language per se - I think its more a tooling issue. And while I agree with what J\u00f6rg W Mittag says, I think looking at scaladoc (or the documentation of a type in your IDE) - it should require as little brain power as possible to grok what a method is, what it takes and returns. There shouldn't be a need to hack up a bit of algebra on a bit of paper to get it :)For sure IDEs need a nice way to show all the methods for any variable/expression/type (which as with Martin's example can have all the generics inlined so its nice and easy to grok). I like Martin's idea of hiding the implicits by default too.To take the example in scaladoc...When looking at this in scaladoc I'd like the generic block [B, That] to be hidden by default as well as the implicit parameter (maybe they show if you hover a little icon with the mouse) - as its extra stuff to grok reading it which usually isn't that relevant. e.g. imagine if this looked like...nice and clear and obvious what it does. You might wonder what 'That' is, if you mouse over or click it it could expand the [B, That] text highlighting the 'That' for example. Maybe a little icon could be used for the [] declaration and (implicit...) block so its clear there are little bits of the statement collapsed? Its hard to use a token for it, but I'll use a . for now...So by default the 'noise' of the type system is hidden from the main 80% of what folks need to look at - the method name, its parameter types and its return type in nice simple concise way - with little expandable links to the detail if you really care that much.Mostly folks are reading scaladoc to find out what methods they can call on a type and what parameters they can pass. We're kinda overloading users with way too much detail right how IMHO.Here's another example...Now if we hid the generics declaration its easier to readThen if folks hover over, say, A1 we could show the declaration of A1 being A1 <: A. Covariant and contravariant types in generics add lots of noise too which can be rendered in a much easier to grok way to users I think.I don't know how to break it to you, but I have a PhD from Cambridge, and I'm using 2.8 just fine.More seriously, I hardly spent any time with 2.7 (it won't inter-op with a Java library I am using) and started using Scala just over a month ago. I have some experience with Haskell (not much), but just ignored the stuff you're worried about and looked for methods that matched my experience with Java (which I use for a living). So: I am a \"new user\" and I wasn't put off - the fact that it works like Java gave me enough confidence to ignore the bits I didn't understand.(However, the reason I was looking at Scala was partly to see whether to push it at work, and I am not going to do so yet.  Making the documentation less intimidating would certainly help, but what surprised me is how much it is still changing and being developed (to be fair what surprised me most was how awesome it is, but the changes came a close second).  So I guess what I am saying is that I'd rather prefer the limited resources were put into getting it into a final state - I don't think they were expecting to be this popular this soon.)Don't know Scala at all, however a few weeks ago I could not read Clojure. Now I can read most of it, but can not write anything yet beyond the most simplistic . I suspect Scala is no different. You need a good book or course depending on how you learn. Just reading the  declaration above, I got  1/3 of it. I believe the bigger problems are not the syntax of these languages, but adopting and internalizing the  that make them usable in everyday production code. For me Java was not a huge leap from C++, which was not a huge leap from C, which was not a leap at all from Pascal, nor Basic etc... But coding in a functional language like Clojure  a huge leap (for me anyway). I guess in Scala you can code in Java style or Scala style. But in Clojure you will create quite the mess trying to keep your imperative habits from Java.Scala has a lot of crazy features (particularly where implicit parameters are concerned) that look very complicated and academic, but are designed to make things easy to use. The most useful ones get syntactic sugar (like  which means that an object of type A has an implicit conversion to an object of type B) and a well-documented explanation of what they do. But most of the time, as a client of these libraries you can ignore the implicit parameters and trust them to do the right thing.I don't think it is the main factor that will affect how popular Scala will become, because Scala has a lot of power and its syntax is not as foreign to a Java/C++/PHP programmer as Haskell, OCaml, SML, Lisps, etc..But I do think Scala's popularity will plateau at less than where Java is today, because I also think the next mainstream language must be much simplified, and the only way I see to get there is pure immutability, i.e. declarative like HTML, but Turing complete. However, I am biased because I am developing such a language, but I only did so after ruling out over a several month study that Scala could not suffice for what I needed.I don't think Scala's reputation will suffer from the Haskell complex. But I think that some will put off learning it, because for most programmers, I don't yet see a use case that forces them to use Scala, and they will procrastinate learning about it. Perhaps the highly-scalable server side is the most compelling use case.And, for the mainstream market, first learning Scala is not a \"breath of fresh air\", where one is writing programs immediately, such as first using HTML or Python. Scala tends to grow on you, after one learns all the details that one stumbles on from the start. However, maybe if I had read Programming in Scala from the start, my experience and opinion of the learning curve would have been different.Definitely.I am using Scala as the initial platform of my new language. I probably wouldn't be building code on Scala's collection library if I was using Scala commercially otherwise. I would create my own category theory based library, since the one time I looked, I found Scalaz's type signatures even more verbose and unwieldy than Scala's collection library. Part of that problem perhaps is Scala's way of implementing type classes, and that is a minor reason I am creating my own language.I decided to write this answer, because I wanted to force myself to research and compare Scala's collection class design to the one I am doing for my language. Might as well share my thought process.The 2.8 Scala collections use of a builder abstraction is a sound design principle. I want to explore two design tradeoffs below.Additionally I am carrying in my mind an incomplete idea that some of Scala's tradeoffs are due to trying to be both an mutable and immutable language, unlike for example Haskell or the language I am developing. This concurs with Tony Morris's comment about for comprehensions. In my language, there are no loops and no mutable constructs. My language will sit on top of Scala (for now) and owes much to it, and this wouldn't be possible if Scala didn't have the general type system and mutability. That might not be true though, because I think Odersky & Moors (\"Fighting Bit Rot with Types\") are incorrect to state that Scala is the only OOP language with higher-kinds, because I verified (myself and via Bob Harper) that Standard ML has them. Also appears SML's type system may be equivalently flexible (since 1980s), which may not be readily appreciated because the syntax is not so much similar to Java (and C++/PHP) as Scala. In any case, this isn't a criticism of Scala, but rather an attempt to present an incomplete analysis of tradeoffs, which is I hope germane to the question. Scala and SML don't suffer from Haskell's inability to do , which is critical and I understand is why so many functions in the Haskell Prelude are repeated for different types.It seems necessary to state ones degree here: B.A. in Political Science and B.ed in Computer Science.To the point:Scala is difficult, because its underlying programming paradigm is difficult. Functional programming scares a lot of people. It is possible to build closures in PHP but people rarely  do. So no, not this signature but all the rest will put people off, if they do not have the specific education to make them value the power of the underlying paradigm.If this education is available, everyone can do it. Last year I build a chess computer with a bunch of school kids in SCALA! They had their problems but they did fine in the end.I would not be worried. I have a maths degree from Oxford too! It took me a while to 'get' the new collections stuff. But I like it a lot now that I do. In fact, the typing of 'map' was one of the first big things that bugged me in 2.7 (perhaps since the first thing I did was subclass one of the collection classes).Reading Martin's paper on the new 2.8 collections really helped explain the use of implicits, but yes the documentation itself definitely needs to do a better job of explaining the role of different kind of implicits within method signatures of core APIs.My main concern is more this: when is 2.8 going to be released? When will the bug reports stop coming in for it? have scala team bitten off more than they can chew with 2.8 / tried to change too much at once?I'd really like to see 2.8 stabilised for release as a priority before adding anything else new at all, and wonder (while watching from the sidelines) if some improvements could be made to the way the development roadmap for the scala compiler is managed.What about error messages in use site?And what about when comes the use case one needs to integrate existing types with a custom one that fits a DSL. One have to be well educated on matters of association, precedence, implicit conversions, implicit parameters, higher kinds, and maybe existential types.It's very good to know that mostly it's simple but it's not necessarily enough. At least there must be one guy who knows this stuff if widespread library is to be designed."},
Scala

I've seen in many examples that sometimes a Seq is being used, while other times is the List...Is there any difference, other than the former one being a Scala type and the List coming from Java?In Java terms, Scala's  would be Java's , and Scala's  would be Java's .Note that  is a , which is equivalent to Java's , but with the equivalent of up-and-coming defender methods. Scala's  is an abstract class that is extended by  and , which are the concrete implementations of .So, where Java's  is an , Scala's  is an implementation.Beyond that, Scala's  is immutable, which is not the case of . In fact, Java has no equivalent to immutable collections (the read only thing only guarantees the new object cannot be changed, but you still can change the old one, and, therefore, the \"read only\" one).Scala's  is highly optimized by compiler and libraries, and it's a fundamental data type in functional programming. However, it has limitations and it's inadequate for parallel programming. These days,  is a better choice than , but habit is hard to break. is a good generalization for sequences, so if you program to interfaces, you should use that. Note that there are actually three of them: ,  and , and it is the latter one that is the \"default\" imported into scope.There's also  and . The latter methods run in parallel where possible, which the former is parent to  and  both, being a suitable generalization for when parallelism of a code doesn't matter. They are both relatively newly introduced, so people doesn't use them much yet.In Scala, a List inherits from Seq, but implements ; here is the proper definition of  : [Note:  is a tad bit more complex, in order to fit in with and make use of Scala's very powerful collection framework.]A  is an Iterable that has a defined order of elements. Sequences provide a method  for indexing, ranging from 0 up to the length of the sequence. Seq has many subclasses including Queue, Range, List, Stack, and LinkedList.A  is a Seq that is implemented as an immutable linked list. It's best used in cases with last-in first-out (LIFO) access patterns."},
Scala

Given a variable with type , how do I cast it to  in Scala?The preferred technique is to use pattern matching.  This allows you to gracefully handle the case that the value in question is  of the given type:This block replicates the semantics of the  method, but with greater flexibility.  For example, you could provide different branches for various types, effectively performing multiple conditional casts at the same time.  Finally, you don't  need to throw an exception in the catch-all area, you could also return  (or preferably, ), or you could enter some fallback branch which works without .In short, this is really the way to go.  It's a little more syntactically bulky than , but the added flexibility is almost always worth it."},
Scala

Suppose we want to write a macro that defines an anonymous class with some type members or methods, and then creates an instance of that class that's statically typed as a structural type with those methods, etc. This is possible with the macro system in 2.10.0, and the type member part is extremely easy:(Where  is a  that provides my  method.)This macro lets us specify the name of the anonymous class's type member as a string literal:Note that it's appropriately typed. We can confirm that everything's working as expected:Now suppose that we try to do the same thing with a method:But when we try it out, we don't get a structural type:But if we stick an extra anonymous class in there:It works:This is extremely handy\u2014it lets you do things like , for example\u2014but I don't understand why it works, and the type member version works, but not . I know this , but does it make any sense? Is there an cleaner way to get a structural type (with the methods on it) from a macro?This question is answered in duplicate by Travis . There are links to the issue in the tracker and to Eugene's discussion (in the comments and mailing list).In the famous \"Skylla and Charybdis\" section of the type checker, our hero decides what shall escape dark anonymity and see the light as a member of the structural type.There are a couple of ways to trick the type checker (which do not entail Odysseus's ploy of hugging a sheep).  The simplest is to insert a dummy statement so that the block doesn't look like an anonymous class followed by its instantiation.If the typer notices that you're a public term that isn't referenced by the outside, it will make you private."},
Scala

Are there any best-practice guidelines on when to use  (or case objects) vs extending Enumeration in Scala?They seem to offer some of the same benefits.One big difference is that s come with support for instantiating them from some  String. For example:Then you can do:This is useful when wishing to persist enumerations (for example, to a database) or create them from data residing in files. However, I find in general that enumerations are a bit clumsy in Scala and have the feel of an awkward add-on, so I now tend to use s. A  is more flexible than an enum:So now I have the advantage of...As  pointed out (with some corrections to ease reading):To follow up on the other answers here, the main drawbacks of s over s are:Case objects already return their name for their toString methods, so passing it in separately is unnecessary.  Here is a version similar to jho's (convenience methods omitted for brevity):Objects are lazy; by using vals instead we can drop the list but have to repeat the name:If you don't mind some cheating, you can pre-load your enumeration values using the reflection API or something like Google Reflections.  Non-lazy case objects give you the cleanest syntax:Nice and clean, with all the advantages of case classes and Java enumerations.  Personally, I define the enumeration values outside of the object to better match idiomatic Scala code:\nA new  has been created which is far superior to the solution I outline below. I strongly recommend using this new .  Whoohoo!\nThere are three basic patterns for attempting to reproduce the Java  within a Scala project. Two of the three patterns; directly using Java  and , are not capable of enabling Scala's exhaustive pattern matching. And the third one; \"sealed trait + case object\", does...but has  resulting in inconsistent ordinal index generation.  I have created a solution with two classes;  and , located in this . I didn't post the code into this thread as the file for Enumeration was quite large (+400 lines - contains lots of comments explaining implementation context).\n\n\n\nThe question you're asking is pretty general; \"...when to use  vs extending \". And it turns out there are MANY possible answers, each answer depending on the subtleties of the specific project requirements you have. The answer can be reduced down to three basic patterns.  To start, let's make sure we are working from the same basic idea of what an enumeration is. Let's define an enumeration mostly in terms of the :Next, let's look at boiled down versions of the three most common solution patterns posted:\n\n\n Actually directly using  pattern (in a mixed Scala/Java project):\nThe following items from the enumeration definition are not available:  For my current projects, I don't have the benefit of taking the risks around the Scala/Java mixed project pathway. And even if I could choose to do a mixed project, item 7 is critical for allowing me to catch compile time issues if/when I either add/remove enumeration members, or am writing some new code to deal with existing enumeration members.\n\n\n Using the \"\" pattern:\nThe following items from the enumeration definition are not available:  It's arguable it really meets enumeration definition items 5 and 6. For 5, it's a stretch to claim it's efficient. For 6, it's not really easy to extend to hold additional associated singleton-ness data.\n\n\n Using the  pattern (inspired by ):\nThe following items from the enumeration definition are not available (happens to be identical to the list for directly using the Java Enum):  Again for my current projects, item 7 is critical for allowing me to catch compile time issues if/when I either add/remove enumeration members, or am writing some new code to deal with existing enumeration members.  So, given the above definition of an enumeration, none of the above three solutions work as they do not provide everything outlined in the enumeration definition above:  Each of these solutions can be eventually reworked/expanded/refactored to attempt to cover some of each one's missing requirements. However, neither the Java  nor the  solutions can be sufficiently expanded to provide item 7. And for my own projects, this is one of the more compelling values of using a closed type within Scala. I strongly prefer compile time warnings/errors to indicate I have a gap/issue in my code as opposed to having to glean it out of a production runtime exception/failure.In that regard, I set about working with the  pathway to see if I could produce a solution which covered all of the enumeration definition above. The first challenge was to push through the core of the JVM class/object initialization issue (covered in detail in ). And I was finally able to figure out a solution.As my solution is two traits;  and , and since the  trait is over +400 lines long (lots of comments explaining context), I am forgoing pasting it into this thread (which would make it stretch down the page considerbly). For details, please jump directly to the .Here's what the solution ends up looking like using the same data idea as above (fully commented version ) and implemented in .\nThis is an example usage of a new pair of enumeration traits I created (located in ) to implement all of the capabilities desired and outlined in the enumeration definition.  One concern expressed is that the enumeration member names must be repeated ( in the example above). While I did minimize it down to a single repetition, I couldn't see how to make it even less due to two issues:  Given these two issues, I had to give up trying to generate an implied ordering and had to explicitly require the client define and declare it with some sort of ordered set notion. As the Scala collections do not have an insert ordered set implementation, the best I could do was use a  and then runtime check that it was truly a set. It's not how I would have preferred to have achieved this.  And given the design required this second list/set ordering , given the  example above, it was possible to add  and then forget to add  to . So, there is a runtime check to verify that the list is not only a set, but contains ALL of the case objects which extend the . That was a special form of reflection/macro hell to work through.\n\n\nPlease leave comments and/or feedback on the .The advantages of using case classes over Enumerations are:The advantages of using Enumerations instead of case classes are:So in general, if you just need a list of simple constants by name, use enumerations.  Otherwise, if you need something a bit more complex or want the extra safety of the compiler telling you if you have all matches specified, use case classes.UPDATE: The code below has a bug, described .  The test program below works, but if you were to use DayOfWeek.Mon (for example) before DayOfWeek itself, it would fail because DayOfWeek has not been initialized (use of an inner object does not cause an outer object to be initialized).  You can still use this code if you do something like  in your main class, forcing initialization of your enums, or you can use chaotic3quilibrium's modifications.  Looking forward to a macro-based enum!If you wantthen the following may be of interest.  Feedback welcome.In this implementation there are abstract Enum and EnumVal base classes, which you extend.  We'll see those classes in a minute, but first, here's how you would define an enum:Note that you have to use each enum value (call its apply method) to bring it to life.  [I wish inner objects weren't lazy unless I specifically ask for them to be.  I think.]We could of course add methods/data to DayOfWeek, Val, or the individual case objects if we so desired.And here's how you would use such an enum:Here's what you get when you compile it:You can replace \"day match\" with \"( day: @unchecked ) match\" where you don't want such warnings, or simply include a catch-all case at the end.When you run the above program, you get this output:Note that since the List and Maps are immutable, you can easily remove elements to create subsets, without breaking the enum itself.Here is the Enum class itself (and EnumVal within it):And here is a more advanced use of it which controls the IDs and adds data/methods to the Val abstraction and to the enum itself:I have a nice simple lib here that allows you to use sealed traits/classes as enum values without having to maintain your own list of values. It relies on a simple macro that is not dependent on the buggy .Another disadvantage of case classes versus Enumerations when you will need to iterate or filter across all instances. This is a built-in capability of Enumeration (and Java enums as well) while case classes don't automatically support such capability.In other words: \"there's no easy way to get a list of the total set of enumerated values with case classes\".If you are serious about maintaining interoperability with other JVM languages (e.g. Java) then the best option is to write Java enums.  Those work transparently from both Scala and Java code, which is more than can be said for  or case objects.  Let's not have a new enumerations library for every new hobby project on GitHub, if it can be avoided!I've seen various versions of making a case class mimic an enumeration.  Here is my version:Which allows you to construct case classes that look like the following:Maybe someone could come up with a better trick than simply adding a each case class to the list like I did.  This was all I could come up with at the time.Update March 2017: as commented by , the  PR has been closed. (next generation compiler for Scala) will take the lead, though  and .Note: there is now (August 2016, 6+ years later) a proposal to remove : I've been going back and forth on these two options the last few times I've needed them.  Up until recently, my preference has been for the sealed trait/case object option.1) Scala Enumeration Declaration2) Sealed Traits + Case ObjectsWhile neither of these really meet all of what a java enumeration gives you, below are the pros and cons:Scala EnumerationPros:\n-Functions for instantiating with option or directly assuming accurate (easier when loading from a persistent store)\n-Iteration over all possible values is supported Cons:\n-Compilation warning for non-exhaustive search is not supported (makes pattern matching less ideal)Case Objects/Sealed traitsPros:\n-Using sealed traits, we can pre-instantiate some values while others can be injected at creation time\n-full support for pattern matching (apply/unapply methods defined)Cons:\n-Instantiating from a persistent store - you often have to use pattern matching here or define your own list of all possible 'enum values'What ultimately made me change my opinion was something like the following snippet:The  calls were hideous - using enumeration instead I can simply call the withName method on the enumeration as follows:So I think my preference going forward is to use Enumerations when the values are intended to be accessed from a repository and case objects/sealed traits otherwise.I prefer  (it's a matter of personal preference). To cope with the problems inherent to that approach (parse string and iterate over all elements), I've added a few lines that are not perfect, but are effective.I'm pasting you the code here expecting it could be useful, and also that others could improve it.For those still looking how to get :\nYou can just reference the case object after declaring it to instantiate it:"},
Scala

What's the best way to parse command-line parameters in Scala?\nI personally prefer something lightweight that does not require external jar.Related:For most cases you do not need an external parser. Scala's pattern matching allows consuming args in a functional style. For example:will print, for example:This version only takes one infile. Easy to improve on (by using a List).Note also that this approach allows for concatenation of multiple command line arguments - even more than two!The above generates the following usage text:This is what I currently use. Clean usage without too much baggage.\n(Disclaimer: I now maintain this project)I realize that the question was asked some time ago, but I thought it might help some people, who are googling around (like me), and hit this page. looks quite promising as well.Features (quote from the linked github page):And some example code (also from that Github page):I like  over arguments for relatively simple configurations.This is largely a shameless clone of .  It turns out that JewelCLI is Scala-friendly in that it doesn't require JavaBean style methods to get automatic argument naming.JewelCLI is a .  It uses Proxied Interfaces Configured with Annotations to dynamically build a type-safe API for your command-line parameters.An example parameter interface :An example usage of the parameter interface :Save copies of the files above to a single directory and download the  to that directory as well.Compile and run the example in Bash on Linux/Mac OS X/etc.:Compile and run the example in the Windows Command Prompt:Running the example should yield the following output:here is mine too! (a bit late in the game though)As opposed to  it is entirely mutable... but wait! That gives us a pretty nice syntax:And a simple way to run it:You can do a lot more of course (multi-commands, many configuration options, ...) and has no dependency.I'll finish with a kind of distinctive feature, the default usage (quite often neglected for multi commands):\nI think scala-optparse-applicative is the most functional command line parser library in Scala.There's also  (disclaimer: I created it):I am from Java world, I like  because its simple, specification is more readable( thanks to annotations) and produces nicely formatted output.Here is my example snippet:I liked the slide() approach of joslinm just not the mutable vars ;) So here's an immutable way to that approach:I've just found an extensive command line parsing library in scalac's scala.tools.cmd package.See I've attempted generalize @pjotrp's solution by taking in a list of required positional key symbols, a map of flag -> key symbol and default options:I based my approach on the top answer (from dave4420), and tried to improve it by making it more general-purpose. It returns a  of all command line parameters\nYou can query this for the specific parameters you want (eg using ) or convert the values into the types you want (eg using ).Example:Gives:another library: Here's a  that is easy to use.  It automatically formats help text, and it converts switch arguments to your desired type. Both short POSIX, and long GNU style switches are supported. Supports switches with required arguments, optional arguments, and multiple value arguments. You can even specify the finite list of acceptable values for a particular switch.  Long switch names can be abbreviated on the command line for convenience.  Similar to the option parser in the Ruby standard library.I like the clean look of this code... gleaned from a discussion here:\nI just created I understand that solution has two major flaws that may distract you: It eliminates the freedom (i.e. the dependence on other libraries, that you value so much) and redundancy (the DRY principle, you do type the option name only once, as Scala program variable and eliminate it second time typed as command line text).I'm going to pile on.  I solved this with a simple line of code.  My command line arguments look like this:This creates an array via Scala's native command line functionality (from either App or a main method):I can then use this line to parse out the default args array:Which creates a map with names associated with the command line values:I can then access the values of named parameters in my code and the order they appear on the command line is no longer relevant.  I realize this is fairly simple and doesn't have all the advanced functionality mentioned above but seems to be sufficient in most cases, only needs one line of code, and doesn't involve external dependencies.I'd suggest to use . There's a scala-port but the Java implementation  works just fine and seems to be better maintained. Here's an example:This is what I cooked. It returns a tuple of a map and a list. List is for input, like input file names. Map is for switches/options.will returnSwitches can be \"--t\" which x will be set to true, or \"--x 10\" which x will be set to \"10\". Everything else will end up in list.This will generate the following usage:How to parse parameters without an external dependency. Great question! You may be interested in . Picocli is specifically designed to solve the problem asked in the question: it is a command line parsing framework in a single file, so you can . This lets users run picocli-based applications . It works by annotating fields so you write very little code. Quick summary:The usage help message is easy to customize with annotations (without programming). For example: ()I couldn't resist adding one more screenshot to show what kind of usage help messages are possible. Usage help is the face of your application, so be creative and have fun!Disclaimer: I created picocli. Feedback or questions very welcome. It is written in java, but let me know if there is any issue using it in scala and I'll try to address it.I have never liked ruby like option parsers. Most developers that used them never write a proper  for their scripts and end up with pages long options not organized in a proper way because of their parser.I have always preferred Perl's way of doing things with Perl's .I am working on a scala implementation of it. The early API looks something like this:So calling  like this:Would print:And return:The project is hosted in github .As everyone posted it's own solution here is mine, cause I wanted something easier to write for the user : The gist contains a code file, plus a test file and a short example copied here:There is not fancy options to force a variable to be in some bounds, cause I don't feel that the parser is the best place to do so.Note : you can have as much alias as you want for a given variable.Here is mine 1-linerIt drops 3 mandatory arguments and gives out the options. Integers are specified like notorious  java option, jointly with the prefix. You can parse binaries and integers as simple asNo need to import anything.Poor man's quick-and-dirty one-liner for parsing key=value pairs:"},
Scala

Sometimes when I read articles in the Scala ecosystem I read the term \"lifting\" / \"lifted\". Unfortunately, it is not explained what that exactly means. I did some research, and it seems that lifting has something to do with functional values or something like that, but I was not able to find a text that explains what lifting actually is about in a beginner friendly way. There is additional confusion through the  framework which has lifting in its name, but it doesn't help answer the question.There are a few usages:Remember a  is a function defined for some subset of the domain  (as specified by the  method). You can \"lift\" a  into a . That is, a function defined over the  of  but whose values are of type This is done by the explicit invocation of the method  on .You can \"lift\" a method invocation into a function. This is called  (thanks to Ben James for this). So for example:We lift a method into a function by applying the Note the fundamental difference between methods and functions.  is an  (i.e. it is a ) of the (function) type A  (as defined by ) is some \"container\" (I use the term  loosely),  such that, if we have an  and a function , then we can get our hands on an  (think, for example,  and the  method)We can encode this property as follows:This is isomorphic to being able to \"lift\" the function  into the domain of the functor. That is:That is, if  is a functor, and we have a function , we have a function . You might try and implement the  method - it's pretty trivial.As  says below (and I've just realized that this would have saved me from writing a ton of unnecessary code), the term \"lift\" also has a meaning within . Recall that a monad transformers are a way of \"stacking\" monads on top of each other (monads do not compose).So for example, suppose you have a function which returns an . This can be converted to the monad transformer . Now you may wish to \"lift\" some other value an  perhaps to that it is also a . You could either write this:Or this:this begs the question: . The answer would be \"to take advantage of composition possibilities\". Let's say you have a function Another usage of  that I've come across in papers (not necessarily Scala-related ones) is overloading a function from  with  (or sets, multisets, ...). This is often used to simplify formalisations because it then doesn't matter whether  is applied to an individual element or to multiple elements.This kind of overloading is often done declaratively, e.g.,oror imperatively, e.g.,Note any collection that extends  (as pointed out by oxbow_lakes) may be lifted; thus for instancewhich turns a partial function into a total function where values not defined in the collection are mapped onto ,Moreover,This shows a neat approach to avoid  exceptions."},
Scala

I've just started learning Scala, and the first thing I'm going to implement is a tiny web application. I've been using  for the last year to implement server-side software, but I've never wrote web applications before. It will be a great experience.Are there web-frameworks for Scala except for ?Don't get me wrong, Lift looks awesome. I just want to know how many frameworks there are so that I can then choose between them. It's always a good to have a choice, but I the only thing I found was Lift.I'm very interested in Scala, but I have not used it yet, so with that caveat, the frameworks I am aware of that are not mentioned in  (Lift, Sweet, Slinky) are:I wrote a  about this.To summarise, some of the options are:I finally found that none were suitable for me, and developed my own little \"framework\". (It is not open-source yet).I like Lift ;-)Play is my second choice for Scala-friendly web frameworks.Wicket is my third choice.Following is a dump of frameworks. It doesn't mean I actually used them:Try , which also support Scala.One very interesting web framework with commercial deployment is , inspired by Ruby's Sinatra. Here's an  about it.I find Unfiltered very interesting .It's mentioned in IttayD's list. Here is a presentation about it  \nand the video Also here there is an article with more info It must be noted that there is also a considerable interest in  and . Wicket fits Scala suprisingly well. If you want to take advantage of the very mature Wicket project and its ecosystem (extensions) plus the concise syntax and productivity advantage of Scala, this one may be for you! See also: is pretty sweet.It is now production ready. It incorporates: a cool template framework,automatic reloading of source files upon safe, a composable action system, akka awesomeness, etc.Its part of the .Having used it for two projects, I can say that it works pretty smoothly and it should be something to consider next time you are looking to learn new web frameworks.I tend to use JAX-RS using  (you can write nice resource beans in Scala, Java or Groovy) to write RESTul web applications. Then I use  for the rendering the views using one of the various template languages (, ,  (Scala Server Pages), , etc.).There's a new web framework, called . From the site:The Scala Pages web framework is likely to appeal to web programmers who come from a Java background and want to program web applications in Scala. The emphasis is on OOP rather than functional programming.Prikrutil, I think we're on the same boat. I also come to Scala from Erlang. I like  a lot so I decided to created a Scala web framework inspired by it.Take a look at .  is quite extensive. From README:Xitrum is an async and clustered Scala web framework and web server on top of Netty and Hazelcast:Hazelcast also gives:Follow the  for a quick start.There's also Pinky, which used to be on bitbucket but got transfered to .By the way, github is a great place to search for Scala projects, as there's a lot being put there.I'd like to add my own efforts to this list.  You can find out more information here:It's in early development and I'm still working on it aggressively.  It includes features like:Any and all feedback is much appreciated.UPDATE: 2011-09-078, I just posted a major update to version 0.9.1.  There's more info at  which includes a screencast.Both Sweet and Slinky seem to be unmaintanted for about a year. Sweet Maven repo sweetsoftwaredesign.com is dead so there's even no way to download dependencies.<>:Spiffy is a web framework using Scala, Akka (a Scala actor implementation), and the Java Servlet 3.0 API. It makes use of the the async interface and aims to provide a massively parallel and scalable environment for web applications. Spiffy's various components are all based on the idea that they need to be independent minimalistic modules that do small amounts of work very quickly and hand off the request to the next component in the pipeline. After the last component is done processing the request it signals the servlet container by \"completing\" the request and sending it back to the client.<>You could also try . It was designed to be a Java-framework but I have successfully used it with Scala also without difficulties. It is a component based framework and has similar properties as Lift or Tapestry.I have stumbled upon your question a few weeks back, but since then also learned about . This is a nice, minimal framework that is therefore easy to learn, and it has pretty good documentation available as well.Beside it's minimal-ness, it also claims to work well with other libraries and lets you use your own implementation of things when you need it.Java EE would work since Scala is built on top of the Java platform."},
Scala

I read  (part of ). In that post he stated:But he didn't explain anything about it. What was he trying to say?Jim has got this pretty much covered in , but I'm posting a briefing here for reference.First, let's see what the Scala Specification tell us. Chapter 3 (types) tell us about  (3.2.9) and  (3.3.1). Chapter 4 (basic declarations) speaks of  (4.1),  (4.2) and  (4.6). Chapter 6 (expressions) speaks of  (6.23) and  (6.7). Curiously, function values is spoken of one time on 3.2.9, and no where else.A  is (roughly) a type of the form , which is a shorthand for the trait  in the standard library.  and  have function types, and function types can be used as part of value, variable and function declarations and definitions. In fact, it can be part of a method type.A  is a . That means there is  value - no object, no instance - with a method type. As mentioned above, a  actually has a . A method type is a  declaration - everything about a  except its body. and  are  and  declarations, including both  - which can be, respectively,  and . Note that, on the JVM, these (method values) are implemented with what Java calls \"methods\".A   is a  declaration, including  and . The type part is the Method Type, and the body is an . This is also implemented on the JVM with what Java calls \"methods\".Finally, an  is an instance of a  (ie, an instance of the trait ), and a  is the same thing! The distinction is that a Method Value is created from methods, either by postfixing an underscore ( is a method value corresponding to the \"function declaration\" () ), or by a process called , which is like an automatic cast from method to function.That is what the specs say, so let me put this up-front:  It leads to too much confusion between so-called , which is a part of the program (chapter 4 -- basic declarations) and , which is an expression, and , which is, well a type -- a trait.The terminology below, and used by experienced Scala programmers, makes one change from the terminology of the specification: . Or even method declaration. Furthermore, we note that  and  are also methods for practical purposes.A  is an object that includes one of the  traits, such as , , , etc. It might be including  as well, which actually extends .Let's see the type signature for one of these traits:This trait has one abstract method (it has a few concrete methods as well):And that tell us all that there is to know about it. A  has an  method which receives  parameters of types , , ..., , and returns something of type . It is contra-variant on the parameters it receives, and co-variant on the result.That variance means that a  is a subtype of . Being a subtype means it can be used  it. One can easily see that if I'm going to call  and expect an  back, either of the two types above would work.Now, what is the  of a method and a function? Well, if  is a function and  is a method local to the scope, then both can be called like this:These calls are actually different, because the first one is just a syntactic sugar. Scala expands it to:Which, of course, is a method call on object . Functions also have other syntactic sugars to its advantage: function literals (two of them, actually) and  type signatures. For example:Another similarity between a method and a function is that the former can be easily converted into the latter:Scala will expand , assuming  type is  into (Scala 2.7):On Scala 2.8, it actually uses an  class to reduce class sizes.Notice that one can't convert the other way around -- from a function to a method.Methods, however, have one big advantage (well, two -- they can be slightly faster): they can receive . For instance, while  above can necessarily specify the type of  it receives ( in the example),  can parameterize it:I think this pretty much covers everything, but I'll be happy to complement this with answers to any questions that may remain.One big practical difference between a method and a function is what  means.   only ever returns from a method.  For example:Returning from a function defined in a method does a non-local return:Whereas returning from a local method only returns from that method.Let Say you have a ListDefine a MethodDefine a FunctionMethod Accepting ArgumentDefining Function with valArgument to function is OptionalArgument to Method is MandatoryCheck the following  that explains passing other differences with examples like other example of diff with Method Vs Function, Using function as Variables, creating function that returned functionFunctions don't support parameter defaults. Methods do. Converting from a method to a function loses parameter defaults. (Scala 2.8.1)"},
Scala

I was reading . When is it better to use abstract types?For example,rather that generics, for example,You have a good point of view on this issue here:  \nA Conversation with Martin Odersky, Part III\nby Bill Venners and Frank Sommers  (May 18, 2009)Update (October2009): what follows below has actually been illustrated in this new article by Bill Venners:\n (see summary at the end)(Here is the relevant extract of the first interview, May 2009, emphasis mine)There have always been two notions of abstraction: In Java you also have both, but it depends on what you are abstracting over.\nIn Java you have abstract methods, but you can't pass a method as a parameter.\nYou don't have abstract fields, but you can pass a value as a parameter.\nAnd similarly you don't have abstract type members, but you can specify a type as a parameter.\nSo in Java you also have all three of these, but there's a distinction about what abstraction principle you can use for what kinds of things. And you could argue that this distinction is fairly arbitrary.We decided to have the .\nSo you can have abstract fields as well as value parameters.\nYou can pass methods (or \"functions\") as parameters, or you can abstract over them.\nYou can specify types as parameters, or you can abstract over them.\nAnd what we get conceptually is that we can model one in terms of the other. At least in principle, we can express every sort of parameterization as a form of object-oriented abstraction. So in a sense you could say Scala is a more orthogonal and complete language.What, in particular,  we talked about before.\nOne standard problem, which has been around for a long time, is the problem of animals and foods.\nThe puzzle was to have a class  with a method, , which eats some food.\nThe problem is if we subclass Animal and have a class such as Cow, then they would eat only Grass and not arbitrary food. A Cow couldn't eat a Fish, for instance.\nWhat you want is to be able to say that a Cow has an eat method that eats only Grass and not other things.\nActually, you can't do that in Java because it turns out you can construct unsound situations, like the problem of assigning a Fruit to an Apple variable that I talked about earlier.The answer is that .\nYou say, my new Animal class has a type of , which I don't know.\nSo it's an abstract type. You don't give an implementation of the type. Then you have an  method that eats only .\nAnd then in the  class I would say, OK, I have a Cow, which extends class , and for .\nSo .Indeed you can. You could parameterize class Animal with the kind of food it eats.\nBut , and usually, what's more, in .\nAt the 1998 ECOOP, Kim Bruce, Phil Wadler, and I had a paper where we showed that .\nSo there are very good reasons not to do parameters, but to have these abstract members, because they don't give you this quadratic blow up.  asks in the comments:I am not sure the relationship is that different between using abstract types or generics. \nWhat is different is:To understand what Martin is speaking about when it comes to \"explosion of parameters, and usually, what's more, in \", and its subsequent quadratically growth when abstract type are modeled using generics, you can consider the paper \"\" written by... Martin Odersky, and Matthias Zenger for OOPSLA 2005, referenced in the  (finished in 2007).Relevant extracts(Note: Family polymorphism has been proposed for object-oriented languages as a solution to supporting reusable yet type-safe mutually recursive classes.\nA key idea of family polymorphism is the notion of families, which are used to group mutually recursive classes)(Note, from Peter Canning, William Cook, Walter Hill, Walter Olthoff paper:\nBounded quantification was introduced by Cardelli and Wegner as a means of typing functions that operate uniformly over all subtypes of a given type.\nThey defined a simple \"object\" model and used bounded quantification to type-check functions that make sense on all objects having a specified set of \"attributes\".\nA more realistic presentation of object-oriented languages would allow objects that are elements of .\nIn this context, bounded quantification no longer serves its intended purpose. It is easy to find functions that makes sense on all objects having a specified set of methods, but which cannot be typed in the Cardelli-Wegner system.\nTo provide a basis for typed polymorphic functions in object-oriented languages, we introduce F-bounded quantification)There are two principal forms of abstraction in programming languages: The first form is typical for functional languages, whereas the second form is typically used in object-oriented languages.  Traditionally, Java supports parameterization for values, and member abstraction for operations.\nThe more recent Java 5.0 with generics supports parameterization also for types.The arguments for including generics in Scala are two-fold:  In a system with bounded polymorphism, rewriting abstract type into generics might entail a . (Bill Venners)(emphasis mine)Example:I had the same question when I was reading about Scala.The advantage to using generics is that you are creating a family of types. Nobody will need to subclass \u2014they can just use , , etc.If you use an abstract type, then people will be forced to create a subclass. People will need classes like , , etc.You need to decide which is better for your particular need.You may use abstract types in conjunction with type parameters to establish custom templates.Let's assume you need to establish a pattern with three connected traits:in the way that arguments mentioned in type parameters are AA,BB,CC itself respectfullyYou may come with some kind of code:which would not work in this simple way because of type parameter bonds. You need to made it covariant to inherit correctlyThis one sample would compile but it sets strong requirements on variance rules and can not be used in some occasionsThe compiler will object with bunch of variance check errorsIn that case you may gather all type requirements in additional trait and parametrize other traits over itNow we can write concrete representation for the described pattern, define left and join methods in all classes and get right and double for freeSo, both abstract types and type parameters are used for creating abstractions. They both have weak and strong point. Abstract types are more specific and capable to describe any type structure but is verbose and require to explicit specified. Type parameters can create bunch of types instantly but gives you additional worry about inheritance and type bounds.They give synergy to each other and can be used in conjunction for creating complex abstractions that can't be expressed with only one of them."},
Scala

You can find the following on the web:So with this in mind, it is difficult to distinguish between ,  and , therefore the question above.Let me make up for starting some of this confusion by pitching in with some disambiguation.  I like to use the analogy to the value level to explain this, as people tend to be more familiar with it.Value constructors are usually called \"functions\" or \"methods\". These \"constructors\" are also said to be \"polymorphic\" (because they can be used to construct \"stuff\" of varying \"shape\"), or \"abstractions\" (since they abstract over what varies between different polymorphic instantiations). In the context of abstraction/polymorphism, first-order refers to \"single use\" of abstraction: you abstract over a type once, but that type itself cannot abstract over anything. Java 5 generics are first-order.The first-order interpretation of the above characterizations of abstractions are:To emphasize there's no abstraction involved (I guess you could call this \"zero-order\", but I have not seen this used anywhere), such as the value  or the type , we usually say something is a \"proper\" value or type. A proper value is \"immediately usable\" in the sense that it is not waiting for arguments (it does not abstract over them). Think of them as values that you can easily print/inspect (serializing a function is cheating!). A proper type is a type that classifies values (including value constructors), type constructors do not classify any values (they first need to be applied to the right type arguments to yield a proper type). To instantiate a type, it's necessary (but not sufficient) that it be a proper type. (It might be an abstract class, or a class that you don't have access to.)\"Higher-order\" is simply a generic term that means repeated use of polymorphism/abstraction. It means the same thing for polymorphic types and values. Concretely, a higher-order abstraction abstracts over something that abstracts over something. For types, the term \"higher-kinded\" is a special-purpose version of the more general \"higher-order\". Thus, the higher-order version of our characterization becomes:Thus, \"higher-order\" simply means that when you say \"abstracting over X\", you really mean it! The  that is abstracted over does not lose its own \"abstraction rights\": it can abstract all it wants. (By the way, I use the verb \"abstract\" here to mean: to leave out something that is not essential for the definition of a value or type, so that it can be varied/provided by the user of the abstraction as an argument.)Here are some examples (inspired by Lutz's questions by email) of proper, first-order and higher-order values and types:Where the used classes were defined as:To avoid the indirection through defining classes, you need to somehow express anonymous type functions, which are not expressible directly in Scala, but you can use structural types without too much syntactic overhead (the -style is due to  afaik):In some hypothetical future version of Scala that supports anonymous type functions, you could shorten that last line from the examples to:(On a personal note, I regret ever having talked about \"higher-kinded types\", they're just types after all! When you absolutely need to disambiguate, I suggest saying things like \"type constructor parameter\", \"type constructor member\", or \"type constructor alias\", to emphasize that you're not talking about just proper types.)ps: To complicate matters further, \"polymorphic\" is ambiguous in a different way, since a polymorphic type sometimes means a universally quantified type, such as , which is a proper type, since it classifies polymorphic values (in Scala, this value can be written as the structural type )(This answer is an attempt to decorate Adriaan Moors answer by some graphical and historical information.)Higher kinded types are part of Scala since 2.5. The  of ordinary types like  and , whose instances are values, is . The kind of unary type constructors like  is ; binary type constructors like  have () kind , and so on. You can view types like  and  as type-level functions: they take one or more types, and return a type.A function is  if it has an  greater than 1, where the order is (informally) the nesting depth, to the left, of function arrows:So, long story short, a  type is just a type-level higher-order function.I would say: A higher kinded type  a type constructor. E.g. consider Here  is a \"higher kinded type\" (as used in the \"Generics of a Higher Kind\" paper). It is not a concrete (\"first-order\") type constructor like  (which abstracts over proper types only). It abstracts over all unary (\"first-order\") type constructors (as denoted with ).Or to put it in another way: In Java, we have clearly type constructors (e.g. ), but we have no \"higher kinded types\", because we can't abstract over them (e.g. we can't write the  interface defined above - at least not ).The term \"higher order (type constructor) polymorphism\" is used to describe systems that support \"higher kinded types\"."},
Scala

The use of symbol literals is not immediately clear from what I've read up on Scala. Would anyone care to share some real world uses?  Is there a particular Java idiom being covered by symbol literals?  What languages have similar constructs?  I'm coming from a Python background and not sure there's anything analogous in that language.What would motivate me to use 'HelloWorld vs \"HelloWorld\"?ThanksIn Java terms, symbols are interned strings. This means, for example, that reference equality comparison ( in Scala and  in Java) gives the same result as normal equality comparison ( in Scala and  in Java):  will return true, while  might not, depending on JVM's whims (well, it should for literals, but not for strings created dynamically in general).Other languages which use symbols are Lisp (which uses  like Scala), Ruby (), Erlang and Prolog (; they are called atoms instead of symbols).I would use a symbol when I don't care about the structure of a string and use it purely as a name for something. For example, if I have a database table representing CDs, which includes a column named \"price\", I don't care that the second character in \"price\" is \"r\", or about concatenating column names; so a database library in Scala could reasonably use symbols for table and column names.If you have plain strings representing say method names in code, that perhaps get passed around, you're not quite conveying things appropriately. This is sort of the Data/Code boundary issue, it's not always easy to the draw the line, but if we were to say that in that example those method names are more code than they are data, then we want something to clearly identify that.A Symbol Literal comes into play where it clearly differentiates just any old string data with a construct being used in the code. It's just really there where you want to indicate, this isn't just some string data, but in fact in some way part of the code. The idea being things like your IDE would highlight it differently, and given the tooling, you could refactor on those, rather than doing text search/replace.This  discusses it fairly well.Python mantains an internal global table of  with the names of all variables, functions, modules, etc. With this table, the interpreter can make faster searchs and optimizations. You can force this process with the  function ( in python3).Also, Java and Scala automatically use  for faster searchs. With scala, you can use the  method to force the intern of a string, but this process don't works with all strings. Symbols benefit from being guaranteed to be interned, so a single reference equality check is both sufficient to prove equality or inequality."},
Scala

Often in the Scala literature, I encounter the phrase \"abstract over\", but I don't understand the intent.  , Martin Odersky writesAs another example, in the  paper, I have read that first order generics \"abstract over types\", while monads \"abstract over type constructors\".  And we also see phrases like this in the .  To quote one of many such examples:Even relevant stack overflow questions use this terminology.  So... what does \"abstract over\" actually mean?In algebra, as in everyday concept formation, abstractions are formed by grouping units by some essential characteristics and omitting their specific other characteristics. The abstraction is unified under a single symbol or word denoting their similarities. We say that we  the differences, but this really means we're  by the similarities.For example, consider a program that takes the sum of the numbers , , and :This program is not very interesting, since it's not very abstract. So we can  the specific numbers, by integrating all lists of numbers under a single symbol :And we don't particularly care that it's a List either. List is a specific type constructor (takes a type and returns a type), but we can  the type constructor by specifying which essential characteristic we want (that it can be folded):And we can have implicit  instances for  and any other thing we can fold. What's more, we can  both the operation and the type of the operands:Now we have something quite general. The method  will fold any  given that we can prove that  is foldable and that  is a monoid or can be mapped into one. For example:We have  monoids and foldables.To a first approximation, being able to \"abstract over\" something means that instead of using that something directly, you can make a parameter of it, or otherwise use it \"anonymously\".  Scala allows you to abstract over types, by allowing classes, methods, and values to have type parameters, and values to have abstract (or anonymous) types.Scala allows you to abstract over actions, by allowing methods to have function parameters.Scala allows you to abstract over features, by allowing types to be defined structurally.Scala allows you to abstract over type parameters, by allowing higher-order type parameters.Scala allows you to abstract over data access patterns, by allowing you to create extractors.Scala allows you to abstract over \"things that can be used as something else\", by allowing implicit conversions as parameters.  Haskell does similarly with type classes.Scala doesn't (yet) allow you to abstract over classes.  You can't pass a class to something, and then use that class to create new objects.   Other languages do allow abstraction over classes.  (\"Monads abstract over type constructors\" is only true in a very restrictive way.  Don't get hung up on it until you have your \"Aha!  I understand monads!!\" moment.)The ability to abstract over some aspect of computation is basically what allows code reuse, and enables the creation of libraries of functionality.  Scala allows many more sorts of things to be abstracted over than more mainstream languages, and libraries in Scala can be correspondingly more powerful.An abstraction is a sort of generalization. Not only in Scala but many languages there is a need to have such mechanisms to reduce complexity(or at least create a hierarchy that partitions information into easier to understand pieces).A class is an abstraction over a simple data type. It is sort of like a basic type but actually generalizes them. So a class is more than a simple data type but has many things in common with it.When he says \"abstracting over\" he means the process by which you generalize. So if you are abstracting over methods as parameters you are generalizing the process of doing that. e.g., instead of passing methods to functions you might create some type of generalized way to handle it(such as not passing methods at all but building up a special system to deal with it).In this case he specifically means the process of abstracting a problem and creating a oop like solution to the problem. C has very little ability to abstract(you can do it but it gets messy real quick and the language doesn't directly support it). If you wrote it in C++ you could use oop concepts to reduce the complexity of the problem(well, it's the same complexity but the conceptualization is generally easier(at least once you learn to think in terms of abstractions)).e.g., If I needed a special data type that was like an int but, lets say restricted I could abstract over it by creating a new type that could be used like an int but had those properties I needed. The process I would use to do such a thing would be called an \"abstracting\".Here is my narrow show and tell interpretation. It's self-explanatory and runs in the REPL.The other answers give already a good idea of what kinds of abstractions exist. Lets go over the quotes one by one, and provide an example:Pass function as a parameter:  Clearly  is passed as parameter here.  itself abstracts over a function that does a certain specialiced thing with each list element.  specifies a type paramter (String). You could write a collection type which uses abstract type members instead: . One difference is that you have to write  but , so the element type is kind of \"hidden\" in the second method.In Swing an event just \"happens\" out of the blue, and you have to deal with it here and now. Event streams allow you to do all the plumbing an wiring in a more declarative way. E.g. when you want to change the responsible listener in Swing, you have to unregister the old and to register the new one, and to know all the gory details (e.g. threading issues). With event streams, the  of the events becomes a thing you can simply pass around, making it not very different from a byte or char stream, hence a more \"abstract\" concept.The Buffer class above is already an example for this."},
Scala

In various Scala literature I see some self-type annotations using \"this\" and others using \"self\":Is there any real difference between using \"this\" or \"self\"?  Does it matter at all what name you use?  Is this just as valid?All three forms are valid, and have the effect that  is assumed as the type of  in class . The variantsintroduce  (respectively, ) as an alias for  in trait . This is useful for accessing the  reference from an inner class. I.e. you could then use  instead of  when accessing the  reference of the trait  from a class nested within it. The third variant,does not introduce an alias for ; it just sets the self type.There is a difference in that  always refers to the object defined by the innermost template.So, if you call your self-type , you could still refer to it as  (unless, of course, you are in an inner template in which case  will refer to the object defined by it \u2013 and unless you don\u2019t give the inner template\u2019s self-type the same name) but obviously not the other way round."},
Scala

I have a file  in .How can I read that file into a new  in my test  in ?Resources are meant to be accessed using the special  style methods that Java provides. Given your example of  being in , you can access it in a test like so:Of course that  is now just a normal Scala IO object so you can do anything you want with it, like reading the contents and using it for test data.There are other methods to get the resource as well (for example as a stream). For more information look at the  methods on the .sbt copies files from  to .You can access the resources in your tests as follows:It does assume that  was directly under the folder . Add any subdirectories, otherwise.Another alternative (especially if you need to access resource as a ); is to obtain it's path via:as has been pointed out in And in cases where  does not work (don't know nor care when or why exactly),  from Google Guava usually doesTo know where you are in file system during test, you can do something like this in a dummy test:Then, when you know your path, in your test you can use it as:"},
Scala

I need to build a JSON string, something like this:I need to be able to add rows to the , something like What is the closest library/solution to this?Unfortunately writing a JSON library is the Scala community's version of coding a todo list app.There are quite a variety of alternatives. I list them in no particular order, with notes:\u00a7 = has Scalaz integration, \u00b1 = supports interop with Jackson In  we use json4s with the Jackson back-end; we've had good experiences with Argonaut too.Lift-json is at version 2.6 and it works really well (and is also very well supported, the maintainer is always ready to fix any bugs users may find.\nYou can find examples using it on the The maintainer (Joni Freeman) is always reachable on the  list. There are also other users on the mailing list  who are very helpful as well.As @Alexey points out, if you want to use the library with other Scala version, say , change  and use  as follows:You can check the  site to find out the latest version as time goes by.I suggest using , it supports most basic type conversions:Number 7 on the list is Jackson, not using Jerkson. It has support for Scala objects, (case classes etc).Below is an example of how I use it.This makes it very simple. In addition is the XmlSerializer and support for JAXB Annotations is very handy. This blog post describes it's use with JAXB Annotations and the Play Framework.Here is my current JacksonMapper.Maybe I've late a bit, but you really should try to use json library from play framework.\nYou could look at . In current 2.1.1 release you could not separately use it without whole play 2, so dependency will looks like this:It will bring you whole play framework with all stuff on board. But as I know guys from Typesafe have a plan to separate it in 2.2 release. So, there is standalone  from 2.2-snapshot. Here is a basic implementation of writing and then reading  file using . is a very flexible JSON parser library in Scala. It also allows generation of custom ASTs; you just need to supply it with a small trait to map to the AST.Worked great for a recent project that needed a little bit of JSON parsing.You should check .\nIt just works and is much easier to use than most of the existing alternatives in Scala. It is fast, has many features and integrations with some other libs (jodatime, json4s DOM api...).All that without any fancy unecessary code like implicits, custom readers/writers for basic cases, ilisible API due to operator overload...Using it is as easy as:Disclaimer: I am Gensons author, but that doesn't meen I am not objective :)@AlaxDean's #7 answer,  is the only one that I was able to get working quickly with sbt and intellij. Actually json4s also took little time but dealing with a raw AST is not what I wanted. I got argonaut to work by putting in a single line into my build.st:And then a simple test to see if it I could get JSON:And then Make sure you are familiar with  which is just a value that can also be null (null safe I guess). Argonaut makes use of  so if you see something you don't understand like the symbol  (an or operation) it's probably Scalaz. Rapture seems to be missing in the list of the answers.\nIt can be obtained from  and allows you (among other thing) to:I don't want to copy/paste Rapture examples from it's page. A nice presentation about Rapture's features was given by Jon Pretty at SBTB 2014: You can try this:\nIt's simple, and has only one scala file with less than 300 lines code.There are samples:I use PLAY JSON library\nyou can find the mavn repo for only the JSON library not the whole framework hereA very good tutorials about how to use them, are available here:Let me also give you the  version:Play released its module for dealing with JSON independently from Play Framework, Made a blog post about that, check it out at Using case classes, and  (already included in Play Framework) you case convert between json and case classes with a simple one-liner implicitI use  which has the big advantage that it will handle nested case classes automatically:Add this to your  to use uPickle:"},
Scala

I've heard that Scala has path-dependent types. It's something to do with inner-classes but what does this actually mean and why do I care?My favorite example:So, the type of  is dependent on the instance of  from which it was instantiated. There are all sort of things that can be accomplished with this, giving a sort of type safety that is dependent on values and not types alone.This might sound like dependent types, but it is more limited. For example, the type of  is dependent on the value of . Above, the last line doesn't work because the type of  is , while 's type is . Note that one can use another identifier with the same type of , so it is not the   that is associated with the type. For example, the following works:"},
Scala

There are several ways to construct an immutable list in Scala (see contrived example code below). You can use a mutable ListBuffer, create a  list and modify it, use a  method, and probably others that I don't know about.Instinctively, I use the ListBuffer, but I don't have a good reason for doing so. Is there a preferred or idiomatic method for creating a list, or are there situations that are best for one method over another? is a mutable list which has constant-time append, and constant-time conversion into a . is immutable and has constant-time prepend and linear-time append.How you construct your list depends on the algorithm you'll use the list for and the order in which you get the elements to create it.For instance, if you get the elements in the opposite order of when they are going to be used, then you can just use a  and do prepends. Whether you'll do so with a tail-recursive function, , or something else is not really relevant.If you get the elements in the same order you use them, then a  is most likely a preferable choice, if performance is critical.But, if you are not on a critical path and the input is low enough, you can always  the list later, or just , or  the input, which is linear-time.What you  do is use a  and append to it. This will give you much worse performance than just prepending and reversing at the end.And for simple cases: :) Uhmm.. these seem too complex to me. May I proposeorYou want to focus on immutability in Scala generally by eliminating any vars.\nReadability is still important for your fellow man so:Try:You probably don't even need to convert to a list in most cases :)The indexed seq will have everything you need:That is, you can now work on that IndexedSeq:I always prefer List and I use \"fold/reduce\" before \"for comprehension\".  However, \"for comprehension\" is preferred if nested \"folds\" are required.  Recursion is the last resort if I can not accomplish the task using \"fold/reduce/for\".so for your example, I will do:before I do:Note: I use \"foldRight(:\\)\" instead of \"foldLeft(/:)\" here because of the order of \"_\"s.  For a version that does not throw StackOverflowException, use \"foldLeft\" instead.Using , like this,The Scala collection classes are going to be redesigned as of Scala 2.8, so be prepared to change the way you create lists very soon.What is the forward compatible way of creating a List? I have no idea since I haven't read the 2.8 docs yet.As a new scala developer i wrote small test to check list creation time with suggested methods above. It looks like  (for ( p <- ( 0 to x ) ) yield p) toList  the fastest approach.  just an example that uses collection.breakOut"},
Scala

How do you provide overloaded constructors in Scala?It's worth explicitly mentioning that Auxiliary Constructors in Scala must either call the primary constructor (as in landon9720's) answer, or another auxiliary constructor from the same class, as their first action. They cannot simply call the superclass's constructor explicitly or implicitly as they can in Java. This ensures that the primary constructor is the sole point of entry to the class.As of Scala 2.8.0 you can also have default values for contructor- and method parameters. Like thisParameters with default values must come after the ones with no default values in the parameter list.While looking at my code, I suddenly realized that I did kind of an overload a constructor. I then remembered that question and came back to give another answer:In Scala, you can\u2019t overload constructors, but you can do this with functions.Also, many choose to make the  function of a companion object a factory for the respective class.Making this class abstract and overloading the  function to implement-instantiate this class, you have your overloaded \u201cconstructor\u201d:Note that I explicitly define each  to return , else it would return a duck-typed .I thought may be  (2008-11-11) could add more information.Try this"},
Scala

Both are BDD (Behavior Driven Development) capable unit test frameworks for Scala written in Scala. And   may also involve the  framework. But what does Specs offer ScalaTest doesn't? What are the differences?Specs and ScalaTest are both good tools with happy users, but they differ in several ways. You will probably want to pick one as your main testing tool in Scala, but need not give up the other because you can use pieces of both. If you like ScalaTest's  syntax and specs' Mockito syntax, for example, you can put both jar files in your classpath and use both at the same time. Here I'll try and capture the main design philosophy differences I've noticed between specs and ScalaTest.Probably the main philosophical difference between the tools is that specs is designed for Behavior-Driven Development (BDD), whereas ScalaTest is more general. ScalaTest provides traits that you can mix together to get the behavior you prefer in your test classes, including BDD, and you can also easily define your own behavior if you want something different.ScalaTest supports BDD through its , , , , and  traits, and also has traits that you can mix in to get a nice matcher syntax. If you like \"should\", you mix in ShouldMatchers. If you like \"must\", you mix in . But if you like BDD but don't like matcher syntax, you can just use one of ScalaTest's Spec traits without mixing in a matchers trait. Specs has a Specification class that you extend, and you must use the word \"must\" in your matcher expressions. A big philosophical difference that is evident here is that ScalaTest gives you a lot more choices. To make this space of choice easier to navigate, I provide a decision tree here:The matcher syntax is also different between ScalaTest and specs. In ScalaTest I tried to see how far I could go with operator notation, and ended up with matcher expressions that read very much like English sentences, with spaces between the words. Specs matcher syntax runs words together more with camel case.Specs has more matchers than ScalaTest, and that I think reflects a difference in design attitude. I actually cut probably 2/3 of the matcher syntax I built and considered for release. I will add more matchers in future releases, but wanted to be sure I knew users actually wanted something before I added it. However ScalaTest's matchers includes a dynamic property matcher syntax takes up some of that slack. For example in Specs you can write on a :This will invoke the  and make sure it is true. ScalaTest does not have any special matchers for  currently, but in ScalaTest, you could just use a dynamic check like this:Anytime you pass a symbol in after , it will use reflection to look for (in this case) a method or field named  or a method named . There's also a way to make this static, by defining a  (which requires only 2 or 3 lines of code usually). So basically in ScalaTest I try to provide more functionality with less API.Another general design attitude difference between specs and ScalaTest\ninvolves implicit conversions. By default you get only one implicit conversion when you use ScalaTest, which is the one that puts the  operator on everything. (If you need to, you can \"turn off\" this implicit conversion with one line of code. The only reason you would need to do that is if you were trying to test something that has its own  operator, and you get a conflict.) ScalaTest defines many other implicit conversions, but to use them you need to explicitly \"invite\" them into your code by mixing in a trait or doing an import. When you extend class  in specs I think you pretty much get dozens of implicit conversions by default. I'm not sure how much that will matter in practice, but I figure people will want to test code that uses their own implicits, and sometimes there may be a conflict between the test framework's implicits and those of the production code. When that happens I think it may be easier to work around the problem in ScalaTest than specs.Another difference in design attitude that I've noticed is comfort with operators. One goal I had was that any programmer looking at someone else's test code that uses ScalaTest would be able to guess what the meaning was without looking anything up in the ScalaTest documentation. I wanted ScalaTest client code to be drop dead obvious. One way that goal manifested itself is that ScalaTest is very conservative about operators. I only define five operators in ScalaTest:That's it. So these things pretty much look like what mean. If you see in someone else's code:My hope is that you won't need to run to the API documentation to guess what that  means. By contrast, specs is much freer with operators. Nothing wrong with that, but it is a difference. Operators can make code more concise, but the tradeoff is you may have to run to the documentation when you find things like  , , , , , or  (which all have special meanings in Specs) in your colleague's test code.One other philosophical difference is that I do try and make it just slightly easier in ScalaTest to use a functional style when you need to share a fixture, whereas Specs by default continues the tradition of the  and  approach popularized by JUnit, in which you reassign vars before each test. However if you want to test that way, it is also very easy in ScalaTest. You just need to mix in the  trait.For more insight into ScalaTest, you can watch the \"Get Higher with ScalaTest\" presentation I gave at the 2009 Devoxx conference here:The main differences are (mostly from a specs point of view :-) ):This is certainly a very partial and biased comparison and many other differences exist (and the libraries are still evolving, ...). At the end of the day I think that it really depends on your testing/specifying style. If it's simple (simple specification structure, setups, expectations, ...) then both libraries will appear very similar. Otherwise, both have their take on how things should be done. As a last example of this you can have a look at tagging: in  and in .I hope this helps.As far as I know, barring a few highly specialized features, it comes down to personal preference according to the style.IDE support may be another pointI've been trying to get Specs to work with Eclipse through JUnit, and I found the official solution to be a bit \"hacky\". Specs setup: ScalaTest's integration (also through JUnit) with seems a bit less hacky. Still, I haven't got any of them to work as well as JUnit and Java.ScalaTest setup: If one decision factor is the compile time, We're currently using specs2 in our project, but suffer from slow compile times in tests. I just finished a POC on moving to scalatest and saw compile times drop by a factor of about 0.82 just by switching the 2 frameworks in some of our sources.The main differences between ScalaTest and Specs2 are:"},
Scala

I'm trying to represent a function that takes no arguments and returns no value (I'm simulating the setTimeout function in JavaScript, if you must know.)doesn't compile, saying \" `val' parameters may not be call-by-name\"compiles, but has to be invoked strangely, instead ofI have to do thisWhat also works isbut is invoked in an even-less-sensible way(What would a variable of type Unit be?)  What I  of course is a constructor that can be invoke the way I would invoke it if it were an ordinary function:Give baby his bottle!The  notation stands for call-by-name, which is one of the  parameters can be passed. If you aren't familiar with them, I recommend taking some time to read that wikipedia article, even though nowadays it is mostly call-by-value and call-by-reference.What it means is that what is passed is  for the value name inside the function. For example, take this function:If I call it like thisThen the code will execute like thisThough that raises the point of what happens if there's a identifier name clash. In traditional call-by-name, a mechanism called capture-avoiding substitution takes place to avoid name clashes. In Scala, however, this is implemented in another way with the same result -- identifier names inside the parameter can't refer to or shadow identifiers in the called function.There are some other points related to call-by-name that I'll speak of after explaining the other two.The syntax  stands for the type of a . That is, a function which takes no parameters and returns something. This is equivalent to, say, calling the method  -- it takes no parameters and returns a number.It is interesting, however, that this syntax is very similar to the syntax for a , which is the cause for some confusion. For example,is an anonymous function literal of arity 0, whose  isSo we could write:It is important not to confuse the type with the value, however.This is actually just a , whose first parameter is of type . Other ways to write it would be  or . The thing is... this is unlikely to ever be what one wants. The  type's main purpose is indicating a value one is not interested in, so doesn't make sense to  that value.Consider, for instance,What could one possibly do with ? It can only have a single value, so one need not receive it. One possible use would be chaining functions returning :Because  is only defined on , and the functions we are chaining are returning , we had to define them as being of type  to be able to chain them.The first source of confusion is thinking the similarity between type and literal that exists for 0-arity functions also exists for call-by-name. In other words, thinking that, becauseis a literal for , thenwould be a literal for . It is not. That is a , not a literal. Another source of confusion is that  type's  is written , which looks like a 0-arity parameter list (but it is not).The  modifier makes implicit  out of each argument to the constructor.  Hence (as someone noted) if you remove  you can use a call-by-name parameter.  The compiler could probably allow it anyway, but it might surprise people if it created  instead of morphing into .When you change to  now your case just takes a function rather than a call-by-name parameter.  Obviously the function can be stored in  so there's no problem.The easiest way to get what you want ( where a call-by-name parameter is used to pass a lambda) is probably to skip the  and explicitly create the  that you couldn't get in the first place:In use:"},
Scala

As noted in , I'm using Scalaz 7 iteratees to process a large (i.e., unbounded) stream of data in constant heap space.My code looks like this: I seem to have run into a memory leak, but I'm not familiar enough with Scalaz/FP to know whether the bug is in Scalaz or in my code. Intuitively, I expect this code to require only (on the order of)  times the -size space.Note: I found  in which an  was encountered, but my code is not using .I ran some tests to try and isolate the problem. To summarize, the leak only appears to arise when both  and  are used.Code for the tests:This will come as little consolation for anyone who's stuck with the older  API, but I recently verified that an equivalent test passes against the . This is a newer stream processing API that is intended to replace .For completeness, here's the test code:This should work with any value for the  parameter (provided you're willing to wait long enough) -- I tested with 2^14 32MiB arrays (i.e., a total of half a TiB of memory allocated over time)."},
Scala

If I have a collection  of type  and there is a property  on  (of type , say), what is the best way to do a ?One way is the following:But now I need a  map. Is there a better way of doing this so that it's in 1 line and I end up with an  Map? (Obviously I could turn the above into a simple library utility, as I would in Java, but I suspect that in Scala there is no need)You can usebut be aware that this needs 2 traversals.You can construct a Map with a variable number of tuples.  So use the map method on the collection to convert it into a collection of tuples and then use the : _* trick to convert the result into a variable argument.In addition to @James Iry's solution, it is also possible to accomplish this using a fold.  I suspect that this solution is slightly faster than the tuple method (fewer garbage objects are created):Another solution (might not work for all types)this avoids the creation of the intermediary list, more info here:\nWhat you're trying to achieve is a bit undefined.\nWhat if two or more items in  share the same ? Which item will be mapped to that  in the map?The more accurate way of looking at this is yielding a map between  and all  items that have it:This could be easily achieved with :If you still want the original map, you can, for instance, map  to the first  that has it:Works well and is very intuitivThis can be implemented immutably and with a single traversal by folding through the collection as follows.The solution works because adding to an immutable Map returns a new immutable Map with the additional entry and this value serves as the accumulator through the fold operation.The tradeoff here is the simplicity of the code versus its efficiency. So, for large collections, this approach may be more suitable than using 2 traversal implementations such as applying  and .For what it's worth, here are two  ways of doing it:This is probably not the most efficient way to turn a list to map, but it makes the calling code more readable. I used implicit conversions to add a  method to List:Calling code example:Note that because of the implicit conversion, the caller code needs to import scala's implicitConversions.This works for me:The Map has to be mutable and the Map has to be return since adding to a mutable Map does not return a map."},
Scala

Since Scala 2.7.2 there is something called  which is a workaround for Java's type erasure. But how does  work exactly and why / when do you need to use it?The blog post  by Jorge Ortiz explains some of it, but it doesn't explain how to use it together with .Also, what is , what's the difference with ?I have some code (part of a larger program, can't easily include it here) that has some warnings with regard to type erasure; I suspect I can solve these by using manifests, but I'm not sure exactly how.The compiler knows more information about types than the JVM runtime can easily represent.  A Manifest is a way for the compiler to send an inter-dimensional message to the code at runtime about the type information that was lost.This is similar to how the Kleptonians have left encoded messages in fossil records and the \"junk\" DNA of humans.  Due to limitations of lightspeed and gravitational resonance fields, they are unable to communicate directly.  But, if you know how to tune into their signal, you can benefit in ways you cannot imagine, from deciding what to eat for lunch or which lotto number to play.It isn't clear if a Manifest would benefit the errors you are seeing without knowing more detail.One common use of Manifests is to have your code behave differently based on the static type of a collection.  For example, what if you wanted to treat a List[String] differently from other types of a List:A reflection-based solution to this would probably involve inspecting each element of the list.A context bound seems most suited to using type-classes in scala, and is well explained here by Debasish Ghosh:\nContext bounds can also just make the method signatures more readable.  For example, the above function could be re-written using context bounds like so:Not a complete answer, but regarding the difference between  and , you can find an example in the :Example:(See this )A Manifest was intended to reify generic types that get type-erased to run on the JVM (which does not support generics). However, they had some serious issues: they were too simplistic, and were unable to fully support Scala's type system. They were thus  in Scala 2.10, and are replaced with s (which are essentially what the Scala compiler itself uses to represent types, and therefore fully support Scala types). For more details on the difference, see:Before 2013-01-04, .Let's also chck out  in  sources (), we see:So with regards to following example code:we can see that the    searches for an implicit  which satisfies the  you provide in our example code it was .  So when you call something like:you are checking if the current  which you defined in your function is of type  and as the  is a function of type  it would search for a specific  and it would find if there is such an implicit."},
Scala

Which build tool is the best for Scala? What are the pros and cons of each of them? How to I determine which one of them to use in a project?We're using Maven to build Scala projects at work because it integrates well with our CI server.  We could just run a shell script to kick off a build, of course, but we've got a bunch of other information coming out of Maven that we want to go into CI.  That's about the only reason I can think of to use Maven for a Scala project.Otherwise, just use SBT.  You get access to the same dependencies (really the best part about maven, IMHO).  You also get the incremental compilation, which is huge.  The ability to start up a shell inside of your project, which is also great.  ScalaMock only works with SBT, and you're probably going to want to use that rather than a Java mocking library.  On top of that, it's  easier to extend SBT since you can write full scala code in the build file, so you don't have to go through all the rigamarole of writing a Mojo.In short, just use SBT unless you really need tight integration into your CI server.The question is in danger of just generating lots of opinions; it would be better to have a clear list of requirements or a description of your environment, previous knowledge, etc.FWIW, there are more opinions in .My 2c are: Go with sbt if you don't have specific requirementsSome people hate sbt because it uses Ivy for dependency management (I can't comment on its pros and cons, but most of the time it is a non-issue), some people hate sbt because you specify the build file in terms of a Scala DSL instead of XML. Some people were disappointed that sbt's format changed from v0.7 to v0.10, but obviously, migration won't affect you if you start from scratch."},
Scala

This is a follow-up to the  to my previous question.Suppose I need to map each item  of  to  with function  and generate .Obviously I cannot just call  on the list but I can use the list . The zipper is a cursor to move around a list. It provides access to the current element () and its neighbors. Now I can replace my  with   and pass this new function  to  method of . The  works like this: it calls that  with the zipper, then moves the zipper, calls with the  \"moved\" zipper, moves the zipper again and so on, and so on ... until the zipper reaches the end of the list.  Finally, the  returns a new zipper of type , which can be transformed to the list and so the problem is solved.Now note the symmetry between  and  That's why  is a  and  is a .Does it make sense ?A  can be viewed as a comonad just as well (in multiple ways), while a  can be cast as a monad (also in many ways). The difference is in whether you are conceptually focused on \"appending\" data constructively to a state machine (that's what the  interface is about), or \"extracting\" state from it \"deconstructively\" (that's what the  does).It is not easy to answer the question, stated as \"does this understanding make sense\", however. In some sense it does, in another it does not."},
Scala

Given the following RDD:where keys appear either twice (k1) or once (k2), never more than that. I want to get:One approach is to use reduceByKey:However, it's too slow for arrays with 7B elements. \nIs there any faster approach on this specific case?What (probably) takes the time here is shuffling the data: when you want to group two or more records together, they must reside within the same partition, so Spark has to first  the records so that all records with same key are in a single partition.Now, even if each key has two records at most, this shuffle will have to take place,  - for example, if you loaded this RDD from HDFS and you somehow know that each key resides on a single file part to begin with. In that (unlikely) case, you can use  to perform the grouping yourself on each partition separately, thus saving the shuffle:None of this is special to the case where the maximum repetition of each key is 2, by the way. "},
Scala

I'm learning  and  at the same time and I got stuck on understanding the syntax used to inintialize the  in the Boot.scala:What exactly is the meaning of the SiteMap parameter?\nI see that the value  is a list of Menu. What is the ?\nAt first I thought it is a method on the List, but I am unable to find such definition...OK, after my colleague mentioned to me, that he encountered this secret incantation in the  book, I did a search in my copy and found it described in . (Though you need to search with space between the colon and underscore :-/ ) There is a one sentence to explain it as:I find the  to be more helpful.So  is  a type declaration that tells the compiler to treat  as  (aka variable-length argument list \u2014 )."},
Scala

I am attempting to use JSON to send data between the browser and my app.I am attempting to use Lift 1.0 to create and parse JSON strings, but for some reason I am unable to parse the JSON I just constructed:How do I programmatically construct a valid JSON message in Scala/Lift that can also be parsed again?You are using Lift 1.0's , which produces JSON with single-quoted strings and attempting to parse it with scala's parser, which only supports double-quoted strings.It is important to realize that there are multiple definitions for JSON.Are single-quoted strings valid in JSON?Lift and Scala provide many ways to parse JSON, sometimes with differing behavior between versions.The strings accepted by these parsers are not equivalent.Here are some comments and examples of the various methods to product and parse JSON strings.example:example:example:example:example:example:example:example:Take a look at .  It's really nice to use and it leverages some of the new tools from  and .  Plus, you can use it from .Taken from the :"},
Scala

I'm working my way through , and though I'm tempted to look at things from the perspective of Python, I don't want to program \"Python in Scala.\"I'm not quite sure what to do as far as control flow goes: in Python, we use  to death, and we love it. A very similar construct exists in Scala which Odersky calls a for , probably to distinguish it from the Java for loop. Also, Scala has a  attribute (I guess it would be an attribute, I don't know enough about Scala to name it correctly) for iterable data types. It doesn't seem like I can use  to do much more than call one function for each item in the container, though.This leaves me with a few questions. First, are for expressions important/heavily used constructs in Scala like they are in Python, and second, when should I use  instead of a for expression (other than the obvious case of calling a function on each item of a container)?I hope I'm not being terribly ambiguous or overbroad, but I'm just trying to grok some of the design/language fundamentals in Scala (which seems very cool so far).python uses  in list comprehensions and generator expressions. Those are  similar to the scala  expression:Each construct can take a number of generators/iterators, apply filters expressions and yield a combined expression. In python the  is roughly equivalent to:In scala  is roughly equivalent to:If you love the python  syntax, you'll likely love the scala  expression.Scala has some additional syntax and translation twists. Syntax wise  can be used with braces so that you can put statements on separate lines. You can also perform value assignments.Also  really performs a match . If there is no match those elements are ignored from the iteration. I think  has an important place in the language. I can tell from the fact there is a whole chapter (23) about it in the book you're reading!Yes, Scala for comprehensions (as they are commonly known) are used a lot, but they are really just syntactic sugar for a particular combination of methods, and many prefer to call these methods directly instead of using the syntactic sugar.To better understand Scala for comprehensions, please refer to . In particular, you'll see that  is the same thing as .Now, you mention that you don't seem much use with  method, but I'll point out that almost all of the methods of Scala collections are (or can be) implemented with just . See the documentation for  -- all of its methods can be implemented with only .Note that Scala's  bears no resemblance to Python's  -- you can look up  question too.With its support for nested iteration, filters, and transformation, I'd say Scala's  is one of the strong points of the language and very central. I tend to favor it over using ,  and .The foreach is a functional style while the for is an imperative style.  If you've ever done any lisp or scheme, you're already familiar with functional programming.  If you haven't then it might be a bit confusing at first.  The first thing I would do is read up on the closure syntax which are anonymous functions you pass into things like foreach.   Once you understand that it will all make more sense.Your questions are largely answered by the following:To summaraize: It's largely stylistic.  Personally, I favor the functional methodology, but prefer the succinctness of comprehensions when dealing with nested loops."},
Scala

Are there any libraries written for Scala enabling Functional Reactive Programming?See also Odersky et al.'s paper \"\". It explains the library , which was developed for the paper.There's reactive -- .\nThe repository currently contains two projects. reactive-core is a standalone FRP library. reactive-web builds on it to make it very easy to make very dynamic and interactive Lift webapps. Functional Reactive Programming library for the JVM, developed by Netflix.I don't Scala so don't know how good these are but here is a blog with comments that talk about FRP in scala:  and  is the reddit that shows a stackoverflow conversation that led me to the above link.There is  by Li Haoyi. In short, it aims to be a simpler, easy-to-use and more interoperable reimagination of (parts of) Scala.React.Don't be misled by the Rx suffix. Scala.Rx has little to do with Reactive Extensions from .NET. Scala.Rx does not focus so much on asynchrony and event streams as rather time-varying values and the expression of functional dependencies with automatic change propagation.Coursera  course promotes .There is scala-reactive: It is inspired by Microsoft's Reactive Extensions library, with an Observable trait taking the place of IObservable, and tailored to the Scala collections API as much Rx is to the LINQ API."},
Scala

Just wondering if anyone has experience with the three.  I have used read through some RoR and used Django.  They seem fairly easy to use.  Is lift \"easy\" like these two are?  I know easy is subjective and has no context here.  I mean in a very high level and general sense.I'm currently working on a series of projects in lift, so I'll give my personal experiences.Its a very capable framework - and I find it makes lighter work of application development than the equivalent in rails or django. However, you will need a reasonable understanding of scala in order to get started on sophisticated app development as documentation is existent but limited, and not centralised.Lift itself has cherry-picked a lot of features from existent frameworks - rails and django included - to form, imho, a best of breed framework. It also uses some novel techniques of its own that truly mean you can take a frontend and build an application around it relatively quickly.Following the tutorials, you can create the classic \"todo\" application demonstrated by many frameworks with little to no experience within 2-3 minutes. But I would say that you need to have a reasonable knowledge of Java, and an understanding of scala in order to get the most out of lift.Setting up a comfortable development environment isn't exactly painless, due to spotty scala support in the mainstream IDEs.If you have a weekend you can dedicate to  and  I would highly recommend taking the plunge.As a more direct answer to your question, in terms of \"ease\", I would say that if you are unfamiliar with Java, scala, ruby and python, then of the three, your best bet would be rails - as ruby is a beautiful language, nigh on self-explanatory, well documented, introduces the majority of OO concepts, and is very easy to learn.  Additionally, I know of many people that have actually learned ruby solely through developing in rails.I have to disagree with the other answers that support Lift over RoR and Django.   Lift is incredibly capable, and it is very flexible.  But anyone who thinks it is easier to grok and get rolling with than Django and RoR isn't being pragmatic.  For one there is a lot more documentation on Django and RoR.  Their are training classes, way more books, lots of web entries on solving common problems.  Django has a huge number of plug-ins,etc.   I know it might not seem like these things matter but they do.  When it's hard to hire, hard to train, you have to solve common problems over again, etc it's a real drain.  I'm a fan of lift, and I think one day my recommendation might not be true.  But if your life is dependent on it you might want to take the safe course and go RoR/Django.  I'd have to say it's a bit more difficult to get started with, due to the complexities of the Java/Scala ecosystem (maven? gradle? .war files? Tomcat? Jetty? ) and the necessity of compilation. The exception is if you have Java development experience, or especially Java web development experience, in which case I'm sure all of this stuff is an old hat to you.Once you've gotten past that and have a workflow, it's great. Scala is a fantastic language, and lift is an engaging framework.If ease of start up is your only concern then you may want to go with RoR or Django.  But if long term performance, scalability and maintainability are significant, if you are capable of learning scala, which is a bit more complicated but quite elegant and enjoyable in my experience, then Lift or Play will probably yield greater longevity and adaptability long term, which may greatly out weigh the slightly larger startup time on a significant project.  Take a look at some of the    "},
Scala

I am a beginner in Scala.  I installed Scala IDE in eclipse and now I want to run my application programme.  It never shows \"run as Scala application\", instead it shows \"run as Java application\" or \"Java applet\"I opened \"run configuration\" and clicked on \"Scala application\" and my project name is \"test\" and second column is of \"Class Main\".  What do I have to fill in?  I filled in \"Main.Scala\", but it states \"could not find mainmain class main.scala\".Can you help me with running this project?If you want to run the whole project it should have a \"main class\", in any of your Scala objects you should be defining:From there it should be \"calling\" the rest of your objects to do whatever the whole project does and in the \"Class Main\" column you should specify the fully qualified name of your object. For instance, if you defined the main in a class called \"Start\" in the package \"starter\", in the \"Class Main\" field you should state \"starter.Start\".But on the other hand if you only want to run a Scala object it should extend App, if it doesn't extend App, Scala IDE won't add the \"Run as Scala Application...\":Right click your project and check the \"Scala Compiler\" settings. Check the \"Project Specific\" checkbox and try checking if you can run your Scala object (which should extend App). make sure your declared  in your source code matches the  under your source directory.in this case, a sourcefile declaring package \"greeter\" will auto-run as scala if the source file is indeed under src/greeter/Hello.scala (and not just under src/Hello.scala)Its a common mistake that doesn't get highlighted by the syntax checker.If you installed Scala plugin for Eclipse, open the Scala perspective. Then right-click on your project and select \"Add Scala Nature\" in \"Configure\" menu.You should now be able to run your Scala applications. Download from this link Restart Eclipse, create Scala Project, then create Scala Object and type this.Run as Scala ApplicationI had issues with the Scala IDE for Eclipse running Scala applications that extend , but running objects with a proper main method, i.e.  always works fine for me.If it is the  you run the Scala IDE for eclipse after setting it up and creating your project, all the thing you need is to just save your project and restart the IDE. At the next start, the \"run as Scala Application\" is appeared and can be used.I was having similar issue. Make sure your java and scala files are not in the same package. I changed the package names and it worked for meUnless you have a strong reason why you need Eclipse, could I recommend that you try IntelliJ?Version 10 was just released earlier today, and the (free) community edition is perfectly happy working with the IntelliJ Scala plugin.Just a pointer ..\nI had faced same difficulty .\nBeing experienced from JAVA , instead of creating a Spark object I was creating spark class that why I was not getting this option .Hope my experience helps . Right click on the Project --> Click on Run Configurations --> In the Run Configurations window select the \"Scala Application\" Try to run the eclipse command of the sbt tool inside your project directory, this will build your scala project for the eclipse IDE. Then you will have no problem to configure your run configuration, It might even be done for you automatically.done! now import your project into Eclipse's workspaceI had this issue using an Eclipse Luna Scala IDE. No of the above solution made it possible to compile my Main.scala file.The problem was the following: My project only referenced the JRE System library but no Scala library. I carried out the following steps:Then, go to the Main.scala file that is lying somewhere in your project folder and contains your main function. If you right-click file, \"Scala Application\" should appear under \"Run as\"."},
Scala

I have read that Scala's type system is weakened by Java interoperability and therefore cannot perform some of the same powers as Haskell's type system.  Is this true?  Is the weakness because of type erasure, or am I wrong in every way?  Is this difference the reason that Scala has no typeclasses?The big difference is that Scala doesn't have Hindley-Milner global type inference and instead uses a form of local type inference, requiring you to specify types for method parameters and the return type for overloaded or recursive functions.This isn't driven by type erasure or by other requirements of the JVM.  All possible difficulties here can be overcome, and have been, just consider Jaskell - H-M inference doesn't work in an object-oriented context.  Specifically, when type-polymorphism is used (as opposed to the ad-hoc polymorphism of type classes).  This is crucial for strong interop with other Java libraries, and (to a lesser extent) to get the best possible optimisation from the JVM.It's not really valid to state that either Haskell or Scala has a stronger type system, just that they are different.  Both languages are pushing the boundaries for type-based programming in different directions, and each language has unique strengths that are hard to duplicate in the other.Scala's type system is different from Haskell's, although Scala's concepts are sometimes directly inspired by Haskell's strengths and its knowledgeable community of researchers and professionals.Of course, running on a VM not primarily intended for functional programming in the first place creates some compatibility concerns with existing languages targeting this platform.\nBecause most of the reasoning about types happens at compile time, the limitations of Java (as a language and as a platform) at runtime are nothing to be concerned about (except Type Erasure, although exactly this bug seems to make the integration into the Java ecosystem more seamless).As far as I know the only \"compromise\" on the type system level with Java is a special syntax to handle Raw Types. While Scala doesn't even allow Raw Types anymore, it accepts older Java class files with that bug.\nMaybe you have seen code like  (or the longer equivalent ). This is a compatibility feature with Java, but is treated as an existential type internally too and doesn't weaken the type system.Scala's type system does support , although in a more verbose way than Haskell. I suggest reading this paper, which might create a different impression on the relative strength of Scala's type system (the table on page 17 serves as a nice list of very powerful type system concepts).Not necessarily related to the power of the type system is the approach Scala's and Haskell's compilers use to infer types, although it has some impact on the way people write code.\nHaving a powerful type inference algorithm can make it worthwhile to write more abstract code (you can decide yourself if that is a good thing in all cases).In the end Scala's and Haskell's type system are driven by the desire to provide their users with the best tools to solve their problems, but have taken different paths to that goal.another interesting point to consider is that Scala directly supports the classical OO-style. Which means, there are  relations (e.g. List is a subclass of Seq). And this makes type inference more tricky. Add to this the fact that you can mix in traits in Scala, which means that a given type can have multiple supertype relations (making it yet more tricky)Scala does not have , although it may be possible to  in certain cases.I only have little experenice with Haskell, but the most obvious thing I note that Scala type system different from Haskell is the type inference.In Scala, there is no global type inference, you must explicit tell the type of function arguments.For example, in Scala you need to write this:instead of This may cause problem when you need generic version of add function that work with all kinds of type has the \"+\" method. There is a workaround for this, but it will get more verbose.But in real use, I found Scala's type system is powerful enough for daily usage, and I almost never use those workaround for generic, maybe this is because I come from Java world.And the limitation of explicit declare the type of arguments is not necessary a bad thing, you need document it anyway.Well are they Turing reducible?See Oleg Kiselyov's page \n...\nOne can implement the lambda calculus in Haskell's type system.  If Scala can do that, then in a sense Haskell's type system and Scala's type system compute the same types.  The questions are: How natural is one over the other?  How elegant is one over the other?"},
Scala

What is the difference between  and  Scala class?The difference is that all subclasses of a sealed class (whether it's abstract or not) must be in the same file as the sealed class.As , all  subclasses of a sealed class (abstract or not) must be in the same file. A practical consequence of this is that the compiler can warn if the pattern match is incomplete. For instance:If the  is , then the compiler warns unless that last line is uncommented."},
Scala

If I wanted to port a Go library that uses Goroutines, would Scala be a good choice because its inbox/akka framework is similar in nature to coroutines?Nope, they're not.  Goroutines are based on the theory of Communicating Sequential Processes, as specified by Tony Hoare in 1978.  The idea is that there can be two processes or threads that act independently of one another but share a \"channel,\" which one process/thread puts data into and the other process/thread consumes.  The most prominent implementations you'll find are Go's channels and Clojure's , but at this time they are limited to the current runtime and cannot be distributed, even between two runtimes on the same physical box.CSP evolved to include a static, formal process algebra for proving the existence of deadlocks in code.  This is a really nice feature, but neither Goroutines nor  currently support it.  If and when they do, it will be extremely nice to know before running your code whether or not a deadlock is possible.  However, CSP does not support fault tolerance in a meaningful way, so you as the developer have to figure out how to handle failure that can occur on both sides of channels, and such logic ends up getting strewn about all over the application.Actors, as specified by Carl Hewitt in 1973, involve entities that have their own mailbox.  They are asynchronous by nature, and have location transparency that spans runtimes and machines - if you have a reference (Akka) or PID (Erlang) of an actor, you can message it.  This is also where some people find fault in Actor-based implementations, in that you have to have a reference to the other actor in order to send it a message, thus coupling the sender and receiver directly.  In the CSP model, the channel is shared, and can be shared by multiple producers and consumers.  In my experience, this has not been much of an issue.  I like the idea of proxy references that mean my code is not littered with implementation details of how to send the message - I just send one, and wherever the actor is located, it receives it.  If that node goes down and the actor is reincarnated elsewhere, it's theoretically transparent to me.Actors have another very nice feature - fault tolerance.  By organizing actors into a supervision hierarchy per the OTP specification devised in Erlang, you can build a domain of failure into your application.  Just like value classes/DTOs/whatever you want to call them, you can model failure, how it should be handled and at what level of the hierarchy.  This is very powerful, as you have very little failure handling capabilities inside of CSP.Actors are also a concurrency paradigm, where the actor can have mutable state inside of it and a guarantee of no multithreaded access to the state, unless the developer building an actor-based system accidentally introduces it, for example by registering the Actor as a listener for a callback, or going asynchronous inside the actor via Futures.Shameless plug - I'm writing a new book with the head of the Akka team, Roland Kuhn, called Reactive Design Patterns where we discuss all of this and more.  Green threads, CSP, event loops, Iteratees, Reactive Extensions, Actors, Futures/Promises, etc.  Expect to see a MEAP on Manning by early next month.Good luck!There are two questions here:This is an easy question, since Scala is a general purpose language, which is no worse or better than many others you can choose to \"port goroutines\". There are of course many  on why Scala is better or worse  (e.g.  is mine), but these are just opinions, and don't let them stop you. \nSince Scala is general purpose, it \"pretty much\" comes down to: everything you can do in language X, you can do in Scala. If it sounds too broad.. how about  :)The only similarity (aside the nitpicking) is they both have to do with concurrency and message passing. But that is where the similarity ends.Since Jamie's answer gave a good overview of Scala actors, I'll focus more on Goroutines/core.async, but with some actor model intro.Where a \"worry free\" piece is usually associated with terms such as: , , , etc.. Without going into grave details how actors work, in two simple terms actors have to do with:Think \"talking processes\" where each process has a reference and a function that gets called when a message arrives.There is much more to it of course (e.g. check out , or ), but the above two is a good start.Where it gets interesting with actors is.. implementation. Two big ones, at the moment, are Erlang OTP and Scala AKKA. While they both aim to solve the same thing, there are some differences. Let's look at a couple: The point of the above is not to say that one is better than the other, but it's to show that purity of the actor model as a concept depends on its implementation.Now to goroutines..As other answers already mentioned, goroutines take roots in , which is a \"formal language for describing patterns of interaction in concurrent systems\", which by definition can mean pretty much anything :)I am going to give examples based on , since I know internals of it better than Goroutines. But  was built after the Goroutines/CSP model, so there should not be too many differences conceptually.The main concurrency primitive in core.async/Goroutine is a . Think about a  as a \"queue on rocks\". This channel is used to \"pass\" messages. Any process that would like to \"participate in a game\" creates or gets a reference to a  and puts/takes (e.g. sends/receives) messages to/from it.Most of work that is done on channels usually happens inside a \"\" or \"\", which \"\" ().It is a lot easier to convey with a visual. Here is what a blocking IO execution looks like:You can see that threads mostly spend time waiting for work. Here is the same work but done via \"Goroutine\"/\"go block\" approach:Here 2 threads did all the work, that 4 threads did in a blocking approach, while taking the same amount of time.The kicker in above description is: \"threads are \" when they have no work, which means, their state gets \"offloaded\" to a state machine, and the actual live JVM thread is free to do other work ( for a great visual): in core.async, channel  used outside of \"go block\"s, which will be backed by a JVM thread without parking ability: e.g. if it blocks, it blocks the real thread.Another huge thing in \"Goroutines\"/\"go blocks\" is operations that can be performed on a channel. For example, a  can be created, which will close in X milliseconds. Or select/ function that, when used in conjunction with many channels, works like a \"are you ready\" polling mechanism across different channels. Think about it as a socket selector in non blocking IO. Here is an example of using  and  together:This code snippet is taken from , where it sends the same request to all three: Yahoo, Bing and Google, and returns a result from the fastest one,  times out (returns a timeout message) if none returned within a given time. Clojure may not be your first language, but you can't disagree on how  this implementation of concurrency looks and feels.  You can also merge/fan-in/fan-out data from/to many channels, map/reduce/filter/... channels data and more. Channels are also first class citizens: you can pass a channel to a channel..Since core.async \"go blocks\" has this ability to \"park\" execution state, and have a very sequential \"look and feel\" when dealing with concurrency, how about JavaScript? There is no concurrency in JavaScript, since there is only one thread, right? And the way concurrency is mimicked is via 1024 callbacks.But it does not have to be this way. The above example from  is in fact written in ClojureScript that compiles down to JavaScript. Yes, it will work on the server with many threads and/or in a browser: the code can stay the same.Again, a couple of implementation differences [there are more] to underline the fact that theoretical concept is not exactly one to one in practice:I hope the above shed some light on differences between the actor model and CSP. Not to cause a flame war, but to give you yet another perspective of let's say Rich Hickey:\"I remain unenthusiastic about actors. They still couple the producer with the consumer. Yes, one can emulate or implement certain kinds of queues with actors (and, notably, people often do), but since any actor mechanism already incorporates a queue, it seems evident that queues are more primitive. It should be noted that Clojure's mechanisms for concurrent use of state remain viable, and channels are oriented towards the flow aspects of a system.\"()However, in practice, Whatsapp is based on Erlang OTP, and it seemed to sell pretty well.It isn't quite true that you could do the exact same things that you do with goroutines in Akka. Go channels are often used as synchronization points. You cannot reproduce that directly in Akka. In Akka, post-sync processing has to be moved into a separate handler (\"strewn\" in jamie's words :D). I'd say the design patterns are different. You can kick off a goroutine with a , do some stuff, and then  to wait for it to finish before moving on. Akka has a less-powerful form of this with , but  isn't really the Akka way IMO.Chans are also typed, while mailboxes are not. That's a big deal IMO, and it's pretty shocking for a Scala-based system. I understand that  is hard to implement with typed messages, but maybe that indicates that  isn't very Scala-like. I could say that about Akka generally. It often feels like its own thing that happens to run on Scala. Goroutines are a key reason Go exists.Don't get me wrong; I like the actor model a lot, and I generally like Akka and find it pleasant to work in. I also generally like Go (I find Scala beautiful, while I find Go merely useful; but it is quite useful).But fault tolerance is really the point of Akka IMO. You happen to get concurrency with that. Concurrency is the heart of goroutines. Fault-tolerance is a separate thing in Go, delegated to  and , which can be used to implement quite a bit of fault tolerance. Akka's fault tolerance is more formal and feature-rich, but it can also be a bit more complicated.All said, despite having some passing similarities, Akka is not a superset of Go, and they have significant divergence in features. Akka and Go are quite different in how they encourage you to approach problems, and things that are easy in one, are awkward, impractical, or at least non-idiomatic in the other. And that's the key differentiators in any system.So bringing it back to your actual question: I would strongly recommend rethinking the Go interface before bringing it to Scala or Akka (which are also quite different things IMO). Make sure you're doing it the way your target environment means to do things. A straight port of a complicated Go library is likely to not fit in well with either environment.These are all great and thorough answers. But for a simple way to look at it, here is my view. Goroutines are a simple abstraction of Actors. Actors are just a more specific use-case of Goroutines.You could implement Actors using Goroutines by creating the Goroutine aside a Channel. By deciding that the channel is 'owned' by that Goroutine you're saying that only that Goroutine will consume from it. Your Goroutine simply runs an inbox-message-matching loop on that Channel. You can then simply pass the Channel around as the 'address' of your \"Actor\" (Goroutine).But as Goroutines are an abstraction, a more general design than actors, Goroutines can be used for far more tasks and designs than Actors.A trade-off though, is that since Actors are a more specific case, implementations of actors like Erlang can optimize them better (rail recursion on the inbox loop) and can provide other built-in features more easily (multi process and machine actors)."},
Scala

I am using SBT 0.12.0. I have read other answers on stackoverflow and followed them, however none of them helps, for example:Am I missing something? How do I set heap size for sbt 0.12, when doing both testing and ?You need , here's what I use in my .bash_profile:\nTo get your 2G heap space you can use this:Older versions of  contain bugs that override these settings, use  for latest  for Mac (assuming brew install) (IDK for Linux). As of March 2015, if you are using sbt on  with  then you should edit the file e.g.\"sbt -mem 23000 run\" works for me.I have found the solution. No matter how you specify JVM heap size, it will never work because SBT executable already has it overridden.There is a line in SBT executable which says:So I edited the file:Remove the  line.Now when you run SBT, it will no longer override your JVM heap size settings. You can specify heap size settings using @Noan's answer.Or alternatively:I was looking to solve a problem like this on Mac OS X with a homebrew install of SBT. If you installed SBT via homebrew, you're in the clear since the  file looks likeThis means that any settings you put in  will stick (your -Xmx will take precedence). Furthermore, the first line of the script will execute any commands in  if it exists so it may be a better place to put your SBT options if you are playing with them quite a bit. You won't have to  every time you make a change to On windows, for sbt 0.13.9.2, you need to set  to the jvm options you want.The  script loads its defaults from  into  but will use  instead if set.Relevant excerpts from :. . . (skip) . . ."},
Scala

I want to implement it like this:  (returns 3).scala collections do have : A somewhat cleaner version of one of the other answers is:giving a  with a count for each item in the original sequence:The question asks how to find the count of a specific item. With this approach, the solution would require mapping the desired element to its count value as follows:I had the same problem as Sharath Prabhal, and I got another (to me clearer) solution :With as result :If you want to use it like  you have to implement it using an .Using , given e.g.then all of these (in the order of less simplified to more simplified)yieldgivesIt is interesting to note that the map with default 0 value, intentionally designed for this case demonstrates the worst performance (and not as concise as )producesIt is curious that most concise  is faster than even mutable map!I ran into the same problem but wanted to count multiple items in one go..Here is another option:"},
Scala

What are some good tutorials on fold left?I am trying to implement a method for finding the boudning box of rectangle, circle, location and the group which all extends Shape. Group is basically an array of ShapesI got the bounding box computed for all three except the Group one. So now for the bounding box method I know I should be using map and fold left for Group, but I just can't find out the exact syntax of creating it.Group bounding box is basically the smallest bounding box with all the shapes enclosed.Now that you've edited to ask an almost completely different question, I'll give a different answer.  Rather than point to a tutorial on maps and folds, I'll just give one.In Scala, you first need to know how to create an anonymous function.  It goes like so, from most general to more specific:Here are some examples:Now, the  method of lists and such will apply a function (anonymous or otherwise) to every element of the map.  That is, if you havethenproducesThere are all sorts of reasons why this might be useful.  Maybe you have a bunch of strings and you want to know how long each is, or you want to make them all upper case, or you want them backwards.  If you have a function that does what you want to  element, map will do it to all elements:So, that's map in general, and in Scala.But what if we want to collect our results?  That's where fold comes in ( being the version that starts on the left and works right).Suppose we have a function , that is, it takes a B and an A, and combines them to produce a B.  Well, we could start with a B, and then feed our list of A's into it one at a time, and at the end of it all, we'd have some B.  That's exactly what fold does.   does it starting from the left end of the list;  starts from the right.  That is,produceswhere  is, of course, your initial value.So, maybe we have a function that takes an int and a string, and returns the int or the length of the string, whichever is greater--if we folded our list using that, it would tell us the longest string (assuming that we start with 0).  Or we could add the length to the int, accumulating values as we go.Let's give it a try.Okay, fine, but what if we want to know  is the longest?  One way (perhaps not the best, but it illustrates a useful pattern well) is to carry along both the length (an integer)  the leading contender (a string).  Let's give that a go:Here,  is now a tuple of type , and  is the first part of that tuple (an Int).But in some cases like this, using a fold isn't really want we want.  If we want the longer of two strings, the most natural function would be one like .  How do we apply that one?Well, in this case, there is a default \"shortest\" case, so we could fold the string-max function starting with \"\".  But a better way is to use .  As with fold, there are two versions, one that works from the left, the other which works from the right.  It takes no initial value, and requires a function .  That is, it takes two things and returns one of the same type.  Here's an example with a string-max function:Now, there are just two more tricks.  First, the following two mean the same thing:Notice how the second is shorter, and it sort of gives you the impression that you're taking  and doing something to the list with it (which you are).  ( is the same as , but you use it like so: Second, if you only refer to a variable once, you can use  instead of the variable name and omit the  part of the anonymous function declaration.  Here are two examples:At this point, you should be able to create functions and map, fold, and reduce them using Scala.  Thus, if you know how your algorithm should work, it should be reasonably straightforward to implement it.The basic algorithm would go like this:Now you have to write  and , which is a pure algorithms problem more than a language problem.If the shapes all had the same center, implementing  would be easier. It would go like this:As for , which takes two shapes and combine them, it will usually be a rectangle, but can be a circle under certain circunstances. Anyway, it is pretty straight-forward, once you have the algorithm figured out.A bounding box is usually a rectangle.  I don't think a circle located at (-r,-r) is the bounding box of a circle of radius r....Anyway, suppose you have a bounding box b1 and another b2 and a function  that computes the bounding box of b1 and b2.Then if you have a  set of shapes in your group, you can use  to compute the whole bounding box of a list of bounding boxes by combining them two at a time until only one giant box remains.  (The same idea can be used to reduce a list of numbers to a sum of numbers by adding them in pairs.  And it's called  because it works left to right across the list.)Suppose that  is a list of bounding boxes of each shape.  (Hint: this is where  comes in.)  ThenYou'll need to catch the empty group case separately, however.  (Since it has a no well-defined bounding box, you don't want to use folds; folds are good for when there is a default empty case that makes sense.  Or you have to fold with , but then your combining function has to understand how to combine  with , which is probably not worth it in this case--but very well might be if you were writing production code that needs to elegantly handle various sorts of empty list situations.)"},
Scala

A discussion came up at work recently about Sets, which in Scala support the  method and how this can lead to bugs, e.g.I think it's pretty clear that s  shouldn't support a  operation, since the elements are not ordered. However, it was suggested that the problem is that  isn't really a functor, and shouldn't have a  method. Certainly, you can get yourself into trouble by mapping over a set. Switching to Haskell now,and now in ghciSo  fails to satisfy the functor lawIt can be argued that this is not a failing of the  operation on s, but a failing of the  instance that we defined, because it doesn't respect the substitution law, namely that for two instances of  on A and B  and a mapping  thenwhich doesn't hold for  (e.g. consider ).Is the substition law a sensible law for the  type that we should try to respect? Certainly, other equality laws are respected by our  type (symmetry, transitivity and reflexivity are trivially satisfied) so substitution is the only place that we can get into trouble.To me, substition seems like a very desirable property for the  class. On the other hand, some comments on a  includeThese three are all pretty well known in the Haskell community, so I'd be hesitant to go against them and insist on substitability for my  types!Another argument against  being a  - it is widely accepted that being a  allows you to transform the \"elements\" of a \"collection\" while preserving the shape. For example, this quote on the Haskell wiki (note that  is a generalization of )and in Real World HaskellClearly, any functor instance for  has the possibility to change the shape, by reducing the number of elements in the set.But it seems as though s really should be functors (ignoring the  requirement for the moment - I see that as an artificial restriction imposed by our desire to work efficiently with sets, not an absolute requirement for any set. For example, sets of functions are a perfectly sensible thing to consider. In any case, Oleg  how to write efficient Functor and Monad instances for  that don't require an  constraint). There are just too many nice uses for them (the same is true for the non-existant  instance).Can anyone clear up this mess? Should  be a ? If so, what does one do about the potential for breaking the Functor laws? What should the laws for  be, and how do they interact with the laws for  and the  instance in particular?I'm afraid that this is a case of taking the \"shape\" analogy as a defining condition when it is not.  Mathematically speaking, there is such a thing as the power set functor.  :The function P(f) ( in the power set functor) does not preserve the size of its argument set, yet this is nonetheless a functor.If you want an ill-considered intuitive analogy, we could say this: in a structure like a list, each element \"cares\" about its relationship to the other elements, and would be \"offended\" if a false functor were to break that relationship.  But a set is the limiting case: a structure whose elements are indifferent to each other, so there is very little you can do to \"offend\" them; the only thing is if a false functor were to map a set that contains that element to a result that doesn't include its \"voice.\"(Ok, I'll shut up now...) I truncated the following bits when I quoted you at the top of my answer:Here's I'd remark that  is a kind of  , not a \"generalization\" of it.  One of the key facts about any  (or, actually, about , which  extends) is that it requires that the elements of any structure have a linear order\u2014you can turn any  into a list of its elements (with ).Another, less obvious fact about  is that the following functions exist (adapted from ):A  instance for sets would violate the proposed law, because all non-empty sets would have the same \u2014the set whose  is .  From this it should be easy to prove that whenever you try to  a set you would only ever get the empty set or a singleton back.Lesson?   \"preserves shape\" in a very specific, stronger sense than  does.Set is \"just\" a functor (not a ) from the subcategory of Hask where  is \"nice\" (i.e. the subcategory where congruence, substitution, holds). If constraint kinds were around from  then perhaps set would be a  of some kind.Well, Set can be treated as a covariant functor, and as a contravariant functor; usually it's a covariant functor. And for it to behave regarding equality one has to make sure that whatever the implementation, it does.Regarding Set.zip - it is nonsense. As well as Set.head (you have it in Scala). It should not exist."},
Scala

If I have something like a  and I want to convert this into a , the standard way is to use :Now  is just an identity function. I would have thought there'd be some way to do:However, I can't get this to work as you can't generify an . I tried a few things to no avail; has anyone got something like this to work?There's an identity .A for expresion is nicer, I suppose:I tried to figure out why the the type parameter (Option[String]) is needed. The problem seems to be the type conversion from Option[T] to Iterable[T].If you define the identity function as:the type parameter can be omitted.FWIW, on Scala 2.8 you just call  on it.  has it mostly covered for Scala 2.7. He only missed one alternative way of using that identity:It won't work with operator notation, however (it seems operator notation does not accept type parameters, which is good to know).You can  call  on Scala 2.7 (on a , at least), but it won't be able to do anything without a type. However, this works:You could just give the type inferencer a little help:"},
Scala

Lets say I have an already functioning Play 2.0 framework based application in Scala that serves a URL such as:which responds with a listing of all known birthdaysI now want to enhance this by adding the ability to restrict results with optional \"from\" (date) and \"to\" request params such as(dates here interpreted as yyyyMMdd)My question is how to handle the request param binding and interpretation in Play 2.0 with Scala, especially given that both of these params should be optional. Should these parameters be somehow expressed in the \"routes\" specification? Alternatively, should the responding Controller method pick apart the params from the request object somehow? Is there another way to do this?Encode your optional parameters as  (or , but you\u2019ll have to implement your own ):And declare the following route:A maybe less clean way of doing this for java users is setting defaults:And in the controllerOne more problem, you'll have to repeat the defaults whenever you link to your page in the templateHere's Julien's example rewritten in java, using F.Option: (works as of play 2.1)Route:You can also just pick arbitrary query parameters out as strings (you have to do the type conversion yourself):In Addition to Julien's answer. If you don't want to include it in the routes file.You can get this attribute in the controller method using RequestHeaderThis will give you the desired request parameters, plus keep your routes file clean.My way of doing this involves using a custom . This way I express parameters in routes as:The code for Period looks like this.} is just a convienence method i use in my controllers if I want to apply date filtering to the query. Obviously you could use other date defaults here, or use some other default than null for start and end date in the  method.For optional Query parameters, you can do it this wayIn routes file, declare APIYou can also give some default value, in case API doesn't contain these query params it will automatically assign the default values to these paramsIn method written inside controller Application these params will have value  if no default values assigned else default values."},
Scala

I feel a bit insecure about using actors in Scala. I have read documentation about how to do stuff, but I guess I would also need some DON'T rules in order to feel free to use them.\nI think I am afraid that I will use them in a wrong way, and I will not even notice it. Can you think of something, that, if applied, would result in breaking the benefits that Scala actors bring, or even erroneous results? .I know this doesn't really answer the question, but you should at least take heart in the fact that message-based concurrency is much less prone to wierd errors than shared-memory-thread-based concurrency.I presume you have seen the actor guidelines in , but for the record:"},
Scala

Could you guys please explain to me how to set main class in SBT project ? I'm trying to use version 0.13.My directory structure is very simple (unlike SBT's documentation). In the root folder I have  with following contentAnd I have subfolder  with single file  which contains following codeI'm able to compile it by calling  but  returnsPS.I'm shocked that after reading SBT's documentation and 15 similar questions on StackOverflow I couldn't make SBT project run. It's basic functionality which should be brain-dead simple and clear in first 10 seconds of looking at SBT's web-site.PS2.And I'd like to ask Typesafe employees to improve documentation of their product instead of downvoting questions of people who are investing significant time in switching to new platform.You need to put your application's source in ,  is for build definition code.Here is how to specify main classTry to use an object instead of classbecause you need to run main method neither main classFor custom modules in SBT (0.13), just enter on the SBT console:  to switch scope to moduleX, as define in Built.scala. All main classes within that scope will be detected automatically. Otherwise you get the same error of no main class detected. \nFor God's sake, SBT does not tell you that the default scope is not set. It has nothing to do with default versus non default source folders but only with SBT not telling anything that it doesn't know which module to use by default. : PLEASE add a default output like:at the end of SBT start to lower the level of frustration while using SBT on multi module projects..... If you have multiple main methods in your project you can add the following line to your build.sbt file:If you want to specify the class that will be added to the manifest when your application is packaged as a JAR file, add this line to your build.sbt file:You can also specify main class using run-main command in sbt and activator to run:orI had the same issue: was mode following the tutorial at , and in my opinion, as a build tool 's interaction and error messages can be quite misleading to a newcomer.It turned out, hours of head scratching later, that I missed the critical  line in the example each time. :-("},
Scala

So, if I have an actor, I can give it a name. But, can I access that name internally? Example:Now, I can pass its name as a constructor parameter. But, that seems like unnecessary duplication if there is a way to get the name internally... as it was set when I instantiated the actor using system.actorOf. API docs didn't seem to have anything.From an  you can use  to get the ."},
Scala

How convert it to immutable?The immutable hierarchy doesn't contain a MultiMap, so you won't be able to use the converted structure with the same convenient syntax.  But if you're happy to deal with key/valueset pairs, then:If you just want a mutable , you can just use  in 2.8 or  in 2.7.But if you want the whole structure to be immutable--including the underlying set!--then you have to do more: you need to convert the sets along the way.  In 2.8:In 2.7:You can use  to convert an a mutable map into immutable in Scala 2.8 and later versions.Looking at definition of  from documentation:You can just to the following"},
Scala

I've downloaded  and I want to try out few things in the  using this library. How do I achieve this? Of course, you can use scala -cp whatever and manually manage your dependencies. But that gets quite tedious, especially if you have multiple dependencies.A more flexible approach is to use  to manage your dependencies. Search for the library you want to use on . Algebird for example is available by simply . Then create a build.sbt referring to that library, enter the directory and enter . It will download all your dependencies and start a scala console session with all dependencies automatically on the classpath.Changing things like the scala version or the library version is just a simple change in the build.sbt. To play around you don't need any scala code in your directory. An empty directory with just the build.sbt will do just fine.Here is a  for using algebird:Edit: often when you want to play around with a library, the first thing you have to do is to import the namespace(s) of the library. This can also be automated in the build.sbt by adding the following line:You can use the scala's  switch to keep jars on the classpath. There are other switches available too, for example,   and  for turning on various warnings. Many more to be found with  and . You can find out more information about these switches with Running  will not import libraries declared with a test scope. To use those libraries in the REPL, start the console with You should be aware, however, that starting the console this way skips compiling your test sources.Source: "},
Scala

Is there any reason for Scala not support the ++ operator to increment primitive types by default?\nFor example, you can not write:ThanksMy guess is this was omitted because it would only work for mutable variables, and it would not make sense for immutable values.  Perhaps it was decided that the  operator doesn't scream assignment, so including it may lead to mistakes with regard to whether or not you are mutating the variable.I feel that something like this is safe to do (on one line):but this would be a bad practice (in any language):You don't want to mix assignment statements and side effects/mutation.I like 's , but I think the point has to be more strongly made.It would require a new language feature. For instance, let's say we create an  keyword. The type signature would need to be changed as well, to indicate that  is not   a , but  it to whatever field is holding the present object. In Scala spirit of not intruding in the programmers namespace, let's say we do that by prefixing the type with .Then it could be like this:The next problem is that postfix operators suck with Scala rules. For instance:Because of Scala rules, that is the same thing as:Which wasn't the intent. Now, Scala privileges a flowing style: . That mixes well C++/Java traditional syntax of  with functional programming concept of pipelining an input through multiple functions to get the end result. This style has been recently called \"fluent interfaces\" as well.The problem is that, by privileging that style, it cripples postfix operators (and prefix ones, but Scala barely has them anyway). So, in the end, Scala would have to make big changes, and it would be able to measure up to the elegance of C/Java's increment and decrement operators anyway -- unless it really departed from the kind of thing it  support.In Scala, ++ is a valid method, and no method implies assignment. Only  can do that.A longer answer is that languages like C++ and Java treat  specially, and Scala treats  specially, and in an inconsistent way.In Scala when you write  the compiler first looks for a method called  on the Int. It's not there so next it does it's magic on  and tries to compile the line as if it read . If you write  then Scala will call the method  on  and assign the result to... nothing. Because only  means assignment. You could write  but that kind of defeats the purpose.The fact that Scala supports method names like  is already controversial and some people think it's operator overloading. They could have added special behavior for  but then it would no longer be a valid method name (like ) and it would be one more thing to remember.I think the reasoning in part is that  is only one more character, and  is used pretty heavily in the collections code for concatenation.  So it keeps the code cleaner.Also, Scala encourages immutable variables, and  is intrinsically a mutating operation.  If you require , at least you can force all your mutations to go through a common assignment procedure (e.g. ).Of course you can have that in Scala, if you really want:And here you go:The primary reason is that there is not the need in Scala, as in C. In C you are constantly:C++ has added higher level methods for avoiding for explicit loops, but Scala has much gone further providing foreach, map, flatMap foldLeft etc. Even if you actually want to operate on a sequence of Integers rather than just cycling though a collection of non integer objects, you can use Scala range.Because the ++ operator is used by the collection library, I feel its better to avoid its use in non collection classes. I used to use ++ as a value returning method in my Util package package object as so: But I removed it. Most of the times when I have used ++ or + 1 on an integer, I have later found a better way, which doesn't require it.    It is possible if you define you own class which can simulate the desired output however it may be a pain if you want to use normal \"Int\" methods as well since you would have to always use *()Some possible test casesLets define a var: ++i is already short enough: Now i++ can look like this: To use above syntax, define somewhere inside a package object, and then import: Operators chaining is also possible:The above example is similar to this Java (C++?) code: The style could depend, of course.It isn't included because Scala developers thought it make the specification more complex while achieving only negligible benefits and because Scala doesn't have operators at all.You could write your own one like this:But I'm sure you will get into some trouble with precedence not working as you expect. Additionally if i++ would be added, people would ask for ++i too, which doesn't really fit into Scala's syntax."},
Scala

I'm trying to pick up some scala. Reading through examples I came across this impossible-to-google nugget: What does the triple colon accomplish?Concatenates two lists - To add to , it's important to understand that methods whose names end in a colon are right-associative. So writing  is the same as writing . In this case it doesn't matter since both operands are lists, but in general you'll need this knowledge to find such methods in the scaladocs. It also helps to know that the  have a comprehensive index of all methods (and classes, etc) with symbolic names. You can reach it by clicking on the  in the upper-left corner."},
Scala

I have code like this:but it throws runtime java.lang.UnsupportedOperationException.I need to declare empty list or empty maps and some where later in the code need to fill them.Scala lists are immutable by default. You cannot \"add\" an element, but you can form a new list by appending the new element in front. Since it is a  list, you need to reassign the reference (so you can't use a val).The operator  creates the new list. You can also use the shorter syntax: In scala don't use the type  but ,  or .If you need to mutate stuff, use  or  instead. However, it would be better to address this statement:Instead of doing that, fill the list with code that returns the elements. There are many ways of doing that, and I'll give some examples:As everyone already mentioned, this is not the best way of using lists in Scala...Per default collections in scala are immutable, so you have a + method which returns a new list with the element added to it.\nIf you really need something like an add method you need a mutable collection, e.g.  which has a += method. "},
Scala

I am calling a webservice like this:The complete error: According to , it is fixed in the documentation. I needed to add the following import:An alternative option: Since Play 2.4 you can inject  via Guice dependency: injection."},
Scala

I am looking for chart which shows equivalents in Scala of LINQ methods for IEnumerable:Does anyone know anything of such \"translate\" table?I am only listing out the equivalents of functions from . This is incomplete as of now. I will try to update this later with more.There is no direct equivalent of some functions, but it's fairly easy to roll your own. Here are some such functions.::    :::I don't know anything about C# or LINQ, but is this what you're looking for?There's no method to get an element or a default, but this will work:"},
Scala

Does Scala support tail recursion optimization?Scala does tail recursion optimisation at compile-time, as other posters have said. That is, a tail recursive function is transformed into a loop by the compiler (a method invoke is transformed into a jump), as can be seen from the stack trace when running a tail recursive function.Try the following snippet:and inspect the stack trace. It will show only one call to the function boom - therefore the compiled bytecode is not recursive. There is a proposal floating around to  - which in my opinion would a great thing to do, as then the JVM could do runtime optimizations, rather than just compile time optimizations of the code - and could possibly mean more flexible tail recursion. Basically a  would behave exactly like a normal method  but will drop the stack of the caller when it's safe to do so - the specification of the JVM states that stack frames must be preserved, so the JIT has to do some static code analysis to find out if the stack frames are never going to be used.The current status of it is . I don't think it will be done in time for Java 7 ( has a greater priority, and the implementation is almost done) but Java 8 might see it implemented.In Scala 2.8 you can use  to mark specific method that you hope the compiler will optimise:If a method can not be optimized you get a warning.Scala 2.7.x supports tail-call optimization for self-recursion (a function calling itself) of final methods and local functions.Scala 2.8 might come with library support for trampoline too, which is a technique to optimize mutually recursive functions.A good deal of information about the state of Scala recursion can be found in .Only in very simple cases where the function is self-recursive.It looks like Scala 2.8 might be improving tail-recursion recognition, though."},
Scala

I came across this  and did the following experiment with scala 2.10.3.I rewrote the Scala version to use explicit tail recursion:and compared it to the following Java version. I consciously made the functions non-static for a fair comparison with Scala:Here are the results on my computer:This is scala 2.10.3 on (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_51).My question is what is the hidden cost with the scala version?Many thanks.Well, OP's benchmarking is not the ideal one. Tons of effects need to be mitigated, including warmup, dead code elimination, forking, etc. Luckily,  already takes care of many things, and has bindings for both Java and Scala. Please follow the procedures on JMH page to get the benchmark project, then you can transplant the benchmarks below there.This is the sample Java benchmark:...and this is the sample Scala benchmark:If you run these on JDK 8 GA, Linux x86_64, then you'll get:Notice we juggle  to see if the effect is local for the particular value of . It is not, the effect is systematic, and Java version being twice as fast.  will shed some light on this. This one is the hottest block in Scala benchmark:...and this is similar block in Java:Notice how in Java version the compiler employed the trick for translating integer remainder calculation into the multiplication and shifting right (see Hacker's Delight, Ch. 10, Sect. 19). This is possible when compiler detects we compute the remainder against the constant, which suggests Java version hit that sweet optimization, but Scala version did not. You can dig into the bytecode disassembly to figure out what quirk in scalac have intervened, but the point of this exercise is that surprising minute differences in code generation are magnified by benchmarks a lot.P.S. So much for ...UPDATE: A more thorough explanation of the effect: I changed the to a and got a significant performance boost, now it seems that both versions perform almost equally [on my system, see update and comments].I have not looked into into the bytecode, but if you use  you can see using  that there is a method (and that version is as slow as the one with the ). So I assume that even a  involves calling a method, and that's not directly comparable with a  in Java.On my system I got these resultsUsing OpenJDK 1.7 on a 32-Bit Linux.In my experience Oracle's JDK on a 64-Bit system does actually perform better, so this probably explains that other measurements yield even better results in favour of the Scala version.As for the Scala version performing better I assume that tail recursion optimization does have an effect here (see Phil's answer, if the Java version is rewritten to use a loop instead of recursion, it performs equally again).I looked at  and edited the Scala version to have  inside :The new Scala version now runs twice as fast as the original Java one:I figured out it is because Java not having tail calls. The optimized Java one with loop instead of recursion runs just as fast:Now my confusion is fully solved:In conclusion, the original Scala version was slow because I didn't declare  to be  (directly or indirectly, as 's  points out). And the original Java version was slow due to lack of tail calls.To make the Java version completely equivalent to your Scala code you need to change it like this.It is slower because the JVM can not optimize the method calls."},
Scala

Has anyone had success developing a substantial Android app in Scala? Is it a viable option yet? Are there any mature development environments? Given the state of the Scala Eclipse plug-in, it looks as if there is no good IDE support at all other than possibly IntelliJ Ultimate.A few people have posted tutorials describing how to  to sort-of support Scala, and how to to  using Proguard, but beyond that there has been worryingly little discussion about this topic. An interesting article on Android+Scala from the developers behind the Bump app: I'm programming my Android application project in Scala.If you are interested, you may take a look at this:Ya, it is a Chinese website, but you may just take a look at screenshots to get some idea about that Scala can do everything with Android SDK just like Java.The source code of these two android application is hosted on GitHub: Currently I don't use any IDE, because Vim / SBT is far more convenient and lightweight then any IDE I ever used.And if you are using SBT to build your Scala Android application, you don't need worry about those progruard stuff, just install the sbt android-plugin and setup your project.You may read  to learn how to build your Android application with SBT.BTW, I use my own handcraft sbt plugin called  in my project, instead of  metioned in that blog post.There is a new plugin, AndroidProguardScala which makes everything simple :Tested on Windows 7, with Eclipse 3.7, scala 2.9 and without even using the command line or custom ant tools. With it, I have build a real application for my business that is currently published on Google play.I have a scala android tutorial it allows you to use the ant lifecycle targets provided by android. please see here  it also has a link to a github project with everything configured."},
Scala

Obviously there is the  library but what else can we expect to see in the next release of scala? Any language changes? Is there a website where I can see a roadmap?Martin Odersky announced new features at Devoxx several days ago. I blogged about it (you can also find photos and presentation slides .The smaller items:Some changes which I hope will be included:Martin Odersky just put slides from ScalaDays 2011 on the web.\nLast few pages of the presentation shows the desired direction for Scala.Odersky's talk  at  contained pretty much the latest details about this."},
Scala

It seems that both Iterator and Stream are lazy and allow you to keep returning elements to your heart's content. What's the difference between the two?Stream  and Iterator does not. You can traverse the same Stream multiple times and get the same result each time. Iterator, on the other hand, can only be traversed once.They are both constructs for accessing a current element, having a yet unknown list of remaining elements (the lazy tail).  is an imperative construct which you can only traverse once. is a functional construct. In theory you can traverse it multiple times (and as others mentioned, it won't recompute the already computed parts), but in practice because Streams are either infinite or very large (that is why you use it in the first place), holding reference to the full stream doesn't make much sense (you run into Out Of Memory pretty easy).Generally it is safer to the mind to avoid plain s. Alternatives are using  of Scalaz which auto-forgets unreferred parts using weak references, or using  (see also ) or ."},
Scala

In this slide show on  what does the single quote indicate when the message is sent to the pong actor? This defines a literal . See also .It indicates a Symbol.  Eg. cfr  :"},
Scala

Why won't the Scala compiler apply tail call optimization unless a method is final?For example, this:results inWhat exactly would go wrong if the compiler applied  in a case such as this?Consider the following interaction with the REPL. First we define a class with a factorial method:Now let's override it in a subclass to double the superclass's answer:What result do you expect for this last call? You might be expecting 240.  But no:That's because when the superclass's method makes a recursive call, the recursive call goes through the subclass.If overriding worked such that 240 was the right answer, then it would be safe for tail-call optimization to be performed in the superclass here.  But that isn't how Scala (or Java) works.Unless a method is marked final,  when it makes a recursive call.And that's why @tailrec doesn't work unless a method is final (or private).UPDATE: I recommend reading the other two answers (John's and Rex's) as well.Recursive calls might be to a subclass instead of to a superclass;  will prevent that.  But why might you want that behavior?  The Fibonacci series doesn't provide any clues.  But this does:If the Pretty call was tail-recursive, we'd print out  instead since the extension wouldn't apply.Since this sort of recursion is plausibly useful, and would be destroyed if tail calls on non-final methods were allowed, the compiler inserts a real call instead.Let foo::fact(n, res) denote your routine.  Let baz::fact(n, res) denone someone else's override of your routine.The compiler is telling you that the semantics allow baz::fact() to be a wrapper, that  upcall (?) foo::fact() if it wants to.  Under such a scenario, the rule is that foo::fact(), when it recurs, must activate baz::fact() rather than foo::fact(), and, while foo::fact() is tail-recursive, baz::fact() may not be.  At that point, rather than looping on the tail-recursive call, foo::fact() must return to baz::fact(), so it can unwind itself.Nothing would go wrong. Any language with proper tail call elimination will do this (SML, OCaml, F#, Haskell etc.). The only reason Scala does not is that the JVM does not support tail recursion and Scala's usual hack of replacing self-recursive calls in tail position with  does not work in this case. Scala on the CLR could do this as F# does."},
Scala

 is the same question for older version of Scala, but they say that Eclipse plugin has been improved vastly. Is it the best IDE now? How do different Scala IDE compare today? I've been pretty successful with IDEA 9. I've briefly tried both Netbeans and Eclipse and wasn't able to get what I wanted. Eclipse's code-complete didn't behave as well as I'd have liked, and I couldn't find a way to make Netbeans handle Scala scripts; It'd just complain that the file wasn't a class.To be clear, I've been using IDEA for a few years for Java, so keep that in mind:)For the moment, Scala Plugin in IntelliJ IDEA is the best. It handles Scala 2.8 well. IntelliJ IDEA Community Edition is now free and open source (and works with Scala), so I can't see any reason for not using it.The plugin is still somewhat buggy (many \"false negatives\", i.e. the code without red underscores may not compile successfully; but almost no \"false positives\"), but perfectly usable. The best thing is that you can use IDEA's excellent debugger with Scala (not without some issues, but it actually works!).FSC (Fast Scala Compiler) is also supported in latest builds. A huge time-saver.The plugin development team is quite responsive. Some of the guys work directly in JetBrains and possess intimate knowledge about IDEA platform, so the development progresses fast.JetBrains IDEA's Scala plug-in handles 2.7 and 2.8 equally well.I cannot make any comparisons because I have used only IDEA.Using Eclipse Helios with the dev-version of the new Scala(2.8) plugin, as there isn't an official release yet. That  beta, definitively -- but I can't confirm the frequently expressed opinion that this plugin is outright horrible ;-)I'd say, the experience is already OK-ish, and indeed better than the current state of affairs with the Groovy plugin. OTOH, the experience with plain Java is way more smooth (feels like flying at times), and the current CDT I'd rate somewhat in between.Incremental compile and error highlighting work quite well for me; tweaking a DSL implementation into form just by continuously rewriting your code until the error markers are gone -- without ever having to test-run your program -- is outright fun and just again shows that FP / static typing rocks!Problems encountered from time to time:\n- implicits and nested types in other compilation units (esp. nested / super packages) aren't picked up at times when there are still other errors around; they will be picked up after an full build\n- there seems to be a memory leak in the version I'm using right now (from end august 2010), necessitating to restart the workbench after some hours of work\n- beware when you're using AspectJ, to make sure you get a version of the Scala plugin which relies on a JDT weaving bundle version which also works with AJDTPS: I'm using maven builds in all my projects and generated the eclipse projects with the eclipse-maven-plugin, and then imported them as plain-flat eclipse projects. I can just strongly recommend everyone to keep away from the M2-eclipse plugin (for maven) in its current (2010) state, it makes your workbench painfully slow, is buggy and has lots of almost unpredictable behaviour, because it constantly tries to do magic things behind the scenes (and besides that, the aspectj support is broken since this spring)i use both eclipse and IDEA in summery i prefer to use IDEA rather than eclipseA non-answer: None.Based on what a perceived majority says, IDEA is probably the best Scala IDE today. And it (read: the Scala plugin) sucks. It does not handle fsc well, type inference is a mess, many errors are not shown, a number of non-errors are marked as errors, it is slow (when inspections are turned on), the test runner silently swallows aborting (!= failing) tests, ...So I switched to a simple text editor with syntax highlighting on one and a maximized shell with SBT (simple build tool) on the other screen. Awesome! SBT is responsive (you can let file changes trigger recompilation of affected code and even reruns of tests), manages dependencies very smoothly and has helpful output (esp for tests; using ScalaTest). SBT increased my productivity compared to IDEA a lot.You lose code completion, of course, altough geany offers me identified symbols. But as long as IDEs don't get type inference to work properly code completion does not help, anyway.Some people care a lot about code refactoring. Well, the IDEs apparently don't make a good job there either. Even if they would, I'd rather only open them for this particular task than use them all the time.My experiences clearly point to IntelliJ IDEA:About six months ago, when I started a serious Scala (multi module) project, I had to abandon Eclipse as my favorite Java IDE and switched to IntelliJ (9.0.x). Eclipse Scala IDE was way to buggy and often stopped responding at some point, even for the most simple projects. For CI (Hudson) and command line build, I depend on Maven (with Scala plugin). The Maven dependencies (incl. Scala libs) are picked up nicely by IntelliJ.A few days back I updated to IDEA X (CE) with the current plugin (nightly build) and work became even smoother. Although fsc still terminates after a while when inactive.From what I see, I'd like to add, that there seems to be way more activity on the IntelliJ side to respond to bugs and improve the plugin continuously. Correct me when I'm wrong, but Eclipse Scala IDE development seems almost stalled. Still no 'official' Helios release!NB: Just to provide some context (not bragging, really): The aforementioned project consists of about 25 Scala modules (POMs), 5 Java modules, 325 Scala files with a total of about 360 Scala classes, case classes and traits (> 19 kLOC, including comments). My platform is OS X 10.6, Scala 2.8.1, Java 1.6.UPDATE: After having the need for pretty extensive refactorings (mainly move class, rename package), I discovered that the recent IDEA 10.0.1 plugin 0.4.413 (and probably older versions, too) has quite some problems getting stuff right. I don't want to explain the specifics, but I (almost ever) ended up manually fixing unresolved references or otherwise messed-up code. You can have a look at  to get an idea.For everyone who is really considering doing some serious development with Scala, I strongly recommend to evaluate the IDEs in question beyond the basics. When you are into an agile approach, which in my option requires a painless refactoring support without surprises (especially in multi-module projects), things are pretty tight at the moment.It would be pretty neat, if someone came up with a IDE independent specification-like list of refactorings (and desired outcomes), which could be used to verify an IDE's refactoring support.The officially endorsed and supported (by Typesafe) for Scala 2.9 is Eclipse. The current version is far superior to prior versions and includes a context-aware REPL, full-featured debugger, and even the ability to debug REPL statements.  I think this question needs to be updated and the answers revisited.I think that the best option so far is the ScalaIDE for Eclipse. You can go to the ScalaIDE Web Site and look around to see by yourself. \nStrong points I see about it are: Here below a summary of the main features:Scala IDE provides support for development of Scala applications in the Eclipse platform. Its main target is the support for the Scala language and the integration with the Eclipse Java tools. It provides many of the features Eclipse users have come to expect including:UPDATE: the features and advantages are mentioned on this answer are for version 2.9 and 2.10 of Scala, because it has been already discontinued. see here:\"The 2.0.1 release is only available for Scala 2.9, if you would like to use the Scala IDE with Scala 2.8, please install the 2.0.0 release \"I don't recommend the Scala IDE/Eclipse.  It doesn't have a lot of the features that are even available for Eclipse with Java.  And there are bugs.I am using the latest NetBeans and haven't tried anything else. I've met at least 2 notable bugs in NetBeans while coding in Scala:One: NB occasionally come unable to run a program, hanging on classpath scanning.\nSolution: Create a new project, copy your code there and go on.\nComment: .Two: Sometimes NB  of particular namespaces or classes and complains when you use them.\nSolution: Just ignore and go on - compiler founds no errors and the program works.I'd recommend IDEA's plugin for now.The Scala plugin for NetBeans is quite nice too. It doesn't yet support NetBeans 6.9, the newest release, though, and you still need to download it manually instead of installing it directly from the plugin manager inside NetBeans. However, it integrates better with Maven projects than IDEA's plugin does (this is true for NB and IDEA in general, in my opinion).It partly depends on your style of working, as all the options have strengths and weaknesses.If you need refactoring across mixed java/scala projects, then IntelliJ is your only option.If you want to do any work on the compiler or a compiler plugin, then Eclipse has the advantage of being able to launch a runtime workspace with a custom compiler build, including breakpoints.  It also improved massively for the 2.8 Scala release.Netbeans is a fine choice to go with if you're already very familiar with that platform, the costs of learning a new environment may well outweigh any benefits, and all three solutions are improving rapidly.I haven't tried netbeans scala plugin yet, but I find that Intellij IDEA plugin is at any way much better a scala ide than the Scala eclipse plugin, which is sooooo slow that drives me crazy.\nThough swing applications don't work well with my tiling window manager.try IDEAX the latest community edition of Intellij IDEA (version 10), it has improved scala plugin which has faster code compilation and exceution in addition to that it has \nMaven3 and SBT support with which we can develop Lift applications.IntelliJ IDEA community edition + Scala Plugin + SBT plugin"},
Scala

For example suppose I haveHow would I do something likeYou can do . You can also do , , and .My prefered way is to add a rounding method, to reduce any potential suprise in the conversion behavior:oror you could do..."},
Scala

Consider the following Scala code:Now in Java, I would have liked to use  as:However, the above does not work (as expected since Java does not allow functional programming). What is the easiest workaround to pass a function in Java? I would like a generic solution that works with functions having arbitrary number of parameters. You have to manually instantiate a  in Java. Something like:This is taken from .In the  package, there are abstract classes named  and so on for other arities. To use them from Java you only need to override , like this:If you're on Java 8 and want to use Java 8 lambda syntax for this, check out .The easiest way for me is to defined a  interface like:Then modify your scala code, overloading  to accept also  objects such as:You will naturally use the first definition from scala, but still be able to use the second one from java:Here's my attempt at a solution, a little library: You wrap your Java 8 lambda in F(...) and then it's converted to a Scala function."},
Scala

The Either class seems useful and the ways of using it are pretty obvious. But then I look at the API documentation and I'm baffled:What do I do with a projection and how do I even  the joins?Google just points me to the API documentation.This might just be a case of \"paying no attention to the man behind the curtain\", but I don't think so. I think this is important. and  are the important ones.  is useful without projections (mostly you do pattern matching), but projections are quite worthy of attention, as they give a much richer API. You will use joins much less. is often used to mean \"a proper value or an error\". In this respect, it is like an extended  . When there is no data, instead of , you have an error. \n has a rich API. The same can be made available on , provided we know, in Either, which one is the result and which one is the error.  and  projection says just that. It is the , plus the added knowledge that the value is respectively at left or at right, and the other one is the error. For instance, in , you can map, so  returns an  with  applied to the value of  if it has a one, and still  if  was . On a left projection, it will apply  on the value at left if it is a , and leave it  unchanged if it is a . Observe the signatures: and  are simply the way to say which side is considered the value when you want to use one of the usual API routines. Alternatives could have been: Now the joins. Left and Right means the same thing as for the projections, and they are closely related to . Consider . The signature may be puzzling: and  are technically necessary, but not critical to the understanding, let's simplifyWhat the implicit means is that the method can only be called if  is an . The method is not available on an  in general, but only on an . As with left projection, we consider that the value is at left (that would be right for ). What the join does is flatten this (think ). When one join, one does not care whether the error (B) is inside or outside, we just want Either[C,B]. So Left(Left(c)) yields Left(c), both Left(Right(b)) and Right(b) yield Right(b). The relation with flatMap is as follows:The  equivalent would work on an ,   would yield  both  and  would yield . It can be written o.flatMap(identity). Note that  is isomorphic to  (if you use left projections and joins) and also to  (using right projections).Ignoring the joins for now, projections are a mechanism allowing you to use use an  as a monad. Think of it as extracting either the left or right side into an , but As always, this probably makes more sense with an example. So imagine you have an  and want to convert the  to a  (if present)This will map over the left side of result, giving you an  and  enable you to \"flatten\" a nested :Edit:  shows one example of how you can use the projections, in this case to fold together a sequence of s without pattern matching or calling  or . If you're familiar with how to use  without matching or calling , it's analagous.While curiously looking at the current , I saw that  and  are implemented with pattern matching. However, I stumbled across this  and saw that it used to implement the join methods using projections:My suggestion is add the following to your utility package:In my experience the only useful provided method is fold. You don't really use isLeft or isRight in functional code. joinLeft and joinRight might be useful as flatten functions as explained by Dider Dupont but, I haven't had occasion to use them that way. The above is using Either as right biased, which I suspect is how most people use them. Its like an Option with an error value instead of None.Here's some of my own code. Apologies its not polished code but its an example of using Either in a for comprehension. Adding the map and flatMap methods to Either allows us to use the special syntax in for comprehensions. Its parsing HTTP headers, either returning an Http and Html error page response or a parsed custom HTTP Request object. Without the use of the for comprehension the code would be very difficult to comprehend."},
Scala

What is the difference between exclamation mark () and question mark () when sending messages to Actors?Shamelessly copied   (look  section for more):From the recipient's point of view, it sees  and  messages the same way. However when receiving a  the value of  will be the reference of the actor who sent the message, whereas for an , the  is set up such that any reply goes to the  created in the actor who did the asking.There is an advantage in , that it is easy to know that the response you're receiving was definitely a result of the message you asked, whereas with Tell, you may need to use unique IDs to achieve a similar result. However with  you need to set a  after which the  will fail if no response is received.In the code below, the same effect is achieved with a  and and ."},
Scala

The type inference engine of Haskell is much more powerful than Scala's. In Haskell I rarely have to explicitly write the types whereas in Scala the types can only be inferred in expressions but not in method definitions.For example, see following Haskell code snippet:It returns the size of a List. The Haskell compiler can recognize what types are used and what the function definition is. The equivalent Scala code:Or with method definitions:My question is: Why can't I write them like the following?Once again with method definitions:Is it because nobody has implemented it yet? Is the type system of Scala not as powerful as needed for this case? Or are there other reasons?The main reason is that the type system of Scala allows sub-typing, which the  does not support.Haskell does not have sub-typing, so the algorithm works much better there, although many popular type system extensions supported by GHC cause type inference to fail again, forcing you to provide explicit type signatures for some expressions.In the end, it's a trade-off between the power of the type system and the amount of type inference that can be done. Scala and Haskell have simply made different trade-offs.I guess the main reasons have already been given, but I find this quote by Scala's creator Martin Odersky to be particularly informative,Source: comment under post .hammar gave the biggest reason. Here are two others:ConsiderHow could Scala possibly infer the type of the argument? Should it look for every class with an  and  field? What if there are more than 1? In Haskellrecord names are unique, which presents its own problems, but means you can always infer what kind of record is being referred to.In Scala the type of the object being matched can be used either as part of the match, or to decide how matching should be done. So even if all the constructors in the  are for , you  want to pass something other than a list to it, and have it fail.Another thing that doesn't play well with Hindley-Milner type inference is , and related features like default arguments and varargs. That's the reason why it is so hard to write things like  in Haskell (which is trivial in Scala)."},
Scala

Suppose that I have a string in scala and I want to try to parse a double out of it.  I know that I can just call toDouble and then catch the java num format exception if this fails, but is there a cleaner way to do this?  For example if there was a parseDouble function that returned Option[Double] this would qualify.  I don't want to put this in my own code if it already exists in the standard library and I am just looking for it in the wrong place.Thanks for any help you can provide.Or just Fancy version:Scalaz provides an extension method  on s, which gives a value of type . You can convert it to  if so required.You could try using  which returns an  type.So using the following returns a Left wrapping a  or a Right wrapping a Unfortunately, this isn't in the standard library.  Here's what I use:There's nothing like this not only in Scala, but even in basic Java. Here's a piece code that does it , though:Usage:I'd usually go with an \"in place\" Try:Note, that you can do further calculation in the for and any exception would project into a Failure(ex). AFAIK this is the idiomatic way of handling a sequence of unreliable operations."},
Scala

(This is a follow up to . The question wasn't answered.)Basically,  says \"I don't know how to create a project under the new sbt. With the old one, I just ran  in a new folder and there was a guided wizard that led me through the setup.\"The  does not explain how to create a new project, it just points to , which also doesn't explicitly say how to create a new project -- only how to write a  file.So I tried first writing a  and then running  in the directory with the  file, but I still don't see a  directory to work with.Could someone post a simple step-by-step (I'm assuming there are like 3 steps at most) guiding how to create a new project under sbt 0.10.X?I found the answer I was looking for at this webpage: .The high-level steps are:I am surprised that noone gave another solution which is the closest to the old way (as mentioned by @dsg) to create a simple project in sbt:\nJust run sbt in your project directory, then issue the following commands in the sbt REPL:Granted, it is only mildly useful as it will just create the build.sbt file (enough to make it a proper sbt project) with the corresponding properties set, and you might as well create the file by hand (I usually prefer to do so myself). It won't create the  directory either.Just a few days ago  () plugin to sbt was released. It intended to dealt exactly with that problem:You can use  to generate project layout using various templatesIn newer versions of sbt, you can just install sbteclipse:then from sbt's console you can run:In version 0.10.x I think this post can help you:I've been using  skeleton. See also my .It was the first one that just worked and I've been a quite happy with it since then.Don't forget the recent sbt 0.13.3 :Example:Check out the GitHub repo . In particular the  file.Just clone the repo, go to that directory, then call the  command. From inside of , you can type  to execute provided code. Have fun!An alternative way to generate the project structure using Intellij: That will create for you the basic skeleton for the sbt project. "},
Scala

I have a server side implemented in  and  based front end. My services return  and they are handled within Scalatra's  for JSON responses. For isomorphic/server side rendering setup I did not want to change services to be blocking so I started with Scala Future->  conversion . But the dispatcher in Flux would like to have JS Promise. So far I found only rather complicated sounding way around this  Is there any recommended way to deal with this Scala Future -> JS Promise conversion?I will try to answer the Scala Future to JS Promise part of the question.\nAs you haven't provided an example. I will provide one here with the conversion.\nIf we say that we have a Future implemented in Scala this way:then the corresponding code in JavaScript/ES6 could look like this:I know this is not Scala, but I wanted to include it for completeness.\nThis is a mapping of  to  taken from  docs:"},
Scala

Is there an easy way to get rid of everything getting generated as a result of performing an SBT build? It turns out it creates target directories all over the place. Performing ... doesn't get rid of all.If you use git:This will remove every file not tracked by git.On my system (Ubuntu Linux) with SBT 0.13.5 and some projects from the Coursera Functional Programming course I found the folders all totalled up to 2.1GB for 12 projects due to all the cache files and duplicated Scala downloads.The current SBT commands that work and get  everything cleaned is:This removes the top level \"target\" and \"lib_managed\" folders (23MB down to 3.2MB in this case) but leaves some target folders under project:This is where the Linux find command (also posted by @jack-oconnor) is very helpful:This gets us back down to a mere 444KB for one of my own projects and the 2.1GB goes down to 5.0MB !In windows you won't have as many useful command line options, e.g. no star wildcards in path names, but you can always try and force it with:The best I can do on automatically finding is a DIR command:Obviously this is very important for reproducible builds on an integration server such as Jenkins!Ensure that all files, , are stored within the integration server workspace, by supplying command line arguments such as this to sbt:and then click the Wipe Out Workspace button in Jenkins, or the equivalent in other integration servers. That should definitely do it!Or if you are using a recent version of the sbt launcher script, you can simply add  instead.On Linux or similar, this is better than , as it won't accidentally remove any directory named  that might exist in your source code:If you're running this command within a shell, you'll need to quote the regular expression, for example, for bash:With BSD find (e.g. on Mac OS X) the command will be:"},
Scala

I am developing an application with  and  that exposes some REST API. These APIs will be used by different applications, web, mobile or desktop, so the OAuth protocol (OAuth2) seems the most suitable.Also I would initially use an external OAuth Provider such as Facebook.My question is: what is the exact flow to authorize the individual REST call? What should I expect on the server side for each call and what I should check with the external provider? With OAuth1 I knew that the client sent the token with all the signed request, but with Oauth2 I think not so, I imagine that if a token is not signed is not trusted and therefore I do not think this is the flow.You could use a module called SecureSocial.This one is quite refined and many people in Play community seem to be aware/using this module.For authorization might be useful.\nFor end to end scala stuff,\nI ported Apache Amber to Play2 Scala, here is the link:\nThe reason to port Apache Amber is:If you want to setup oauth2 server on your site, you can try use my port. It has document.Basically, the standard flow is the following:If you want more details, just ask :-)OAuth is an Authorization Protocol, so if you're looking at a Authentication Solution, this might not be the one. You're question saying the consumer of the API will be various application. This lead to 2 scenarios, To support OAuth Eco-System you need a Key Management System. \nTo, now coming to endpoint you would have to expose, Otherwise simplest/robust solution would be, \nYou can use existing OAuth ecosystem of Apigee.I had the same problem, what I did ( I suppose It's not the best solution) was, to place the methods of the REST server, inside an \"@Security.Authenticated(Secure.class)\" , and,  use a session cookie (which also was registered inside a Hash table in backend). The session cookie was generated after user sign-inandHope this helps I did not try it myself , but how about  module.\nAs in the github repo it says:I hope this helpsYou can try using this template for play that combines OAuth 2 provider with Deadbolt.\nThe OAuth scope maps to the Deadbolt permission and role concept.\nIt uses Redis to store access tokens, and they expire automatically after the time period you configure."},
Scala

I want to write a backend system for a web site (it'll be a custom search-style service). It needs to be highly concurrent and fast. Given my wish for concurrency, I was planning on using a functional language such as Haskell or Scala.However, speed is also a priority.  results appear to show that Java is almost as fast as C/C++, Scala is generally pretty good, but Haskell ranges from slower to a lot slower for most tasks.Does anyone have any performance benchmarks/experience of using Haskell vs Scala vs Java for performing highly concurrent tasks? Some sites I've seen suggest that Scala has memory leaks which could be terrible for long running services such as this one. What should I write my service in, or what should I take into account before choosing (performance and concurrency being the highest priorities)?ThanksThis question is superficially about performance of code compiled with GHC vs code running on the JVM. But there are a lot of other factors that come into play.There are a million and one other factors that you should consider. Whether you choose Scala, Java, or Haskell, I can almost guarantee that you will be able to meet your performance requirements (meaning, it probably requires approximately the same amount of intelligence to meet your performance requirements in any of those languages). The Haskell community is notoriously helpful, and my limited experience with the Scala community has been much the same as with Haskell. Personally I am starting to find Java rather icky compared to languages that at least have first-class functions. Also, there are a lot more Java programmers out there, causing a proliferation of information on the internet about Java, for better (more likely what you need to know is out there) or worse (lots of noise to sift through). I'm pretty sure performance is roughly the same. Consider other criteria.You should pick the language that you know the best and which has the best library support for what you are trying to accomplish (note that Scala can use Java libraries).  Haskell is very likely adequate for your needs, if you learn enough to use it efficiently, and the same for Scala.  If you don't know the language reasonably well, it can be hard to write high-performance code.My observation has been that one can write moderately faster  more compact high-performance parallel code in Scala than in Haskell.  You can't just use whatever most obviously comes to mind in either language, however, and expect it to be blazing fast.Scala doesn't have actor-related memory leaks any more  if you use the default actors in a case where either you're CPU-limited so messages get created faster than they're consumed, or you forget to process all your messages.  This is a design choice rather than a bug, but can be the wrong design choice for certain types of fault-tolerant applications.  Akka overcomes these problems by using a different implementation of actors.Take a look at the head-to-head comparison. For some problems ghc and java7-server are very close. For equally many, there's a 2x difference, and for only one there's a 5x difference. That problem is k-nucleotide for which the GHC version uses a hand-rolled mutable hashtable since there isn't a good one in the stdlibs. I'd be willing to bet that some of the new datastructures work provides better hashtables than that one now.In any case, if your problem is more like the first set of problems (pure computation) then there's not a big performance difference and if its more like the second (typically making essential use of mutation) then even with mutation you'll probably notice somewhat of a performance difference. But again, it really depends on what you're doing. If you're searching over a large data set, you'll tend to be IO bound. If you're optimizing traversal of an immutable structure, haskell will be fine. If you're mutating a complex structure, then you may (depending) pay somewhat more.Additionally, GHC's lightweight green threads can make certain types of server applications extremely efficient. So if the serving/switching itself would tend to be a bottleneck, then GHC may have the leg up.Speed is well and good to care about, but the real difference is between using any compiled language and any scripting language. Beyond that, only in certain HPC situations are the sorts of differences we're talking about  going to matter.The shootout benchmark assumes the same algorithm is used in all implementations.  This gives the most advantage to C/C++ (which is the reference implementation in most cases) and languages like it.  If you were to use a different approach which suited a different language, this is disqualified.If you start with a problem which more naturally described in Haskell it will perform best in that language (or one very much like it)Often when people talk about using concurrency they forget the reason they are doing it is to make the application faster.  There are plenty of examples where using multiple threads is not much faster or much much slower.  I would start with an efficient single threaded implementation, as profiled/tuned as you can make it and then consider what could be performed concurrently. If its not faster this more than one CPU, don't make it concurrent.IMHO: Performance is your highest priority (behind correctness), concurrency is only a priority in homework exercise.I would say Scala, but then I have been experimenting with Scala so my preference would definitely be Scala. Any how, I have seen quite a few high performance multi-threaded applications written in Java, so I am not sure why this nature of an application would mandate going for FP. I would suggest you write a very small module based on what your application would need in both scala and haskell and measure the performance on your set up. And, may I also add clojure to the mix ? :-) I suspect you may want to stay with java, unless you are looking at benefiting from any other feature of the language you choose.Your specific solution architecture matters - ."},
Scala

Why were the case classes without a parameter list deprecated from Scala? And why does compiler suggest to use  as parameter list instead?Someone please answer  my second question... :|It is really easy to accidentally use a no-arg case class incorrectly as a pattern.Instead of:Or better: Hopefully the transcript below will demonstrate why an empty parameter list is preferred to the deprecated missing parameter list.A case object would usually still be preferred over an empty parameter list.Without parameters, every instance of the case class is indistinguishable and hence is essentially a constant. Use an object for that case."},
Scala

I'm pretty sure I'm missing something here, since I'm pretty new to Shapeless and I'm learning, but when is the Aux technique actually ? I see that it is used to expose a  statement by raising it up into the signature of another \"companion\"  definition. but isn't this nearly equivalent to just putting R in the type signature of F ?I see that path-dependent type would bring benefits  one could use them in argument lists, but we know we can't do thus, we are still forced to put an additional type parameter in the signature of . By using the  technique, we are  required to spend additional time writing the companion . From a usage standpoint, it would look to a naive user like me that there is no benefit in using path-dependent types at all. There is only one case I can think of, that is, for a given type-level computation more than one type-level result is returned, and you may want to use only one of them.I guess it all boils down to me overlooking something in my simple example. There are two separate questions here:I'll start with the second question because the answer is more straightforward: the  type aliases are entirely a syntactic convenience. You don't ever  to use them. For example, suppose we want to write a method that will only compile when called with two hlists that have the same length:The  type class has one type parameter (for the  type) and one type member (for the ). The  syntax makes it relatively easy to refer to the  type member in the implicit parameter list, but it's just a convenience\u2014the following is exactly equivalent:The  version has a couple of advantages over writing out the type refinements in this way: it's less noisy, and it doesn't require us to remember the name of the type member. These are purely ergonomic issues, though\u2014the  aliases make our code a little easier to read and write, but they don't change what we can or can't do with the code in any meaningful way.The answer to the first question is a little more complex. In many cases, including my , there's no advantage to  being a type member instead of a type parameter. Because Scala , we need  to be a type parameter for our method if we want to verify that the two  instances have the same  type. At that point, the  on  might as well be a type parameter (at least from our perspective as the authors of ).In other cases, though, we can take advantage of the fact that Shapeless sometimes (I'll talk about specifically  in a moment) uses type members instead of type parameters. For example, suppose we want to write a method that will return a function that will convert a specified case class type into an :Now we can use it like this:And we'll get a nice . If 's  were a type parameter instead of a type member, we'd have to write something like this instead:Scala doesn't support partial application of type parameters, so every time we call this (hypothetical) method we'd have to specify both type parameters since we want to specify :This makes it basically worthless, since the whole point was to let the generic machinery figure out the representation.In general, whenever a type is uniquely determined by a type class's other parameters, Shapeless will make it a type member instead of a type parameter. Every case class has a single generic representation, so  has one type parameter (for the case class type) and one type member (for the representation type); every  has a single length, so  has one type parameter and one type member, etc.Making uniquely-determined types type members instead of type parameters means that if we want to use them only as path-dependent types (as in the first  above), we can, but if we want to use them as if they were type parameters, we can always either write out the type refinement (or the syntactically nicer  version). If Shapeless made these types type parameters from the beginning, it wouldn't be possible to go in the opposite direction.As a side note, this relationship between a type class's type \"parameters\" (I'm using quotation marks since they may not be  in the literal Scala sense) is called a  in languages like Haskell, but you shouldn't feel like you need to understand anything about functional dependencies in Haskell to get what's going on in Shapeless."},
Scala

I recently followed a way , which reduces the code and the compile time without using Proguard or Treeshake.Following this article, I should be able use the last Eclipse build (3.7), almost the last version of Scala (2.8.1) updated on an emulator version 10, the version 2.8.3 within Eclipse with the provided plug-in.The presented way is to provide a specific ramdisk image version, where we can upload scala libraries, which drastically shrinks the size of the code to upload to the emulator.I followed the steps, created a hello world, added scala nature, added a dummy scala class, moved the Scala builder before the Android Package Installer, everything builds perfectly, but when I launch the apk on a emulator from Eclipse, the application crashes and I get the following error, which looks like the \n (at the end of the document) :If I remove the scala reference in the activity file, it runs well.Here is the TestSinceInstallation.java file:and here is the ComputeSum.scala fileWhat do you think I should do to make this work ? I feel so close to the goal.Here is the solution, to use Android with  and with Scala 3.0.0 without any problems.Now, to create a scala project,You're done.Now good things happen.\nFirst, you can scalafy any activity, and you will get access to scala unique features, such as:Here is an example of some of them.Now after all the previous boilerplate, it is very useful to write concise activities. Note how we can directly operate on ids as if they were views. Disambiguation is needed as  if the methods can be inferred from various structures.Make sure that the name of the scala file matches the main activity contained in it, in this case it should be .Second, to set up a scala project as a library project, to use is as a base for applications having different resources, follow the . Right-click on the scala project that you want as a base library project, , , and check .\nTo create derivated project using this library and for which you can generate an APK, create a new android project, and without adding any scala or androidproguardscala nature, just right-click, , , and add the previous scala project as a library. With the new version of the Android Plug-in, you should go to  and check . This will allow to export the scala library, both in the library project and the main project, even if the main project is not assigned Scala. Using the plug-in  makes it easy to test your android scala project. Just follow the steps for creating a test project, add Scala nature to it. You can even use the new scala debugger, and by adding the  library, you can use should matchers and many other features Scala has."},
Scala

I'm going to develop new HTTP/REST services using Scala and Akka Actors.I have experience working with Play, but I don't really need a complete web Framework.\nFrom what I read, I think Spray is a suitable choice. \nMy question come from the future of Spray after the new arrived AKKA-HTTP.Does the Spray project will grow independently from the Akka-HTTP project, or are the two project going to be merged into one Akka-HTTTP? What is the impact of this if I start developing with Spray?\nAlso I read that Play will integrate AKKA-HTTP. \nSo I finally wonder if a should not go with Play?Thanks for your help.Spray is production ready, but the development team (Mathias Doenitz) works for Typesafe on Akka-http now.The status of Akka-http is .  There are vague promises of a full release \"within a few months\", but nothing you can take to the bank.Jonas Boner from Typesafe has referred to Akka-http as \"Spray 2.0\".  So don't expect any future versions of Spray and at some point you'll have to make the switch.  I saw Jonas' Akka-http presentation at Scala Days and it looks like porting Spray code to Akka-http should be straight forward as the DSL is mostly unchanged (even though the underlying implementation of the library will be different).To answer your questions specifically: Spray is finished as a separate project, it is being imported into Akka under the name Akka-http (not a merge as Akka didn't have any equivalent before hand).  If you need to start development now go with Spray, if you can afford to work with the inevitable bugs in a preview release go with Akka-http.  Your Spray code will never stop working, but it won't be supported either outside of minor bug fixes.  All new functionality will be added in Akka-http, so instead of updating to Spray 2.0 you update to Akka-http.You have already given answer to your question in your comment. As long as if you don't need to deal with UI I would suggest go with .I don't think you will have impact if you starts with Spray.io as there are many projects running their production environment on Spray.For more details please refer below link.ThanksWell, if you have to learn everything from scratch, I would recommend choosing spray - Akka hhtp documentation is really incomplete and a lot of route directives are not implemented yet on akka.http. I started with akka but I was forced to go to spray...As per Johannes Rudolphsource: "},
Scala

Scala 2.10 seems to have broken some of the old libraries (at least for the time being) like Jerkson and lift-json.  The target usability is as follows:But I'm having trouble finding good existing ways of generating and deserializing Json that work with Scala 2.10.Are there best practice ways of doing this in Scala 2.10?  is a Java library to process JSON fast. The Jerkson project wraps Jackson, but appears to be abandoned. I've switched to Jackson's  for serialization and deserialization to native Scala data structures.To get it, include the following in your :Then your examples will work verbatim with the following Jackson wrapper (I extracted it from jackson-module-scala test files):Other Scala 2.10 JSON options include Twitter's  based on the Programming Scala book--it's simple, at the cost of performance. There is also , which uses  for parsing. Finally,  looks nice, but it does not easily decouple from the Play project.Mentioning  that wraps jackson, lift-json or its own native implementation as a long term solution:I can heartily recommend  for json support in scala. All you need to configure it to serialize your Customer object is one line:  That will pimp your class to give it an  method which turns it into a string. It will also pimp the string class to give it a method  to parse strings. It handles the options in your class fine. Here is a working class with a passing test and a running main method which you can drop into a git clone of argonaut to see it all working fine: The developers are also helpful and responsive to folks getting started. There is now a fork of Jerkson that supports Scala 2.10 at .So, based on the absence of an error message and the incorrect sample code, I'm suspecting this is more of an issue of just not understanding how the lift-json extraction works. If I've misunderstood, do comment and let me know. So, if I'm right then here's what you need.To serialize:Then to reverse the process you'd do something like:If that's not the part you're having trouble with, then do let me know and I can try to revise my answer to be more helpful."},
Scala

This should be an easy one.  How do I apply a function to a tuple in Scala? Viz:Many thanks in advance.In Scala 2.7:In Scala 2.8:Following up on the other answer, one could write (tested with 2.11.4):See :"},
Scala

Kinda silly question, but I used  to get started with the play framework, and now need to see what version I'm using. 2.3 came out with support for docker, but when I put in my , it complains it doesn't know what dockerExposedPorts is, so I'm thinking I might be running 2.2. Type  within the activator console. Alternatively you can look in  for the line In this example, the play version is 2.3.2"},
Scala

There's something I don't understand about Scala's . It describes the interface for all mutable sequences, yet I don't see methods to append or prepend elements without creating a new sequence. Am I missing something obvious here?There are  and  for append and prepend, respectively, but they create new collections \u2014 in order to be consistent with the behavior of immutable sequences, I assume. This is fine, but why is there no method like  and , like  and  define, for in-place append and prepend? Does it mean that I cannot refer to a mutable seq that's typed as  if I want to do in-place append?Again, I must have missed something obvious, but cannot find what\u2026Mutability for sequences  guarantees that you'll be able to swap out the items for different ones (via the  method), as you can with e.g. primitive arrays.  It does  guarantee that you'll be able to make the sequence larger (that's what the  trait is for) or smaller (). is the abstract trait that contains  and , not ."},
Scala

When you create a case class, the compiler creates a corresponding companion object with a few of the case class goodies: an  factory method matching the primary constructor, , , and .Somewhat oddly, this generated object extends FunctionN.This is only the case if: Seems like this was  about two years ago. The latest incarnation is .Does anyone use this, or know why it was added? It increases the size of the generated bytecode a little with static forwarder methods, and shows up in the  method of the companion objects:Manually created objects with a single  method are not automatically considered as :The reason why case class companion objects implement FunctionN is that before, case classes generated a class and a factory method, not a companion object. When we added extractors to Scala it made more sense to turn the factory method into a full companion object with apply and unapply methods. But then, since the factory method did conform to FunctionN, the companion object needed to conform, too.[Edit] That said, it would make sense to have companion objects show as their own name, not as \"function\"Well, given that  in Scala:it seems natural that a companion object:is really:So the addition seems to be natural to me (I'm not sure why it seems \"odd\" to you?). As to whether it actually  anything; well, that is for someone smarter than me!Aside from oxbow_lakes's reply about the naturalness of it, it can often be useful to have constructors available as first-class functions, particularly in conjunction with Scala collections higher-order functions. For (a trivial) example,"},
Scala

I started learning scala a few days ago and when learning it, I am comparing it with other  languages like (, ) which I had some familiarity with. Does Scala has  sequences available?I went through pattern matching in Scala, but is there any concept equivalent to guards with  and all?Yes, it uses the keyword . From the  section of A Tour of Scala, near the bottom:(This isn't mentioned on the  page, maybe because the Tour is such a quick overview.)In Haskell,  is actually just a variable bound to . So it doesn't add any power to the concept of pattern matching. You can get it just by repeating your initial pattern without the guard:Yes, there are pattern guards. They're used like this:Note that instead of an -clause, you simply specifiy the pattern without a guard.The simple answer is no. It is not exactly what you are looking for (an exact match for Haskell syntax). You would use Scala's \"match\" statement with a guard, and supply a wild card, like:I stumbled to this post looking how to apply guards to matches with multiple arguments, it is not really intuitive, so I am adding an random example here. "},
Scala

Given a function that takes a variable number of arguments, e.g.How can I pass a sequence of arguments to the function? I would like to write:Obviously, this does not work. does the trick. Instead of applying the sequence as one single argument, each element in the sequence will be used as an argument."},
Scala

What would be good purely functional data structures for text editors? I want to be able to insert single characters into the text and delete single characters from the text with acceptable efficiency, and I would like to be able to hold on to old versions, so I can undo changes with ease.Should I just use a list of strings and reuse the lines that don't change from version to version?A  would probably be a good bet. It is an  so has decent update / prepend / update performance, unlike the  you mention. If you look at , it's the only immutable collection mentioned that has effective constant-time update.I don't know whether this suggestion is \"good\" for sophisticated definitions of \"good\", but it's easy and fun. I often set an exercise to write the core of a text editor in Haskell, linking with rendering code that I provide. The data model is as follows.First, I define what it is to be a cursor inside a list of -elements, where the information available at the cursor has some type . (The  will turn out to be  or .)This  thing is just the backward \"snoc-lists\". I want to keep strong spatial intuitions, so I turn things around in my code, not in my head. The idea is that the stuff nearest the cursor is the most easily accessible. That's the spirit of The Zipper.I provide a gratuitous singleton type to act as a readable marker for the cursor......and I can thus say what it is to be somewhere in a Now, to represent a buffer of multiple lines, we need s above and below the line with the cursor, and a  in the middle, for the line we're currently editing.This  type is all I use to represent the state of the edit buffer. It's a two layer zipper. I provide the students with code to render a viewport on the text in an ANSI-escape-enabled shell window, ensuring that the viewport contains the cursor. All they have to do is implement the code that updates the  in response to keystrokes.where  should return  if the keystroke is meaningless, but otherwise deliver  an updated  and a \"damage report\", the latter being one of(If you're wondering what the difference is between returning  and returning , consider whether you also want the editor to go beep.) The damage report tells the renderer how much work it needs to do to bring the displayed image up to date.The  type just gives a readable dataype representation to the possible keystrokes, abstracting away from the raw ANSI escape sequences. It's unremarkable.I provide the students with a big clue about to go up and down with this data model by offering these pieces of kit:The  function is used to shift focus out of a , giving you an ordinary list, but telling you where the cursor . The corresponding  function attempts to place the cursor at a given position in a list:I offer the students a deliberately incorrect and incomplete definition of which just handles ordinary character keystrokes but makes the text come out backwards. It's easy to see that the character  appears  of . I invite them to fix the bug and add functionality for the arrow keys, backspace, delete, return, and so on.It may not be the most efficient representation ever, but it's purely functional and enables the code to conform concretely to our spatial intuitions about the text that's being edited.We use a text zipper in Yi, a serious text editor implementation in Haskell. The implementation of the immutable state types is described in the following,and other papers.I'd suggest to use  in combination with  which is based on . So you could represent the current state as\nThis gives you  complexity for moving cursor up/down a single line, and since  and  (union) have both  complexity, you'll get  complexity for skipping  lines up/down.You could have a similar zipper structure for  to keep a sequence of character before, at and after the cursor. could be something space-efficient, such as .I've implemented a zipper for this purpose for my  library.  You can take a look here:The Clojure community is looking at  (Relaxed Radix Balanced) as a persistent data strcuture for vectors of data that can be efficiently concatenated / sliced / inserted etc.It allows concatenation, insert-at-index and split operations in O(log N) time.I imagine a RRB Tree specialised for character data would be perfectly suited for large \"editable\" text data structures.The possibilities that spring to mind are:"},
Scala

Just a simple velocity standalone app based on maven structure. Here is the code snippet written in Scala to render the template  in  folder: when to compile and run the program, I got the following error:Great question - I solved my issue today as follows using Ecilpse:See how first we tell VelocityEngine to look in the classpath. Without this it wouldn't know where to look.I put my .vm under the , then the code is :this works in web project.  In eclipse Velocity.getTemplate(\"my.vm\") works since velocity will look for the .vm file in src/main/resources/ or src/main/resources/templates, but in web project, we have to use Velocity.getTemplate(\"templates/my.vm\");You can just use it like this: It works.Make sure you have a properly configured resource loader. See Velocity documentation for help selecting and configuring a resource loader: you can try to add these code:I do this, and pass!you could use the above code to set the properties for velocity template. You can then give the name of the tempalte file when initializing the Template and it will find if it exists in the classpath.All the above classes come from package org.apache.velocity*While using embedded jetty the property webapp.resource.loader.path should starts with slash:otherwise templates will not be found in ../webapp/templatesYou can also put your templates folder under src/main/resources instead of src/main/java. Works for me and it's a preferable location since templates are not java source.I faced the similar problem with intellij IDEA.\nyou can use this "},
Scala

Is it possible to match a range of values in Scala?For example: would be  if  was between 0 and 10, but false otherwise. This little bit doesn't work of course, but is there any way to achieve something like it?Guard using :You can use guards:Here's another way to match using a range:With these definitions:You can do checks like these:So the code you need would be:"},
Scala

How do I check if a path / file exists in Scala similar to Python ? An example below:  Since Java 7 the better way would beWell, sorry I found the answer to my own question: you can use scala library as well :"},
Scala

I know a lot of Java people have started looking at Scala since it runs on the JVM, and a lot of people in the Microsoft world are looking at F#, but what does Ruby have as a natural functional successor?In a pure FP sense Ruby doesn't lack anything, instead it has too much some may say. A functional language forces the programmer to not use global variables and other idioms so much (although it is possible to use globals in functional languages)There's two  different definitions of what \"functional programming\" means. You can kind-of do the one in Ruby, but you cannot do the other.Those two definitions are:You can kind-of program with first-class functions in Ruby. It has support for first-class functions. In fact, it has  support for them: there is , , , , , blocks,  and  (and probably some others that I forget).All of these , have slightly different syntax, slightly different behavior and slightly different restrictions. For example: the only one of these which is syntactically lightweight enough that you can actually use it densely, is blocks. But blocks have some rather severe restrictions: you can only pass one block to a method, blocks aren't objects (which in an object-oriented language in wich \"everything is an object\" is a  severe restriction) and at least in Ruby 1.8 there are also some restrictions w.r.t parameters.Referring to a method is another thing that is fairly awkward. In  or  for example, I can just say  to refer to the  method of the  object. In Ruby,  is a method , if I want to refer to the  method of , I have to say . And if I now want to  that method, I cannot just say , I have to say  or  or (in Ruby 1.9) .So, first-class functions in Ruby aren't  first-class. They are much better than second-class, and they are \u2122, but they aren't fully first-class.But generally, Rubyists do not leave Ruby just for first-class functions. Ruby's support is good enough that any advantages you might gain from better support in another language usually is eaten up by the training effort for the new language or by something  that you are accustomed to that you must now give up. Like, say RubyGems or tight Unix integration or Ruby on Rails or syntax or \u2026However, the  definition of FP is where Ruby falls flat on its face. If you want to do programming with mathematical functions in Ruby, you are in for a world of pain. You cannot use the absolute majority of Ruby libraries, because most of them are stateful, effectful, encourage mutation or are otherwise impure. You cannot use the standard library for the same reasons. You cannot use the core library. You cannot use any of the core datatypes, because they are all mutable. You could just say \"I don't care that they are mutable, I will simply not mutate them and always copy them\", but the problem is: someone else still can mutate them. Also, because they are mutable, Ruby cannot optimize the copying and the garbage collector isn't tuned for that kind of workload.It just doesn't work.There is also a couple of features that have really nothing to do with functional programming but that most functional languages tend to have, that Ruby is missing. Pattern matching, for example. Laziness also was not that easy to achieve before s were more aggressively used in Ruby 1.9. And there's still some stuff that works with strict s or s but not with lazy s, although there's actually no reason for them to  strictness.And for  definition of FP, it definitely makes sense to leave Ruby behind.The two main languages that Rubyists have been flocking to, are  and . These are both relatively good matches for Ruby, because they are both dynamically typed, have a similar REPL culture as Ruby, and (this is more a Rails thing than a Ruby thing) are also very good on the web. They have still pretty small and welcoming communities, the original language creators are still active in the community, there is a strong focus on doing new, exciting and edgy things, all of which are traits that the Ruby community also has.The interest in Erlang started, when someone showed the original 1993 introduction video \"\" at RubyConf 2006. A couple of high-profile Rails projects started using Erlang, for example  and . Erlang is also easy to master for Rubyists, because it doesn't take purity quite as far as  or . The  of an actor is pretty pure, but the act of sending messages itself is of course a side-effect. Another thing that makes Erlang easy to grasp, is that Actors and Objects are actually the same thing, when you follow .Clojure has been a recent addition to the Rubyist's toolbelt. Its popularity is I guess mostly driven by the fact that the Ruby community has finally warmed up to the idea that JVM \u2260 Java and embraced  and then they started to look around what  interesting stuff there was on the JVM. And again, Clojure is much more pragmatic than both other functional languages like Haskell and other Lisps like  and much simpler and more modern than CommonLisp, so it is a natural fit for Rubyists.Another cool thing about Clojure is that because both Clojure and Ruby run on the JVM, you can  them.The author of \"\" (Stuart Halloway) is a (former?) Rubyist, for example, as is , the author of the  build tool for Clojure.However, Rubyists are also looking at both  (as one of the more pragmatic statically typed FP languages) and Haskell (as one of the more elegant ones). Then there is projects like  and  which are bridges that let you integrate Ruby with Scala and Haskell, respectively. Twitter's decision to move part of their low-level messaging infrastructure first from MySQL to Ruby, then from Ruby to Scala is also pretty widely known. doesn't seem to play any role at all, possibly due to an irrational fear towards all things Microsoft the Ruby community has. (Which, BTW, seems mostly unfounded, given that the F# team has  made versions available for Mono.)Java people are using a language on the JVM and want a more functional one compatible with their runtime, so they go to Scala.C# people are using a language on the CLR and want a more functional one compatible with their runtime, so they go to F#.Ruby people are using a language that's already pretty functional, and they're using it on a number of underlying runtimes (JRuby, IronRuby, MRI, MacRuby, Rubinius, etc...).  I don't think it has a natural functional successor, or even needs one.Any version of Lisp should be fine.Ruby it self is a kind of Functional programming language, So I don't see any special dialects for FP using ruby.In hype level, Haskell.Assuming Ruby people don't just go to the JVM themselves, I think most would adopt Erlang, being another dynamically typed language.Ruby isn't as functional as say Lisp, but it is just functional enough that you can do some functional programming in a good fun way. (unlike trying to do functional programming in something like C#)Also, it actually forces you into functional paradigms in some of its syntax, such as the heavy use of blocks and yield. (which I fell in love with after learning Ruby). "},
Scala

With the intention of learning and further to this , I've remained curious of the idiomatic alternatives to explicit recursion for an algorithm that checks whether a list (or collection) is ordered.  (I'm keeping things simple here by using an operator to compare and Int as type; I'd like to look at the algorithm before delving into the generics of it)The basic recursive version would be (by @Luigi Plinge): A poor performing idiomatic way would be:An alternative algorithm using fold:It has the drawback that it will compare for all n elements of the list even if it could stop earlier after finding the first out-of-order element. Is there a way to \"stop\" fold and therefore making this a better solution?Any other (elegant) alternatives? By \"idiomatic\", I assume you're talking about McBride and Paterson's \"Idioms\" in their paper . :o)Here's how you would use their idioms to check if a collection is ordered:Here's how this works:Any data structure  where there exists an implementation of , can be traversed with an  functor, or \"idiom\", or \"strong lax monoidal functor\". It just so happens that every  induces such an idiom for free (see section 4 of the paper).A monoid is just an associative binary operation over some type, and an identity element for that operation. I'm defining a  (a semigroup is the same as a monoid, except without the identity element) whose associative operation tracks the lesser of two values and whether the left value is less than the right value. And of course  is just the monoid generated freely by our semigroup.Finally,  traverses the collection type  in the idiom induced by the monoid. The result  will contain true if each value was less than all the following ones (meaning the collection was ordered), or  if the  had no elements. Since an empty  is sorted by convention, we pass  as the second argument to the final  of the .As a bonus, this works for all traversable collections. A demo:A test:And  how you do  traversal to detect if a collection is ordered.This will exit after the first element that is out of order. It should thus perform well, but I haven't tested that. It's also a lot more elegant in my opinion. :)I'm going with this, which is pretty similar to Kim Stebel's, as a matter of fact.In case you missed missingfaktor's elegant solution in the comments :This solution is very readable and will exit on the first out-of-order element.The recursive version is fine, but limited to  (with limited changes, it would work well on ).If it was implemented in the standard library (would make sense) it would probably be done in  and have a completely imperative implementation (see for instance method )You can interrupt the  with a  (in which case you need only the previous element and not boolean all along)but I don't see how it is any better or even idiomatic than an imperative implementation. I'm not sure I would not call it imperative actually. Another solution could be Rather concise, and maybe that could be called idiomatic, I'm not sure. But I think it is not too clear. Moreover, all of those methods would probably perform much worse than the imperative or tail recursive version, and I do not think they have any added clarity that would buy that. Also you should have a look at .To stop iteration, you can use :If you split the List into two parts, and check whether the last of the first part is lower than the first of the second part. If so, you could check in  for both parts. Here the schematic idea, first without parallel: And now with parallel, and using  instead of :my solution combine with missingfaktor's solution and Orderingand you can use your own comparison method. E.g."},
Scala

So I've got this macro:I've said three times that I want  to return a , and yet I can do the following (in 2.10.0-RC3):The same thing happens if I remove the type parameters on either . If I really want to make sure that whoever's calling  can't see that they're getting a , I have to add a type ascription in the tree itself.This is actually pretty great\u2014it means for example that I can point a macro at a schema of some sort and create an anonymous subclass of some  class with member methods representing terms in the vocabulary, and these will be available on the returned object.I'd like to understand exactly what I'm doing, though, so I have a couple of questions. First, what is the return type on the  method actually for? Is it just available for (optional) documentation? It clearly constrains the return type (e.g., I can't change it to  in this case), and if I remove it entirely I get an error like this:But I  change it to  and still get a statically typed  when I call .Second, is this behavior specified somewhere? This seems like a fairly elementary set of issues, but I haven't been able to search up a clear explanation or discussion.This behavior is underspecified but intended, though it might appear confusing. We plan to elaborate on the role of return type in macro signatures, but at the moment I feel like the flexibility is a good thing to have.Also at times the behavior is inconsistent, e.g. when the macro is caught in the middle of type inference, its static signature will be used (i.e.  in your example), not the type of the actual expansion. That's because macro expansion is intentionally delayed until type inference is done (so that macro implementations get to see inferred types, not type vars). This is a trade-off and not necessarily the best one, so we're planning to revisit it soon: .Another problem in this department is with implicit macros. When the return type of an implicit macro is generic and needs to be inferred from the requested type of an implicit value, bad things happen. This makes it currently impossible to use macros to generate type tags: ."},
Scala

I have a  of  and I'd like to be able to convert the tuple to a list so that I can then use . Is there any way to do this? Also, I know it's a , though I'm always a fan of generic solutions.Works with any tuple (scala 2.8):Scala 2.7:Not sure how to maintain type info for a general Product or Tuple, but for Tuple2:You could, of course, define similar type-safe conversions for all the Tuples (up to 22).Using Shapeless -Note that type information is not lost using Shapeless's ."},
Scala

Given this  case class:... and this instanceIs there a reason to prefer this code (with )... over the following?Perhaps I'm missing the meaning/power of ?You only include the  when you want to also deal with the object itself. Hence:Otherwise, there's no real point in including it."},
Scala

I am an experienced C++ programmer with average Python skills. The reasons I studied Python in the first place were:I think that Python is great and I believe that I have achieved the above goals. I will continue to use it for small projects, scripts and web development.I doubt that I can use it for medium to large projects though. While the dynamic typing is convenient, it allows a certain class of bugs that I find disturbing. Unit testing and linting can alleviate this problem, but static typing completely eliminates it.After looking at some programming languages, I think that Scala looks like a good candidate:\nI like the type inference and it runs on the JVM so it should be available wherever the JVM is available. I can also learn more about functional programming when using it.But... I also have some doubts, and this is where I hope that the Stack Overflow community can help:Finally, what do you think that are some of Scalas disadvantages?Yes. There is quite some movement about Scala on Android. As for J2ME, I saw something in that respect, but not much. There is some code pertaining to J2ME on the source code repository. I'm not sure how viable it is, but it looks to me that there isn't much demand for that.I'll also mention that there is/was a pool on Scala-Lang about the desired target platforms, and J2ME was one of them, very low on the totem pole.As well as you can mix C++ with Java, for whatever that is worth. If you haven't any experience with that, you can just read the Java resources, as anything in them will be applicable with Scala with no changes (aside Scala syntax).Definitely, yes. Scala goes out of it's way to make sure you don't need to program in a functional style. This is the main criticism of Scala from functional folks, as a matter of fact: some do not consider a language functional unless it forces the programmer to write in functional style.Anyway, you can go right on doing things your way. My bet, though, is that you'll pick up functional habits without even realizing they are functional.Perhaps you can look at the  series in my own blog about writing a Matrix class. Even though it looks like standard OO code, it is, in fact, very functional.IDEA (IntelliJ), NetBeans and Eclipse all have good support for Scala. It seems IDEA's is the best, and NetBeans/Eclipse keep frog-jumping each other, though NetBeans has certainly been more stable than Eclipse of late. On the other hand, the support on Eclipse is taking a very promising route that should produce results in the next 6 months or so -- it's just that it's a bumping route. :-)Some interesting signs of Scala tooling for these enviroments is the fact that the Eclipse plugin in development uses AOP to merge more seamlessly with the whole IDE, that the NetBeans plugin is being completely rewritten in Scala, and that there's a Scala Power Pack on IDEA that supports, among other things, translating Java code into Scala code.The EMACS folks have extensive tools for Scala as well, and lots of smaller editors have support for it too. I'm very comfortable with jEdit's support for small programs and scripts, for instance.There is also good Maven support -- in fact, the standard way to install  is to install maven, and then build a Lift archetype. That will pull in an appropriate Scala version. There's an  target that will do triggered recompilation as well.Speaking of recompilation, neither Maven, and particularly nor Ant do a good job at identifying what needs to be recompiled. From that problem sprung  (Simple Build Tool), written in Scala, which solves that problem through the use of Scala compiler plugin. SBT uses the same project layout as Maven, as well as Maven/Ivy repositories, but project configurations are done in Scala code instead of XML -- with support for Maven/Ivy configuration files as well.Very fast. As a purely OO language, Scala already introduces some nice features, comparable to some stuff that's present in C++ but not Java, though they work in different fashion. In that respect, once you realize what such features are for and relate them to C++ stuff, you'll be much ahead of Java programmers, as you'll already know what to do with them.The same thing as Java. You can deploy JARs, WARs, or any other of Java targets, because the scala compiler generate class files. In fact, you use Java's jar to generate a Scala's JAR file from the class files, and the Maven targets for Lift support building WAR files.There is an alternative for script files, though. You can call \"scala\" to run Scala source code directly, similar to a Perl of Shell script. It can also be done on Windows. However, even with the use of a compilation daemon to speed up execution, start up times are slow enough that effective use of Scala in a heavy scripting environment needs something like .As for Scala's disadvantages, take a look at my answer (and other's) in  Stack Overflow question.Scala is an evolving language well worth to invest in, especially if you are coming from Java world. Scala is widely covered at . See this  from Bill Venners and also read about a.Regarding your questions:Scala has full support for imperative programming, writing programs with no FP elements in it is a breeze (however, FP is useful and worth learning anyway).Quickly. There is a number of interesting features in Scala that may be not familiar to people coming from a C++, Java environment, like for example some of the features of the typing system. Some argue that the fact that there is a lot to learn in Scala before you know all of it is a  with the language; I disagree. The presence of those feature is  of the language. The more features the merrier. After all, you don't have to use them all at once, just like you don't have to buy everything that is being sold in the store.I also come from a C++ background, one thing I noticed is that since you will write a lot less code as compared to C++ for a comparable task, your learning will be expedited as you will get more done in the same time period.  This was the same phenomenon that I experienced with Ruby. Actually - if I were you - I'd study programming paradigms instead of languages. Of course you have to study an example language to study the paradigm. Knowing the drawbacks & benefits of different paradigms enables you to view your problems from a different side and makes you a better programmer (even in the languages you already know).Picking up a language of a paradigm already known is a relativly easy task if needed. Since Scala is FP (at least you mentioned it) and C++/Python is OOP, it's a good language for you, I'd say.You should register for this course by the Creator of Scala himself.James Strachan (productive Java open source developer, for those not in the loop) has an interesting discussion of Scala , and why he feels it's a progression from Java (the langauge, not the platform).Scala looks like it's gaining a lot of traction. I don't think it's a flash in the pan, and is currently on my list of languages to learn (partly for the functional aspect)Here's an anecdotal evidence regarding learnability of Scala.In our company, we got several interns from U.Waterloo. They were told to write in Scala; never saw it before.They picked up Scala and Lift remarkably fast; now they are producing Scala code; it may be not perfect, but nobody's perfect.So, the fact that a manager does not know Scala may be not the best argument when you decide on adoption."},
Scala

How to reduce the amount of trace info the Spark runtime produces?The default is too verbose,How to turn off it, and turn on it when I need.Thanksquoting from '' book.I think that you could just try:It worked for me (Spark 1.4.1).From comments in source code:We can do this in Log4j way also.Set Logging  for packages  and  "},
Scala

How do I read a large CSV file (> 1 Gb) with a Scala Stream? Do you have a code example? Or would you use a different way to read a large CSV file without loading it into memory first?Just use  as you already stated.That returns an Iterator, which is already lazy (You'd use stream as a lazy collection where you wanted previously retrieved values to be memoized, so you can read them again)If you're getting memory problems, then the problem will lie in what you're doing  getLines.  Any operation like , which forces a strict collection, will cause the problem.I hope you don't mean Scala's  with Stream. This is  what you want. Stream is lazy, but does memoization.I don't know what you plan to do, but just reading the file line-by-line should work very well without using high amounts of memory. should evaluate lazily and should not crash (as long as your file does not have more than 2\u00b3\u00b2 lines, afaik). If it does, ask on #scala or file a bug ticket (or do both).If you are looking to process the large file line-by-line while avoiding requiring the entire file's contents be loaded into memory all at once, then you can use the  returned by .I have a small function, , (containing two sub-functions) which I use for exactly these types of use-cases. The function takes up to four parameters, of which only the first is required. The other parameters have sane default values provided.Here's the function profile (full function implementation is at the bottom):The first parameter, , is required. And it is just any valid instance of  which points to a line-oriented text file, like a CSV.The second parameter, , is optional. And if provided, it must be a function expecting to receive two input parameters; , . And then return an . The function may return a  wrapped  consisting of the valid column values. Or it may return a  which indicates the entire streaming process is aborting early. If this parameter is not provided, a default value of  is provided. This default results in the entire line being returned as a single  value.The third parameter, , is optional. And if provided, it must be a function expecting to receive two input parameters; , . And then return an . The function may return a  wrapped  indicating whether this particular line should be included in the output. Or it may return a  which indicates the entire streaming process is aborting early. If this parameter is not provided, a default value of  is provided. This default results in all lines being included.The fourth and final parameter, , is optional. And if provided, it must be a function expecting to receive two input parameters; , . And then return an . The function may return a  wrapped  consisting of some subset and/or alteration of the existing column values. Or it may return a  which indicates the entire streaming process is aborting early. If this parameter is not provided, a default value of  is provided. This default results in the values parsed by the second parameter, .Consider a file with the following contents (4 lines):The following calling profile......results in this output for  (the unaltered contents of the file):The following calling profile......results in this output for  (each line parsed into the individual column values):The following calling profile......results in this output for  (each line parsed into the individual column values, no header and only the two rows in Irving,Tx):Here's the entire  function implementation:While this solution is relatively succinct, it took me considerable time and many refactoring passes before I was finally able to get to here. Please let me know if you see any ways it might be improved.UPDATE: I have just asked the issue below as . And it now  mentioned below.I had the idea to try and make this even more generic changing the  parameter to  with the new generics-ified function definition below. However, I keep getting the highlight error in IntelliJ \"Expression of type Some[List[String]] doesn't conform to expected type Option[A]\" and wasn't able to figure out how to change the default value so the error goes away.Any assistance on how to make this work would be greatly appreciated."},
Scala

Say, I have a sequence of strings as an input and I want to get a new immutable  which consists of elements of the input and an item . Here are two methods that I've discovered to be working:My questions are:Use the  (append) operator to append an element to a :Note that some implementations of  are more suitable for appending than others.  is optimised for prepending.  has fast append and prepend operations. is a method on  which requires another  as its parameter - what are the advantages that you see in it accepting other types of sequence? It would have to convert other types to a . If you know that  is efficient for your use case then use  (if you must). If you want polymorphic behaviour then use the generic .There's no instantiation overhead to using ; you don't instantiate it because it's a singleton."},
Scala

I am learning Scala and I have a Java project to migrate to Scala. I want to migrate it by rewriting classes one-by-one and checking that new class didn't break the project.This Java project uses lots of  and . In new Scala classes I would like to use Scala\u2019s  and  to have good-looking Scala code.The problem is that new classes (those are wtitten in Scala) do not integrate seamelessly with existing Java code: Java needs , Scala needs its own .Here is a simplified example of the problem. There are classes , , . They call each other in a line: .In my situation, classes  and  are framework classes (I don\u2019t need to migrate them). Class  is business-logic and will benefit a lot from Scala cool features.I need to rewrite class  in Scala while preserving integrity with classes  and . The best rewrite would look like (doesn\u2019t work):Ideal behaviour: Lists inside  are native Scala Lists. All in/out  get boxed/unboxed automagically. But this doesn't work.Instead, this does work (thanks to  ()):But it looks ugly.How do I achieve transparent magic conversion of Lists and Maps between Java <-> Scala (without need to do toScala/toJava)?If it is not possible, what are the best practices for migrating Java -> Scala code that uses  and friends?Trust me; you don't  transparent conversion back and forth.  This is precisely what the  functions attempted to do.  In practice, it causes a lot of headaches.The root of the problem with this approach is Scala will automatically inject implicit conversions as necessary to make a method call work.  This can have some really unfortunate consequences.  For example:This code wouldn't be entirely out of character for someone who is new to the Scala collections framework or even just the concept of immutable collections.  Unfortunately, it is completely wrong.  The result of this function is the  map.  The call to  triggers an implicit conversion to , which happily accepts the new values and is promptly discarded.  The original  is unmodified (as it is, indeed, immutable).Jorge Ortiz puts it best when he says that you should only define implicit conversions for one of two purposes:Since  is obviously not a new type unrelated to anything in our hierarchy, we can't fall under the first proviso.  Thus, our only hope is for our conversion  to qualify for the second one.  However, it makes absolutely no sense for Scala's  to inherit from .  They are really completely orthogonal interfaces/traits.  As demonstrated above, attempting to ignore these guidelines will almost always result in weird and unexpected behavior.The truth is that the javautils  and  methods were designed to solve this exact problem.  There is an implicit conversion (a number of them actually) in javautils from .   is a brand new type defined by javautils, so its only purpose is to add members to .  In particular, it adds the  method, which returns a wrapper map which implements  and delegates to your original  instance.  This makes the process much more explicit and far less error prone.In other words, using  and   the best practice.  Having gone down both of these roads independently in a production application, I can tell you first-hand that the javautils approach is much safer and easier to work with.  Don't try to circumvent its protections merely for the sake of saving yourself 8 characters! Here are some quick examples using Jorge Ortiz's :the javautils project is available from the With Scala 2.8, it could be done like this:"},
Scala

I know what the monads are and how to use them. What I don't understand is  makes, let's say,  a monad? In Haskell a monad  is a monad because it's instantiated from  class (which has at least 2 necessary functions  and  that makes class , indeed, a monad). But in Scala we've got this:Nothing related to a monad.If I create my own class in Scala, will it be a monad by default? Why not? is a concept, an abstract interface if you will, that simply defines a way of composing data. supports composition via , and that's pretty much everything that is needed to wear the \"monad badge\".From a theoretical point of view, it should also:but this is not strictly enforced by Scala.Monads in scala are a much looser concept that in Haskell, and the approach is more practical.\nThe only thing monads are relevant for, from a language perspective, is the ability of being used in a for-comprehension. is a basic requirement, and you can  provide ,  and .However, there's no such thing as strict conformance to a  typeclass, like in Haskell.Here's an example: let's define our own monad.As you see, we're only implementing  and  (well, and  as a commodity).\nCongratulations, we have a monad! Let's try it out:Nice! We are not doing any filtering, so we don't need to implement . Also since we're yielding a value, we don't need  either. Basically you implement whatever you wish to support, without strict requirements. If you try to filter in a for-comprehension and you haven't implemented , you'll simply get a compile-time error.Anything that (partially) implements, through duck-typing, the  trait is considered to be a monad in Scala. This is different than how monads are represented in Haskell, or the . However, in order to benefit of the  comprehension syntactic sugar in Scala, an object has to expose some of the methods defined in the  trait.Also, in Scala, the equivalent of the Haskell  function is the  keyword used for producing values out of a  comprehension. The desugaring of  is a call to the  method of the \"monad\".The way I'd put it is that there's an emerging distinction between monads as a  vs. a .  Haskell has the latter, in the form of the  type class.  But if you have a type that has (or can implement) the monadic operations and obeys the laws, that's a monad as well.These days you can see monads as a design pattern in Java 8's libraries.  The  and  types in Java 8 come with a static  method that corresponds to Haskell , and a  method.  There is however no  type.Somewhere in between you also have the \"duck-typed\" approach, as Ionu\u021b G. Stan's answer calls out.  C# has this as well\u2014LINQ syntax isn't tied to a specific type, but rather it can be used with any class that implements certain methods."},
Scala

Are there any special concurrency operators, or is functional style programming good for concurrency? And why?At the moment, Scala already supports two major strategies for concurrency -  concurrency (derived from Java) and  concurrency (inspired by Erlang). In the nearest future (Scala 2.9), there will be two big additions to that: Actors syntax (concurrency operators) is heavily influenced with Erlang (with some important additions) - with regards to the library you use (standard actors, Akka, Lift, scalaz), there will be different combinations of question and exclamation marks:  (in the most cases for sending a message one-way), , , etc. Besides that, first-class functions make your life way easier even when you work with old Java concurrency frameworks: ExecutorService, Fork-Join Framework, etc. Above all of that stands immutability that simplifies concurrency a lot, making code more predictable and reliable.There are a number of language features that make Scala good for concurrency.  For example:Further reading:Well, there is the hype and there is the reality. Scala got a fame for being good for concurrency because it is a functional language and because of its actors library. Functional languages are good for concurrency because they focus on immutability, which helps concurrent algorithms. Actors got their reputation because they are the base to Erlang's track record of massively concurrent systems.So, in a sense, Scala's reputation is due to being a \"me too\" of successful techniques. Yet, there is something that Scala does bring to the table, which is its ability to support such additions to the language through libraries, which makes it able to adapt and adopt new techniques as they are devised.Actors are not native to Scala, and yet there are already there different libraries in wide use that all seem to be. Neither is transactional memory, but, again, there are already libraries that look like they are.They, these libraries, are even available for java, but there they are clunky to use. So the secret is not so much what it can do, but that it makes it look easy.The big keyword here is immutability. See . Since any variable can be defined as mutable or immutable, this is a big win for concurrency, since if an object cannot be changed, it is thread safe and therefore writing concurrent programs is easier.Just to rain on everyone's parade a bit, .I've dual-coded a fair few multithreaded things in Scala (mainly using Futures, a bit with Actors too) and C++ (using TBB) since then (mostly Project Euler problems).  General picture seems to be that Scala needs ~1/3 the number of lines of code of the C++ solution (and is quicker to write), but the C++ solution will be ~x10 faster runtime (unless you go to some efforts to avoid any \"object churn\", as shown in the fast version in the answer referenced above, but at that point you're losing much of the elegance of Scala).  I'm still on 2.7.7 mind you; haven't tried Scala 2.8 yet.Using Scala was my first real encounter with a language which strongly emphasised immutability and I'm impressed by its power to hugely simplify the mental model you have to maintain of object \"state machines\" while programming (and this in turn makes coding  for concurrency easier).  It's certainly influenced how I approach C++ coding."},
Scala

Does Scala have a native way to count all occurrences of a character in a string? If so, how do I do it? If not, do I need to use Java? If so, how do I do that? Thanks!i don't use Scala or even java but google search for \"Scala string\" brought me to which contains :Seems pretty straight forward but i dont use Scala so don't know the syntax of calling a member function.  May be more overhead than needed this way because it looks like it can search for a sequence of characters. read on a different result page a string can be changed into a sequence of characters and you can probably easily loop through them and increase a counter. "},
Scala

I have 50,000 tasks and want to execute them with 10 threads.\nIn Java I should create Executers.threadPool(10) and pass runnable to is then wait to process all. Scala as I understand especially useful for that task, but I can't find solution in docs. THe simplest approach is to use the  class and associated infrastructure. The  method asynchronously evaluates the block passed to it and immediately returns a  representing the asynchronous computation. Futures can be manipulated in a number of non-blocking ways, including mapping, flatMapping, filtering, recovering errors, etc.For example, here's a sample that creates 10 tasks, where each tasks sleeps an arbitrary amount of time and then returns the square of the value passed to it.In this example, we first create a sequence of individual asynchronous tasks that, when complete, provide an int. We then use  to combine those async tasks in to a single async task -- swapping the position of the  and the  in the type. Finally, we block the current thread for up to 15 seconds while waiting for the result. In the example, we use the global execution context, which is backed by a fork/join thread pool. For non-trivial examples, you probably would want to use an application specific .Generally, blocking should be avoided when at all possible. There are other combinators available on the  class that can help program in an asynchronous style, including , , and .Also, consider investigating the  library, which provides actor-based concurrency for Scala and Java, and interoperates with .This simplest approach is to use Scala's Future class, which is a sub-component of the Actors framework.  The scala.actors.Futures.future method creates a Future for the block passed to it.  You can then use scala.actors.Futures.awaitAll to wait for all tasks to complete.For example, here's a sample that creates 10 tasks, where each tasks sleeps an arbitrary amount of time and then returns the square of the value passed to it.You want to look at either the Scala actors library or Akka. Akka has cleaner syntax, but either will do the trick.So it sounds like you need to create a pool of actors that know how to process your tasks. An Actor can basically be any class with a receive method - from the Akka tutorial ():You'll want to create a pool of actor instances and fire your tasks to them as messages. Here's a post on Akka actor pooling that may be helpful: In your case, one actor per task may be appropriate (actors are extremely lightweight compared to threads so you can have a LOT of them in a single VM), or you might need some more sophisticated load balancing between them.EDIT:\nUsing the example actor above, sending it a message is as easy as this:The actor will then output \"received test\" to standard output.Messages can be of any type, and when combined with Scala's pattern matching, you have a powerful pattern for building flexible concurrent applications.In general Akka actors will \"do the right thing\" in terms of thread sharing, and for the OP's needs, I imagine the defaults are fine. But if you need to, you can set the dispatcher the actor should use to one of several types:It's trivial to set a dispatcher for an actor:See In this way, you could limit the thread pool size, but again, the original use case could probably be satisfied with 50K Akka actor instances using default dispatchers and it would parallelize nicely.This really only scratches the surface of what Akka can do. It brings a lot of what Erlang offers to the Scala language. Actors can monitor other actors and restart them, creating self-healing applications. Akka also provides Software Transactional Memory and many other features. It's arguably the \"killer app\" or \"killer framework\" for Scala.If you want to \"execute them with 10 threads\", then use threads. Scala's actor model, which is usually what people is speaking of when they say Scala is good for concurrency,  such details so you won't see them.Using actors, or futures with all you have are simple computations, you'd just create 50000 of them and let them run. You might be faced with issues, but they are of a different nature.Here's another answer similar to mpilquist's response but without deprecated API and including the thread settings via a custom ExecutionContext:"},
Scala

I'm trying to search a scala collection for an item in a list that matches some predicate. I don't necessarily need the return value, just testing if the list contains it.In Java, I might do something like:In Groovy, I can do something like:What's the idiomatic way to do this in Scala? I could of course convert the Java loop style to Scala, but I feel like there's a more functional way to do this.Use filter: But if all you need is to check use :If you're just interested in testing if a value exists, you can do it with.... Other methods (some based on comments):Count elements that satisfy predicate (and check if count  > 0)Find the first element that satisfies predicate (as suggested by Tomer Gabel and Luigi Plinge this should be more efficient because it returns as soon as it finds one element that satisfies the predicate, rather than traversing the whole List anyway)For the simple case where we're actually only checking if one specific element is in the list"},
Scala

While learning functional programming, I keep coming across the term \"reason about\" especially in the context of pure functions and/or referential transparency. Can somebody explain what exactly does this mean?Typically when writing a program, your job doesn't end with merely writing the code, but you would also want to know some properties your code exhibits. You can arrive at these properties by two means: either by logical analysis or by empirical observation.Examples of such properties include:When you measure these properties empirically, you get results with limited precision. Therefore mathematically proving these properties is far superior, however it is not always easy to do. Functional languages typically have as one of their design goals making mathematical proofs of their properties more tractable. This is what is typically meant by reasoning about programs.In terms of functions or lesser units, the above applies, but also sometimes the author simply means thinking about the algorithm or designing the algorithm. It depends on the particular usage.As an aside, some examples of how one might reason about some of these things and how empirical observation can be made: We can prove that code is correct, if we can show equationally that it does what it is supposed to do. So for a sort function if we can show that any list we give it will have the property of being sorted, we know our code is correct. Empirically we can create a unit test suite where we give our code examples of input and check that the code has the desired output. We can analyze our code and prove performance bounds of the algorithm so that we know how does the time it takes depend on the size of the input. Empirically we can benchmark our code and see how quickly it actually runs on a particular machine. We can perform load testing and seeing how much actual input can our machine/algorithm take before it folds/becomes impractical.Reasoning about code, in , means thinking about your code and what it  does (not what you think it should do.) It meansamong other things. For me, the reasoning part plays the biggest role when I'm debugging or refactoring.To use an example you mentioned: Referential transparency helps me a lot when I'm trying to figure out what's wrong with a function. The referential transparency guarantees that as I'm poking around with the function, giving it different arguments, I know that the function will react the same way inside my program. It doesn't depend on anything other than its arguments. That makes the function easier to reason about \u2013 as opposed to an imperative language where the function may depend on some external variable that can change under my nose.Another way of looking at it (and this is more helpful when refactoring) is that the more you know your code satisfies certain properties, the easier it becomes to reason about. I know, for example, thatThis is a useful property I can just apply directly when I'm refactoring. The fact that I can state such properties of Haskell code makes it easier to reason about. I could try to state this property in a Python program, but I would be much, much less confident of it, because if I'm unlucky in my choices of  and  the results may vary wildly.Usually when people say \"reasoning\" they mean \"equational reasoning\", which means proving properties about your code without ever running it.These properties can be very simple.  For example, given the following definition of  and :... we might then want to prove that:This is easy to prove because:Notice how I've proven this for  .  This means that I know that this property is always true no matter what, therefore I no longer need to test this property in some sort of unit test suite because I know that it can never fail.Informally it means, \"Being able to tell what a program will do just by looking at the code.\"  This can be surprisingly difficult in most languages, due to side-effects, casting, implicit conversions, overloaded functions and operators, etc.  I.e., what you can't reason about code using just your brain, you have to run it to see what it will do for a given input.\"Reasoning about a program\" is just \"analyzing a program to see what it does\".The idea is that purity simplifies understanding, both by a human changing a program and by a machine compiling a program or analyzing it for broken corner cases."},
Scala

I'm learning scala, and I'm looking to update a nested node in some xml. I've got something working but i'm wondering if its the most elegant way.I have some xml: And i want to update the  node in , but not the one in .Here is my function: Is there a more succint way of writing this function?I think the original logic is good. \nThis is the same code with (shall I dare to say?) a more Scala-ish flavor:It looks more compact (but is actually the same :) )if you want, you can get rid of the updateElements too. You want to apply the updateVersion to all the elements of the sequence. That's the . With that, you can rewrite the linewithAs update version takes only 1 parameter I'm 99% sure you can omit it and write:And end with:What do you think?All this time, and no one actually gave the most appropriate answer! Now that I have learned of it, though, here's my new take on it:Now, for a few explanations. The class  is abstract. It defines two methods, both called . One of them takes a single , the other a  of . It's an abstract class, so we can't instantiate it directly. By adding a definition, in this case override one of the methods, we are creating an anonymous subclass of it. Each RewriteRule needs concern itself with a single task, though it can do many.Next, class  takes as parameters a variable number of . It's transform method takes a  and return a  of , by applying each and every  used to instantiate it.Both classes derive from , which defines a few methods with which one need not concern oneself at a higher level. It's  method calls , though, so both  and  can use the syntactic sugar associated with it. In the example, the former does and the later does not.Here we use two levels of , as the first applies a filter to higher level nodes, and the second apply the change to whatever passes the filter.The extractor  is also used, so that there is no need to concern oneself with details such as namespace or whether there are attributes or not. Not that the content of the element  is completely discarded and replaced with . It can be matched against too, if needed.Note also that the last parameter of the extractor is , and not . That means these elements can have multiple children. If you forget the , the match may fail. In the example, the match would not fail if there were no whitespaces. Because whitespaces are translated into  elements, a single whitespace under  would case the match to fail.This code is bigger than the other suggestions presented, but it has the advantage of having much less knowledge of the structure of the XML than the others. It changes any element called  that is below -- no matter how many levels -- an element called , no matter namespaces, attributes, etc.Furthermore... well, if you have many transformations to do, recursive pattern matching becomes quickly unyielding. Using  and , you can effectively replace  files with Scala code.You can use Lift's CSS Selector Transforms and write:See I have since learned more and presented what I deem to be a superior solution in another answer. I have also fixed this one, as I noticed I was failing to account for the  restriction.Thanks for the question! I just learned some cool stuff when dealing with XML. Here is what you want:Now, explanation. First and last case statements should be obvious. The last one exists to catch those parts of an XML which are not elements. Or, in other words, text. Note in the first statement, though, the test against the flag to indicate whether  may be changed or not.The second and third case statements will use a pattern matcher against the object Elem. This will break an element into  its component parts. The last parameter, \"children @ _*\", will match children to a list of anything. Or, more specifically, a Seq[Node]. Then we reconstruct the element, with the parts we extracted, but pass the Seq[Node] to updateNodes, doing the recursion step. If we are matching against the element , then we change the flag mayChange to , enabling the change of the version.In the last line, we use node.theSeq to generate a Seq[Node] from Node, and (0) to get the first element of the Seq[Node] returned as result. Since updateNodes is essentially a map function (for ... yield is translated into map), we know the result will only have one element. We pass a  flag to ensure that no  will be changed unless a  element is an ancestor.There is a slightly different way of doing it, that's more powerful but a bit more verbose and obscure:This version allows you to change any \"version\" tag, whatever it's prefix, attribs and scope. provides tools for \"in place\" edits.  Of course its all immutable but here's the solution in Scales:The XPath like syntax is a Scales signature feature, the  after the string specifies it should have no namespace (local name only). iterates over the resulting elements and transforms them, joining the results back together.One approach would be lenses (e.g. scalaz's). See  for a very clear presentation.I really don't know how this could be done elegantly. FWIW, I would go for a different approach: use a custom model class for the info you're handling, and have conversion to and from Xml for it. You're probably going to find it's a better way to handle the data, and it's even more succint.However there is a nice way to do it with Xml directly, I'd like to see it."},
Scala

I would like to check constructor arguments and refuse to construct throwing  in case the arguments set is not valid (the values don't fit in expected constraints). How to code this in Scala?In Scala, the whole body of the class is your primary constructor, so you can add your validation logic there.Scala provides a utility method  that lets you write the same thing more concisely as follows:A better approach might be to provide a factory method that gives a  instead of throwing an exception. (Note: requires Scalaz)"},
Scala

In the file Parsers.scala (Scala 2.9.1) from the parser combinators library I seem to have come across a lesser known Scala feature called \"lazy arguments\". Here's an example:Apparently, there's something going on here with the assignment of the call-by-name argument  to the lazy val .So far I have not been able to work out what this does and why it's useful. Can anyone help?Call-by-name arguments are called .  Lazy vals are called  and then the value is stored.  If you ask for it again, you'll get the stored value.Thus, a pattern likeis the ultimate put-off-work-as-long-as-possible-and-only-do-it-once pattern.  If your code path never takes you to need  at all, then it will never get evaluated.  If you need it multiple times, it'll only be evaluated once and stored for future use.  So you do the expensive call either zero (if possible) or one (if not) times, guaranteed.The wikipedia article for  even answers what the  keyword does:Additionally, what you have in this code sample with  is a call-by-name parameter. A parameter declared this way remains unevaluated, until you explicitly evaluate it somewhere in your method.Here is an example from the scala REPL on how the call-by-name parameters work:As you can see, the  does not get evaluated at all in the second call. Combining the lazy value with a call-by-name parameter like above results in the following meaning: the parameter  is not evaluated immediately when calling the method. Instead it is assigned to the lazy value , which is also not evaluated immediately. Only lateron, when  is used this leads to the evaluation of . But, as  is a  the parameter  will only be evaluated  and the result is stored in  for later reuse in the loop.You can easily see in the repl, that the multiple evaluation can happen otherwise:"},
Scala

I did all the preference work, installed scala, everything works except this, i just can not test a scala class in the console window. In tutorials I see they just type in something behind the scala> but it just won't work, i can type some random stuff there below which doesn't do anything when I press enter.Can you guys help me out? I would be very thankful.\nCheers Once you type on the Scala console in IntelliJ Community Edition. Hit + instead of enter to execute.took me a while to get around it :)If you want the console to execute when you hit enter, go to , and right-click . Select  and hit enter in the first box. Then click  and then .\nYou have to press \u2318-Enter on Mac OS X when you're done typing.I guess it's better to change the message from \n\"Type in expressions to have them evaluated.\"\nto \n\"Type in expressions and press Ctrl + Enter to have them evaluated.\""},
Scala

Still the newbie in Scala and I'm now looking for a way to implement the following code on it:What would be the best way to implement the same funcionality that RetryableService implements but in Scala?It basically calls the  method N times, if all of them fail the exception is then raised, if they succeed it moves on. This one does not return anything but then I have another version that allows for returning a value (so, i have two classes in Java) and I believe I could do with a single class/function in Scala.Any ideas?Current implementation in java is as follows:Recursion +  by-name parameters == awesome.Usage is like this:: slight variation inspired by 's answer.  One fewer line of code :-): The recursion bothered me in that it added several calls to the stack trace.  For some reason, the compiler couldn't optimize tail recursion in the catch handler.  Tail recursion not in the catch handler, though, optimizes just fine :-): Apparently I'm going to make it a hobby to keep coming back and adding alternatives to this answer. Here's a tail-recursive version that's a bit more straightforward than using , but using  to short-circuit a function isn't idiomatic Scala.. As is my hobby, I revisit this answer occasionally. Scala 2.10 as introduced , which provides a clean way of implementing retry in a tail-recursive way.Here is one possible implementation:You can use it like this: also returns  if body was processed successfully and  if body was only  throwing exceptions.If you want to bobble up last exception, then you can take very similar approach but use  instead of :Also, as you can see, at the end, instead of having only last exception, I have them all. So you can also wrap them in some  if you want and then throw it. (for simplicity, I just throw last exception)There is a method in : Given a , you can create a new  which will retry a certain number of times, where the delay between retries is defined by the  parameter. e.g.:I'd suggest this - It does: It can probably be improved to be more idiomatic Scala, but I am not a big fan of one-liners that require the reader to know the entire standard library by heart anyways.You can express the idea in functional style using :As we can see, tail recursion can be used here.This approach gives you the additional benefit that you can parametrize the catch container, so you can only retry a certain subset of exceptions, add finalizers etc. So the final version of  might look like:With this, you can do complex stuff like:I like the accepted solution, but suggest checking the exception is NonFatal:You don't want to retry a control flow exception, and usually not for thread interrupts...There is an existing library that can help with that, called , and there is a Java library too, called .Here are some examples of using :If you want control of which exceptions you retry, you can use methods in :(As written, it will also retry on null; that's the  part.  If you want nulls to be returned, use  inside the iterator fill instead.)Let's try this out withDoes it work?Looks good!I ended up adapting a previous answer to allow filtering on which exceptions to retry on:You can call in two ways:or with partial functions (also showing version where don't care about return value)This project seems to provide some nice implementations for different retry mechanisms\nThis solution is not optimized by compiler to tail recursion for some reason (who knows why?), but in case of rare retries would be an option:Usage:Usage:Usage:A reusable object/method with a pause between attempts:Code:"},
Scala

What makes Scala such a wonderful language,  than the type system?  Almost everything I read about the language brings out 'strong typing' as a big reason to use Scala, but there has to be more than that.  What are some of the other compelling and/or cool language features that make Scala a really useful tool?Here are some of the things that made me favour Scala (over, say, usual Java):a) Type inference. The Java way of doing it:.. is rather verbose compared to Scala. The compiler should be able to figure it out if you give one of these lists.b) First-order functions. Again, this functionality can be emulated with classes, but it's ugly.c) Collections that have  and . These two tie in with (b), and also these two are something I wish for every time I have to write Java.d) Pattern matching and case classes.e) Variances, which mean that if ,  then  as well.Throw in some static types goodness as well, and I was sold on the language quite fast.It's a mash up of the best bits from a bunch of languages, what's not to love:Scala is often paraded for having closures and implicits.  Not surprising really, as lack of closures and explicit typing are perhaps the two biggest sources of Java boilerplate!But once you examine it a little deeper, it goes far beyond Java-without-the-annoying bits,  Perhaps the greatest strength of Scala is not one specific named feature, but how successful it is in unifying all of the features mentioned in other answers.The union of object orientation and functional programming for example:  Because functions are objects, Scala was able to make Maps implement the Function interface, so when you use a map to look up a value, it's no different syntactically from using a function to calculate a value.  In unifying these paradigms so well, Scala truly is a post-functional language.Or operator overloading, which is achieved by not actually having operators, they're just methods used in infix notation.  So  is just calling the  method on an integer.  If the method was named  instead then you'd use it as  which is no different from .  This is made possible because of another combination of features; everything in Scala is an object, there are no primitives, so integers can have methods.Type classes were also mentioned, achieved by a combination of higher-kinded types, singleton objects, and implicits.Other features that work well together are case classes and pattern matching, allowing you to easily build and deconstruct algebraic data types, without having to manually write all the tedious equality, hashcode, constructor and getter/setter logic that Java demands.Specifying immutability by default, offering lazy values, and providing first class functions all combine to give you a language that's very suited to building efficient functional data structures.The list goes on, but I've been using Scala for over 3 years now, and I'm still amazed almost daily at how well everything just works together.Scala is also a small language, with a spec that (surprisingly!) only needs to be around 1/3 the size of Java's.  This is partly because Java has a lot of special cases in the spec that Scala simplifies away, partly because of removing features such as primitives and operators, and partly because a lot of functionality has been moved from the language and into the libraries.As a benefit of this, all the techniques available to the Scala library authors are also available to any Scala user, which makes it a great language for defining your own control-flow constructs and for building DSLs.  This has been used to great effect in projects like Akka - a 3rd-party Actor framework.Finally, it scales the full range of programming styles.The runtime interpreter (known as the REPL) allows you to very quickly explore ideas in an interactive session, and Scala files can also be run as scripts without needing explicit compilation.  When coupled with type inference, this gives Scala the feel of a dynamic language such as Ruby, Perl, or a bash script.At the other end of the spectrum, traits, classes, objects and self-types allow you to build a full-scale enterprise system based on distinct components and using dependency injection without the need of 3rd-party tools.  Scala also integrates with Java libraries at a level almost on-par with native Java, and by running on the JVM can take advantage of all the speed benefits offered on that platform, as well as being perfectly usable in containers such as tomcat, or with OSGi.I'm new to Scala, but my impression is:Really good JVM integration will be the driving factor. JRuby can call java and java can call JRuby code, but it's explicitly calling into another language, not the clean integration of Scala-Java. So you can use Java libraries, and even mix and match in the same project.I started looking at scala when I had a realization that the thing which will drive the next great language is easy concurrency. The JVM has good concurrency from a performance standpoint. I'm sure someone will say that Erlang is better, but Scala is actually usable by normal programmers.Where Java falls down is that it's just so painfully verbose. It takes way too many characters to create and pass a Functor. Scala allows passing functions as arguments.It isn't possible in Java to create a union type, or to apply an interface to an existing class. These are both easy in Scala.Static typing usually has a big penalty of verboseness. Scala eliminates this downside while still giving the upside of static typing, which is compile time type checking, and it makes code assist in editors easier.The ability to extend the language. This has been the thing that has kept Lisp going for decades, and that allowed Ruby on Rails.The type system really is Scala's most distinguishing feature. It also has a lot of syntactic conveniences over, say, Java.But for me, the most compelling features of Scala are:In effect, these features let you approximate (and in some ways surpass) Haskell's . Combined, they let you write exceptionally modular code.Just shortly:What I find especially attractive in all of its magnificient features, among others:Supposedly it's very easy to make Scala code run  on multiple processors.Expressiveness of control flow. For example, it's very common to have a collection of data which you need to process in some way. This might be a list of trades in which the processing involves grouping by some properties (the currencies of the investment instruments) and then doing a summation (to get totals-per-currency perhaps).In Java this involves separating out a piece of code to do the grouping (a few lines of for-loop) and then another piece of code to do the summation (another for loop). In Scala, this type of thing is typically achievable in one line of code using functional programming and then folding, which reads very expressively l-to-r.Of course, this is just an argument for a functional language over Java.The great features of Scala has already been mentioned. One thing that shines through past all features though, is how tastefully everything is integrated.Scala manages to be one of the most powerful language around without having a feeling of having bolted on features in haste. Neither are the language an academic exercise in proving a point. Innovation and really advanced concepts are brought in to the language with uncanny practicality and elegance.In short: Martin Odersky is a pure design genius. That is what's so great about Scala!I want to add the multi-paradigm (OO and FP) nature gives Scala an edge over other languagesEvery day you code Java you will become more and more miserable, every day you code Scala you will become happier.Here's a few fairly in depth explanations for the appeal of functional languages.If we abandon feature discussion and will talk about style, i would say it's pipe-line style of coding. You start from some object or collection, types dot and property or dot and transformation and do it until you form desired result. This way it's easy to write a chain of transoformations that will be easy to read them also. Traits to some extend will also allow you to apply the same approach to constructing types."},
Scala

Just wondering if anyone knows of a web-scraping library that takes advantage of Scala's succinct syntax. So far, I've found , but this seems poorly-documented and maintained. I'm wondering if anyone out there has done scraping with Scala and has advice. (I'm trying to integrate into an existing Scala framework rather than use a scraper written in, say, Python.)First there is a plethora of HTML scraping libs in JVM all you need to do is .The four I have used are:I have used Selenium but never for scraping. .I would recommend pimping an existing Java library over some half baked Scala lib.I don't have a Scala-specific recommendation, but for the JVM in general I've had good success with:The Tagsoup route actually works quite well with Scala since Scala's built-in XML \"dsl\" is pretty concise (if you can forgive its perf issues and occasional API weirdness).  Also, Tagsoup will handle nearly any garbage document you give it.  It also has niceties like built-in understanding of many HTML entities that other SAXParsers will choke on as being undeclared. - JSoup + CSS selectors if possible, otherwise Tagsoup + scala XML. If slow is ok, tagsoup first, then jsoup the result.I'd recommend Goose: It's not as general-use as you might need but if you are scraping article content from popular sites, it may work out of the box. It also provides a framework for you to work from if you want to extend their code to cover other sites."},
Scala

I would like to be able to encrypt files on disk and/or data in memory using GnuPG from a Java application.  If possible I'd like to avoid having to make system calls out to the GPG command line tools.Is there a recommended library, or can you recommend the best approach to GPG encrypting from Java (or Scala)?I'm developing and intend to run the application in a Linux environment, although a cross-platform solution would be preferred.You can try to call the JAVA API of .Its  mentions:You have here .There might be some  though, since BouncyCastle does not use GnuPG, but rather implements OpenPGP (RFC2440) in Java.I recently had to work on GPG encryption-decryption and did find BountyCastle's PGP library does the trick. The steps were1) Add the version in pom.xml properties2) Add the following dependencies3) In the implementation class added the provider with Java Security4) The rest of the code was just simple Java implementationI hope this helps.There is  which is based on gpgme, and works on top of GnuPG 1.4.  We're updating it for GnuPG 2.x and are using it in our Android app.  You can get the code to those here:"},
Scala

When do you choose to type a given function's return type as  vs  vs  (or alternatively even deeper within 's hierarchy)?How do you make that decision? We have a lot of code that returns s by default (usually starting from results of a DB query and successive transformations). I tend to want to make the return types  by default and  when specifically expecting a given order. But I don't have a strong justification for doing so.I am perfectly familiar with the definition of each trait, so please don't answer with defining the terms.This is a good question. You have to balance two concerns:Where (1) asks you to be as little specific about the type (e.g.  over ), and (2) asks you the opposite.Even if the return type is just , you can still return let's say a , so if the caller wishes to gain extra power, it can just call  or  on it, and that operation is cheap for a .As a measure of the balance, I would add a third point:Here are my rules of thumb:Of course, this is my personal choice, but I hope it sounds sane.Make your method's return type as specific as possible. Then if the caller wants to keep it as a  or type it as a , they can. This is why the compiler infers the most specific type by default.These are the \"common-sense\" guidelines.  They are simple, practical, and work well in practice while balancing principles and performance.  The principles are: satisfies both principles.  As described in :90% of the time, your data is a Seq.Other notes:Drawbacks:There are some slight downsides to these \"common-sense\" conventions.Footnotes:A rule of thumb I follow is, depending on implementation, to make the return types as specific as possible and the types of arguments as general as possible. It's an easy to follow rule and it provides you with consistent guarantees on the type properties with maximum freedom.Say, if you have a function implementation which just traverses a data structure with methods like ,  or  - those that are implemented in the trait , you can expect it to perform equally on any type of input collection - be it a , ,  or even a , so your input argument should be specified as . The choice of output type of the function should only depend on its implementation: in this case it should be  too. If however in your function you force this data structure to some more specific type with methods like ,  or , you should specify the appropriate type. Notice the consistency between the implementation and the return type?If your function accesses the elements of input by index, the input should be specified as , as it is the most general type that provides you with guarantees on effective implementation of method . In case of abstract members the same rule applies with the only difference that you should specify the return types based on how you plan to use them instead of implementation, thus most often they will be more general than in implementation. The categorical choices ,  or  are the most expected.Following this rule you protect yourself from very common cases of bottleneck when, for instance, items get appended to  or  gets called on a  instead of a , yet your program remains a nice degree of freedom and is consistent in sense of choice of types."},
Scala

I have seen many people in the Scala community advise on avoiding subtyping \"like a plague\". What are the various reasons against the use of subtyping? What are the alternatives?Types determine the granularity of composition, i.e. of extensibility.For example, an interface, e.g. Comparable, that combines (thus conflates) equality and relational operators. Thus it is impossible to compose on just one of the equality or relational interface.In general, the  of inheritance is undecidable. Russell's paradox implies that any set that is extensible (i.e. does not enumerate the type of every possible member or subtype), can include itself, i.e. is a subtype of itself. But in order to identify (decide) what is a subtype and not itself, the invariants of itself must be completely enumerated, thus it is no longer extensible. This is the paradox that subtyped extensibility makes inheritance undecidable. This paradox must exist, else knowledge would be static and thus .Function composition is the surjective substitution of subtyping, because the input of a function can be substituted for its output, i.e. any where the output type is expected, the input type can be substituted, by wrapping it in the function call. But composition does not make the bijective contract of subtyping-- accessing the interface of the output of a function, does not access the input instance of the function.Thus composition does not have to maintain the  (i.e. unbounded) invariants and thus can be both extensible and decidable. Subtyping can be  more powerful where it is provably decidable, because it maintains this bijective contract, e.g. a function that sorts a immutable list of the supertype, can operate on the immutable list of the subtype.So the conclusion is to enumerate all the invariants of each type (i.e. of its interfaces), make these types orthogonal (maximize granularity of composition), and then use function composition to accomplish extension where those invariants would not be orthogonal. Thus a subtype is appropriate only where it provably models the invariants of the supertype interface, and the additional interface(s) of the subtype are provably orthogonal to the invariants of the supertype interface. Thus the invariants of interfaces should be orthogonal.Category theory  of the invariants of each subtype, i.e. of Functor, Applicative, and Monad, which , i.e. see the aforementioned example of the power of subtyping for lists.One reason is that equals() is very hard to get right when sub-typing is involved. See . Specifically \"Pitfall #4: Failing to define equals as an equivalence relation\". In essence: to get equality right under sub-typing, you need a double dispatch. I think the general context is for the lanaguage to be as \"pure\" as possible (ie using as much as possible ), and comes from the comparison with Haskell.\nFrom \"\"As mentioned in this :But the actual recommendation would be to use the best solution adapted to the program you are currently developing.Focusing on subtyping, ignoring the issues related to classes, inheritance, OOP, etc.. We have the idea subtyping represents a isa relation between types. For example, types A and B have different operations but if A isa B we then can use any of B's operations on an A.OTOH, using another traditional relation, if C hasa B then we can reuse any of B's operations on a C. Usually languages let you write one with a nicer syntax, a.opOnB instead of a.super.opOnB as it would be in the case of composition, c.b.opOnBThe problem is that in many cases there's more than one way to relate two types. For example Real can be embedded in Complex assuming 0 on the imaginary part, but Complex can be embedded in Real by ignoring the imaginary part, so both can be seen as subtypes of the other and subtyping forces one relation to be viewed as preferred. Also, there are more possible relations (e.g. view Complex as a Real using theta component of polar representation).In formal terminology we usually say morphism to such relations between types and there are special kinds of morphisms for relations with different properties (e.g. isomorphism, homomorphism).In a language with subtyping usually there's much more sugar on isa relations and given many possible embeddings we tend to see unnecessary friction whenever we're using the unpreferred relation. If we bring inheritance, classes and OOP to the mix the problem becomes much more visible and messy.My answer does not answer why it is avoided but tries to give another hint at why it  be avoided. Using \"type classes\" you can add an abstraction over existing types/classes without modifying them. Inheritance is used to express that some classes are specializations of a more abstract class. But with type classes you can take any existing classes and express that they all share a common property, for example they are . And as long as you are not concerned with them being  you don't even notice it. The classes don't inherit any methods from some abstract  type as long as you don't use them. It's a bit like programming in dynamic languages.Further reads:I don't know Scala, but I think the mantra 'prefer composition over inheritance' applies for Scala exactly the way it does for every other OO programming language (and subtyping is often used with the same meaning as 'inheritance'). Here you will find some more information.I think lots of Scala programmers are former Java programmers. They are used to think in term of Object Oriented subtyping and they should be able to easily find OO-like solution for most problems. But Functional Programing is a new paradigm to discover, so people ask for a different kind of solutions. is the best paper I have found on the subject. A motivating quote from the paper \u2013"},
Scala

The path from SBT to Scala-IDE is well described in many places:What is the reverse for this? If I start a new project in Scala-IDE, can I just add a build.sbt file and somehow tell Eclipse to use this when running the application?Apologies if this seems obvious to some, but I've recently moved from ItelliJ Idea to Scala-IDE and I'm not certain about setting up Scala-IDE to use SBT and my sbt config files.No, you cannot do this. The way to do it is as you described. Then, whenever you make changes to build.sbt (e.g., new jar dependency), rerun the  command from sbt and refresh the project in Eclipse so that the newly generated files are reloaded.As a seasoned Eclipse user, I wondered the same thing. Amazed that no one seemed to be going that direction, I decided to roll my own project.Install plugin, create or modify build.sbt and dependencies are fetched, project files updated.It works for me, I use it every day. But it's not perfect or finished, and I'm not putting in a lot of effort in it at the moment. But do feel free to contribute!"},
Scala

Play framework 2.0 is a full-stack standalone framework for creating web applications. Probably, many people need to integrate it into their build management, nevertheless. Unfortunately, I did not find much information about his.Here is my use case: I want to create a new project, which uses Scala and Play 2.0. I do NOT want to use sbt. I want to use Gradle, and dependency management should be done via Maven repositories.I have only found this play module:  which supports dependency management via Maven. I am looking for something like these examples in Grails:\n or Of course, I could write scripts / tasks which call \"play console commands\". Though, I do not like this solution. Is there a better way to use Gradle / Maven for build management? \nIf this is the only solution, then I would use Gradle, which then calls Play commands (i.e. sbt internally), right? Does this even work, or will there emerge other problems?Thanks in advance...Best regards,\nKaiThis is a very tricky business. SBT in Play is used for fetching dependencies, compiling source and templates, and for the SBT incremental compilation + auto-reloading feature. I have written a  script to resolve all Play 2.0 dependencies and set-up Eclipse or IntelliJ IDEA classpaths, and made it .I will try to implement the compilation later when I have time, but that would require some research. \nOf course, you can add compile and run tasks that just delegate to SBT but that would require describing all your project dependencies in both SBT and Gradle, which will become difficult to manage.I have updated the  file. I have added  and  tasks that should help in a CI environment. The  task does the following:You can use  and  to remove the output of the above commands, respectively.Note that there appears to be a strange problem (bug?) on Windows, which means that even if  fails, gradle will tell you it succeeded.I think you are simply missingin your file. Check .Good news, as of Gradle 2.7 there is an official play plugin: . They are rolling this out in 3 milestones:  It's available via the . On the above linked blog post, they encourage people to give it a try.I designed a simple build script in Gradle for Play Framework 1.2.x which you could also use for Play 2.x"},
Scala

As per Scala 2.10, what are the advantages (if any) of emitting bytecode for the JVM 1.7, when compared to the default of emitting for the 1.6?Previous Scala versions emitted version 49.0 of the byte code, which corresponded to Java 5. With Scala 2.10 version , corresponding to Java 6 and which has the principal advantage of activating the faster verifier introduced with that version, so it should lead to (slightly) better run time performance.As you note, with 2.10 it became possible to emit version 51.0 byte code, which corresponds to Java 7. There are a few differences between version 50.0 and version 51.0:  the biggest is the inclusion of the  instruction, with the plumbing that goes with it (see  for the gory details).As far as Scala usage of the 51.0 byte code goes, even though the technical parts are in place it is my understanding that work is still at an experimental stage in using this feature. See  and  which shows that the team is working on getting the performance benefits of method handles without having to introduce a dependency on Java 7.Scala 2.11 maintained the default of emitting version 50.0 bytecode, but the  is now to jump straight to Java 8 bytecode with Scala 2.12. In the meantime, there is a  available for Scala 2.11 that will let you try out  that are being prototyped for Scala 2.12, and which will become the default back-end with Scala 2.12.Anyway, the long-awaited proposed benefits all come from using the  bytecode (and its associated MethodHandle structures). They include:(Spoiler: Using  to implement closures in the experimental backend is currently  than the present optimised closure creation!)"},
Scala

I know about the parallel collections in Scala.  They are handy!  However, I would like to iterate over the lines of a file that is too large for memory in parallel.  I could create threads and set up a lock over a Scanner, for example, but it would be great if I could run code such as:Unfortunately, howeverWhat is the easiest way to accomplish some parallelism here?  For now, I will read in somes lines and handle them in parallel.You could use grouping to easily slice the iterator into chunks you can load into memory and then process in parallel.In my opinion, something like this is the simplest way to do it.I'll put this as a separate answer since it's fundamentally different from my last one (and it actually works)Here's an outline for a solution using actors, which is basically what Kim Stebel's comment describes.  There are two actor classes, a single FileReader actor that reads individual lines from the file on demand, and several Worker actors.  The workers all send requests for lines to the reader, and process lines in parallel as they are read from the file.I'm using Akka actors here but using another implementation is basically the same idea.This way, no more than 4 (or however many workers you have) unprocessed lines are in memory at a time.The comments on Dan Simon's answer got me thinking.  Why don't we try wrapping the Source in a Stream:Then you could consume it in parallel like this:I tried this out, and it compiles and runs at any rate.  I'm not honestly sure if it's loading the whole file into memory or not, but I don't  it is.I realize this is an old question, but you may find the  implementation in the  to be a useful no-assembly-required implementation of this:Below helped me to achieveWe ended up writing  at our company so we would understand the parallelism exactly."},
Scala

How can I change Scala version in a sbt project?I would like SBT to check whether the system's Scala version is correct and if it is not the case then download it.Change  in  to whatever Scala version your project should be using - see .As mentioned in , you can:But the  is more suited for what you want, as it shows in action how to change the  property.So you should be able toand each time trigger a compilation with a different Scala version."},
Scala

I'm using IntelliJ IDEA with the Scala plugin. If I reference HashMap in code, and then use Alt-Enter to add the import, the package gets imported as:What's the  part of this? It seems to work with and without it.It has to do scala imports being relative -  gives you a way to specify an absolute package name.  See the You would only need it if inside your current package you had a nested package scala.collection.immutable containing HashMap. This would be preferred by a relative import without the _root_ part. That was not quite right, the problems start already if you have a scala package either as an ancestor or nested in the current package.The Scala language specification has this to say about  in section 9.4 See the following PDF for the full language reference: "},
Scala

Some time ago Oracle decided that adding Closures to Java 8 would be an good idea. I wonder how design problems are solved there in comparison to Scala, which had closures since day one.Citing the  from :As far as I understand 2., 6. and 7. aren't a problem in Scala, because Scala doesn't use Checked Exceptions as some sort of \"Shadow type-system\" like Java.What about the rest?Scala targets JDK 5 and 6 which don't have method handles, so it hasn't tried to deal with that issue yet.Scala doesn't have checked exceptions.Scala doesn't have loop index variables.  Still, the same idea can be expressed with a certain kind of while loop .  Scala's semantics are pretty standard here.  Symbols bindings are captured and if the symbol happens to map to a mutable reference cell then on your own head be it.Scala users tend to use functions (or implicit functions) to coerce functions of the right type to an interface. e.g.Scala's standard library includes FuncitonN traits for 0 <= N <= 22 and the spec says that function literals create instances of those traitsSince Scala doesn't have checked exceptions it can punt on this whole issueSame deal, no checked exceptions.Type erasure is type erasure.  The above literals produce scala.lang.Function1 regardless of the choice for A and B. If you prefer, you can write Scala arbitrarily limits the number of arguments to be at most 22 so that it doesn't have to generate the FunctionN classes dynamically.The Scala specification does not say that it must.  But as of 2.8.1 the the compiler does not optimizes the case where a lambda does not capture anything from its environment.  I haven't tested with 2.9.0 yet.I'll address only number 4 here.One of the things that distinguishes Java \"closures\" from closures found in other languages is that they can be used in place of interface that does not describe a function -- for example, . This is what is meant by SAM, Single Abstract Method.Java does this because these interfaces abound in Java library, and they abound in Java library  Java was created without function types or closures. In their absence, every code that needed inversion of control had to resort to using a SAM interface. For example,  takes a  object that will perform comparison between members of the array to be sorted. By contrast, Scala can sort a  by receiving a function , which is easily passed through a closure. See note 1 at the end, however.So, because Scala's library was created for a language with function types and closures, there isn't need to support such a thing as SAM closures in Scala.Of course, there's a question of Scala/Java interoperability -- while Scala's library might not need something like SAM,  library does. There are two ways that can be solved. First, because Scala supports closures and function types, it is very easy to create helper methods. For example:Actually, this particular example can be made even shorter by use of Scala's by-name parameters, but that's beside the point. Anyway, this is something that, arguably, Java could have done instead of what it is going to do. Given the prevalence of SAM interfaces, it is not all that surprising.The other way Scala handles this is through implicit conversions. By just prepending  to the  method above, one creates a method that gets automatically (note 2) applied whenever a  is required but a function  is provided.Implicits are very unique, however, and still controversial to some extent.: Actually, this particular example was choose with some malice...  has  abstract methods instead of one, which is the whole problem with it. Since one of its methods can be implemented in terms of the other, I think they'll just \"subtract\" defender methods from the abstract list.And, on the Scala side, even though there's a sort method that uses , not , the standard sorting method calls for a  object, which is quite similar to Java's ! In Scala's case, though,  performs the role of a .: Implicits are automatically applied, ."},
Scala

In Scala, the syntax for selecting a type from a class is different from that of selecting anything else from a class. In that the former uses a hash as the selection operator instead of a dot. Why is that?Example: If we have a class like so...Why do we select the type from the class like this...instead of like this? is called a  and will match any type  of any enclosing instance of type . If you write a type , the compiler will look for the  (and not ) called  and will refer to its enclosing  type only. This is often used in the context of singleton objects.For instance:If Scala used  for type projections, this would lead to confusion because the preceding identifier could be interpreted either as a type or as a value\u2026 Hence the . Note that, as @kassens writes, Java  has type projections in that respect."},
Scala

I am working my way through the AngularJS tutorial. Angular uses it's own JS routing mechanism to allow for single page apps. A sample routing file for Angular looks like this:I am trying to come up with a good place to store my partials (Angular specific HTML files). Ideally i WOULD like the ability to template them from within Play (i.e. have them as *.scala.html files). I can accomplish this using a a Play routes file like so:I basically partials/ to a controller action like this:The solution I am looking for is a combination of two ideals:Any ideas? When I was trying something similar I came to the conclusion that it's better to break it on 2 parts:I know it doesn't sound great and really doesn't answer your question on how to do it, but trying to link both frameworks may be problematic due to the way templates and their urls are mapped in Angular, and the benefit will be very small as any change will imply a lot of work, thus removing the arguably main benefit of both Play and Angular, rapid development. This also allows you to separate concerns better, which if your project grows may be important as you can just take the AngularJS code away as a standalone app connecting to a backend, and it will work fine.You can see some sample code of what I said (based on the TODO tutorial of AngularJS) in this . I warn you, the code is not too nice, but should give you an idea and as a bonus shows you how to integrate Jasmine into Play, for AngularJS unit testing.The eventual seed () is yet another way to build a Play + AngularJS app. The code is a sweetheart and well-documented.This won't answer your question directly, but I found this to be the best way to build Play + Angular apps: Yes, it's possible to create server-side meta-templates of client-side templates. This offers some unique abilities, as the two methods don't overlap completely. There's also plenty of room for confusion so be sure you know why you're writing a Play block instead of an Angular directive.Whether or not you should do it remains an open question; it really depends on whether you actually need access to server information in your templates. An example of where I think it would be necessary and appropriate would be for implementing access control in your views.Now to answer your question. The problem is solved by inlining the partials instead of trying to provide a route for them to be loaded on demand. See .Here's what the template looks like:And the app:Just include this helper:And make sure to use it within the root scope of your angular app.For question #1 you could introduce a route like this:Then in your controller you would need to map from view name to actual view:You might want to render the templates lazy or require the request to be present, then you should probably do something like this:Your action would look something like this:If you want a specific controller method for a certain route (question #2) you simple add a route  the dynamic one:I really think it's not a very good idea even it comes from a respectfully mind indeed.I think it's a very good practice to leave every think as defaulted (convention over configuration principle) which means for me that we've probably more interest to keep each Paradigms (Play and AngularJS) separated as one or both could evolve in the near or the far future which will have its cost for code maintenance.The second very important point is testability, if you mix both technos you'll end up with a mix to come up with real good coverage of tests in both side of your application.\nCheers This might not answer the question exactly but you can try follow this project as it seems good example to build Play/scala/Angular apps:"},
Scala

Having a traithow do I implement a method that accepts an instance of any case class and returns its copy with the trait mixed in?The signature of the method looks like:This can be done with macros (that are officially a part of Scala since 2.10.0-M3). .1) My macro generates a local class that inherits from the provided case class and Persisted, much like  would do. Then it caches its argument (to prevent multiple evaluations) and creates an instance of the created class.2) How did I know what trees to generate? I have a simple app, parse.exe that prints the AST that results from parsing input code. So I just invoked , noted the output and reproduced it in my macro. parse.exe is a wrapper for . There are different ways to explore ASTs, read more in .3) Macro expansions can be sanity-checked if you provide  as an argument to scalac. In that case all expansions will be printed out, and you'll be able to detect codegen errors faster.edit. Updated the example for 2.10.0-M7It is not possible to achieve what you want using vanilla scala. The problem is that the mixins like the following:create a  mixed in, but it is not done at runtime. The compiler simply generates a new anonymous class:See  for more info.What you are trying to do is known as record concatenation, something that Scala's type system does not support. (Fwiw, there exist type systems - such as  and  - that provide this feature.)I think type classes might fit your use case, but I cannot tell for sure as the question doesn't provide sufficient information on what problem you are trying to solve.You can find an up to date working solution, which utilizes a Toolboxes API of Scala 2.10.0-RC1 as part of  project.The following solution is based on the Scala 2.10.0-M3 reflection API and Scala Interpreter. It dynamically creates and caches classes inheriting from the original case classes with the trait mixed in. Thanks to caching at maximum this solution should dynamically create only one class for each original case class and reuse it later. The following code was tested with Scala 2.10.0-M3.The trait to be mixed in. The actual worker objectThe test appWhile it's not possible to compose an object AFTER it's creation, you can have very wide tests to determine if the object is of a specific composition using type aliases and definition structs:Any object with a  will qualify as Persisted.Achieving what I THINK you are trying to do is possible with implicit conversions:"},
Scala

Soooo...Semigroups, Monoids, Monads, Functors, Lenses, Catamorphisms, Anamorphisms, Arrows... These all sound good, and after an exercise or two (or ten), you can grasp their essence. And with , you get them for free...However, in terms of real-world programming, I find myself struggling to find usages to these notions. Yes, of course I always find someone on the web using Monads for IO or Lenses in Scala, but... still... What I am trying to find is something along the \"prescriptive\" lines of a pattern. Something like: \"here, you are trying to solves , and one good way to solve it is by using lenses !\"Suggestions?Update: Something along these lines, with a book or two, would be great (thanks Paul): I gave  focused on the practical application of monoids and applicative functors/monads via . I gave another version of the same talk , where the emphasis was more on the validation. I would watch the first talk until I start on validations and then skip to the second talk (27 minutes in).There's also  which shows how you might use  in a \"practical\" application. That is, if you are designing software for nightclub bouncers.The key to functional programming is abstraction, and composability of abstractions. Monads, Arrows, Lenses, these are all abstractions which have proven themselves useful, mostly because they are composable. You've asked for a \"prescriptive\" answer, but I'm going to say no. Perhaps you're not convinced that ?I'm sure plenty of people on StackOverflow would be more than happy to try and help you solve a  problem the FP way. Have a list of stuff and you want to traverse the list and build up some result? Use a fold. Want to parse XML?  uses arrows for that. And monads? Well, tons of data types turn out to be Monads, so learn about them and you'll discover a wealth of ways you can manipulate these data types. But its kind of hard to just pull examples out of thin air and say \"lenses are the Right Way to do this\", \"monoids are the best way to do that\", etc. How would you explain to a newbie what the use of a for loop is? If you want to [blank], then use a for loop [in this way]. It's so general; there are tons of ways to use a for loop. The same goes for these FP abstractions.If you have many years of OOP experience, then don't forget you were once a newbie at OOP. It takes time to learn the FP way, and even more time to unlearn some OOP tendencies. Give it time and you will find plenty of uses for a Functional approach.I think you can take the reverse approach and instead when writing a small piece of functionality, ask yourself whether any of those would apply: Semigroups, Monoids, Monads, Functors, Lenses, Catamorphisms, Anamorphisms, Arrows... A lots of those concepts can be used in a local way.Once you start down that route, you may see usage everywhere. For me, I sort of get Semigroups, Monoids, Monads, Functors. So take the example of answering this question . It's a real usage for the person asking the question (a self described noob). I am trying to answer in a simple way but I have to  myself from scratching the itch \"there are monoids in here\". Scratching it now: using  and the fact that Int and List are monoids and that the monoid property is preserved when dealing with tuple, maps and options:But I don't come to that result by thinking . It comes more naturally by thinking  combined with the fact that scalaz has utility methods like . Interestingly when looking at the resulting code it's not obvious that I'm totally thinking in terms of monoid.You might like  by Chris Marshall. He covers a couple of Scalaz goodies - namely Monoid and Validation - with many practical examples. Ittay Dror has written a very accessible  on how Functor, Applicative Functor, and Monad can be useful in practice.  and 's blogs also have a bunch of posts covering use cases for categorical constructs.This answer just lists a few links instead of providing some real substance here. (Too lazy to write.) Hope you find it helpful anyway.I understand your situation, but you will find that to learn functional programming you will need to adjust your point of view to the documentation you find, instead of the other way around. Luckily in Scala you have the possibility of becoming a functional programmer gradually.To answer your questions and explain the point-of-view difference, I need to distinguish between \"type classes\" (monoids, functors, arrows), mathematically called \"structures\", and generic operations or algorithms (catamorphisms or folds, anamorphisms or unfolds, etc.). These two often interact, since many generic operations are defined for specific classes of data types.You look for prescriptive answers similar to design patterns: when does this concept apply? The truth is that you have surely seen the prescriptive answers, and they are simply the definitions of the different concepts. The problem (for you) is that those answers are intrinsically different from design patterns, but it is so for good reasons.On the one hand, generic algorithms are not design patterns, which suggest a structure for the code you write; they are abstractions defined in the language which you can directly apply. They are general descriptions for common algorithms which you already implement today, but by hand. For instance, whenever you are computing the maximum element of a list by scanning it, you are hardcoding a fold; when you sum elements, you are doing the same; and so on. When you recognize that, you can declare the essence of the operation you are performing by calling the appropriate fold function. This way, you save code and bugs (no opportunity for off-by-one errors), and you save the reader the effort to read all the needed code.On the other hand, structures concern not the goal you have in mind but properties of the entities you are modeling. They are more useful for bottom-up software construction, rather than top-down: when defining your data, you can declare that it is a e.g. a monoid. Later, when processing your data, you have the opportunity to use operations on e.g. monoids to implement your processing. In some cases it is useful to strive to express your algorithm in terms of the predefined ones. For instance, very often if you need to reduce a tree to a single value, a fold can do most or all of what you need. Of course, you can also declare that your data type is a monoid when you need a generic algorithm on monoids; but the earlier you notice that, the earlier you can start reusing generic algorithms for monoids.Last advice is that probably most of the documentation you will find about these concepts concerns Haskell, because this language has been around for much more time and supports them in a quite elegant way. Quite recommended here are , a Haskell course for beginners, where among others chapters 11 to 14 focus on some type classes, and  (which contains links to various articles with specific examples). EDIT: Finally, an example of applications of Monoids, taken from Typeclassopedia, is here: . I'm not saying there is little documentation for Scala, just that there is more in Haskell, and Haskell is where the application of these concepts to programming was born."},
Scala

Suppose I have a , and I want to call  on each element, and get back the result as a .What are the various ways to do this in Scala? Is there a solution with a minimal amount of explicit typing? \u2014 i.e., I want to specify that I want a  rather than a , but I'd like the  argument to be inferred from the filter function.Or should I explicitly pass a  instance? Where do I get these from \u2014 for s, s and s?Use  as the  and let the typer know what you want your result type to be (unfortunately you need to specify String here)Scala 2.10.0 introduced an easy way to convert a collection to another collection:Alternatively ask for an  explicitly:If you want to do this without creating the intermediate , then:You could do it (awkwardly, but more generally) using Now provide a typeclass instance from the List ~> Vector transformation:Define a wrapper and an implicit conversion:Then:"},
Scala

I've created a play project with play 2.3.7In the project directory, I ran activator and ran the  command to generate eclipse project files.When I go to eclipse (I'm using the Scala IDE from typesafe Build id: 4.0.0-vfinal-20150119-1023-Typesafe , there is an error in my Application.scala file:Is there something amiss with my setup? The app runs fine when I execute  at the activation console prompt.Thanks!EDIT: Added codeThe error is on the 'Ok..' line.There is a file in views called index.scala.html, and the app runs file when I run it from activator..Occasionally after adding a view in Play 2.4.x, IntelliJ IDEA sometimes gets confused and absolutely refuses to build. Even rebuild Project fails:This still happens from time-to-time in IDEA 15. And when it does, the command line provides the quickest, most-reliable fix:That's it! IDEA will now compile the project as expected.Update:In the rare case that  completed successfully on the command line, but IntelliJ IDEA 15 still gives the same \"object x is not a member\" error, then this has solved IDEA's confusion:File Menu:The other solutions did not work for me. Some would give me different errors, some would clear the Problems tab but leave me with a red squiggle under  and auto-complete would not work with the scala.html templates.What finally worked was to open the project's properties, go to , and add both of the following directories:If you only do  then you'll miss out on the class files generated from the  directory.In  you can find the solution (in brief: adding  folder to the compilation path), give it a try.I had the same problem. I added  and  to my Java build path and Eclipse stopped complaining.Adding  which is having  package to source fixed for me.I had the same issue running Play 2.4.0-RC1 using default SBT layout () and solved it by adding to :@brent-foust 's answer worked for me but only initially.  Every time I rebuilt the project from within IDEA I would then get \"not found: routes\" errors from within  until I performed Brent's workaround again.I eventually discovered the solution to that was changing a line in the .iml file fromtoI don't know what the long term implications of doing this are but it has fixed this problem.  Some of the other similar problems mentioned might also be fixed by applying the same change to some of the other folders listed in the .iml.For me when importing the project into intellij making sure I \"checked\" the \"auto import\" checkbox did the trick.1) Add the following line to your sbt.build file:2) Add the follwing line to your plugins.sbt file under the project folder:3) Run the \"eclipse\" command from within sbtas explained in the documentation of the play framework:"},
Scala

I get notified about \"unchecked\" warnings when I compile my Scala project with SBT 0.11, but I can't see the warnings themselves.What I see isWhat exactly am I to \"re-run with -unchecked\" and how to do that? Neither , nor , nor  seem to work.I've found the answer .The solution is to addto the project's  file.It can also take \"-feature\" as an option and works with sbt 0.13"},
Scala

How would you sort a scala.collection.Map[java.lang.String, Int] by its values (so on the Int)? What is a short and elegant way to do that?Depending on what the expected output collection type is (s are sorted on the keys), you could use something like this:Result would be the list of key/value pairs sorted by the value:There is a Map type that retains the original order, , if you apply this, you have a map again:Then you have:(Scala 2.8)"},
Scala

Say I have a . It can thus have the following values:\n\nI want to reduce it so that the first becomes  while the two others become . Obviously there are many ways to accomplish this, but I'm looking for a simple, perhaps built-in, less-than-one-liner.Flatten does exist now.As before,(in addition to the other answers) will also do the same thing.You could use   to do this, as this is one of the  operations:Here it is in the REPL:It's available to anything with a typeclass instance for a Monad.followed by a bunch of characters to get me up to the minimum that stackoverflow allowsI think the conversion to the Iterable is just fine.  Use these steps to go from  to a single (which returns )You might use flatMap like the following:This will map the  to a .\nIf you just have an Option you can use it as following:This will flatten your  to .Well, I actually don't understand how come it could be just None (the third case). If it can really be also just None, then I would vote for Rex Kerr's answer, otherwise just .get would be enough:"},
Scala

In Scala one might define methods inside other methods. This limits their scope of use to inside of definition block. I use them to improve readability of code that uses several higher-order functions. In contrast to anonymous function literals, this allows me to give them meaningful names before passing them on.For example:Is there any runtime cost because of the nested method definition I should be aware of?Does the answer differ for closures?During compilaton, the nested functions are  and  are moved out to the same level as . They get compiler synthesized names:  and .In addition, when you refer to one of these methods without an argument list, it is lifted into a function. So  is the same as writing . This anonymous function is compiled to a separate class , which does nothing more than forward to .As a side note, the process of lifting the method to a function is called Eta Expansion. It is triggered if you omit the argument list in a context where a function type is expected (as in your example), or if you use  in place of the entire argument list, or in place of each argument (.If the code was directly in the closure, you would have one fewer method call in your stack, and one fewer synthetic method generated. The performance impact of this is likely to be zero in most cases.I find it to be a fantastically useful tool to structure code, and consider your example very idiomatic Scala.Another useful tool is using small blocks to initialize a val:You can use  to see exactly how Scala code is translated into a form ready for the JVM. Heres the output from your program: There is a small runtime cost.  You can observe it here (apologies for the long code):There are four different methods for summing integers:And we see the results on my machine in terms of nanoseconds taken in the inner loop:So, bottom line is: nesting functions really doesn't hurt you at all in simple cases--the JVM will figure out that the call can be inlined (thus  and  give the same times).  If you take a more functional approach, the function call can't be  neglected, but the time taken is vanishingly small (approximately 0.4 ns extra per call).  If you use a lot of closures, then closing them gives an overhead of something like 1 ns per call at least in this case where a single mutable variable is written to.You can modify the code above to find answers to other questions, but the bottom line is that it is all very fast, ranging between \"no penalty whatsoever\" through to \"only worry about in the very tightest inner loops that otherwise have minimal work to do\".(P.S. For comparison, the creation of a single small object takes ~4 ns on my machine.) The current benchmark is ~3 years old and Hotspot and the compiler have significantly evolved. I am also using  to perform the benchmarks.What is very surprising is that closure test was completed about 4ns faster than the others. This seems to be an idiosyncrasy of Hotspot instead of the execution environment, multiple runs have returned the same trend.Using a closure that performs boxing is a huge performance hit, it takes approx 3.579ns to perform one unboxing and reboxing, enough to do a lot of primitive math operations. In this specific position, things might get better with the work being done on a . In the general case, boxing might be alleviated by .\nThe new optimizer doesn't really help here, it makes  0.1 ns slower and  0.1 ns faster: Performed with 2.11.0-20131209-220002-9587726041 from magarciaEPFL/scala"},
Scala

I'm looking at alternatives to  or  as a way of figuring out what the compiler is doing in Scala. With the new reflection/macros library,  seems a good candidate for that, as shown in retronym's 's . It even shows how one used to do that, pre-M4.So the question is, what's the shortest/easiest thing I can type on Scala's REPL to get the AST for an expression, post-Scala 2.10.0-M4?A lot of things previously defined in package  have moved to :Furthermore it is possible to check if a string containing some Scala code is a valid Scala expression and - even better - do some evaluation:. In 2.10.0-RC1 some methods of  have been renamed.  is now just , and  is now called .The most complicated thing here is the raw tree representation of an expression. When one wants to use macros, the macros have to be defined the same way as shown by . But with some helper methods it is possible to define some not so ugly looking macro implementations:But now we come in problems with path-dependent-types - we have to write their paths explicitly if we want not import them.There is improve of new Scala version"},
Scala

I want to make a scala function which returns a scala tuple.I can do a function like this:and this will work fine, but now I want to tell the compiler what I expect to be returned from the function instead of using the built in type inference (after all, I have no idea what a  is).The compiler will interpret the type  as a Also, you can create a type alias if you get tired of writing (Int,String,String)"},
Scala

I'm running Scala 2.10.2. I want to create a list, then add some elements to the list and expect to see all the elements in the lists when I call the list's name. But I observed something quite weird (At least weird for me since I'm a newbie). Below is the what I tried to do in my First, I created the list  with 2 elements (1.0 and 5.5). I call  and get what I expect; the two elements. Now I tried to add another element to the list using  which returned a new list with a new list of elements I added (2.2 and 3.7) Sweet! I even checked someone else's code for help:  to use a new construct . So at this stage I'm all happy, but I call  and I get the unexpected: `res3: List[Double] = List(1.0, 5.5)'. Where are the elements I added? And how do I add these elements correctly so that when I call  I get a new list with all the stuff I added? You are using an immutable list. The operations on the List return a new List. The old List remains unchanged. This can be very useful if another class / method holds a reference to the original collection and is relying on it remaining unchanged. You can either use different named vals as inor use a var as inThis is equivalent syntax for:Or you could use one of the mutable collections such asNot to be confused with the following that does not modify the original mutable List, but returns a new value:However you should only use mutable collections in performance critical code. Immutable collections are much easier to reason about and use. One big advantage is that immutable List and  are Covariant. Don't worry if that doesn't mean anything to you yet. The advantage of it is you can use it without fully understanding it. Hence the collection you were using by default is actually  its just imported for you automatically.Note: personally I use Seq as my default collection. This uses the immutable Seq trait. List /Vector / Array is an implementation detail for performance not functionality. List is more efficient for small collections.Use  or similar if you really need mutation.I will try to explain the results of all the commands you tried.First of all,  is a type alias to  (defined in Predef.scala).Using the List companion object is more straightforward way to instantiate a . Ex:  returns a list resulting from the concatenation of the given list prefix and this listThe original List is NOT modified is a  Definitely not what you want. returns a new list consisting of all elements of this list followed by elem.The type is  because it is the common superclass between  and l is left unmodified because no method on  modified the List.Since you want to append elements to existing list, you can use var List[Int] and then keep on adding elements to the same list. \nNote -> You have to make sure that you insert an element into existing list as follows:-var l: List[int] = List()   // creates an empty listl = 3 :: l                 // adds 3 to the head of the listl = 4 :: l                // makes int 4 as the head of the list// Now when you will print l, you will see two elements in the list ( 4, 3)"},
Scala

I have read that with Scala, it is generally advised to use Traits instead of Abstract classes to extend a base class.Is the following a good design pattern and layout? Is this how Traits were intended to replace Abstract?I don't know what your source is for the claim that you should prefer traits over abstract classes in Scala, but there are several reasons  to:The last reason is by far the most important in my view. At least a couple of the other issues  in future versions of Scala, but it will remain the case that defaulting to classes will constrain your programs in ways that are (at least arguably) consistent with good design. If you decide you actually really do want the power provided by traits, they'll still be there, but that'll be a decision you make, not something you just slip into.So no, in the absence of other information, I'd suggest using an abstract class (ideally a sealed one) and two concrete classes that provide implementations.OTOH, traits allow you to build and test the functionality of complex objects in a granular fashion, and to reuse core logic so as to provide different flavors. For example, a domain object might be deployed to a data server, which persists to a database, while a web server might employ read-only versions of the same object that are updated from the data server.Nothing is suitable for every scenario. Use the right construct for the task at hand. Sometimes the reality of an implementation brings to light issues for specific use cases which were unknown at design time. Re-implementing using different assumptions and constructs can yield surprising results."},
Scala

I'm trying to use the negation of a boolean function in Scala, such as:But I get the error:How can I refer to the negation of p? The negation of  is a function that applies  to its argument and negates the result.If you want to be able to write  or  you can use , which pimps functions that return a bool with various logical operators.Shortest negation of p: When you apply the predicate  as an argument to another function: For example, using a Set of integers (try it on a Scala worksheet):Another way to solve it without the use of an anonym function is to define a concrete function for this task.You can also define ! yourselfbut this only seems to works for functions of type Int=>Boolean, and not (Int)=>Boolean. The not(even) solution works with both."},
Scala

I just noticed this construct somewhere on web:What does  mean? Is this a syntax sugar for some method call? What constraints should my custom class satisfy so that it can take advantage of this syntax sugar?Generally, the  notation is used for type ascription, forcing the compiler to see a value as some particular type.  This is not  the same as casting.In this case, you're ascribing the special  type.  This mirrors the asterisk notation used for declaring a varargs parameter and can be used on a variable of any type that subclasses :That's scala syntax for exploding an array. Some functions take a variable number of arguments and to pass in an array you need to append  to the array argument.I'm psychic, I predict you'll see that wildcard a  in scala:"},
Scala

I've studied scala for several months, but still at the beginner level. Now I found I have huge trouble with functional programming and scala's type system. I tried finding some documents and blogs, but I can't understand most of them(especially type-system ones). So I'm looking for some small and good scala projects that I can read the sources to learn.Could you please recommend me some?There's a popular set of \"Scala Problems\" out there, called Problems come in all difficulties, and many flavors, basic functional programming included.If you follow the community there are the common suspects(those writing the scalaz book):If you through this I have some more :)\nIf you want an suggested order I word start with debasishs blog , then the simple exercises from tonys blog then read through runars blog(even the java ones!) then Erics after that Pauls and have a look at lucs ideas.There is also scala labs: You can try the \"\"  by the designer of Scala, Martin Odersky. You only need to register at Coursera (click on the \"Join for Free\" button on the right sidebar) and then you will have access to the class which consists of lecture , between 6 and 15 minutes in length, that are accompanied by ,  and  per video.The course also provides learning resources, discussion forums, instructions to setup tools, sbt tutorial, Eclipse tutorial, IntelliJ IDEA tutorial, Scala tutorial, Scala style guide and a Scala cheatsheet.I also came across a series of very nicely written blog posts on Scala by Joel Abrahamsson:I hope the resources that I provided will prove to be helpful.If you are looking for some step-by-step tutorial than you should test  Try to complete  from sample chapters  &  to see if it match your expectations. has tons of problems that you can code up in multiple functional programming languages including Scala. The best part is that they have pre-written tests like an online judge. "},
Scala

How does  supercede the answers given in Stack Overflow question  (it doesn't work because the \"jcl\" package is gone) and in  (it doesn't work for me in a complicated test which I'll try to boil down and post here later).The latter is actually a Scala Map question, but I think I need to know both answers in order to iterate over a .In 2.8, you import  and use as a Scala map.  Here's an example (in 2.8.0.RC1):If you specifically want a Scala iterator, use  (after the conversions import)."},
Scala

What are the advantages and dis\u00adadvantages of frameworks Lift, Play and Wicket? What characteristics are best or only supported by each?Thanks:Lightweight Java-based framework, with Scala support available as an extra.very good for rapid prototyping, fast-feedback-loop kind of work.  Embeds the compiler, so you just edit source code in place and pages get immediately updated.  Learning curve is shallow.:Stateful Java-based framework, with Scala support available as an extra.Shallower learning curve into Scala, especially if you already have wicket experience.\nGood separation of concerns, POJO-based model.  Arguably one of the best Java web frameworks currently available.:Stateful native-Scala framework.\nDeep Scala integration, so no need to generate bean setter/getter methods or worry about interop between Java/Scala collections.  Fully embraces functional-programming concepts, such as immutability and closures.Also the steepest learning-curve of the three.  One common piece of advice is therefore to learn the Scala language before getting started with Lift, especially if you come from a Java background.:There are also other Scala-based frameworks available (such as Scalatra and Pinky) for web development, though not as well-known as Lift.  It wouldn't hurt to check these out as well!For more information, see this question: There are many threads that compares these web frameworks for Scala. SeeLift / Wicket here: Talking about the advantages of Lift, one should mention  where Lift really excels. In short:Just visit the linked page for more details - these features really make Lift unique among competitors.See also: - Stateful Java-based framework for desktop-like applications (GWT based, but server-side, no javascript, no html). - stateless Java-based framework for light web applications.Both have excellent documentation and are easy to learn. "},
Scala

I am reading through the Scala Cookbook ()There is an example related to Future use that involves for comprehension.So far my understanding about for comprehension is when use with a collection it will produce another collection with the same type. For example, if each   is of type , the following should also be of type :Could someone explain me what exactly happening when use  in this code?\nI know if it was a generator it will fetch each element by looping.First about for comprehension. It was answered on SO many many times, that it's an abstraction over a couple of monadic operations: , , . When you use , scalac desugars this lines into monadic : into it looks like an imperative computation (what a monad is all about), you bind a computation result to the . And  part is desugared into  call. Result type depends on the type of 's. trait has a  and  functions, so we can use for comprehension with it. In your example can be desugared into the following code:It goes without saying that if execution of  depends on  then you can't escape sequential execution, but if the future computations are independent, you have two choices. You can enforce sequential execution, or  for parallel execution. You can't  the latter, as the execution context will handle this.will always run sequentailly. It can be easily explained by the desugaring, after which the subsequent  calls are only invoked inside of the flatMaps.is able to run in parallel and the for comprehension aggregates the results.It allows , ,  to run in parallel, if possible. It may not be possible, depending things like how many threads are available to execute Future computations, but by using this syntax you are telling the compiler to run these computations in parallel if possible, then execute the  when all have completed."},
Scala

I always thought that  was merely a shortcut for , but apparently I am mistaken, since it doesn't seem to use  at all. Why is that so? And how can I do the \"redirecting\" of  below in Scala? is shortcut for  and you can use  or  for redirecting. Also,  only affects the current thread while System.setOut\naffects the whole JVM. Additionally Scala 2.9  evaluates each line in its own thread, so  is not usable there."},
Scala

String interpolation is  starting Scala 2.10 This is the basic example I was wondering if there is a way to do dynamic interpolation, e.g. the following (doesn't compile, just for illustration purposes) is actually a method on  (or something which can be implicitly converted from ).  When you writethe compiler desugars it intoBy default,  gives you , , and * methods.As you can see, the compiler itself picks out the name and gives it to the method.  Since this happens at compile time, you can't sensibly do it dynamically--the compiler doesn't have information about variable names at runtime.You can use vars, however, so you can swap in values that you want.  And the default  method just calls  (as you'd expect) so you can play games like(0 was already called by the REPL in this example).That's about the best you can do.*Here is a possible  solution to #1 in the context of the original question based on Rex's excellent answerNote that  can be a user-defined interpolator introduced through an implicit class. The documentation gives an example for a  interpolator,This is inherently impossible in the current implementation: local variable names are not available at execution time -- may be kept around as debug symbols, but can also have been stripped. (Member variable names are, but that's not what you're describing here)."},
Scala

Browsing Shapeless code, I came across this seemingly extraneous   and :I almost ignored it as a typo since it does nothing but apparently it does something. See this commit: I have no idea what it does. Can someone explain?Any type can be followed by a  enclosed sequence of type and abstract non-type member definitions. This is known as a \"refinement\" and is used to provide additional precision over the base type that is being refined. In practice refinements are most commonly used to express constraints on abstract type members of the type being refined.It's a little known fact that this sequence is allowed to be empty, and in the form that you can see in the shapeless source code,  is the type  with an empty refinement. Any empty refinement is ... empty ... so doesn't add any additional constraints to the refined type and hence the types  and  are equivalent. We can get the Scala compiler to verify that for us like so,So why would I do such an apparently pointless thing in shapeless? It's because of the interaction between the presence of refinements and type inference. If you look in  of the Scala Language Specification you will see that the type inference algorithm attempts to avoid inferring singleton types in at least some circumstances. Here is an example of it doing just that,As you can see from the definition of  the Scala compiler knows that the value  has the more precise type  (ie. the singleton type of ), however, unless explicitly requested it won't infer that more precise type. Instead it infers the non-singleton (ie. widened) type  as you can see in the case of .But in the case of  in shapeless I explicitly  the singleton type to be inferred for uses of the  member (the whole point of  is enable us to pass between the type and value levels via singleton types), so is there any way the Scala compiler can be persuaded to do that?It turns out that an empty refinement does exactly that,As you can see in the above REPL transcript, in the first case  has been typed as the widened type  whereas  has been assigned the singleton type .Is this mandated by the SLS? No, but it is consistent with it, and it makes some sort of sense. Much of Scala's type inference mechanics are implementation defined rather than spec'ed and this is probably one of the least surprising and problematic instances of that."},
Scala

In Java, it's a common best practice to do string concatenation with StringBuilder due to the poor performance of appending strings using the + operator. Is the same practice recommended for Scala or has the language improved on how java performs its string concatenation?Scala uses Java strings (), so its string concatenation is the same as Java's: the same thing is taking place in both. (The runtime is the same, after all.) There is a special  class in Scala, that \"provides an API compatible with \"; see .But in terms of \"best practices\", I think most people would generally consider it better to write simple, clear code than maximally efficient code, except when there's an actual performance problem or a good reason to expect one. The  operator doesn't really have \"poor performance\", it's just that  is equivalent to  (i.e. it creates a new  object), which means that, if you're doing a lot of concatenations to (what looks like) \"a single string\", you can avoid creating unnecessary objects \u2014 and repeatedly recopying earlier portions from one string to another \u2014 by using a  instead of a . Usually the difference is not important. (Of course, \"simple, clear code\" is slightly contradictory: using  is simpler, using  is clearer. But still, the decision should usually be based on code-writing considerations rather than minor performance considerations.)Scalas String concatenation works the same way as Javas does.is translated toStringBuilder is . That's the reason why the value appended to the StringBuilder is boxed by the compiler.You can check the behavior by decompile the bytecode with javap.Scala uses  as the type for strings, so it is subject to the same characteristics.I want to add: if you have a sequence of strings, then there is already a method to create a new string out of them (all items, concatenated). It's called .Example: ()"},
Scala

I'm doing a bit of Scala gymnastics where I have  in which I try to find the \"smallest\" element. This is what I do right now:It works fine, but I'm not quite satisfied - it's a bit long for such a simple thing, and . Using  would be much more elegant:... but  and  throw exceptions when the sequence is empty. Is there an idiomatic, more elegant way of finding the smallest element of a possibly empty list as an ? does what you want?Edit: Here's an example incorporating your :or, as generic method:which you could invoke with A safe, compact and  version with Scalaz:Hardly an option for any larger list due to  complexity:Scala allows us to capture the error with . Let's write a function that makes use of it:Now let's test that:How about this?Or, more verbose, if you don't want to swallow other exceptions:Alternatively, you can pimp all collections with something like this:And then just write .In Haskell you'd wrap the  call as"},
Scala

For a monad , Is it possible to turn  into ?I've tried following the types to no avail, which makes me think it's not possible, but I thought I'd ask anyway. Also, searching Hoogle for  didn't return anything, so I'm not holding out much luck.No, it can not be done, at least not in a meaningful way.Consider this Haskell codeThis takes  first, prints it (IO performed here), then reads a line from the user.Assume we had an hypothetical . Then as a mental experiment, consider:The above has to do all the IO in advance, before knowing , and then return a pure function. This can not be equivalent to the code above.To stress the point, consider this nonsense code below:Magically,  should know in advance what the user is going to type next! A session would look asThis requires a time machine, so it can not be done.No, it can not be done. The argument is similar to .Assume by contradiction  exists.\nSpecialize  to the continuation monad   (I omit the newtype wrapper).Specialize :Apply:By the Curry-Howard isomorphism, the following is an intuitionistic tautologybut this is Peirce's Law, which is not provable in intuitionistic logic. Contradiction.The other replies have nicely illustrated that in general it is not possible to implement a function from  to  for any monad . However, there are specific monads where it is quite possible to implement this function. One example is the reader monad:No.For example,  is a monad, but the function  has no meaningful implementation:What do you put instead of ? ?  of what then? Or ?"},
Scala

I started working my way through the , which is organized around a suite of unit tests with blanks that one needs to fill in.  (This idea was modeled after a similar Ruby Koans project.)   You start the sbt tool running a test, and it admonishes:  ...and so you go look at this unit test and it says:...and, after meditation, you realize that you should fill in the blank like this:...and then it moves on to the next unit test.   My question, though, is what is this  operator? I can't seem to find it anywhere.  Is this a DSL operator defined in the Scala Koans project itself?  Or is it part of the ScalaTest framework?  Or in Scala proper?This is the triple-equals operator from . Have a look at this page: . It says:"},
Scala

is there a way to extend a case class without constantly picking up new vals along the way? For example this doesn't work\"a\" conflicts with \"a\" , so I'm forced to rename to a1. But I don't want all kinds of extra public copies of \"a\" so I made it private. This just doesn't seem clean to me.. am I missing something?As the previous commenter mentioned: case class extension should be avoided but you could convert your Edge class into a trait. If you want to avoid the private statements you can also mark the variables as override Don't forget to prefer  over  in traitsThis solution offers some advantages over the previous solutions:In this way:Case classes can't be extended via subclassing. Or rather, the sub-class of a case class cannot be a case class itself."},
Scala

I almost always have a Scala REPL session or two open, which makes it very easy to give Java or Scala classes a quick test.  But if I change a class and recompile it, the REPL continues with the old one loaded.  Is there a way to get it to reload the class, rather than having to restart the REPL?Just to give a concrete example, suppose we have the file Test.scala:We compile it and start the REPL:Then we change the source file tobut we can't use it:Class reloading is not an easy problem.  In fact, it's something that the JVM makes very difficult.  You do have a couple options though:Unfortunately, both of these are limited by the Scala REPL's implementation details.  I use JRebel, and it usually does the trick, but there are still cases where the REPL will not reflect the reloaded class(es).  Still, it's better than nothing.There is an alternative to reloading the class if the goal is to not have to repeat previous commands.  The REPL has the commandwhich restarts the REPL environment and plays back all previous valid commands.  (The invalid ones are skipped, so if it was wrong before, it won't suddenly work.)  When the REPL is reset, it does reload classes, so new commands can use the contents of recompiled classes (in fact, the old commands will also use those recompiled classes).This is not a general solution, but is a useful shortcut to extend an individual session with re-computable state.There is an command meet you requirementwhich will reload the scala source file and recompiled to classes , then you can replay you code This works for me....If your new source file  looks something like this...You first have to load the new changes into Scala console (REPL).Then re-import the package so you can reference the new code in Scala console.Now enjoy your new code without restarting your session :)If the .scala file is in the directory where you start the REPL you can ommit the full path, just put , and then import."},
Scala

How do I create an array of multiple dimensions? For example, I want an integer or double matrix, something like  in Java.I know for a fact that arrays changed in Scala 2.8 and that the old arrays are deprecated, but are there multiple ways to do it now and if yes, which is best?Like so:It's deprecated. Companion object exports factory methods :"},
Scala

I have a DataFrame generated as follow:The results look like:As you can see, the DataFrame is ordered by  in an increasing order, then by  in a descending order.I would like to select the top row of each group, i.e.So the desired output would be:It might be handy to be able to select the top N rows of each group as well.Any help is highly appreciated.:Something like this should do the trick:This method will be inefficient in case of significant data skew.:Alternatively you can join with aggregated data frame:It will keep duplicate values (if there is more than one category per hour with the same total value). You can remove these as follows::Neat, although not very well tested, trick which doesn't require joins or window functions: (Spark 1.6+, 2.0+):::The last two methods can leverage map side combine and don't require full shuffle so most of the time should exhibit a better performance compared to window functions and joins.To get only the first row of each group, you can try this.For Spark 2.0.2 with grouping by multiple columns:If the dataframe has to be grouped by multiple columns, this can helpHope this helps someone with similar problemWe can use the rank() window function (where you would choose the rank = 1)\nrank just adds a number for every row of a group (in this case it would be the hour)here's an example. ( from  )"},
Scala

(Yes I know I can call Java code from Scala; but that is pointless; I want to DELETE the Java code, not keep it around and have to look at it and maintain it forever!)Are there any utilities out there to convert Java source to Scala source?I believe theoretically it should be possible to accomplish with minimal lossage.I have found this but it seems inactive, probably buggy/incomplete...\nAny alternatives?IntelliJ kinda, sorta, does this. You need to open a project with your Java sources. You can then copy/paste expressions, methods, or entire classes in to a .scala file. This converts to equivalent Scala code.The fidelity of conversion isn't perfect, and, for this reason, it doesn't support a bulk conversion yet.I recommend using the latest version of  and the . The Community Edition is free.Aside from this, Paul Phillips once started the  project to translate code from Java to Scala (or, potentially, ), and even improve it in the process! He explains the concept in this . However this effort was stalled, presumably because he turned his attention to directly contributing to the Scala compiler and standard library.In IntelliJ IDEA theres is a refactoring called \"Convert to Scala\". It's under Refactor menu (after you install Scala plugin) Ctrl+Shift+G.\nSo you don't need to play with copy/paste.Just make sure you have a java file opened, there is no this option if it's a scala or other file.I just published the following tool : . I tried Jatran as well, but was frustrated with some bugs and difficult integration. Scalagen is extensible and comes with a Maven plugin.You can use online  which uses  library.(I haven't used this)noticed this, Mar 2012: I don't think it's possible to automatically convert Java to Scala in the general case.  Many of the lower-level constructs in Java don't exist in Scala (e.g. fields and static members), Scala places limitations on constructors that don't exist in Java, and Scala doesn't have raw types like Java (generics without the generic parameters specified)."},
Scala

In scala, we cannot extend :gives an error In my case someone has defined some functionality in an object and I need to extend it (basically add another method). What would be the easiest way to extend this object? As so often the correct answer depends on the actual business requirement. Extending from an object would in some sense defy the purpose of that object since it wouldn't be a singleton any longer.What might be a solution is to extract the behavior into an abstract trait. And create objects extending that trait like so:If you want use methods and values from another object you can use import.You can't actually extend an object, because that would create two of it, and an object by definition exists only once (edit: well, that's not quite true, because the object definition can be in a class or method).For your purposes, try this:It doesn't actually extend, but it does allow you to call new methods on it than were originally defined.The only way to share code between two objects is by having one or more common superclass/trait.You can convert parent into class + companion object, and then have child extend class E.g.in Parent.scalaAnd then in Child.scalaYes, it's more a hack than a solution."},
Scala

Why using , ,  etc. are considered better than using  for Scala Options? If I use I can call  safely. Well, it kind of comes back to \"tell, don't ask\". Consider these two lines:In the first case, you are looking inside  and then reacting depending on what you see. In the second case you are just telling  what you want done, and let it deal with it.The first case knows too much about , replicates logic internal to it, is fragile and prone to errors (it can result in run-time errors, instead of compile-time errors, if written incorrectly).Add to that, it is not composable. If you have three options, a single for comprehension takes care of them:With , things start to get messy fast.One nice reason to use  is parsing something with nested options. If you have something likeThe console prints . If you extend this to a case where you have a class that optionally stores a reference to something, which in turn stores another reference, for comprehensions allow you to avoid a giant \"pyramid\" of None/Some checking.There are already excellent answers to the actual question, but for more -foo you should definitely check out .The reason it's more useful to apply things like , , and  directly to the  instead of using  and then performing the function is that it works on either    and you don't have to do special checks to make sure the value is there. The result for  here is an , which is desirable since if  is optional, then  might be undetermined as well.  Since  doesn't work on , you'd have to do a bunch of extra work to make sure you didn't get any errors; extra work that is done for you by .Trying to perform  our Operations with    is more imperative style where u need to tel  . In other words , we are dictating things and  digging more into the  internals. Where as    are more functional way of doing things where we are say . Put simply:"},
Scala

For example, there is a string val . How do you separate it into ?You can use  as follows:If you want an array, you can use Do you need characters?Do you need bytes?Do you need strings?Do you need UTF-32 code points?  Okay, that's a tougher one.Additionally, it should be noted that if what you actually want isn't an actual list object, but simply to do something which each character, then Strings can be used as iterable collections of characters in ScalaActually you don't need to do anything special. There is already implicit conversion  in  to  and  extends  so you have all goodies that available in it, like: has  conversion that has higher priority than  in . So String end up being , that is also  of chars. "},
Scala

Here is a little Scala session that defines and tries out some functions:works nicely.oops.    works well!Now, I've seen the  syntax when folding (, etc). So as I understand it  basically means \"an argument\". So  basically means a function with an argument, which is given to \". But why isn't that  the same as just ? Why is there a difference if I append a ?So I kept exploring...Here it works without ! What's the difference between a ed function, and a ed function?There's no difference between a def'ed function and a val'ed function:See? All of these are functions, which is indicated by the  type they have.Do you see an  type? If you do, go see an ophthalmologist, because there's none. The type here is , commonly used to denote a .Actually, , ,  and  are all methods, which return functions.  is a method which returns a . Also,  through  do not take parameters (only  could, anyway), while  does.So, the difference is pretty simple. In the first case, you tried to assign a method to a val, but did not fill in the parameters the method take. So it failed, until you added a trailing underscore, which meant .In the second example you had a function, so you didn't need to do anything else.A method is not a function, and vice versa. A function is an object of one of the  classes. A method is a handle to some piece of code associated with an object.See various questions about methods vs functions on Stack Overflow.The  declares a method within a surrounding object/class/trait, similar to the way you define methods in Java. You can only use s within other objects/classes/traits. In the REPL, you cannot see the surrounding object because it's \"hidden\", but it does exist.You cannot assign a  to a value, because the  is not a value - it's a method in the object.The  declares and instantiates a , which exists at runtime. Function objects are instances of anonymous classes which extend  traits.  traits come with an  method. The name  is special, because it can be omitted. Expression  is desugared into .The bottomline is - since function objects are runtime values which exist on the heap, you can assign them to values, variables and parameters, or return them from methods as return values.To solve the issue of assigning methods to values (which can be useful), Scala allows you to use the placeholder character to create a function object from a method. Expression  in your example above actually creates a wrapper function around the method  - it is equivalent to .The underscore means different things in different contexts. But it can always be thought of as .When applied in place of parameters, the effect is to lift the method to a function.Note, the method has become a function of type (String) => String. The distinction between a method and a function in Scala is that methods are akin to traditional Java methods. You can't pass them around as values. However functions are values in their own right and can be used as input parameters and return values.The lifting can go further:Lifting this function results in another function. This time of type () => (String) => (String)From what I can tell, this syntax is equivalent to substituting all of the parameters with an underscore explicitly. For example:"},
Scala

How do you update multiple columns using Slick Lifted Embedding ?  doesn't say much.I expected it to be something like thisI figured it out. It should be like this, why your documentation is so bad ? I have to Google pretty much every silly thing or dig through unit-tests for hours. Please improve it. Thanks.With Slick 2.x and 3.x, this way of writing it works: "},
Scala

scala-2.11 folder appeared after recent update of IDEA and Scala plugin.\nWhat should it be used for?  Usually such directories are used for binary version-dependent code. For example, macros in 2.10 are not source-compatible with macros in 2.11, so if you're building your project for different binary versions and you're using macros, it makes sense to put code which is only valid for the specific version in different source roots. SBT then will use the appropriate directory when compiling for 2.10 or 2.11.If you're using SBT, though, you would need to set such thing up manually in the build definition. If you're not using SBT, then probably IDEA plugin was updated to handle such things by itself."},
Scala

What I'd like to achieve is having a proper implementation forI may know what B is, but don't know what A is (but if B has a self type then I could add some constraints on A).\nThe scala compiler is happy with the above signature, but I could not yet figure out how the implementation would look like - if it is possible at all. Some options that came to my mind:Do you have any other ideas that might work? Which way would you recommend? What kind of \"challenges\" to expect?\nOr should I forget it, because it is not possible with the current Scala constraints?Intention behind my problem:\nSay I have a business workflow, but it's not too strict. Some steps have fixed order, but others do not, but at the end all of them has to be done (or some of them required for further processing).\nA bit more concrete example: I have an A, I can add B and C to it. I don't care which is done first, but at the end I'll need an A with B with C.Comment: I don't know too much about Groovy but SO popped up  and I guess it's more or less the same as what I'd like, at least conceptional.I believe this is impossible to do strictly at runtime, because traits are mixed in at compile-time into new Java classes.  If you mix a trait with an existing class anonymously you can see, looking at the classfiles and using javap, that an anonymous, name-mangled class is created by scalac: returnsWhile  returnsAs you can see, scalac creates a new anonymous class that is loaded at runtime; presumably the method  in this anonymous class creates an instance of  and calls  on it, but I'm not completely sure., we can do a pretty hacky trick here:Since you  to use the Scala compiler, AFAIK, this is probably close to the cleanest solution you could do to get this.  It's quite slow, but memoization would probably help greatly.This approach is pretty ridiculous, hacky, and goes against the grain of the language.  I imagine all sorts of weirdo bugs could creep in; people who have used Java longer than me warn of the insanity that comes with messing around with classloaders.I wanted to be able to construct Scala beans in my Spring application context, but I also wanted to be able to specify the mixins to be included in the constructed bean:The difficulty is that Class.forName function does not allow me to specify the mixins. In the end, I extended the above hacky solution to Scala 2.9.1. So, here it is in its full gory; including bits of Spring.The code cannot yet deal with constructors with parameters and does not copy annotations from the parent class\u2019s constructor (should it do that?). However, it gives us a good starting point that is usable in the scala Spring namespace. Of course, don\u2019t just take my word for it, verify it in a Specs2 specification:"},
Scala

I need to get a simple JSON serialization solution with minimum ceremony. So I was quite happy finding . This works perfectly with plain case classes, e.g.But the following fails:Or would you recommend any other standalone library that handles my case more or less fully automatically? I don't care whether that is with macros at compile time or reflection at runtime, as long as it works out of the box.Here is a manual implementation of the  companion object:Verification:Alternatively the direct format definition:Now ideally I would like to automatically generate the  and  methods. It seems I will need to use either reflection or dive into macros.The library  includes the  strategy, but also the [play-json-extensions] strategy (flat string for case objects mixed with objects for case classes no extra $variant or $type unless needed). It also provides serializers and deserializers for   based enums.\nThere is now a library called  which allows you to write :This will generate the corresponding formats automatically, it will also handle disambiguation of the following case by adding a $variant attribute (the equivalent of 0__ 's  attribute)would generate "},
Scala

I'd like to estimate the big-oh performance of some methods in a library through benchmarks. I don't need precision -- it suffices to show that something is O(1), O(logn), O(n), O(nlogn), O(n^2) or worse than that. Since big-oh means upper-bound, estimating O(logn) for something that is O(log logn) is not a problem.Right now, I'm thinking of finding the constant multiplier k that best fits data for each big-oh (but will top all results), and then choosing the big-oh with the best fit.Given the comments so far, I need to make a few things clear:Here's one example of the kind of stuff I want to measure. I have a method with this signature:Given an , it will return the nth element of a sequence. This method can have O(1), O(logn) or O(n) given the existing implementations, and small changes can get it to use a suboptimal implementation by mistake. Or, more easily, could get some other method that  on it to use a suboptimal version of it.In order to get started, you have to make a couple of assumptions.In particular, (3) is difficult to achieve in concert with (1).  So you may get something with an exponential worst case, but never run into that worst case, and thus think your algorithm is much better than it is on average.With that said, all you need is any standard curve fitting library.   has a fully adequate one.  You then either create a function with all the common terms that you want to test (e.g. constant, log n, n, n log n, nn*n, e^n), or you take the log of your data and fit the exponent, and then if you get an exponent not close to an integer, see if throwing in a log n gives a better fit.(In more detail, if you fit  for  and , or more easily , you can get the exponent ; in the all-common-terms-at-once scheme, you'll get weights for each term, so if you have  where  is large, you'll pick up that term also.)You'll want to vary the size by enough so that you can tell the different cases apart (might be hard with log terms, if you care about those), and safely more different sizes than you have parameters (probably 3x excess would start being okay, as long as you do at least a dozen or so runs total).Edit: Here is Scala code that does all this for you.  Rather than explain each little piece, I'll leave it to you to investigate; it implements the scheme above using the C*x^a fit, and returns ((a,C),(lower bound for a, upper bound for a)).  The bounds are quite conservative, as you can see from running the thing a few times.  The units of  are seconds ( is unitless), but don't trust that  much as there is some looping overhead (and also some noise).Note that the  method is expected to take about sqrt(2)m*time to run, assuming that static initialization data is used and is relatively cheap compared to whatever you're running.  Here are some examples with parameters chosen to take ~15s to run:Anyway, for the stated use case--where you are checking to make sure the order doesn't change--this is probably adequate, since you can play with the values a bit when setting up the test to make sure they give something sensible.  One could also create heuristics that search for stability, but that's probably overkill.(Incidentally, there is no explicit warmup step here; the robust fitting of the Theil-Sen estimator should make it unnecessary for sensibly large benchmarks.  This also is why I don't use any other benching framework; any statistics that it does just loses power from this test.)Edit again: if you replace the  method with the following:then you can get an estimate of the exponent when there's a log term also--error estimates exist to pick whether the log term or not is the correct way to go, but it's up to you to make the call (i.e. I'm assuming you'll be supervising this initially and reading the numbers that come off):(Edit: fixed the RMS computation so it's actually the mean, plus demonstrated that you only need to do timings once and can then try both fits.)I don't think your approach will work in general.The problem is that \"big O\" complexity is based on a limit as some scaling variable tends to infinity.  For smaller values of that variable, the performance behavior can appear to fit a different curve entirely.The problem is that with an empirical approach you can never know if the scaling variable is large enough for the limit to be apparent in the results.Another problem is that if you implement this in Java / Scala, you have to go to considerable lengths to eliminate distortions and \"noise\" in your timings due to things like JVM warmup (e.g. class loading, JIT compilation, heap resizing) and garbage collection.Finally, nobody is going to place much trust in empirical estimates of complexity.  Or at least, they wouldn't if they understood the mathematics of complexity analysis.In response to this comment:This is true, though my point is that you (Daniel) haven't factored this in.For simple cases, yes.For complicated cases and real world cases, that is a dubious assumption.  For example:If you are happy to estimate this empirically, you can measure how long it takes to do exponentially increasing numbers of operations.  Using the ratio you can get which function you estimate it to be.e.g. if the ratio of 1000 operations to 10000 operations (10x) is (test the longer one first)  You need to do a realistic number of operations to see what the order is for the range you have.Its is just an estimate as time complexity is intended for an ideal machine and something should can be mathematically proven rather than measures.e.g. Many people tried to prove empirically that PI is a fraction. When they measured the ratio of circumference to diameter for circles they had made it was always a fraction. Eventually, it was generally accepted that PI is not a fraction.What you are looking to achieve is impossible in general. Even the fact that an algorithm will ever stop cannot be proven in general case (see ). And even if it does stop on your data you still cannot deduce the complexity by running it. For instance, bubble sort has complexity O(n^2), while on already sorted data it performs as if it was O(n). There is no way to select \"appropriate\" data for an unknow algorithm to estimate its worst case.We have lately implemented a tool that does  for JVM code. You do not even have to have access to the sources. It is not published yet (still ironing out some usability flaws) but will be soon, I hope.It is based on . In short, byte code is augmented with cost counters. The target algorithm is then run (distributed, if you want) on a bunch of inputs whose distribution you control. The aggregated counters are extrapolated to functions using involved heuristics (method of least squares on crack, sort of). From those, more science leads to an estimate for the average runtime asymptotics (, for instance). For example, the method is able to reproduce rigorous classic analyses done by Knuth and Sedgewick with high precision.The big advantage of this method compared to what others post is that you are , that is in particular independent of machine, virtual machine and even programming language. You really get information about your algorithm, without all the noise.And---probably the killer feature---it comes with a complete GUI that guides you through the whole process.You can find a preliminary website (including a beta version of the tool and the papers published) .(Note that average runtime can be estimated that way while worst case runtime can never be, except in case you  the worst case. If you do, you can use the average case for worst case analysis; just feed the tool only worst case instances. In general, runtime bounds , though.)You should consider changing a critical aspects of your task.  Change the terminology that you are using to: \"estimate the runtime of the algorithm\" or \"setup performance regression testing\"Can you estimate the runtime of the algorithm?  Well you propose to try different input sizes and measure either some critical operation or the time it takes.  Then for the series of input sizes you plan to programmaticly estimate if the algorithm's runtime has no growth, constant growth, exponential growth etc.So you have two problems, running the tests, and programmatically estimating the growth rate as you input set grows.  This sounds like a reasonable task.  I'm not sure I get 100% what you want. But I understand that you test your own code, so you can modify it, e.g. inject observing statements. Otherwise you could use some form of aspect weaving?How about adding resetable counters to your data structures and then increase them each time a particular sub-function is invoked? You could make those counting  so they will be gone in the deployed library.Then for a given method, say , you would test that with all sorts of automatically generated data sets, trying to give them some skew, etc., and gather the counts. While as Igor points out you cannot verify that the data structure won't ever violate a big-O bound, you will at least be able to assert that in the actual experiment a given limit count is never exceeded (e.g. going down a node in a tree is never done more than  times) -- so you can detect some mistakes.Of course, you would need certain assumptions, e.g. that calling a method is O(1) in your computer model.This requirement is key. You want to detect outliers with minimal data (because testing should be , dammit), and in my experience fitting curves to numerical evaluations of complex recurrences, linear regression and the like will overfit. I think your initial idea is a good one.What I would do to implement it is prepare a list of expected complexity functions g1, g2, ..., and for data f, test how close to constant f/gi + gi/f is for each i. With a least squares cost function, this is just computing the  of that quantity for each i and reporting the smallest. Eyeball the variances at the end and manually inspect unusually poor fits.For an empiric analysis of the complexity of the program, what you would do is run (and time) the algorithm given 10, 50, 100, 500, 1000, etc input elements. You can then graph the results and determine the best-fit function order from the most common basic types: constant, logarithmic, linear, nlogn, quadratic, cubic, higher-polynomial, exponential. This is a normal part of load testing, which makes sure that the algorithm is first behaving as theorized, and second that it meets real-world performance expectations despite its theoretical complexity (a logarithmic-time algorithm in which each step takes 5 minutes is going to lose all but the absolute highest-cardinality tests to a quadratic-complexity algorithm in which each step is a few millis).EDIT: Breaking it down, the algorithm is very simple:Define a list, N, of various cardinalities for which you want to evaluate performance (10,100,1000,10000 etc)For each element X in N: Create a suitable set of test data that has X elements.Start a stopwatch, or determine and store the current system time.Run the algorithm over the X-element test set.Stop the stopwatch, or determine the system time again.The difference between start and stop times is your algorithm's run time over X elements.Repeat for each X in N.Plot the results; given X elements (x-axis), the algorithm takes T time (y-axis). The closest basic function governing the increase in T as X increases is your Big-Oh approximation. As was stated by Raphael, this approximation is exactly that, and will not get you very fine distinctions such as coefficients of N, that could make the difference between a N^2 algorithm and a 2N^2 algorithm (both are technically O(N^2) but given the same number of elements one will perform twice as fast)."},
Scala

Is there a  method in Groovy? I want to do something like I do with the following Scala snippet:there is such a method in groovy, it is called collect:\n"},
Scala

I've found myself stuck on a very trivial thing :-]I've got an enum:In a code I have to convert it conditionally to a number (varianr-number correspondence differs on context). I write:And this gives me an \"unreachable code\" compiler error for every branch but whatever is the first (\"case FOO => 4\" in this case). What am I doing wrong?I suspect the code you are actually using is not , but , lowercase, which will cause Scala to just assign the value to , instead of comparing the value to it.In other words:The following code works fine for me: it produces 6Could you say how this differs from your problem please?"},
Scala

Where I can learn how to construct the AST's that Scala's macros generate?The Scaladoc isn't as helpful as I'd like. For example:But how do I figure out what an Apply node is? Where can I find a list of the node types in AST's, and how they fit together?There isn't a lot of documentation for the internals of the compiler available, but the things that are available should be enough to get started., has written his . In Appendix D (p. 95) he describes the architecture of the AST. It includes also a graphical overview:Another way to find information about the AST is to look directly into the sources of , which contains the AST.If one needs to find out how a specific source code snippet is represented internally there is :You could take a look at the scaladoc () or at the slides (, the \"Learn to learn\" part).Here's what I usually do. I wrote a simple script called , which takes Scala code as an argument and then compiles it with  ( uses another helper script: .  to see its sources as well). The advantage this approach has over  is that it doesn't require the code to typecheck. You could write a small snippet of code, which refers to non-existent variables or classes, and it still will successfully run and show you the AST. Here's an example of output:There's also a script called , which does the same, but stops after . That's sometimes useful to understand how exactly the typechecker transforms the parser trees. However, both toolboxes and macros work with parser trees, so I use  for tree construction purposes very rarely."},
Scala

 says:I'd like to know exactly how and where Akka is used in Play, and what are the consequences of having Play build on top of Akka.In Play 2.0, Play delegated all requests to go through an actor.  It heavily depended on Akka's future API and other parts.In Play 2.1, with the move of Akka's future API into Scala 2.10, Play started depending less directly on Akka.  It gets all it's execution contexts from Akka, and provides integration with Akka, but that's about the extent of it.In Play 2.3, we're adding new features to aid Akka integration, particularly around WebSockets.In Play 2.4, Play will be ported to the new akka-http (formerly known as spray), at which point, Play will be as built on Akka as you can get.What are the consequences?  Akka provides a paradigm for programming that makes concurrency simple to deal with.  It also provides great abstractions for distributed programming - the hardest thing about distributed programming is dealing with failures (which happen all the time) appropriately.  Most tools try to address this by trying to hide failures from you, but unfortunately hiding something doesn't make it go away, and actually really makes things harder because when you try to address specific types of failures, the fact that they are hidden away from you gets in your way.  Akka pushes failures in your face, so that when you're coding, you are forced to think about how your application will respond to failures.  Consequently you're forced to design/code your application in such a way that it is tolerant to failures.  It also gives you the tools to deal with them in a hierarchical fashion, allowing you to specify at what level you want to handle what type of failure, and how the failure should be responded to (die, retry up to n times, etc).So how does this help Play?  The better question is how does it help a Play user?  Akka helps me to implement Play itself, but it's possible to implement it without Akka (in fact Netty does most of the heavy lifting now, that will change in Play 2.4).  The important thing is that Play seamlessly integrates with Akka, making it easy to handle HTTP requests with actors, handle failures etc, and this helps Play users because it allows them to design their application in such a way that it is scalable and resilient.UPDATE: The above was written 3 years ago, a lot has changed since then. Play 2.4 did provide experimental support for akka-http, but Play still by default uses Netty.In Play 2.5, we deprecated the iteratees API and switched to Akka streams. This meant that now all asynchronous IO was going through Akka streams. Soon (not sure if that will be Play 2.6 or later), Play will flick the switch to make akka-http the default backing implementation of the server (though not yet the WS client)."},
Scala

As you know, SBT is compatible with Maven in some way -- SBT recognizes simple Maven POMs and can use dependencies and repositories specified in them. However,  says that, if inline dependency is specified in SBT project definition, POM will be ignored (so using both in this case is impossible):Does anyone know, if any kind of converter from Maven POM to SBT project definition exists (translating POM's XML into project definition Scala code)? I'm considering writing such script (that will help to migrate my old Scala/Maven projects to SBT), but want to know first, if this functionality already exists.Converter is far too strong a term for this hack, but I wrote a script to take a block of  and output SBT style deps: All the tips above had the issue for me that properties were not resolved, and as we make heavy use of the dependencyManagement from parent poms, I was hoping for something that actually could fully understand maven.  I whipped together a simplistic scriptlet that outputs the dependencies from maven and just takes the top level items and then does a simple regex for the group, artifact, version, and scope (the artifact type is ignored)I piped this directly to project/build.sbt.  The sample output is (remember to keep empty spaces between sbt lines)I didn't manage to find an undocumented capability in SBT that allows to make such conversions (POM -> project definition), and have came up with writing  that creates  with repos/dependencies from .In case you just need to convert Maven/XML dependencies into SBT/Scala, you can use  provided by Not a converter, but a step-by-step guide for moving a multimodule project from Maven to SBT can be found .Quite nice for understanding what actually happens and ensuring you have a fair amount of control over the proces..I wrote  project for convertion java maven project to sbt project.Take a look a CodaHale's Maven-SBT project over at Git-Hub. Basically, CodaHale has swapped out IVY from SBT and replaced it with Maven, so POM related tasks  be be more compatible/flexible.I wrote yet another hack to convert between  and .  It's useful for converting the bulk of what I'm interested in.I just had the same problem and created a solution in javascript that you can access here:\n "},
Scala

I am building an app with SBT (0.11.0) using a Scala build definition like so:I'm packaging a .jar at the end of the process.My question is a simple one: is there a way of accessing the application's name (\"my-app-name\") and version (\"0.1\") programmatically from my Scala code? I don't want to repeat them in two places if I can help it.Any guidance greatly appreciated!I just wrote .\nAfter installing the plugin:Edit: The above snippet has been updated to reflect more recent version of sbt-buildinfo.It generates  object with any setting you want by customizing . (I wrote it) but here's a quick script to generate a file:You can get your version as .Name and version are inserted into manifest. You can access them using java reflection from  class."},
Scala

Scala seems to define 3 kinds of assertions: ,  and .As far as I can understand, the difference (compared to a generic assertion) of  is that it is specifically meant for checking inputs (arguments, incoming messages etc). And what's the meaning of  then?If you look at the code in  you'll see that all three do very similar job:There are also versions which take extra arguments for reporting purposes (see ).The difference is in the exception type they throw and error message they generate.However, static checkers could treat all three differently. The intention is for  to specify a condition that a static check should attempt to prove,  is to be used for a condition that the checker may assume to hold, while  specifies a condition that the caller must ensure. If a static checker finds a violation of  it considers it an error in the code, while when  is violated it assumes the caller is at fault.The difference between assert() and assume() is that The intended consumer / context of assert() is testing, such as a Scala JUnit test, while that of assume() is \"as a means of design-by-contract style specification of pre- and post-conditions on functions, with the intention that these specifications could be consumed by a static analysis tool\" (excerpted from the ).In the context of static analysis, as Adam Zalcman has pointed out, assert() is an all-execution-paths assertion, to check a global invariant, while assume() works locally to pare down the amount of checking that the analyzer needs to do. assume() is used in the context of assume-guarantee reasoning, which is a divide and conquer mechanism to help model checkers assume something about the method so as to tackle the state explosion problem that arises when one attempts to check all paths that the program may take. For example, if you knew that in the design of your program, a function f1(n1 : Int, n2:Int) is NEVER passed n2 < n1, then stating this assumption explicitly would help the analyzer not have to check a LOT of combinations of n1 and n2.In practice, since such whole-program model checkers are still mostly theory, let's look at what the scala compiler and interpreter does:More from the excellent scaladoc on this topic:A set of  functions are provided for use as a way to document and dynamically check invariants in code. assert statements can be elided at runtime by providing the command line argument  to the  command.Variants of  intended for use with static analysis tools are also provided: ,  and .  and ensuring are intended for use as a means of design-by-contract style specification of pre- and post-conditions on functions, with the intention that these specifications could be consumed by a static analysis tool. For instance,The declaration of addNaturals states that the list of integers passed should only contain natural numbers (i.e. non-negative), and that the result returned will also be natural. require is distinct from assert in that if the condition fails, then the caller of the function is to blame rather than a logical error having been made within addNaturals itself. ensures is a form of assert that declares the guarantee the function is providing with regards to it's return value.\n)I second Adams answer, here are just some small additions:When  is violated, the verification tool silently prunes the path, i.e. does not follow the path any deeper. Hence  is often used to formulate pre-conditions,  to formulate post-conditions.These concepts are used by many tools, e.g. the concolic testing tool , software bounded model checking tools like  and , and partly also by static code analysis tools based on abstract interpretation. The article  introduces these concepts and tries to standardize them. "},
Scala

I'm trying to get started with Scala and cannot get out of the starting gate.A file consisting of the linegives meRegardless of what x is and regardless of where I put the file (I had a theory that I had to place the file in a directory hierarchy to match the package definition, but no).  I get the same error with the example code from the web site and with the REPL.It looks like you're trying to declare the  membership in a Scala script (run using the  command) or in the REPL.Only files defining just classes and objects which are compiled with  may be defined as belonging to a package.When you run code in a script or a REPL session, behind the scenes it is actually compiled inside a method of an object, in which scope a package declaration wouldn't be legal.Since Scala 2.11.0-M7 you can use  (fix for issue ). This option allows defining packages in the REPL:I don't get this error. How are you compiling this? And, by the way, what web site? As for REPL, it doesn't accept packages. Packages are only for compiled code."},
Scala

Here is the only way I know to ask it at the moment.  As Understand it Scala uses the Java Virtual Machine.  I thought Jruby did also.  Twitter switched its middleware to Scala.   Could they have started with Jruby to start with and not had their scaling problems that caused them to move from Ruby to Scala in the first place?  Do I not understand what Jruby is?  I'm assuming that because Jruby can use Java it would have scaled where Ruby would not.Does it all boil down to the static versus dynamic types, in this case?Scala is \"scalable\" in the sense that the  can be improved upon by libraries in a way that makes the extensions look like they are part of the language. That's why actors looks like part of the language, or why BigInt looks like part of the language.This also applies to most other JVM languages. It does not apply to Java, because it has special treatment for it's basic types (Int, Boolean, etc), for operators, cumbersome syntax that makes clear what is built in the language and what is library, etc.Now, Scala is more performatic than dynamic languages  because the JVM has no support for them. Dynamic languages on JVM have to resort t reflection, which is very slow.No, not really.  It's not that the JVM is somehow magic and makes things scale by its magic powers; it's that Scala, as a language, is architected to help people write scalable systems.  That it's on top of the JVM is almost incidental.I don't really think that the language is the biggest problem here. Twitter grew insanely fast, which always leads to a code mess. And if you do a rewrite, it is a good idea to go for a different language - that bars you from building your own mistakes again and/or to \"reuse some parts\". Also, Ruby is not really meant for that kind of heavy data handling that the twitter backend does.\nThe frontend remains Ruby, so they still use it.You have to separate out different meanings of scaling:Scala helps on the first point because it compiles to Java bytecode that's really similar to Java, and therefore usually has the same performance as Java.  I say \"usually,\" because Scala there are some cases where idiomatic Scala causes large amount of boxing to take place where idiomatic Java would not (this is slated to change in Scala 2.8).Performance is of course different than scaling.  Equivalent code written in JRuby would scale just as well, but the slope of the line would be steeper - you'd need more hardware to handle the same number of requests, but the shape of the line would be the same.  But from a more practical perspective the performance helps because you rarely can scale in a perfectly linear fashion with respect to adding core or especially servers and having better performance slows the rate at which you have to add capacity.Scala helps with the second point because it has an expressive, compile-time enforced type system and it provides a lot of other means for managing the complexity of your code, such as mixins.  You can write spaghetti code in any language, but the Scala compiler will tell you when some of the noodles are broken while with JRuby you'll have to rely solely on tests.  I've personally found that for me Python breaks down at about 1000 closely related LOCs, and which point I have to refactor to either substantially reduce of the LOCs or make the structure more modular.  Of course this refactoring would be a good idea regardless of what your language, but occasionally the complexity is inherent.  Dealing with a large number of tightly couple LOCs isn't easy in any language, but it is much easier in Scala than it is in Python, and I think the analogy extends to Ruby/JRuby as well.Scala is a statically typed language. JRuby is dynamically typed. That is why Scala is faster than JRuby, even though both run on the JVM. JRuby has to do a lot of work at runtime (method resolution, etc.) that Scala does at compile-time. For what it's worth, though, JRuby is a very fast Ruby implementation.Scalability is not an inherit language capability. You are talking about speed.A better question to ask would be \"Why is Scala faster than other JVM languages (or is it)?\". As others have pointed out, it's a static vs. dynamic language thing.There's an interesting discussion from the Twitter developers themselves in the comments of . \nThey've evaluated the different options and decided to implement the back-end in Scala because: it ran faster than the Ruby/JRuby alternatives and they felt they could benefit from static typing."},
Scala

Is there an easy way to convert a    to a? In Scala 2.8 this became much much easier, and there are two ways to achieve it.  One that's sort of explicit (although it  implicits): Since I wrote this, the Scala community has arrived at a broad consensus that  is good, and  is bad, because of the potential for spooky-action-at-a-distance.  So don't use  at all!Yes use  conversions:Which can then be easily implemented:"},
Scala

Is it possible and what would be the most efficient neat method to add a column to Data Frame? More specifically, column may serve as Row IDs for the existing Data Frame.In a simplified case, reading from file and not tokenizing it, I can think of something as below (in Scala), but it completes with errors (at line 3), and anyways doesn't look like the best route possible: It's been a while since I posted the question and it seems that some other people would like to get an answer as well. Below is what I found.So the original task was to append a column with row identificators (basically, a sequence ) to any given data frame, so the rows order/presence can be tracked (e.g. when you sample). This can be achieved by something along these lines:The \"closest\" to this functionality in Spark API are  and . According to , the former . In my opinion, this is a bit confusing and incomplete definition. Both of these functions can operate on  data frame only, i.e. given two data frames  and  with column :So unless you can manage to transform a column in an existing dataframe to the shape you need, you can't use  or  for appending arbitrary columns (standalone or other data frames).As it was commented above, the workaround solution may be to use a  - this would be pretty messy, although possible - attaching the unique keys like above with  to both data frames or columns might work. Although efficiency is ...It's clear that appending a column to the data frame is not an easy functionality for distributed environment and there may not be very efficient, neat method for that at all. But I think that it's still very important to have this core functionality available, even with performance warnings.not sure if it works in spark 1.3 but in spark 1.5 I use withColumn:I use this when I need to use a value that is not related to existing columns of the dataframeThis is similar to @NehaM's answer but simplerI took help from above answer. However, I find it incomplete if we want to change a  and current APIs are little different in . \n returns a  of  which contains each row and corresponding index. We can use it to create new  according to our need. I hope this will be helpful."},
Scala

I'm kinda new to Scala trying it out while reading Beggining Scala by David Pollack.\nHe defines a simple recursive function that loads all strings from the file:It's elegant and awesome except that it had thrown a StackOverflow exception when I tried to load a huge dictionary file.Now as far as I understand Scala supports tail recursion, so that function call couldn't possibly overflow the stack, probably compiler doesn't recognize it? So after some googling I tried @tailrec annotation to help the compiler out, but it saidAm I understanding tail recursion wrong? How do I fix this code?Scala can only optimise this if the last call is a call to the method itself.Well, the last call is not to , it's actually to the  (cons) method.A way to make this tail recursive is to add an accumulator parameter, for example:To prevent the accumulator leaking into the API, you can define the tail recursive method as a nested method:It's not tail recursive (and can't ever be) because the final operation is not a recursive call to , it's a call to the  method.The safest way to resolve this is with a nested method that uses an accumulator:In this particular case, you could also lift the accumulator to a parameter on , give it a default value of , and avoid the need for an inner method.  But that's not always possible, and it can't be called nicely from Java code if you're concerned about interop."},
Scala

Specifically I'm looking at Problem 1 hereThe code as listed is as followsI can follow everything except for \"view\".  In fact if I take out view the code still compiles and produces exactly the same answer.View produces a lazy collection, so that calls to e.g.  do not evaluate every element of the collection. Elements are only evaluated once they are explicitly accessed. Now  does access all elements, but with  the call to  doesn't create a full Vector. (See comment by Steve)A good example of the use of view would be:Here Scala tries to create a collection with  elements to then access the first 10. But with view:I don't know much about Scala, but perhaps  might help...So it sounds as if the code will still work without , but might in theory be doing some extra work constructing all the elements of your collection in  rather than  fashion. "},
Scala

When I try to compile any class in my project I get the error below:I've seen how to set the output path in IDEA and I've done it. But as the error claims that it is shared between the same module I couldn't solve it.Obs.: Using Maven and IntelliJ IDEA.Please, can anyone help?all you need to do is:EnjoySet up the output paths for your modules to different directories, as explained here: I resolved this by selecting \"Inherit project compile output path\" in the Project Structure settings window.I had this happen with the root module in a multi-module project. Since the root module was just a placeholder, it didn't actually contain any code, but IDEA still complained that it was sharing an output path () between test and production.The fix was to addat the top of the root  file (applying the otherwise unnecessary Java plugin) and reimporting the project. This allowed IDEA to pick up the Java-default  and  output directories.Open up the module settings and look for errors. Fix said errors and everything should work.Problem solved!I have reset backward and forward my git repository many times and close-reopen idea after some of it. When finaly IDEA shows a red message at the right top while it was starting. It says something like: the project has already a eval module, and if I want to delete eval module. Yes, it was quite confusing, but I click on delete and my problem disappear. I guess that for some reason I become with 2 eval modules and it delete one of it solving output path error."},
Scala

 is used to preserve insertion order in the map, but this only works for mutable maps. Which is the immutable  implementation that preserves insertion order? implements an immutable map using a list-based data structure, and thus preserves insertion order.The following extension method -  can be quite useful when working with s.While  will preserve insertion order, it is not very efficient - e.g. lookup time is linear. I suggest you create a new collection class which wraps both the  and the . The immutable map should be parametrized as , where the  in the tuple gives you the pointer to the corresponding entry in the . You then keep an entry counter on the side. This tree map will sort the entries according to the insertion order.You implement insertion and lookup in the straightforward way - increment the counter, insert into the hash map and insert to the the counter-key pair into the treemap. You use the hash map for the lookup.You implement iteration by using the tree map.To implement remove, you have to remove the key-value pair from the hash map and use the index from the tuple to remove the corresponding entry from the tree map."},
Scala

I am trying to use IntelliJ with a play framework 2.11 application.I installed the Play Framework 2 plugin and the Scala plugin for IntelliJ.I created a Play application.  I have been struggling writing and running Specs 2 tests in IntelliJ.  My run config says to run \"make\" first when running the Specs 2 test, however it doesn't look like my test classes are being generated.  Keeps on telling me that it could not find the specification.  When I look on the file system, there is no code in target/test-classes, the directory is empty.  Further, it seems to take a LONG time to do the build, at least compared to running the Play console.I wanted to see how people are using Play with IntelliJ.  Do you just use IntelliJ as an editor, and run everything through the Play console?Is there a way whereby you can run your Application tests in IntelliJ (getting your test classes to run)?I have never had any problem running the Play console and running ~test-only test=xxx.Spec.  It has typically been rather fast.Here is the exception I am getting in IntelliJ when I try to run my Specs2 tests:: In newer versions if IntelliJ IDEA, it is no longer necessary to create the module from play/activator. IntelliJ IDEA has now a really good support for SBT projects. If exists, delete all the idea related directories inside your project. Then in IntelliJ IDEA click File -> Open and choose your build.sbt file. That's all.IntelliJ IDEA has a good integration for the Play Framework 2. Sometimes it jams, but most of the time it runs. I use it to run(single, all) tests, start or debug the play application and edit my code (o; And this all from within the IDE and without the sbt console.Here is a short tutorial with the most important steps. Currently I use IntelliJ IDEA 12.1 with the newest Play Framework 2 and Scala plugins.Start the play console:Create the module:Select the  under the test directory and click  from the context menu. You should get an error that the compiled template could not be found. This is because the IDE doesn't compile the templates, but this can be done by run the application once. Also follow point 5 and then run the test again.Select a controller and click  from context menu. This should start the application on address: .If you update your application dependencies then you must tell the IDE about this changes. Also after running the  command you must close the IDE and remove some files from project directory. If you execute the  command before removing the files, you get double dependencies in your play project.Execute the following steps to update your dependencies:Play console includes a fork of a sbt plugin named . The play's fork got a little lagged behind the original plugin, and has some problems in IntelliJ when you run . You can use the original plugin, which doesn't have any issues. In order to use this plugin in your play project, you need to..1.Add the following lines to  file: (the blank line in the middle is required)2.Run  from the play console.I usually used IntellijIDEA (version 12.0.4) only for Play Framework code editor because of: And I usually run and debug the apps with Play SBT console. It's reasonable fast. But, sometimes when executing  command on console, I found that the  task take too long time (nearly 10 minutes). I don't know why this sometimes happen, but overall the use of Play SBT console is my choice.I'm doing that because there is usually  intepreted as  like following :The first time when I start learning Play Framework, I was facing such problem. So, at the end, I choose to use Play SBT console to run and debugging app then.And sorry I cannot answer for the question number 2. Until now I only tried running and debugging play application. For testing purpose I've never tried before for Play 2.x. "},
Scala

I want to do the following, but the self-type line just doesn't compile. Do I have this syntax wrong or is this just impossible?You can have a single self-type which is a compound type.Try this:With  you can do it with :Reflection used.But, firstly you should not overuse self-types because of . Methods from question can be added simply by extending other tait:or type both methods explicitly:Self-types are usually used with classes. This is a good way for trait to require being a subclass of a desired class.There is also one good use of self-type with triats: when you want to manipulate order of class initialization with multi-inheritance."},
Scala

I just started exploring Scala in my free time. I have to say that so far I'm very impressed. Scala sits on top of the JVM, seamlessly integrates with existing Java code and has many features that Java doesn't. Beyond learning a new language, what's the downside to switching over to Scala?Well, the downside is that you have to be prepared for Scala to be a bit rough around the edges: You also have to take some risk that Scala as a language will fizzle out.That said, ! My experiences are positive overall; the IDE's are useable, you get used to what the cryptic compiler errors mean and, whilst your Scala codebase is small, a backwards-compatibility break is not a major hassle.It's worth it for , the  functionality of the collections, , the  model, extractors, covariant types etc. It's an awesome language.It's also of great  benefit to be able to approach problems from a different angle, something that the above constructs allow and encourage.Some of the downsides of Scala are not related at all to the relative youth of the language. After all, Scala, has about 5 years of age, and Java was very different 5 years into its own lifespan.In particular, because Scala does not have the backing of an enterprise which considers it a strategic priority, the support resources for it are rather lacking. For example:Another important difference is due to how Sun saw Java and  sees Scala. Sun saw Java as a product to get enterprise customers. EPFL sees Scala as a language intended to be a better language than existing ones, in some particular respects (OOxFunctional integration, and type system design, mostly).As a consequence, where Sun made JVM glacially-stable, and Java fully backward compatible, with very slow deprecation and removal of features (actually, removal?), JAR files generated with one version of Scala won't work at all with other versions (a serious problem for third party libraries), and the language is constantly getting new features as well as actually removing deprecated ones, and so is Scala's library. The revision history for Scala 2.x, which I think is barely 3 years old, is impressive.Finally, because of all of the above, third party support for Scala is . But it's important to note, though, that , which makes  out of selling the  IDE, has supported Scala for quite some time, and keeps improving its support. That means, to me, that there is demand for third party support, and support is bound to increase.I point to the book situation. One year ago there was no Scala book on the market. Right now there are two or three introductory Scala books , about the same number of books should be out before the end of the year, and there is a book about a very important web framework based on Scala, .I bet we'll see a book about  not too far in the future, as well as books about Scala and concurrency. The publishing market has apparently reached the tipping point. Once that happens, enterprises will follow.I was unshackled from the J2EE leash last year wanted to do something new after 12 years of Java in the enterprise building very large system for some of the worlds biggest companies.I had tried Ruby on Rails in the past. After building a few sample apps I did not like the feel of it or the fact that I would have to write a ton of unit tests to cover stuff that is normally done by a compiler. Groovy on Grails was my next port of call. I have to say I do like this but it suffers from the same dynamic typing problems as ROR. Don't get me wrong I am not putting Grails down as it is an excellent framework and I will still use it. Each has its own place IMO. I then jumped on Scala and have now built a hybrid application based on Scala and Spring MVC. At first working with Scala is difficult but it gets easier and more productive the more time you put into it. I've reached a tipping point where I now want to invest time in Lift as well. The combination of \"Programming in Scala\" and David Pollak's \"Beginning Scala\" books is good for learning the language, the latter with a less academic bent. Scala is still young and has some way to go. I think it has a bright future and I see momentum is already picking up. Recently one of the creators of the Groovy language said in a blog post he would never have bothered designing Groovy if Scala had been around at the time.  I think some more work on better Java API integration/wrapping will give Scala the boost it needs to win more followers. The basic integration is there already but I think its could be polished a bit more. Yes IDE support is there but it is basic at the moment. The powerfully refactoring support of Intellij is not there yet and I miss that a lot. The compiler + IDE support with a mix of of other plugins is not mature yet. I sometimes get very weird internal compiler errors  caused by how Scala sits with JDO enhancement for the Goggle app engine. However these are little things that can be easily fixed. Early adaptation of new technologies and languages always comes with a little pain. But this bit of pain can produce great pleasure in the future.If I look at the capabilities of Scala compared to early Java its miles ahead. When I moved from C++ to Java the JVM was not ready yet regarding scalability. There used to be lots of weird crash and burn JVM core dumps on various OSes. All of this has now been fixed in Java and the JVM is rock solid. Scals runs in the JVM so it has been given a massive head start on native platform integration. Its standing on the shoulders of giants! After years of building and supporting enterprise applications my vote is for a language where a compiler can catch most of the non functional bugs before even unit tests are built. I love the type checking mixed with the power of functional programming. I like the fact that I am doing OO++. I think the development community will decide if Scala is the future or not. The downside of  adopting Scala now would be if it did not pick up momentum and adaptation. It would be very difficult to maintain an Scala code base with very few Scala developers around.  However I watched Java come from the skunk works into the enterprise to replace C++ and it was all pushed from the bottom up by the developer community. Time will tell for Scala but currently it has my vote. I'll tell you my little personal experience, and how I found that it wasn't so easy to integrate Scala with existing Java libraries:I wanted to get started with something easy, and as I thought that Scala was very well suited for scientific computation I wanted to do a little wrapper around JAMA (Java Matrix library)... My initial approach was to extend the Matrix type with a Scala class and then overload the arithmetic operators and call the Java native methods, but:I think I could have used an empty primary constructor that initialized the superclass with some default values (for example, a [[0]]), or just make an adapter class that used the Jama.Matrix as a delegate, but if a language is supposed to be elegant and seamless integrated with another, that kind of things shouldn't happen.Those are my two cents.I don't think there are any downsides.  Actually learning new language is very helpful for broadening your programming knowledge. You might gain from Scala such things as generic classes, variance annotations, upper and lower type bounds, inner classes and abstract types as object members, compound types, explicitly typed self references, views, and polymorphic methods. It consistently breaks backwards compatibilty.\nCommunity size is small.\nIDE support isn't there yet.Otherwise its fine.\nIt is just a young language, it will get there eventually.\nGreat for hobbyists, not ready for enterprise.The two, by which I mean four, biggest downsides I'm seeing are:"},
Scala

I want to iterate over a list of values using a beautiful one-liner in Scala.For example, this one works well:But if I use the placeholder , it gives me an error:Why is that? Can't compiler infer type here?This:is equivalent to this:There's no indication as to what might be the type of , and, to be honest, it doesn't make any sense to print a function.You obviously (to me) meant to print , where  would the the parameter passed by , instead. But, let's consider this...  takes, as a parameter, a , where  is the type parameter of the list. What you are passing to  instead is , which is an expression that returns .If you wrote, instead , you'd be passing a completely different thing. You'd be passing the function(*) , which takes  and returns , fitting, therefore, the requirements of .This gets slightly confused because of the rules of expansion of . It expands to the innermost expression delimiter (parenthesis or curly braces), except if they are in place of a parameter, in which case it means a different thing: partial function application.To explain this better, look at these examples:Here, we applies the second and third arguments to , and returned a function requiring just the remaining argument. Note that it only worked as is because I indicated the type of , otherwise I'd have to indicate the type of the argument I was not applying. Let's continue:Let discuss  in more detail, because this is a very important point. Recall that  is a function , right? So, if I were to type , would that make any sense? That's what was done in .What confuses people is that what they really wanted was:In other words, they want the  replacing  to jump to  the parenthesis, and to the proper place. The problem here is that, while it may seem obvious to them what the proper place is, it is not obvious to the compiler. Consider this example, for instance:Now, if we were to expand this to outside the parenthesis, we would get this:Which is definitely not what we want. Now, back to the confusion between anonymous function and partial application, look here:The first line doesn't work because of how operation notation works. Scala just sees that  returns , which is not what expects.The second line works because the parenthesis let Scala evaluate  as a whole. It is a partial function application, so it returns , which is acceptable.The third line doesn't work because  is anonymous function, which you are passing as a parameter to . You are  making  part of an anonymous function, which is what you wanted.Finally, what few people expect:This works. Why it does is left as an exercise to the reader. :-)(*) Actually,  is a method. When you write , you are not passing a method, because methods can't be passed. Instead, Scala creates a closure and passes it. It expands like this: The underscore is a bit tricky.  According to the spec, the phrase:is equivalent toTryingyields:If you add some types in:The problem is that you are passing an anonymous function to  and it's not able to deal with it.  What you really want to do (if you are trying to print the successor to each item in the list) is:There is a strange limitation in Scala for the nesting depth of expressions with underscore. It's well seen on the following example:Looks like a bug for me."},
Scala

In , the author said:Why is a  object more object-oriented? What's the good of not using static members, but singleton objects?Trying for the \"big picture\";  most of this has been covered in other answers, but there doesn't seem to be a single comprehensive reply that puts it all together and joins the dots.  So here goes...Static methods on a class are not methods on an object, this means that:The whole point of objects is that they can inherit from parent objects, implement interfaces, and be passed as arguments - static members have none of these properties, so they aren't truly object-oriented, they're little more than a namespace.Singleton objects, on the other hand, are fully-fledged members of the object community.Another very useful property of singletons is that they can easily be changed at some later point in time to not be singletons, this is a particularly painful refactoring if you start from static methods.Imagine you designed a program for printing addresses and represented interactions with the printer via static methods on some class, then later you want to be able to add a second printer and allow the user to chose which one they'll use...  It wouldn't be a fun experience!Singleton objects behave like classes in that they can extend/implement other types.Can't do that in Java with just static classes -- it's  over the  with a  that allows (at least) nicer namespaces/stable identifiers and hides the distinction.Hint: it's called -oriented programming.Seriously.Maybe I am missing something fundamentally important, but I don't see what the fuss is all about: objects are more object-oriented than non-objects because they are objects. Does that really need an explanation?Note: Although it sure sounds that way, I am really  trying to sound smug here. I have looked at all the other answers and I found them terribly confusing. To me, it's kind of obvious that objects and methods are more object-oriented than namespaces and procedures (which is what static \"methods\" really are) by the very  of \"object-oriented\".An alternative to having singleton objects would be to make classes themselves objects, as e.g. Ruby, Python, Smalltalk, Newspeak do.For static members, there is no . The class really just is a namespace.In a singleton, there is always at least  object.In all honesty, it's splitting hairs.It's more object oriented in the sense that given a Scala class, every method call is a method call on that object. In Java, the static methods don't interact with the object state.In fact, given an object  of a class  with the static method , it's considered bad practice to call . Instead it's recommended to call  (I believe Eclipse will give you a warning). Java static methods can't be overridden, they can just be hidden by another method:What will  print? In Scala, you would stick the static methods in companion objects A and B and the intent would be clearer as you would refer explicitly to the companion A or B.Adding the same example in Scala:There is some difference that may be important in some scenarios. In Java you \n so if you had class with static methods you would not be able to customize and override part of its behavior. If you used singleton object, you could just plug singleton created from subclass.It's a marketing thing, really.  Consider two examples:Now, what are the observable differences here?It reminds me of the religious wars 20 years ago over whether C++ or Java were \"really\" Object Oriented, since after all both exposed primitive types that aren't \"really\" objects -- so, for example you can't inherit from  but can from ."},
Scala

In java exceptions have at least these four constructors:If you want to define your own extensions, you just have to declare a descendent exceptions and implement each desired constructor calling the corresponden super constructorHow can you achieve the same thing in scala?so far now I saw  and this , but I suspect there must be an easier way to achieve such a common thingDefault value for  is null. And for  it is either  or null:So you can just use default values:well, this is the best I've found so farthis way you may use the \"new MissingConfigurationException\" or the apply method from the companion objectAnyway, I'm still surprised that there isn't a simpler way to achieve itYou can use .To me, it appears there are three different needs which have a dynamic tension with each other:If one doesn't care about number 3, then  (a peer to this one) seems pretty succinct.However, if one values number 3 while trying to get as close to number 1 and 2 as possible, the solution below effectively encapsulates the Java  leak into your Scala API.And if you would like to eliminate having to use  where  is actually used, add this companion object (which just forwards all of the apply calls to the existing \"master\" class constructor):Personally, I prefer to actually suppress the use of the  operator in as much code as possible so as to ease possible future refactorings. It is especially helpful if said refactoring happens to strongly to the Factory pattern. My final result, while more verbose, should be quite nice for clients to use.  It's only a small leap from the original question to desire to create an ecosystem of specialized s for a package or API. The idea is to define a \"root\"  from which a new ecosystem of specific descendant exceptions can be created. For me, it was important to make using  and  much easier to exploit for specific types of errors.For example, I have a  method defined which verifies a set of conditions prior to allowing a case class to be created. Each condition that fails generates a  instance. And then the List of s are returned by the method. This gives the client the ability to decide how they would like to handle the response;  the list holding exception, scan the list for something specific and  that or just push the entire thing up the call chain without engaging the very expensive JVM  command.This particular problem space has three different descendants of , one abstract () and two concrete ( and ).The first, , is a direct descendant to , very similar to , and is abstract (to prevent direct instantiations).  has a \"companion object trait\",  which acts as the instantiation factory (suppressing the  operator).The second, , is an indirect  descendant and a direct concrete implementation of . It defines both a companion object and a class. The companion object extends the trait . And the class simply extends the abstract class  and marks it  to prevent any further extensions.The third, , is a direct descendant to  which wraps a  of s and then dynamically manages the emitting of the exception message.And then bringing all of that together as a whole and tidy things up, I place both  and  within object . And this is what the final result looks like:And this is what it would look like for a client to use the above code to create their own exception derivation called :And then the use of this exception looks like this:I went well beyond answering the original question because I found it so difficult to locate anything close to being both specific and comprehensive in Scala-ifying  in specific or extending into the more general \"exception ecosystem\" with which I grew so comfortable when in Java.I'd love to hear feedback (other than variations on, \"Wow! That's way too verbose for me.\") on my solution set. And I would love any additional optimizations or ways to reduce the verbosity WITHOUT LOSING any of the value or terseness I have generated for the clients of this pattern.Scala pattern matching in try/catch blocks works on interfaces. My solution is to use an interface for the exception name then use separate class instances.Instantiating MyClass will output \"oops\".Here is a similar approach to the one of @roman-borisov but more typesafe.\nThen, you can create Exceptions in the Java manner:"},
Scala

I'm following the tutorial  on Scala  and  methods. There's such an example:When I try to use it I get an error:However, this works:or even What's wrong with the code in the tutorial? Isn't the latter expression the same as the first one without parenthesis? is a method.  method is defined on functions.  converts  from method to function, so  can be called on it.  expects a function as it's argument. You are giving it a method  by converting  into a function with  (The underscore can be left out because the compiler can automatically convert a method into a function when it knows that a function is expected anyway). So your code:is the same asbut notPS\nI didn't look at the link you provided.Well, this:is an eta expansion. It converts methods into functions. On the other hand, this:is an anonymous function. In fact, it is a partial function application, in that this parameter is not applied, and the whole thing converted into a function. It expands to:The exact rules for expansion are a bit difficult to explain, but, basically, the function will \"start\" at the innermost expression delimiter. The exception is partial function applications, where the \"x\" is moved outside the function -- if  is used in place of a parameter.Anyway, this is how it expands:Alas, the type inferencer doesn't know the type of x or y. If you wish, you can see exactly what it tried using the parameter .From  documentation: so you should writeto treat  and  as partially applied functions (i.e )I believe the tutorial was written for an earlier version of Scala (probably 2.7.7 or earlier). There have been some changes in the compiler since then, namely, extensions to the type system, which now cause the type inferencing to fail on the:The lifting to a function still works with that syntax if you just write:"},
Scala

What are the key differences between the approaches taken by Scala and F# to unify OO and FP paradigms?What are the relative merits and demerits of each approach? If, in spite of the support for subtyping, F# can infer the types of function arguments then why can't Scala?I have looked at F#, doing low level tutorials, so my knowledge of it is very limited. However, it was apparent to me that its style was essentially functional, with OO being more like an add on -- much more of an ADT + module system than true OO. The feeling I get can be best described as if all methods in it were static (as in Java static).See, for instance, any code using the pipe operator (). Take this snippet from the :The function  is not a method of the list instance. Instead, it works like a static method on a  module which takes a list instance as one of its parameters.Scala, on the other hand, is fully OO. Let's start, first, with the Scala equivalent of that code:Here,  is a method on the instance of . Static-like methods, such as  on  or  on , are much more uncommon. Then there are functions, such as  above. Here,  is not a method on , but neither it is a static method. Instead, it is an  -- the second main difference I see between F# and Scala.Let's consider the F# implementation from the Wikipedia, and an equivalent Scala implementation:The above Scala implementation is a method, but Scala converts that into a function to be able to pass it to . I'll modify it below so that it becomes a method that returns a function instead, to show how functions work in Scala.So, in Scala, all functions are objects implementing the trait , which defines a method called . As shown here and in the list creation above,  can be omitted, which makes function calls look just like method calls.In the end, everything in Scala is an object -- and instance of a class -- and every such object does belong to a class, and all code belong to a method, which gets executed somehow. Even  in the example above  a method, but has been converted into a keyword to avoid some problems quite a while ago.So, how about the functional part of it? F# belongs to one of the most traditional families of functional languages. While it doesn't have some features some people think are important for functional languages, the fact is that F# is function by , so to speak.Scala, on the other hand, was created with the intent of  functional and OO models, instead of just providing them as separate parts of the language. The extent to which it was succesful depends on what you deem to be functional programming. Here are some of the things that were focused on by Martin Odersky:In my opinion, Scala is unparalled in combining FP and OO. It comes from the OO side of the spectrum towards the FP side, which is unusual. Mostly, I see FP languages with OO tackled on it -- and it  tackled on it to me. I guess FP on Scala probably feels the same way for functional languages programmers.Reading some other answers I realized there was another important topic: type inference. Lisp was a dynamically typed language, and that pretty much set the expectations for functional languages. The modern statically typed functional languages all have strong type inference systems, most often the  algorithm, which makes type declarations essentially optional.Scala can't use the Hindley-Milner algorithm because of Scala's support for . So Scala has to adopt a much less powerful type inference algorithm -- in fact, type inference in Scala is intentionally undefined in the specification, and subject of on-going improvements (it's improvement is one of the biggest features of the upcoming 2.8 version of Scala, for instance).In the end, however, Scala requires all parameters to have their types declared when defining methods. In some situations, such as recursion, return types for methods also have to be declared.Functions in Scala can often have their types  instead of declared, though. For instance, no type declaration is necessary here: , where  is actually an anonymous function of type . Likewise, type declaration of variables is often unnecessary, but inheritance may require it. For instance,  and  have a common superclass , but actually belong to different subclases. So one would usually declare  to make sure the correct type is assigned.This limited form of type inference is much better than statically typed OO languages usually offer, which gives Scala a sense of lightness, and much worse than statically typed FP languages usually offer, which gives Scala a sense of heavyness. :-)Notes: is functional - It  OO pretty well, but the design and philosophy is functional nevertheless. Examples:It feels relatively clumsy to use F# in a mainly object-oriented way, so one could describe the main goal as to . is multi-paradigm with focus on flexibility. You can choose between authentic FP, OOP and procedural style depending on what currently fits best. It's really about .There are quite a few points that you can use for comparing the two (or three). First, here are some notable points that I can think of:The key difference is that Scala tries to blend the paradigms by making sacrifices (usually on the FP side) whereas F# (and OCaml) generally draw a line between the paradigms and let the programmer choose between them for each task.Scala had to make sacrifices in order to unify the paradigms. For example:Another consequence of this is that F# is based upon tried and tested ideas whereas Scala is pioneering in this respect. This is ideal for the motivations behind the projects: F# is a commercial product and Scala is programming language research.As an aside, Scala also sacrificed other core features of FP such as tail-call optimization for pragmatic reasons due to limitations of their VM of choice (the JVM). This also makes Scala much more OOP than FP. Note that there is a project to bring Scala to .NET that will use the CLR to do genuine TCO.Type inference is at odds with OO-centric features like overloading and subtypes. F# chose type inference over consistency with respect to overloading. Scala chose ubiquitous overloading and subtypes over type inference. This makes F# more like OCaml and Scala more like C#. In particular, Scala is no more a functional programming language than C# is.Which is better is entirely subjective, of course, but I personally much prefer the tremendous brevity and clarity that comes from powerful type inference in the general case. OCaml is a wonderful language but one pain point was the lack of operator overloading that required programmers to use  for ints,  for floats,  for rationals and so on. Once again, F# chooses pragmatism over obsession by sacrificing type inference for overloading specifically in the context of numerics, not only on arithmetic operators but also on arithmetic functions such as . Every corner of the F# language is the result of carefully chosen pragmatic trade-offs like this. Despite the resulting inconsistencies, I believe this makes F# far more useful.From  article on Programming Languages:From the above excerpt it is clear that Scala's approach to unify OO and FP paradigms is far more superior to that of OCaml or F#.HTH.Regards,\nEric.The syntax of F# was taken from OCaml but the object model of F# was taken from .NET. This gives F# a light and terse syntax that is characteristic of functional programming languages and at the same time allows F# to interoperate with the existing .NET languages and .NET libraries very smoothly through its object model.Scala does a similar job on the JVM that F# does on the CLR. However Scala has chosen to adopt a more Java-like syntax. This may assist in its adoption by object-oriented programmers but to a functional programmer it can feel a bit heavy. Its object model is similar to Java's allowing for seamless interoperation with Java but has some interesting differences such as support for traits.If functional programming means programming with , then Scala bends that a bit.  In Scala, if I understand correctly, you're programming with  instead of functions.When the class (and the object of that class) behind the method don't matter, Scala will let you  it's just a function.  Perhaps a Scala language lawyer can elaborate on this distinction (if it even is a distinction), and any consequences."},
Scala

I'm very new to Scala. I have downloaded it, got it working in Eclipse where I'll be developing it; but I can't make it work in Terminal.All sites and books say to just type  - this doesn't work.The  infuriatingly says:I'm very new to this, and using Jargon or assuming too much knowledge of frameworks around Scala will ruin a good response; please keep it simple.Thank youFor OS X, I highly recommend .The  is incredibly easy.  Once installed, you just need to run  and scala will be installed and ready to go.  Homebrew also has tons of other goodies just a  away.If you don't already have Java installed, you can install that with . or  may have something similar, but I prefer Homebrew.Not a big fan of cluttering up my  variable. I just symlink all my programs to /usr/local/bin, which is in the classpath. For example, if you downloaded scala and uncompress it in /opt/scala-2.9.0-1, run the following in the terminal.Now just type  in the terminal and you're all set.\nThis way you don't have to set your  or change it when you have a new version of scala you want to try out. If you download a new version, you can uncompress it in any location and symlink the new version. Say you download version 2.9.1 and uncompress it in /opt/scala-2.9.1. You can type the following in the terminalNow, to use scala 2.9.1 you just run  at the terminal.\nWhen you are ready to switch to 2.9.1 fulltime, just update the symlink.You could also add scaladoc, scalac, scalap and others in the same wayYou need to add  to your  environment variable.On Mac OS X the path to Scala bin is usually:  and on Windows usually: .On Mac OS X use the Terminal and write (using your username):then close the Terminal and start it again.Scala recommends using Homebrew to install the Typesafe stack for Scala 2.9.2.Homebrew will install soft links in  for , , , , ,  and . Follow the soft links to its final referent in order to determine where $SCALA_HOME needs to be. $SCALA_HOME should contain  and .Typesafe recommends using  instead of  to get the interpreter going, because  will also manage library dependencies to libraries such as Akka. That said, if you want to use , , ,  and  directly, you may need to run a  on the referents of the soft links.If you don't want to add more directories to your path, try these steps:My way of making Scala run every time you type \"scala\" in Terminal was to add the path not to the .bashrc file but to the /etc/paths one.I hope this helps.If you downloaded scala with macports try typing scala-2.9 (or whatever is the filename of the contents of folder /opt/local/bin/scala/)(At least this works for OSX mountain lion)"},
Scala

I would like to convert a  to a  or a .  Is there an easy way to do it?Assuming you're using immutable mapsThe  companion object's apply method takes repeated map entry parameters (which are instances of  of the appropriate parameter types).  produces an  (in this particular case). The  tells the compiler that the array's contents are to be treated as repeated parameters.An alternative to using  as described by sblundy is to append the existing map to an empty Here's a general way to convert between various Scala collections.See also this question describing : Is it possible to adjust the implicits such that this works? Or would this only be possible if  were added to ?Here's a way you can do it with a Scala implicit class:Since Map[A,B] has an implicit path to a TraversableOnce[Tuple2[A, B]], the following works:It will even work on a list of Tuple2s, similar to toMap:Since internal data structures in implementations are completely different, you'll have to add elements one-by-one anyway. So, do it explicitly:"},
Scala

After years of working OK, I'm suddenly getting this message when trying to start the JVM:I tried uninstalling, and got a message saying a DLL was missing (unspecified)\nTried re-installing, all to no avail.At the same time, when trying to start Scala I get:Checked  and  - both OKCan anyone help?Might be a slightly different cause, but that second issue occurs for me in scala 2.9.0.1 on Win7 (x64), though scala-2.9.1.final has already resolved this issue mentioned here:My  set to a path like this: Note the space and the parentheses.If you change line 24 in  from:toIt works fine. Note the quotes around the set command parameters, this will properly enclose any spaces and 'special' characters (eg: spaces and parentheses) in the variable's value.Hope this helps someone else searching for an answer.I checked my environment variables - JAVA_HOME & PATH and they all refer to c:\\java. So this was bit frustrating. After sometime I found that the default installation also copied java.exe, javaw.exe and javaws.exe to C:\\Windows\\System32 (i.e. uninstall of JRE didnt went well). I just removed them and voila, I'm back on track. That annoying error is no longer popping.This works for meput  %JAVA_HOME%\\bin   at the begin of PATH.I had the same problem: I have a 64 bit Windows and when I typed \"java -version\" in CMD-Console i received the same Error message.\nTry to start a 64bit-cmd(C:\\Windows\\SysWOW64\\cmd.exe) and you will see, it works there ;)If this was working before, it means the  isn't correct anymore.That can happen when the  becomes too long and gets truncated.\nAll posts (like ) suggest , which you can test first in a separate DOS session, by setting a minimal path and see if java works again there.Finally the  concludes:scary ;)I thought I will share how I resolved the same issue \"Error Could not open lib\\amd64\\jvm.cfg\". I found the Java run time Jre7 is missing amd64 folder under lib. However, I have 1.7.0_25 JDK which is having jre folder and also having amd64.I moved the original contents of jre7 folder to a backup file and copied everything from 1.7.0_25\\jre.Now I am not getting this error anymore and able to proceed with scene builder.The Java 7 install on my work PC broke after a patch was forced out to us, giving this error any time you tried to run a Java program.  Somehow the entire 'lib' subdirectory of the Java 7 install vanished!  Might have been related to having both Java 6 and Java 7 installed -- the 'jre6' directory still had everything there.In any case, I fixed it by uninstalling both Java 6 and Java 7 and reinstalling just Java 7.  But if the file it's complaining about is actually there, then you're likely having a path issue as described in some of the other answers here.Had suddenly the same Problem, from one day to another eclipse saidafter trying to run java on the consolenow i just deleted the whole directory and everything worked again... i don't know there this jre came from, i hope it was not a virusI had a similar problem (trying to start a Jenkins slave agent on Windows) on Windows 2008R2, Java 1.7.0_15.\nI had two situations that contributed to the problem and that changing both of them fixed it:\n1) Installing Java in a unix-compatible path (changing from c:\\Program Files... to c:\\Software...); I don't think this directly affected the problem described in this thread, but noting the change;\n2) Running Java not through a shortcut. It originally failed with a shortcut, but re-running from the direct executable (C:\\Software\\Java...\\bin\\java) worked.Reinstalling java didn't help me. But the trick to put the JAVA_HOME variable at the beginning of the env-vars. The problem occoured after an upgrade from jdk1.7.0_11 to jdk1.7.0_13Another workaround is using shortpath in windows:This should work in windows 64 environment as it worked for me in win7 64bit version.I have changed the java installation path from  to another folder like  and updated the  and path values accordingly,it worked.exampleI had the same problem in  and I fixed it by changing the  from 64 bit to :Window > Preferences > Java > Installed JREs > Add... > Next > Directory > select \"C:\\Program Files (x86)\\Java\\jre1.8.0_65\" instead of \"C:\\Program Files\\Java\\jre1.8.0_60\"I had this problem after updating your java. The best way to solve this problem is just go to your  folder. There you will find two jre folders one is as jre.your version and other with exactly like jdk folder. Try to remove jre.1.your version folder. There you go your problem is solved. Hope this might help. It's worked for me.Typically it because of upgrading JRE.It changes symlinks into C:\\ProgramData\\Oracle\\Java\\javapath\\Intall JDK - it will fix this.C:\\ProgramData\\Oracle\\Java\\javapath worked for me .. , I have took back up of the files and removed the files in it.Opened new cmd prompt and then .. tested and works like charmIt wasn't in the path. Finally fixed by uninstalling java, removing all references to it from the registry, and then re-installing. None the wiser, but back working again. Thanks all @Highland Mark- Can you tell me the process to removing references from registry. I tried all possible way people mentioned here, nothing worked."},
Scala

I wonder why  doesn't have a method  like this defined:equivalent toIs there no better than using  + ?You can do:or  But what you really want is Scalaz\u2019s   (basically a  which not only handles the  value but also maps the  part, which is what you described)defined as (where  is the pimped option value)which is equivalent to .Although I should remark that you should only use cata when it is the \u2018more natural\u2019 way of expressing it. There are many cases where a simple \u2013 suffices, especially when it involves potentially chaining lots of s. (Though you could also chain the s with function composition, of course \u2013 it depends on whether you want to focus on the function composition or the value transformation.)I personally find methods like  that take two closures as arguments are often overdoing it. Do you really gain in readability over  + ? Think of a newcomer to your code: What will they make of Do you really think this is clearer thanIn fact I would argue that neither is preferable over the good oldAs always, there's a limit where additional abstraction does not give you benefits and turns counter-productive.It was finally added , with the signature .As mentioned by Debilski, you can use Scalaz's  or . As Jason commented, named parameters make this look nice:Now, if the value you want in the  case is  for some  and you have a function  for the  case, you can do this:So,becomesPersonally, I think  should have an  method which would be the catamorphism. That way you could just do this:orIn fact, this would be nice to have for all algebraic data structures."},
Scala

I'm replacing some code generation components in a Java program with Scala macros, and am running into the Java Virtual Machine's limit on the size of the generated byte code for individual methods (64 kilobytes).For example, suppose we have a large-ish XML file that represents a mapping from integers to integers that we want to use in our program. We want to avoid parsing this file at run time, so we'll write a macro that will do the parsing at compile time and use the contents of the file to create the body of our method:In this case the compiled method would be just over the size limit, but instead of a nice error saying that, we're given a giant stack trace with a lot of calls to  and are told that we've slain the compiler.I have  that involves splitting the cases into fixed-sized groups, creating a separate method for each group, and adding a top-level match that dispatches the input value to the appropriate group's method. It works, but it's unpleasant, and I'd prefer not to have to use this approach every time I write a macro where the size of the generated code depends on some external resource.Is there a cleaner way to tackle this problem? More importantly, is there a way to deal with this kind of compiler error more gracefully? I don't like the idea of a library user getting an unintelligible \"That entry seems to have slain the compiler\" error message just because some XML file that's being processed by a macro has crossed some (fairly low) size threshhold.Since somebody has to say something, I followed the instructions at  to try to compile the tree before returning it.If you give the compiler plenty of stack, it will correctly report the error.(It didn't seem to know what to do with the switch annotation, left as a future exercise.)as opposed towhere the client code is just that:My first time using this API, but not my last. Thanks for getting me kickstarted.Imo putting data into .class isn't really a good idea.\nThey are parsed as well, they're just binary. But storing them in JVM may have negative impact on performance of the garbagge collector and JIT compiler.In your situation, I would pre-compile the XML into a binary file of proper format and parse that. Elligible formats with existing tooling can be e.g.  or good old . Some implementations of the latter may also provide basic indexing which could even leave the parsing out - the app would just read from the respective offset."},
Scala

Is there a simple, hassle-free approach to serialization in Scala/Java that's similar to Python's pickle?  Pickle is a dead-simple solution that's reasonably efficient in space and time (i.e. not abysmal) but doesn't care about cross-language accessibility, versioning, etc. and allows for optional customization.What I'm aware of:Kryo and protostuff are the closest solutions I've found, but I'm wondering if there's anything else out there (or if there's some way to use these that I should be aware of). Please include usage examples! Ideally also include benchmarks.Scala now has  which performs as good or better than Kyro depending on scenario - See slides 34-39 in  presentation.I actually think you'd be best off with kryo (I'm not aware of alternatives that offer less schema defining other than non-binary protocols). You mention that pickle is not susceptible to the slowdowns and bloat that kryo gets without registering classes, but kryo is still faster and less bloated than pickle even without registering classes. See the following micro-benchmark (obviously take it with a grain of salt, but this is what I could do easily):Outputs 174 bytes and 1.18-1.23 seconds for me (Python 2.7.1 on 64-bit Linux)Outputs 68 bytes for me and 30-40ms (Kryo 1.04, Scala 2.9.1, Java 1.6.0.26 hotspot JVM on 64-bit Linux). For comparison, it outputs 51 bytes and 18-25ms if I register the classes.Kryo uses about 40% of the space and 3% of the time as Python pickle when not registering classes, and about 30% of the space and 2% of the time when registering classes. And you can always write a custom serializer when you want more control.Twitter's  is just awesome. It uses Kryo for serialization but is ultra simple to use. Also nice: provides a MeatLocker[X] type which makes any X a Serializable.I would recommend . It uses implicits which are resolved at compile time, so it's very effective and typesafe. It comes with built-in support for many common Scala datatypes. You have to manually write the serialization code for your (case) classes, but it's easy to do.Another good option is the recent (2016) :For example:"},
Scala

In Java I sometimes use class variables to assign a unique ID to each new instance. I do something likeHow can I do this in Scala?Variables on the companion object:To amplify on Thomas' answer:The  definition is usually put in the same file with the class, and  have the same name. This results in a single instance of an object having the name of the class, which contains whatever fields you define for it.A handy do-it-yourself Singleton construction kit, in other words.At the JVM level, the object definition actually results in the definition of a new class; I think it's the same name with a  appended, e.g. . Just in case you have to interoperate some of this stuff with Java."},
Scala

Can anybody provide some details on  operator in scala. \nI think: Are there any other explanations? I see many definitions in the scala source file.  is  - it is an  and is therefore one of:In this case,  appears twice in the library, once in  as a class and once as a method on . For the method on , it checks whether the type represented by  manifest is a subtype of that represented by the manifest argument.For the type in , this is relatively new and I am also slightly confused about it because it seems to be part of a triumvirate of identical declarations!The  type is defined in  along with the related types  and  as follows:This uses the Scala feature that a generic type  can be written .  This can be used, as noted by aioobe, to provide an evidence parameter for methods that only apply to some instances of a generic type (the example given is the  method that can only be used on a  of ).  As noted in the comment, this generalizes a normal generic type constraint to allow it to refer to any in-scope abstract type/type parameter.  Using this () has the advantage over simply using an evidence parameter like () in that the latter can lead to unintended in-scope implicit values being used for the conversion.I'm sure I'd seen some discussion on this on one of the Scala mailing lists, but can't find it at the moment.I asked around, and this is the explanation I got: is typically used as an evidence parameter. For example in ,  is declared as . This expresses the constraint that the  method only works if the traversable contains 2-tuples.  is another example.  is used to express the constraint that you can only flatten a traversable of traversables.Actually, it checks if the class  by the  apple is a subclass of the class represented by the manifest fruit.For instance:Copy from scala.Predef.scala:To better understand the .I tried to devise a simpler implementation. The following did not work.At least because it won't type check in all  cases.Hmm... I can't seem to find \"<:<\" anywhere as well, but \"<:\" denotes subtyping.\nFrom  : "},
Scala

Why should I choose Scala over another language for a new project?  In what areas does it excel in?There were a few nice answers given, sadly I could only mark one as the accepted answer.  However, overall it looks like Scala's appeal comes from two primary things:First read this: Concurrency is becoming ever-more important.  Already we have 1000 core processors being demonstrated, and what computer nowadays doesn't already come with a GPU capable of highly-parallel operations?In order to take advantage of future machines, your software has to be able to make use of all this concurrency, and Java's current threading primitives just aren't going to help here.  Let's face it, concurrent programming under current mainstream paradigms is crazy-hard.Scala is a functional language.  As such it fully embraces concepts such as immutability, for-comprehensions, closures, etc.  It also has 4 native actor libraries available (at last count).  All of this is perfectly suited to the next generation of concurrent programming.  You can't bury your head in the sand and pretend that none of this exists -  - imperative loops simply aren't going to cut it any more!Scala 2.9, due to be released early 2011, will support parallel operations such as:On top of all that, Scala can do everything that Java does, typically with a much cleaner syntax.  It's also far more object-oriented than Java (with its primitives and static methods), a fact which is often overlooked in the false belief that object orientation and functional programming are mutually exclusive.In what area does Scala excel?  I guess that area would have to be \"the future\"...My own comment on Landei's answer suggested a powerful reason to use Scala: if you want your project/team/company to appeal to forward-looking, talented engineers, instead of guys who managed to pick up some Java from a CS elective at Reed or somewhere and have been writing JSP pages for Visa International's internal HR systems for the last eight years, then you'll need a more interesting language choice.Scala runs on JVM and is fully compatible with Java. In fact, it's nearly identical to Java in terms of what you can do and how it works, so you could use Scala for anything Java would be a good choice for as well (notably: enterprise environments and cross-platform applications). According to the  it's ideal for web-services.As for what makes it better/worse than Java for any given task, well, I'll let  do the talking.Scala is clearly the best all-purpose weapon on the JVM. Scala can do everything Java can do, and almost always Scala can do it better (with very good interoperability to Java), so IMHO there is no good reason to consider Java at all for a new project.There are a few cases where dynamic typing (JRuby, Jython, Groovy) or meta-programming features (Clojure) can give you an initial edge, but there is nothing else that scales as good as Scala, and which gives you the freedom to mix paradigms as you need it, so as bigger as a project gets, as bigger gets the advantage of using Scala.[Update]\nIn response to the questions:Scala does a couple of things well:Good use cases for Scala development? Anything that deals with XML, concurrent applications, or situations where functional programming is preferable (many cases).Why should you prefer Scala over other languages? You shouldn't necessarily. I think that it's a great choice for a project that would otherwise be implemented in Java, because it has some concrete advantages over Java.A guy from Twitter actually put together , and he makes a lot of the same points I have (with a few more).Scala is the best statically typed on the JVM.That is the result of Scala's advanced type system, the orthogonality of features, the way it was written so that it could be extended seamlessly through libraries, and its easy integration with existing Java code.I could make a list of these features, but it would be meaningless without knowing the language. I could say Scala has definition-site declaration of variance with correct enforcement, but how one would measure that without having experienced it?The outcome, however, is that code written in Scala is fast, compact, reliable and indicative of the domain of the problem. That's valid on all levels too, so Scala  are also like that.Let's discuss a bit about the alternatives here, to make the distinction clear.There are non-JVM languages, but the decision on whether to go for a JVM language or not is almost completely separate from the decision about the language itself. That's a technological decision that has to be made before choosing a language. Because of that, I'm only comparing Scala to other JVM languages.Most other JVM languages are dynamically typed. While there are factors to consider when choosing between dynamically typed and statically typed languages, the one that really makes a difference in the end is personal preference. Otherwise, just refer to one of many resources about dynamically typed and statically typed languages.As far as statically typed languages on the JVM goes, Scala has the most advanced type system. In fact, as far as I know it is almost alone in having a type system which is inspired by actual type system theory instead of being hacked together based on preferences and experience of the language implementor.Java, for instance, does not have safe variance. Other languages go the opposite way of Scala, by providing \"most common\" data structures in the language itself, and making it impossible for anyone to write other complex data structures as libraries.So, if you choose JVM and statically typed, and you have the flexibility of choosing a language, then Scala is the best language for that project, whatever that project may be.For my own private projects, I already adopted Scala as a natural successor for Java (for the reasons mentioned in other answers). But I'm very hesitant to suggest that Scala development tools (especially IDEs) are fit for large-scale commercial projects. Namely the IDEs refactoring support, which in my opinion is mandatory for agile development, is not up to Java standards, yet (using current IDEA 10, nightly build plugin). In addition, I think it's quite hard for companies to come up with Scrum-sized teams of decent Scala developers. See also the video 'Sneaking Scala Into Your Organization' by David Copeland: For the time being, I can imagine mixing-in smaller Scala modules into larger Java projects."},
Scala

In a previous question, , it seems that people had used  to figure out how to access  from Java. I would like to know how they did that. FYI, the answer is:which can be shorted to:Given this program ():I ran  on it like this:This is a portion of the  output:I also ran javap on  and . How would one figure out from the  output that:?There are rules how Scala code is compiled to JVM-bytecode. Because of potential name clashes the generated code is not always intuitive to understand but if the rules are known it is possible to get access to the compiled Scala code within Java.There are no special rules here. The following Scala classcan be accessed like a normal Java class. It is compiled to a file named :Notice, that for methods without a parameterlist an empty parameterlist is created. Multiple parameterlists are merged to a single one.For a class  Getters and Setters are created. For a class  only a Getter is created:Notice, that in Java an identifier is not allowed to include special signs. Therefore scalac generates for each of these special signs a specific name. There is a class  which can encode/decode the ops:A class  is translated by the same schema as when the field is created in the constructor. Direct access to the variable  from Java is not possible, because it is private.There is no such thing as a Scala object in Java. Therefore scalac has to do some magic. For an object  two JVM-class files are generated:  and . The first one works like an interface, it includes static methods to access fields and methods of the Scala object. The latter is a singleton class which cannot be instantiated. It has a Field which holds the singleton instance of the class, named , which allows access to the singleton:The Scala compiler automatically generates an apply-method for a case class and Getters for fields. The case class  is easily accessed:A trait , which contains only abstract members, is compiled to an interface, which is placed in a class files named . Therefore it can easily implemented by a Java class:If the trait contains concrete members there is a class file named  generated, additionally to the normal interface. The traitcan also easily implemented within Java. The class file  contains the concrete members of the trait, but it seems that they are impossible to access from Java. Neither javac nor the eclipse-javac will compile an access to this class.Some more detail about how traits are compiled can be found .Function literals are compiled as anonymous instances of the classes FunctionN. A Scala objectis compiled to the normal class-files, as describes above. Furthermore each function literal gets its own class-file. So, for function values a class file named  is generated, where N is a continuous number. For function methods (methods, which return a function) a class file named  is generated. The parts of the function name are separated by dollar signs and in front of the  identifier there are also two dollar signs. For nested functions the name of the nested function is appended to the outer function, this means an inner function will get a class file like . When an inner function does not have a name, as seen in  it gets the name .This means in our case we get:To access them use their apply-method:You should know:javap says it has a constructor and an apply method. Furthermore it says the class is abstract. Thus only the apply-method can used:It has a constructor and an apply-method (because we know Option has one and Some extends Option). Use one of them and be happy:It has no constructor, no apply-method and doesn't extend Option. So, we will take a look to :Yeah! We found a  field and the apply-method of Option. Furthermore we found the private constructor: is abstract, thus we have to use . It has an apply-method which expects an . So to get a List we need first a Seq. But if we look to Seq there is no apply-method. Furthermore when we look at the super-classes of Seq and at  we can only find an apply-methods which expects a Seq. So, what to do?We have to take a look how scalac creates an instance of List or Seq. First create a Scala class:Compile it with scalac and look at the class file with javap:The constructor is interesting. It tells us, that an array of ints is created (l. 12) which is filled with 1, 2 and 3. (l. 14-25). After that this array is delivered to  (l. 26). This resulting  is again delivered to our List (l. 29). At the end, the List is stored in the field (l. 32).\nWhen we wanna create a List in Java, we have to do the same:This looks ugly, but it works. If you create a nice looking library which wraps the access to the Scala library it will be easy to use Scala from Java.I know there are some more rules how Scala code is compiled to bytecode. But I think with the information above it should be possible to find these rules by yourself.I'm not competing with the other answer, but since people seem often not to notice this, you can do this in the repl."},
Scala

I am in the process of migrating from Slick to Slick 2, and in Slick 2 you are meant to use the  method when projecting onto a case class (as shown here )The problem is when the case class has a companion object, i.e. if you have something like thisAlong with a companion objectIn the same scope, the  method no longer works, because its trying to run  on the , instead of the .Is there a way to retrieve the  of  rather than the , so you can call  properly?You can also writeto avoid repeating the types.This is very similar to what Alexey Romanov said, but in order to avoid lifting  whenever you need , we just add it to our companion objects.Now you can call  just like you would have if it didn't have a companion object.One workaround is define a companion object as follows:See. To build on some of the other comments you could do the following as well since tuple is calling the generated default apply method for the case class."},
Scala

I am trying to show the SBT dependency tree as described in the :But I get this error:What is wrong? Why doesn't SBT build the tree?, each argument sent to sbt is supposed to be a command,  so will:This obviously fails, since  needs an argument. This will do what you want:If you want to actually view the library dependencies (as you would with Maven) rather than the task dependencies (which is what  displays), then you'll want to use the  plugin.Add the following to your project/plugins.sbt (or the global plugins.sbt).Then you have access to the  command, and others.If you want to view , you can use the  plugin: Output example:\n\ntext (without colors): Note that the plugin has a completely different nature than printing trees. It's designed for fast and concurrent dependency downloads. But it's nice and can be added to almost any project, so I think it's worth mentioning."},
Scala

I'm still fairly new to Scala, and I'm discovering new and interesting ways for doing things on an almost daily basis, but they're not always sensible, and sometimes already exist within the language as a construct and I just don't know about them.  So, with that preamble, I'm checking to see if a given string is comprised entirely of digits, so I'm doing:is this sensible or just needlessly silly?  It there a better way?  Is it better just to call x.toInt and catch the exception, or is that less idiomatic?  Is there a performance benefit/drawback to either?Try this: takes a function (in this case ) that takes an argument that is of the type of the elements of the collection and returns a ; it returns  if the function returns  for all elements in the collection, and  otherwise.Do you want to know if the string is an integer?  Then  it and catch the exception.  Do you instead want to know if the string is all digits?  Then ask one of:You also may consider something like this:You could simply use a regex for this.Or simplyAnd to improve this a little bit, you can use the pimp my library pattern to make it a method on your string:@Jesper's answer is spot on.Do  do what I'm suggesting below (explanation follows)Since you are checking if a given string is numeric (title states you want a decimal), the assumption is that you intend to make a conversion if the forall guard passes.A simple implicit in scope will save a whopping 9 key strokes ;-)  The compiler will now allow  since the implicit tries to convert whatever string you use to Double, with zero guarantee of success, yikes.implicit conversions then seem better suited to situations where an acceptable default value is supplied on conversion failure (which is not always the case; therefore implicit with caution) might not performance-wise be the optimal choice, but otherwise it's neat:"},
Scala

What is the difference between = and := in Scala?I have googled extensively for \"scala colon-equals\", but was unable to find anything definitive. in scala is the actual assignment operator -- it does a handful of specific things that for the most part you don't have control over, such as is not a built-in operator -- anyone can overload it and define it to mean whatever they like. The reason people like to use  is because it looks very assignmenty and is used as an assignment operator in other languages.So, if you're trying to find out what  means in the particular library you're using... my advice is look through the Scaladocs (if they exist) for a method named .from Martin Odersky:from Scala allows for operator overloading, where you can define the behaviour of an operator just like you could write a method.As in other languages,  is an assignment operator.The is no standard operator I'm aware of called , but could define one with this name.  If you see an operator like this, you should check up the documentation of whatever you're looking at, or search for where that operator is defined.There is  you can do with Scala operators.  You can essentially make an operator out of virtually any characters you like. performs assignment.   is not defined in the standard library or the language specification.  It's a name that is free for other libraries or your code to use, if you wish."},
Scala

In Scala variables are declared like:Where the type (Double) follows the identifier (stockPrice). Traditionally in imperative languages such as C, Java, C#, the type name precedes the identifier.Is it purely a matter of taste, or does having the type name in the end help the compiler in any way? Go also has the same style.As well as supporting type inference, this has an ergonomic benefit too.For any given variable name + type, chances are that the name is the more important piece of information.  Moving it to the left makes it more prominent, and the code more readable once you're accustomed to the style.Other ergonomic benefits:Kevin's got it right. The main observation is that the \"type name\" syntax works great as long as types are short keywords such as  or :For the price of one you get two pieces of information: \"A new definition starts here\", and \"here's the (result) type of the definition\". But we are way past the area of simple primitive types nowadays. If you writethe most important part of what you define (the name) is buried behind the type expression. Compare withIt says clearlyIt's afterwards so that it can be removed for type inference:However, it is  true that imperative languages traditionally have types first. For example, Pascal doesn't.Now, C does it, and C++, Java and C# are based on C's syntax, so naturally they do it that way too, but that has absolutely nothing to do with imperative languages.It should be noted that even C doesn't \"traditionally\" define the type before the variable name, but indeed allows the declarations to be interleaved.where the type for foo is declared both before and after it, lexically.Beyond that, I'm guessing this is a distinction without a difference.  The compiler developers certainly couldn't care one way or another."},
Scala

There are more and more programming languages (Scala, Clojure,...) coming out that are made for the Java VM and are therefore compatible with the Java Byte-Code.I'm beginning to ask myself: Why the Java VM?That one is easy:The JVM is rock solid and works from the tiniest Java SmartCard (ok, a tiny VM ;) to the biggest clustered super-computers you can imagine.Because it is rock solid, there are entire countries where people have:I'm developping commercial software in Java: we're selling on Windows and on OS X but we're all developping on Linux. And it just works. And it works on Solaris too, etc.  And that's because we're targetting the JVM: goodbye portability issue. As long as the platform has a VM, the software shall work.Then I can't believe anyone mentioned it yet: it is a very good start from a security point of view.The Java VM is, by design, immune to buffer overrun/overflow. This is . This is actually .The only \"Java\" buffer overflow that I remember on Linux (that prompted me to upgrade due to security concern) was actually a buffer overflow leading to arbitrary code execution in... a C written lib (zlib if I remember correctly, back in the days Java on Linux was still defaulting to that lib).Sure, for webapps buffer overrun/overflow leading to arbitrary code execution are not the most important vector of attack anymore (now that XSS and SQL injection have stolen the show).  But in all the other cases buffer overrun/overflow are  source of most security issues.The JVM is immune to that.In addition to that thanks to its design it's easy to plug various tools on it like profilers and debuggers.It is a very solid and secure (when used correctly) technology. That is why it is so widely used by both tech-savvy (Java is  at Google, from GMail to their Android to GWT etc.) and tech-not-that-savvy companies.It is actually arguable that Java's success comes from the JVM and that \"Java the VM\" is much more important than \"Java the language\".The JVM is the biggest \"language\" success story of these last 20 years. And it is deserved. And it is here to stay :) Because somebody else has already taken the trouble to make sure it runs well on every major platform.If you write your own VM, you have to write one for Linux/Unix/BSD, one for Mac, and one for Windows, and you have to support the VM on all those platforms as well as supporting your language compiler and runtime libraries.  If you use the Java VM, the first part is taken care of for you by Oracle, IBM and Apple.Because with almost 20 years of effort the Java VM isI mean, if i would plan to release a new language why shouldn't I use the JVM? Ok, there are others vms (llvm, parrot) but the JVM is estensively supported, known, and tested.And it works also quite good! The lack of  will be solved with the relase of Java7 so better than this..It's free & open, mature (stable, complete), and the surrounding ecosystem is huge.Writing a VM as good as the JVM is hard. JVM's spec and its implementations have been refined for well over a decade by the finest minds in the industry.Second question first: Why reinvent the wheel? There are multiple implementations of the Java VM, including highly-optimized ones, and there's at least one available for darned near any platform out there.First question second: There is a  amount of third party library and tool support for code compiled to Java bytecode and run on the VM. When you create a new language, one big issue is that you have to create everything that people can use with it, or make it compatible with something else (like linking to existing static C libraries, or .Net, or COM, or the Java VM). The Java VM's open specification (erm, so far), deep history, and broad applicability make it a nice target for new languages.Obvious reasons:Because its not a Microsoft technology.  As others have mentioned, there are a lot of great reasons to use the JVM, but I think it would be slightly less popular if Microsoft's CLR was as free, as portable, and as open."},
Scala

So I was just learning new Java 8, specially lambdas and date and time api. I was comparing it with scala. My basic idea was to find the execution time difference between imperative, Stream and parallel stream. So I decided to create a Library application and do some operations like searching, filtering, sorting etc. I created a Library class with a list field called books and populated it with 1000 books. Then created a functional interface for search and did some operation in all three styles. It all worked fine. My code is:Now I tried to re-create the same program in scala and see whether the execution is faster or not? Surprisingly scala didn't allow me to do parallel sorting (Or may be I'm being ignorant here). My scala library isHere the  gives a ParSeq. This doesn't have a sort method. Is there any way I could create a parallel sort with my books list in scala. So I could write something like:Your help is much appreciated. Thanks.One can implement a parallel sort in scala e.g.  . I don't know why ParSeq doesn't offer sorting in its API. Note that there are a number of alternatives to , so don't necessarily assume that your results from ParSeq are representative of Scala parallelism in general. (But benchmarks are valuable and I wish you well with yours).i am very much new to scala but as far as my understanding goes:  the sort itself will never be parallel, only the conversion to and from the Java array might.\nsorted is provided by scala.collection.SeqLike only \nTry this link:\nGitHub.Com/Scala/Scala/blob/master/src/library/scala/collection/\u2026"},
Scala

Scala 2.11 is out and the 22 fields limit for case classes seems to be fixed (, ).This has been an issue for me for a while because I use case classes to model database entities that have more than 22 fields in Play + . My solution in Scala 2.10 was to break the models into multiple case classes, but I find this solution hard to maintain and extend, and I was hoping I could implement something as described below after switching to Play 2.3.0-RC1 + Scala 2.11.0:The code above fails to compile with the following message for both the \"Reads\" and the \"Writes\":Updating the \"Reads\" and \"Writes\" to:Also doesn't work:My understanding is that Scala 2.11 still has some limitations on functions and that something like what I described above is not possible yet. This seems weird to me as I don't see the benefit of lifting the restrictions on case classes if one it's major users cases is still not supported, so I'm wondering if I'm missing something.Pointers to issues or implementation details are more than welcome! Thanks!This is not possible, out of the box, for several reasons:However it is possible to bypass the second point by either:First, creating the missing :and then by providing your own  instance:Finally, regarding the first point, I have sent a  to try to simplify the current implementation.We were also breaking our models into multiple case classes, but this was quickly becoming unmanageable.  We use  as our object relational mapper, and Slick 2.0 comes with a  that we use to generate classes (which come with apply methods and copy constructors to mimic case classes) along with methods to instantiate models from Json (we do not automatically generate methods to convert models into Json because we have too many special cases to deal with).  Using the Slick code generator does not require you to use Slick as your object relational mapper.This is part of the input to the code generator - this method takes a JsObject and uses it to either instantiate a new model or update an existing model.For example, with our ActivityLog model this produces the following code.  If \"original\" is None then this is being called from a \"createFromJson\" method and we instantiate a new model; if \"original\" is Some(activityLog) then this is being called from an \"updateFromJson\" method and we update the existing model.  The \"condenseUnit\" method being called on the \"val errs = ...\" line takes a Seq[Try[Unit]] and produces a Try[Unit]; if the Seq has any errors then the Try[Unit] concatenates the exception messages.  The parseJsonField and parseField methods are not generated - they're just referenced from the generated code.You can use Jackson's Scala module. Play's json feature is built upon Jackson scala . I don't know why they put a 22 field limit here while jackson supports more than 22 fields. It may make sense that a function call can never use more than 22 parameters, but we can have hundreds of columns inside a DB entity, so this restriction here is ridiculous and makes Play a less productive toy.\ncheck this out:I'm making a library. please try this cases where case classes might not work; one of these cases is that the case classes cannot take more than 22 fields. Another case can be that you do not know about schema beforehand. In this approach, the data is loaded as an RDD of the row  objects. Schema is created separately using the StructType and StructField  objects, which represent a table and a field respectively. Schema is applied to the row RDD to create .I tried Shapeless \"Automatic Typeclass Derivation\" based solution proposed in another answer, and it didn't work for our models - was throwing StackOverflow exceptions (case class with ~30 fields and 4 nested collections of case classes with 4-10 fields).So, we've adopted  solution and it worked flawlessly. Confirmed that by writing ScalaCheck test. Notice, that it requires Play Json 2.4."},
Scala

I hear .sbt files have been improved in various ways in 0.13, and that now I can specify multi-project builds in them. mentions that we can now define subprojects in a .sbt file. I also know that multiple .sbt files in the root will be aggregated into a single conceptual file.What I'd really like, though, is to not pollute my root with a dozen subproject .sbt files. Is there a way I can throw the subproject build.sbt files into their respective subdirectories, keep some common code between them somewhere shared, and then have a root build.sbt for the entire project that aggregates the subprojects? I have a similar setup in .scala files right now but would prefer to use .sbt files if possible.If that isn't possible, what is the \"correct\" way to construct large multi-project builds with .sbt files?It should already be the case in 0.12 that you can put  files in the base directory of a subproject and the settings there will be included in that project's scope.Code is reused between  files by creating a normal  file in .  The code in  will be available for use in the  files.  The definitions in one  are not visible to other  files, at least in 0.13.  This is mainly an implementation restriction and it is undetermined whether this will be lifted in future versions.The default root project will aggregate all subprojects, including those coming from projects defined in .The current difficulty is making it explicit.\nFor example, the following  in the root directory would define a subproject in .\nThis is a full definition, defining the ID, base directory, etc... for the project.However, it cannot reference anything defined in .  (The existence of  is not known until after  is compiled and evaluated.)\nSo, to explicitly define what  aggregates, you'd need something like:However, this duplicates the definition of .A possible solution going forward is to make the root definition just a reference, like:"},
Scala

 .I have made this question community wiki and invite others to keep it updated.  Is anyone aware of benchmarks of Clojure's performance?  I have done some of my own (although nothing too formal) and it didn't fair too well in comparison to other functional languages (tried Haskell and OCaml).  But how does it look compared to Java or another language on the JVM (e.g. Scala)?  And how does it compare to other Lisps?There was some  on the  forum about adding Clojure on there, but nothing has been done yet.   I'm going to continue to add to this as I find more:@igouy pointed out that the benchmark scripts for clojure  by jafingerhut on github.Two very relevant threads from the Clojure discussion group:And separately, these blog posts:And lastly, a related question on stackoverflow:Most of these discussions lead me to think that Clojure's performance is very favorable in comparison to other languages running on the JVM, although there is no doubt that it can be very difficult to come to a broad conclusion when comparing languages because their performance can vary dramatically dependent on the task.Lau Jensen just posted a great discussion about benchmarking with JVM languages on his blog: .See     the current clojure implementation has not been focussed on performance, but the next version supposedly will.This is an important question that just about everyone thinks about before considering clojure. Its also a hard question even for mature languages that are not adding things, like chunked sequences, that radically change the performance of some specific (though common) tasks. I found some good thoughs in . Many of the benchmarks you find will be related to previous versions of both java and clojure so its unlikely that anyone can find \"really good benchmarks\". I great question to ask your self here is . This is a precondition to clojure being fast enough. If you can convince your self that the answer to this question is yes then it is safe to proceed in Clojure and implement the parts that your profiling identifies as bottle necks in Java. Because you have a failback language with well known performance It will generally be safe to go with Clojure. For performance questions please refer to this blogpost:This shows a Clojure implementation of the WideFinder2 challenge which is faster than both Java, Scala and single threaded C. Compare with official times.Regarding Daniels remark that Clojure will never be faster, we see that its obviously incorrect based on the results above. Mutability is faster than immutability which is Clojures default, yet Clojure allows for local transients (ie. temporarily mutable data), so that one can achieve optimal speed.Refer to clj-me.cgrand.net for many optimization techniques.In conclusion: Clojure can be as fast as you would like it to be while still allowing you to maintain a simple elegant and robust codebase, almost a unique combination.You might also be interested in the  serie from Tim Bray. He discusses some performance issues.Clojure will never be able to match a Scala program that takes full advantage of mutability in an algorithm that's benefitted by it. There's also the fact that Clojure is a dynamic language, which, presently, isn't very well supported by JVM.On the other hand, Clojure excels at enabling parallel, asynchronous and distributed algorithms, and immutable algorithms generally speaking.So, if you want (mostly) immutability and multicore efficiency, Clojure will make those much easier to achieve. If your algorithms really, really need to heavily use mutability for efficiency, then Scala will make those easier.Anything in between, it likely won't matter either way."},
Scala

I've searched for the use of  in the source code of the standard library of Scala 2.8.1. It looks like only a handful of traits and classes use this annotation: , , , , , , , , , .None of the collection classes are . Why not? Would this generate too many classes?This means that using collection classes with primitive types is very inefficient, because there will be a lot of unnecessary boxing and unboxing going on.What's the most efficient way to have an immutable list or sequence (with  characteristics) of s, avoiding boxing and unboxing?Specialization has a high cost on the size of classes, so it must be added with careful consideration. In the particular case of collections, I imagine the impact will be huge.Still, it is an on-going effort -- Scala library has barely started to be specialized.Specialized can be expensive (  ) in both size of classes and compile time. Its not just the size like the accepted answer says. Open your scala REPL and type this. Sorry :-). Its like a compiler bomb.Now, lets take a simple traitThe above will result in two compiled classes. Foo, the pure interface and Foo$1, the class implementation.Now, A specialized template parameter here gets expanded/rewritten for 9 different primitive types ( void, boolean, byte, char, int, long, short, double, float ). So, basically you end up with 20 classes instead of 2.Going back to the trait with 5 specialized template parameters, the classes get generated for every combination of possible primitive types. i.e its exponential in complexity.2 * 10 ^ If you are defining a class for a specific primitive type, you should be more explicit about it such asUnderstandably one has to be frugal using specialized when building general purpose libraries. is Paul Phillips ranting about it. Partial answer to my own question: I can wrap an array in an  like this:(Ofcourse you could still modify the contents if you have access to the underlying array, but I would make sure that the array isn't passed to other parts of my program)."},
Scala

I'm using an external library written in Java (). One of the function calls has the signature , and I keep getting compiler errors when trying to call it from Scala, that is:Is there a workaround for this issue?"},
Scala

Should my custom exception types be es? On the plus side, I get extractors. On the minus side, I get incorrect equality semantics. But I can avoid that by overriding . So does it make sense, at a conceptual level, to make them es?This is very subjective of course, but in my opinion it is good practice to have exception classes as case classes.\nThe main rationale being that when you catch an exception, you are doing pattern matching, and  case classes are much nicer to use in pattern matching.\nHere's an example that takes advantadge of the ability to use the full power of pattern matching in a catch block, when using a case class exception:In this example, we have only one exception, but it contains an  field for when you want to know the exact error type that occured (usually this is modelled through a hierarchy of exception, I'm not saying this is better or worse, the example is just illustrative). Because the  is a case class I can simply do  to catch the exception only for the error type . Without the extractors that we get for free with case classes, I would have to catch the exception everytime, and then retrow in case I'm actually not interested, which is definitly more verbose.You say that case classes give you incorrect equality semantics. I don't think so. , as the writer of the exception class gets to decides what equality semantics makes sense. After all when you catch an exception, the catch block is where you decide which exceptions to catch usually based on the type alone, but could be based on the value of its fields or whatever, as in my example. The point is that the equality semantics of the exception class has little to do with that.One common idiom you lose by making exceptions case classes is the pattern of creating a subclass hierarchy of exceptions with subclassing used to indicate greater specificity of the error condition.    Case classes can't be subclassed.I like the answer from R\u00e9gis Jean-Gilles. But if you have a good reason to not make a case class (see answer of Dave Griffith), you can archieve the same as in the sample above with a normal class and unapply:"},
Scala

Let's say I store bank accounts information in an immutable : and I want to withdraw, say, $50 from Mark's account. I can do it as follows: But this code seems ugly to me. Is there better way to write this? There's no  in the  API, unfortunately. I've sometimes used a function like the following (modeled on Haskell's , with a different order of arguments):Now  does what you want. You could also use the  to get the more natural  syntax, if you really wanted something cleaner.(Note that the short version above throws an exception if  isn't in the map, which is different from the Haskell behavior and probably something you'd want to fix in real code.)This could be done with . The very idea of a lens is to be able to zoom in on a particular part of an immutable structure, and be able to 1) retrieve the smaller part from a larger structure, or 2) create a new larger structure with a modified smaller part. In this case, what you desire is #2.Firstly, a simple implementation of , stolen from , stolen from scalaz:Next, a smart constructor to create a lens from \"larger structure\"  to \"smaller part\" . We indicate which \"smaller part\" we want to look at by providing a particular key. (Inspired by what I remember from ):Now your code can be written:n.b. I actually changed  from the answer I stole it from so that it takes its inputs curried. This helps to avoid extra type annotations. Also notice , because remember, our lens is from  to . This means the map will be unchanged if it does not contain the key . Otherwise, this solution ends up being very similar to the  solution presented by Travis.An  proposes another alternative, using the  operator from scalazThe  operator will sum the values of an existing key, or insert the value under a new key."},
Scala

Related questions: I have a  (more than 5 millions items) and I need to get  items from it. The most natural way to do it is to use heap/priority queue . There are several good implementations of priority queue for JVM (Scala/Java), namely: First 2 are nice, but they store all the items, which in my case gives critical memory overhead. Third (Lucene implementation) doesn't have such a drawback, but as I can see from documentation it also doesn't support custom comparator, which makes it useless for me. So, my question is: Is there a  with  and ? Finally I've created my own implementation, based on Peter's answer:(where  is taken from  question)You could use a SortedSet e.g. TreeSet with a custom comparator and remove the smallest when the size reachs N.How can you say Lucene's doesn't support a custom comparator?Its abstract and you must implement the abstract method Though an old question but it may be helpful to somebody else.\nYou can use  of Google's Java library guava. I can't think of a ready-to-use one, but you can check  of this collection with similar requirements.The difference is the comparator, but if you extend from  you'll have it. And on each addition check if you haven't reached the limit, and if you have - drop the last item. Below is the implementation I used before. Complies with Peter's suggestion.I would appreciate any feedback btw. It seems like using a  is not very efficient after all because the calls to  seem to take sublinear time. I changed the  to a . The modified  method looks like this:Exactly what I was looking for. However, the implementation contains a bug:Namely: if elementsLeft > 0 and e is already contained in the TreeSet.\nIn this case, elementsLeft is decreased, but the number of elements in the TreeSet stays the same. I would suggest to replace the corresponding lines in the add() method byTry this code:Here is one I put together if you have guava. I think it is is pretty complete. Let me know if I missed something. You can use the gauva ForwardingBlockingQueue so you don't have to map all the other methods. Create a PriorityQueue that has size limit. It stores N max numbers."},
Scala

Given that it's impossible to see into the future, what factors related to Clojure, Scala or Haskell are likely to determine whether one of them catches on?Are there cultural or economic issues that could give one of these languages an advantage over the others?Or are none of these languages likely to gain traction because of their conceptual complexity?On the top of my head:Scala, for instance, is still evolving and moving \"too fast\" to be \"largely\" used even though some big projects have already adopted it.Edit: November 2009See  presentation, Slide 10 and 11:From the Haskell world, I see the main things to continue to push on as:Besides this, it is hard to say. Some random thoughts: Haskell's been around for 20 years, has a very large user base, and plenty of commercial support. Clojure is tiny in comparison. Scala and Clojure get \"free points\" by running on .NET or JVM. Does that matter? How much does the runtime matter? GHC has a very fast custom parallel runtime, because it isn't the JVM, but people like to use the JVM. Same for .NET. Does maturity/stability matter?And on top of all of this, who is doing the best outreach?Oh, and we have .I think that to break into the  (i.e. C, C#, C++, Java) they need  which do in-house development but . I'm think of large banks, insurance companies, service-companies, management consultancies etc.However, there is a big barrier to this acceptance these days; namely ,  and . Without a large company like Sun, IBM or Microsoft providing support it's going to be very difficult to persuade companies like these that any new language is a .Without persuading these companies, the market for developers familiar with the languages will be small. As long as there is a small base of users, the language can afford to make backwards-incompatible changes requested by the community. Hence a vicious cycle of non-mainstream-adoption.Some of these languages may easily gain acceptance first in non-commercial and open source environment. More or less what happened to Perl, Python, Ruby (and some other languages).Ease of deployment of the software (think apt-get) and freedom of the programmer promotes language diversity in the open source world. Once some of the software becomes sufficiently important, the language becomes immortal in terms of support. Once its immortal, it is a safe bet for everyone. Small developers will be first, and if they gain some advantages from using the language, big companies will follow.So, it's a matter of which community is more friendly to open source (teaching, documentation, infrastructure) and which language allows a programmer to be more productive.OK, I'll take a wild guess. I think the factor needed for success is \"can it do Java's job?\".The real thing that Java does is static typing. While this is annoying for small programs it allows the construction of large stable systems. It allows refactoring with confidence. Think about it: every language has kind of a maximum size program that it supports. To go over that size requires increasingly above-average design and implementation.As a secondary consideration, Java is quite fast and has a rather complete library.So, I'm guessing those are the criteria, and so Scala has a chance.The only negative is the difficulty of running cheap shared server web hosts with the JVM.Backing by a large software development company.  Look at what it took Java and C# to get where they are.  That is what it will take for others to get there as well.One cultural factor is how similar a language is to existing popular languages. For example, the evolution of C -> C++ -> Java -> C#. Haskell has the largest gap from the mainstream, with an unfamiliar syntax, runtime stack, programming paradigm and a community oriented much more towards academia than industry.In my humble opinion, the main factor regards the outcome of the research aiming at providing implicit parallelism in purely functional languages. If/when this will work, then Haskell is likely to become the mainstream.As for Scala and Clojure... Scala has the historically more acceptable syntax. That's an overkill. Some can argue that Clojure has a macro system, but macros are expressively equivalent to clojures, so this is not a real advantage.Anyway, I believe that statically-typed languages are not appropriate for all the areas, namely Web Development. And curiously nowadays there's a tendency to make everything web-based. I do not think that Ruby was a hype: It is maturing very fast.Haskell or Ruby will sweep evryone in the world. Chances are more for Ruby to be successful since Haskell is complex and difficult to learn.Ruby 2.x will become father of 'Scala and Clojure'. It will have new version with high speed, GIL removed and built-in modules for Parallel processing, functional programing, macros. Thinking further, more libraries are to be built in ruby for various tasks. This will be done once the version 2.X will come with all the above mentioned feechurs.I believe Matz and Antonio !!!!! C++, Java, .NET, Python, Scala will be seen in musuems. XXXXX \nC, Perl and PHP will still live for small apps/tasks.  \nMySQL, Oracle, SQLServer will also be seen in 'db section' of museum. XXXXX \nSQlite, PostgreSQL will be still alive outside.  Cheers,\nUr man"},
Scala

In sbt 0.10.1, I frequently use  to narrow down the number of my tests.However, I want to narrow down such that I only run tests whose name/description matches a regular expression. Is there some syntax to achieve something like this?Full regular expressions are not supported by .  Wildcards are supported, however.Only the asterisk  is interpreted specially here and not the periods.  This will select all tests beginning with  and ending with .Or just all test s: and other testing information is documented here: You can match on test  by their name (instead of or in addition to suite class names) by using . ScalaTest  with the  argument:This runs all tests with \"insert\" in their name, then only the matching cases within suites ending in , as you would intuit. You can also use  and  to include or exclude, respectively, tags from ScalaTest's tagging support, and  to match an exact test name.Specs2  with an  argument: and  support Spec2's tagging features.See the inline links for full lists of arguments that the runners support. These appear to only work with the  sbt command and not ."},
Scala

I have a small script that's written in Scala which is intended to load a MongoDB instance up with 100,000,000 sample records. The idea is to get the DB all loaded, and then do some performance testing (and tune/re-load if necessary).The problem is that the load-time per 100,000 records increases pretty linearly. At the beginning of my load process it took only 4 seconds to load those records. Now, at nearly 6,000,000 records, it's taking between 300 and 400 seconds to load the same amount (100,000)! That's two orders of magnitude slower! Queries are still snappy, but at this rate, I'll never be able to load the amount of data that I'd like.Will this work faster if I write a file out with all of my records (all 100,000,000!), and then use  to import the whole thing? Or are my expectations too high and I'm using the DB beyond what it's supposed to handle?Any thoughts? Thanks!Here's my script:Here's the output from my script:Some tips :I've had the same thing.  As far as I can tell, it comes down to the randomness of the index values.  Whenever a new document is inserted, it obviously also needs to update all the underlying indexes.  Because you're inserting random, as opposed to sequential, values into these indexes, you're constantly accessing the entire index to find where to place the new value.This is all fine to begin with when all the indexes are sitting happily in memory, but as soon as they grow too large you need to start hitting the disk to do index inserts, then the disk starts thrashing and write performance dies.As you're loading the data, try comparing  with the available memory, and you'll probably see this happen.Your best bet is to create the indexes  you've loaded the data.  However, this still doesn't solve the problem when it's the required _id index that contains a random value (GUID, hash, etc.), then your best approach might be to think about sharding or getting more RAM.What I did in my project was adding up a bit of multithreading (the project is in C# but I hope the code is self-explanatory). After playing with the necessary number of threads it turned out that setting the number of threads to the number of cores leads to a slightly better performance(10-20%) but I suppose this boost is hardware specific. Here is the code:Another alternative is to try . They use Fractal Indexes which means that .TokuMX is going to be included as a custom storage driver in an upcoming version of MongoDB.The current version of MongoDB runs under Linux. I was up and running on Windows quite quickly using ."},
Scala

How can I code my bundle in Scala and then deploy it into OSGI container?Do I compile it into \"java\" first or can i deploy scala straight into OSGI and use some kind of bundles to recognize it?Any pointers would be great.\nCurrently I am using Apache Felix as my osgi-container, but just a simple explanation of generic concepts would suffice to get me started.: Code in scala, deploy to OSGi.A quick intro video by the author here OSGi does not care what language you write your code in: JVM bytecode is just JVM bytecode. So:You'll notice that your bundle has dependencies on the Scala library. Again there is nothing strange about this, it's just like having dependencies in you Java code. In order for those dependencies to resolve, you need to install the Scala library bundle from There is nothing special to it: write your code in Scala and wrap it up as an OSGi bundle by providing the necessary bundle meta data and service descriptors as you would do with Java.  can help you in the process. Have a look at the  (a Scala script engine) for a working example. The  in the  takes care of generating and including the bundle meta data in the final jar file. It refers to the  xml file which you need to provide."},
Scala

Is there any equivalent in scala parallel collections to LINQ's  which sets the number of threads which will run a query? I want to run an operation in parallel which needs to have a set number of threads running.With the newest trunk, using the JVM 1.6 or newer, use the:This may be a subject to changes in the future, though. A more unified approach to configuring all Scala task parallel APIs is planned for the next releases.Note, however, that while this will determine the number of processors the query utilizes, this may not be the actual number of threads involved in running a query. Since parallel collections support nested parallelism, the actual thread pool implementation may allocate more threads to run the query if it detects this is necessary.EDIT:Starting from Scala 2.10, the preferred way to set the parallelism level is through setting the  field to a new  object, as in the following example:While instantiating the  object with a fork join pool, the parallelism level of the fork join pool must be set to the desired value ( in the example).Independently of the JVM version, with Scala 2.9+ (introduced parallel collections), you can also use a combination of the  and  functions to execute parallel jobs on small chunks, like this: creates chunks of length 2 or less,  makes sure the collection of chunks is not parallel (useless in this example), then the  function is executed on the small parallel chunks (created with ), thus insuring that at most 2 threads is executed in parallel.This might be however slightly less efficient than setting the worker pool parameter, I'm not sure about that."},
Scala

Anyone know of a good scala library to do whitespace removal/compaction from XML?to:scala.xml.Utility.trim() should do what you want:For whatever it's worth, this is what I've got going on now in the \"roll my own\" strategy:"},
Scala

Here are two solutions to exercise 4.9 in Cay Horstmann's Scala for the Impatient: \"Write a function lteqgt(values: Array[Int], v: Int) that returns a triple containing the counts of values less than v, equal to v, and greater than v.\" One uses tail recursion, the other uses a while loop. I thought that both would compile to similar bytecode but the while loop is slower than the tail recursion by a factor of almost 2. This suggests to me that my while method is badly written.Adjust the size of bigArray according to your heap size. Here is some sample output:Why is the while method so much slower than the tailrec? Naively the tailrec version looks to be at a slight disadvantage, as it must always perform 3 \"if\" checks for every iteration, whereas the while version will often only perform 1 or 2 tests due to the else construct. (NB reversing the order I perform the two methods does not affect the outcome). (after reducing array size to 20000000)Under Java  I get  for tail-recursion and while-loop respectively.Under Java  I get    So under Java 6 your while-loop is actually faster; both have improved in performance under Java 7, but the tail-recursive version has overtaken the loop.The performance difference is due to the fact that in your loop, you conditionally add 1 to the totals, while for recursion you always add either 1 or 0. So they are not equivalent. The equivalent while-loop to your recursive method is:and this gives exactly the same execution time as the recursive method (regardless of Java version).I'm not an expert on why the Java 7 VM (HotSpot) can optimize this better than your first version, but I'd guess it's because it's taking the same path through the code each time (rather than branching along the  /  paths), so the bytecode can be inlined more efficiently.But remember that this is not the case in Java 6. Why one while-loop outperforms the other is a question of JVM internals. Happily for the Scala programmer, the version produced from idiomatic tail-recursion is the faster one in the latest version of the JVM.The difference could also be occurring at the processor level. See , which explains how code slows down if it contains unpredictable branching.The two constructs are not identical.  In particular, in the first case you don't need any jumps (on x86, you can use cmp and setle and add, instead of having to use cmp and jb and (if you don't jump) add.  Not jumping is faster than jumping on pretty much every modern architecture.So, if you have code that looks likewhere you  add or you  jump instead, vs.(which only makes sense in C/C++ where 1 = true and 0 = false), the latter tends to be faster as it can be turned into more compact assembly code.  In Scala/Java, you can't do this, but you  dowhich a smart JVM should recognize is the same as x += (a < b), which has a jump-free machine code translation, which is usually faster than jumping.  An even smarter JVM would recognize thatis the same yet again (because adding zero doesn't do anything).C/C++ compilers routinely perform optimizations like this.  Being unable to apply any of these optimizations was not a mark in the JIT compiler's favor; apparently it can as of 1.7, but only partially (i.e. it doesn't recognize that adding zero is the same as a conditional adding one, but it does at least convert  into fast machine code).Now, none of this has anything to do with tail recursion or while loops per se.  With tail recursion it's more natural to write the  form, but you can do either; and with while loops you can also do either.  It just so happened that you picked one form for tail recursion and the other for the while loop, making it look like recursion vs. looping was the change instead of the two different ways to do the conditionals."},
Scala

What is the Scala's way to write the following code:I.e. what is the idiomatic way of executing the same piece of code based on multiple case values? Doesn't quite seem do the trick, since Scala evaluates the match value based on the first matching case, i.e. if i=2 the code will return nothing.Thanks for help!According to  there is no fallthrough, but you can make use of .This should do the trick:Case statements can actually include additional logic guards using a standard if statement.  So you could do something like:The matching guards can be any boolean function or composition of functions, so it gives it a lot more power than the standard switch statement in Java.While not applicable here, for more complex problems you can 'fallthrough' in a sense using the andThen function on partial functions.If you are dealing with actual classes (instead of strings or ints), you need  before each class to make them into a pattern before joining them with .You get nice exhaustive checking too! Note that you cannot do case class destructuring when using alternative pattern matching (e.g.  will fail to compile."},
Scala

I am teaching Scala for the first time and my students are finding the deliberate \"punning\" involved in companion objects very confusing.  Consider the following example:The confusion comes in when I use verbal phrases such as \"a stack object\" or \"stack objects\" or especially \"the stack object\".  My students have difficulty understanding whether I mean the singleton object Stack or objects of the Stack class.I'm looking for alternative ways to verbalize such things that beginners can understand more easily.  I've considered always referring to objects of the Stack class as \"Stack instances\" or \"instances of Stack\", but it seems crazy when trying to teach OO not to be able to call these things objects.  I've been trying to ALWAYS use the phrase \"singleton object\" or \"companion object\" when talking about the singleton object Stack, but the syntax of Scala is working against me there because it only uses the word \"object\".In this case, I could rename the singleton object StackFactory instead of Stack, but that's only an option for my own classes, not for the thousand and one companion objects already built into Scala.Edit: Sorry, I wasn't clear enough in my question.  The main confusion happens NOT when referring to the companion object.  In that case, as several people have noted, it is easy enough to use to a phrase such as \"the companion object\".  Instead, the main confusion happens when referring to ordinary instances.  Then, if I say \"a stack object\" (meaning some stack instance) or \"the stack object\" (meaning  particular instance), some fraction of the students will think I mean the companion object -- even though I did not use the word companion or singleton.And I can see perfectly well where the confusion comes from, because the word \"object\" appears  only with the companion object.This issue in Scala is certainly not without irony, but even in the Java space there can be naming issues regarding , its instances, its class and instances of its class.For Scala I propose the following terminology:In the end, I would say that the idea of OO includes objects (in the sense of modules and composition) as much as objects (in the sense of instances).Regardless of how you decide, consistency is key, especially for teaching.I think  (if it stands alone) or  (if it comes with a class) is the best way to name . The Scala Language Reference calls them modules. But modules have by now been too much associated with run-time entities (as in OSGI) to be comfortable with that.I think using the phrase \"companion object\" should be clear enough. I'd go forI think your solution sounds good. \"The  singleton\" very clearly denotes the fact that you're talking about a singleton object rather than a whole class of objects. As for the names working against you, explain that  declares a  object (singleton), whereas  is a template for a whole  of objects (class instances).One other thing you should probably make sure is that   . If the students don't understand that point then they'll probably have a harder time making the distinction between the singleton  and instances of .Note that if you rename the object then it's no longer a companion object. Classes and their companion objects have special permissions granted by the Scala compiler to access each other's private members. If you change the name of the singleton so that it doesn't match the class then there's no longer any indicator to the compiler that it's a companion object and it loses the companion privileges.If you're really good about being consistent you can also refer to the instances of  as \"Stack instances\", but that might require a bit much habit twisting. Other than that, \"the Stack companion object\" or \"object Stack\", never \"the Stack object\". Maybe my proposal is a bit naive, but I would just call(In fact, in Odersky's \"programming scala\" the term most often used is \"companion object\", which I think is pretty clear...)I would also stress the difference between a stack instance and the stack companion, it's a common source of confusion.and regarding the confusion of your students, I would empathize how important is for a university student to be careful and consistent with the use of terminology, you could also provide some quiz or exercises to tell the difference between each of these concepts.Sometimes terminology is better learnt by using it.If you want a singleton object to be a companion of a class or trait, it  have the same name (and package and source file).Companions can access each others private members, e.g. a factory in the companion object can still create instances of a (companion) class with a private constructor."},
Scala

I have a Boolean and would like to avoid this pattern:What I'd like to do is Any suggestions with a code example would be much appreciated.Scalaz has a way to do it with .\nThat would allow you to write :If you don't want to add a Scalaz dependency, just add the following in your code : Option().collect() is a good pattern for this kind of thing.from the REPL:None of the other answers answer the question as stated!  To get the exact semantics you specified use:You can then writeeg:Here, the guard holds the condition and the value passed to  is the value returned if the guard evaluates to true.Another choice:Usage:If you don't mind  being evaluated no matter the value of  you can also useThis would give you:"},
Scala

What is a difference between tell and forward, in case I will send the same message:andThe  will be different on the receiving end.\nMessage sends using  (also known as ):  message  to . \n  that message to . \n thinks the  of message  is .\nMessage sends using :  message  to . \n  that message to .\n thinks the  of message  is .\nWorth pointing out is, that you can achieve the same as  when explicitly setting the sender of a message using , however this is not typical Akka-style:\nFor more info refer to the .Tell sets the sender as the actor sending the message.Forward keeps the original sender of the message."},
Scala

in normal Scala map and flatMap are different in that flatMap will return a iterable of the data flattened out into a list.\nHowever in the Akka documentation, map and flatMap seem to do something different?It says \"Normally this works quite well as it means there is very little overhead to running a quick function. If there is a possibility of the function taking a non-trivial amount of time to process it might be better to have this done concurrently, and for that we use flatMap:\"Can someone please explain what is the difference between map and flatMap here in Akka futures?In \"normal\" Scala (as you say), map and flatMap have nothing to do with Lists (check Option for example).Alexey gave you the correct answer. Now, if you want to know why we need both, it allows the nice  syntax when composing futures. Given something like:The compiler rewrites it as:If you follow the method signature, you should see that the expression will return something of type . Suppose now only map was used, the compiler could have done something like:However, the result whould have been of type . That's why you need to flatten it. To learn about the concept behind, here is one the best introduction I've read:The type, basically:I am pasting the implementation of the two methods here.\nthe difference in english terms is below\nFrom implementation the difference is that flatMap actually calls the function with result when the promise completes.For a great article read:http//danielwestheide.com/blog/2013/01/16/the-neophytes-guide-to-scala-part-9-promises-and-futures-in-practice.html"},
Scala

I tried  but it sorted in ascending order.  also sorts in descending order. I looked on stackoverflow and the answers I found were all outdated or . I'd like to use the native dataframe in spark.You can also sort the column by importing the spark sql functionsOr Or It's in  for  method:Note  and  inside  for the column to sort the results by."},
Scala

Having  I am trying to get the first and the last  of the set by means of  and  respectively but the compiler says . How to define this ordering (both implicit and explicit options are interesting)?To facilitate working with Joda DateTime in Scala, nscala-time was created:\nAfter including it in your project with you can just import . Either all at once:or a particular one:"},
Scala

How do you replace an element by index with an immutable List.E.g.In addition to what has been said before, you can use  function that replaces sub-sequences of a sequence:If you want to replace index 2, thenIf you want to find every place where there's a 2 and put a 5 in instead,In both cases, you're not really \"replacing\", you're returning a new list that has a different element(s) at that (those) position(s).You can use  (which is a method on ).It's probably better to use a  for this purpose, becuase updates on  take (I think) constant time.If you do a lot of such replacements, it is better to use a muttable class or Array.You can use map to generate a new list , like this :"},
Scala

I'd like to use  to declare multiple variable like this:But for whatever reason, it's a syntax error, so I ended up using either:orI personally find both options overly verbose and kind of ugly.Also, I know Scala is very well thought-out language, so why isn't the  syntax allowed?The trivial answer is to declare them as tuples:What might be interesting here is that this is based on pattern matching. What is actually happens is that you are constructing a tuple, and then, through pattern matching, assigning values to ,  and .Let's consider some other pattern matching examples to explore this a bit further:Just as a side note, the  example, in particular, may be written more simply, and without illustrating pattern matching, as shown below.Daniel's answer nicely sums up the correct way to do this, as well as why it works.  Since he already covered that angle, I'll attempt to answer your broader question (regarding language design)...Wherever possible, Scala strives to avoid adding language features in favor of handling things through existing mechanisms.  For example, Scala doesn't include a  statement.  However, it's almost trivial to roll one of your own as a library:This can be used in the following way:( this is included in the standard library for Scala 2.8)Multiple assignment syntaxes such as are allowed by languages like Ruby (e.g. ) fall into the category of \"redundant syntax\".  When Scala already has a feature which enables a particular pattern, it avoids adding a new feature just to handle a special case of that pattern.  In this case, Scala already has pattern matching (a general feature) which can be used to handle multiple assignment (by using the tuple trick outlined in other answers).  There is no need for it to handle that particular special case in a separate way.On a slightly different aside, it's worth noting that C's (and thus, Java's) multiple assignment syntax is also a special case of another, more general feature.  Consider:This exploits the fact that assignment returns the value assigned in C-derivative languages (as well as the fact that assignment is right-associative).  This is not the case in Scala.  In Scala, assignment returns .  While this does have some annoying drawbacks, it is more theoretically valid as it emphasizes the side-effecting nature of assignment directly in its type.I'll add one quirk here, because it hit myself and might help others.When using pattern matching, s.a. in declaring multiple variables, don't use Capital names for the variables. They are treated as names of classes in pattern matching, and it applies here as well.Error message does not really tell what's going on:I thought `-ticking would solve the issue but for some reason does not seem to (not sure, why not):Still the same errors even with that.Please comment if you know how to use tuple-initialization pattern with capital variable names.It seems to work if you declare them in a tupleAlthough I would probably go for individual statements. To me this looks clearer:especially if the variables are meaningfully named.If all your variables are of the same type and take same initial value, you could do this."},
Scala

In a Scala Compiler Plugin, I'm trying to create a new class that implement a pre-existing trait. So far my code looks like this:But it doesn't seem to get added to the package. I suspect that is because actually the package got \"traversed\" before the trait that causes the generation, and/or because the \"override def transform(tree: Tree): Tree\" method of the TypingTransformer can only return  Tree, for every Tree that it receives, so it cannot actually produce a new Tree, but only modify one.So, how do you add a new Class to an existing package? Maybe it would work if I transformed the package when \"transform(Tree)\" gets it, but I that point I don't know the content of the package yet, so I cannot generate the new Class this early (or could I?). Or maybe it's related to the \"Position\" parameter of the Symbol?So far I found several examples where Trees are modified, but none where a completely new Class is created in a Compiler Plugin.The full source code is here: The trick is to store the newly created s and use them when creating a new . Note that you need to deal with both Symbols and trees: a package symbol is just a handle. In order to generate code, you need to generate an AST (just like for a class, where the symbol holds the class name and type, but the code is in the  trees).As you noted, package definitions are higher up the tree than classes, so you'd need to recurse first (assuming you'll generate the new class from an existing class). Then, once the subtrees are traversed, you can prepare a new PackageDef (every compilation unit has a package definition, which by default is the empty package) with the new classes. In the example, assuming the source code is the compiler wraps it intoand the plugin transforms it into"},
Scala

I was reading  about using the  method in the REPL code for interactive debugging, but then I found  saying that  and  were removed from  in Scala 2.10. Unfortunately, that post doesn't explain  the code was removed. I'm assuming that these functions were removed because there's a better way of doing this. If that's the case, could someone please enlighten me?Perhaps the idea is that you should just work with the  directly? As far as I can tell, it shouldn't be much more complex than:Compared to the old  API, this approach gets rid of an additional level of indirection for both the  condition (which was wrapped into a ) and the / (which were temporary wrappers used only to fill in the  arguments).This approach also allows you to specify your  as needed. For example, ."},
Scala

Now with announcement of  Google clarified the foreseeable future of Java in relation to Android. But what are the implications to Scala and other JVM-based languages developers. In particular:All these questions boil down to one: Can Scala be used for Android development in future without sacrificing the benefits of new Scala features and new Android tool chain?Related reading:Related questions: Related:Please vote for Jack tool feature request:EDIT:Below is a hypothetical flow of Jack build with some extra blocks that was added basing on my logic and what i have learned from available docs.Base assumption is that Dalvik supports up to Java 7 bytecode instructions. If that is correct Java 8 instructions can not be directly passed to Dalvik, they should be somehow transformed to Java 7. (May be something similar to that Scala compiler always does).Than the question is where is that transformation happens? Seems Jill can't process Java 8 bytecode as for now, so that possibly happens in block (3) of hypothetical flow. If that is correct than only Java source project files are subject to transformation and the answer to  is - No. Java 8 classes from libraries can not be utilized until Jill will be able to do it (if it's possible at all). That is we can not use Scala 12+.If all code optimization is performed in block (6)  than the answer to  is - Yes. Scala code being converted to library .jar can benefit from Jack optimizations. But preliminarily it should be transformed to .jayce (AST-like representation) that will increase build time.And finally Jack produces .dex Dalvik bytecode to maintain compatibility with older Dalvik runtimes (ART consumes Dalvik bytecode too). So the answer to  is: Yes, Java 8 features can be used. But only in project Java sources. App is still compatible with any runtime. But Java 8 advantages are dropped due to converting to Java 7 (Dalvik bytecode).It\u2019s important to understand that there is  introduced:So it sounds like there is  here:Joan is correct, but I think Jill will have support for Java 8 at some point to, otherwise it will be impossible to use Java 8 in android libraries that will be consumed by android apps, as they package their code in a jar files inside of aar and I don't see this format change happening anywhere soon. Anyway we can only guess, as Google is currently a blackbox in respect to those kinds of changes.Google just announced that the Jack toolchain will deprecate the Jack toolchain and Android adds \"support for Java 8 language features directly into the current javac and dx set of tools\"Source: and:"},
Scala

By all accounts, Scala's  is a bit of a mess - everything I've read about it mentions resources left open, mysterious bugs...I was wondering whether that was still the case in recent versions of Scala and, if so, what are worthy alternatives?I've mostly heard of  and  (and, obviously standard Java IO primitives). Did I miss anything? If anyone has experience with these or other projects, what are their respective pros and cons?I'm inclined to go for , since I found the author's  to be a fairly high quality source of useful of information, but I'd love to know more about the alternatives and what other people use. might be worth trying.It provides some nice DSL for managing IO resources of various kinds.Using the package  in Java standard library may also be simple enough if you don't require advance features. For example, to read the lines of a file into memory:And to write a sequence of lines into a file:Check\n\nfor more information."},
Scala

I have a fairly normal  currently being built using Maven. I would like to support both Scala 2.9.x and the forthcoming 2.10, which is not binary or source compatible. I am willing to entertain converting to SBT if necessary, but I have run into some challenges.My requirements for this project are:Things I have tried:I accept that there may not be a solution that does what I want for Scala, and/or I may need to write my own Maven or Scala plugins to accomplish the goal. But if I can I'd like to find an existing solution.I am close to accepting @Jon-Ander's excellent , but there is still one outstanding piece for me, which is a unified release process. The current state of my . (I'll reproduce it here in an answer later for posterity).The sbt-release plugin does not support multi-version builds (i.e.,  does not behave as one might like), which makes a sort of sense as the process of release tagging doesn't really need to happen across versions. But I would like two parts of the process to be multi-version: testing and publishing.What I'd like to have happen is something akin to two-stage maven-release-plugin process. The first stage would do the administrative work of updating Git and running the tests, which in this case would mean running  so that all versions are tested, tagging, updating to snapshot, and then pushing the result to upstream.The second stage would checkout the tagged version and , which will rerun the tests and push the tagged versions up to the Sonatype repository.I suspect that I could write  values that do each of these, but I'm not sure if I can support multiple  values in my . It probably can work with some additional scopes, but that part of SBT is still strange majick to me.What I currently have done is changed the  to not publish. I then have to checkout the tagged version by hand and run  after the fact, which is close to what I want but does compromise, especially since the tests are only run on the current scala version in the release process. I could live with a process that isn't two-stage like the maven plugin, but does implement multi-version test and publish.Any additional feedback that can get me across the last mile would be appreciated.Most of this is well supported in sbt within a single source treeVersion specific source directories are usually not need. Scala programs tends to be source compatible - so often in fact that \ncrossbuilding () has first class support in sbt.If you really need version specific code, you can add extra source folders.\nPutting this in your build.sbt file will add \"src/main/scala-[scalaVersion]\" as a source directory for each version as you crossbuild in addition to the regular \"src/main/scala\".\n(there is also a plugin available for generating shims between version, but I haven't tried it - )version specific source jars - see crossbuilding, works out of the boxintegrated deployment -  (has awesome git integration too)Maven end-users - Shaded - I have used this one  which have worked fine for my needs.\nYour problem with the assembly plugin can be solved by rewriting the generated pom.\nHere is an example ripping out joda-time.Complete build.sbt for for referenceI've done something similar to this with SBT as an example:\nIt's made possible by SBT allowing all the settings to be determined based on other settings, which means that most other things should \"just work\".As far as the pom.xml aspect I can only recommend asking the question in the SBT mailing list, I would be surprised if you couldn't do that however.My blog post  contains an example of a slightly more finegrained solution for attaching different source directories; one per major S. Also it explains how to create scala-version-specific code that can be used by not-specific code.: Sbt now supports this out of the box: "},
Scala

While trying to find a solution to another question () I came across a diverging implicit expansion error. I'm looking for an explanation about what this meansHere's the use case:If you run this in scala with the  argument passed, you get more information:This is mostly speculation, but would seem to make some sense. I will try to investigate further:This seems to suggest that there are three implicits that are being considered here. Ultimately, the signature of  requires it to find something of type . So it's trying to construct your implicit function . Firstly, it's trying to fill in  by finding an implicit of type , where it's searching in Predef - which seems like barking up the wrong tree. It's then trying to find an implicit for  in the same place, since  takes an implicit parameter of type , where  is  by virtue of . So it can't construct .It then tries to use  in math.Ordering, but this also doesn't fit. However, I think this is what's giving the somewhat confusing 'diverging implicits' message. The problem isn't that they're diverging, it's that there isn't a suitable one in scope, but it's being confused by the fact that there are two paths to go down. If one tries to define  without the implicit ordered function, then it fails with just a nice message saying that it can't find a suitable implicit."},
Scala

 has 2 methods that are specified to prepend an element to an (immutable) list: technically has a more general type signature\u2014\u2014but ignoring the implicit, which according to the doc message merely requires  to be , the signatures are equivalent. If they are in fact identical, I assume  would be preferred to avoid depending on the concrete implementation . But why was another public method defined, and when would client code call it?There is also an extractor for  in pattern matching, but I'm wondering about these particular methods.See also: The best way to determine the difference between both methods is to look it the source code.The  of :The  of :As you can see, for , both methods do one and the same (the compiler will choose  for the  argument).So, which method to use? Normally one would choose the interface () than the implementation () but because  is a general data structure in functional languages it has its own methods which are widely used. Many algorithms are build up the way how  works. For example you will find a lot of methods which prepend single elements to  or call the convenient  or  methods because all these operations are . Therefore, if you work locally with a  (inside of single methods or classes), there is no problem to choose the -specific methods. But if you want to communicate between classes, i.e. you want to write some interfaces, you should choose the more general  interface. is more generic, since it allows the result type to be different from the type of the object it is called on. For example:"},
Scala

Is it lack of time, some technical problem or is there a reason why it should not exist?It's just a missing case that will presumably eventually be filled in.  There is no reason not to do it, and in certain cases it would be considerably faster than the immutable tree (since modifications require log(n) object creations with an immutable tree and only 1 with a mutable tree).Edit: and in fact it was filled in in 2.12..(There is a corresponding  also.)Meanwhile you can use the Java TreeMap, which is exactly what you need.I assume that the reason is that having a mutable variant doesn't bring a big benefit. There are some cases mentioned in the other answers when a mutable map could be a bit more efficient, for example when replacing an already existing value: A mutable variant would save creation of new nodes, but the complexity would be still .If you want to keep a shared reference to the map, you can use  which wraps any immutable map into a mutable structure.You'll also notice that  doesn't have a mutable equivalent either. It's because they share the common base class , and the underlying data structure that keeps the  ordered by elements or keys is a . I don't know too much about this data structure, but it's pretty complex (insertion and removal are pretty expensive compared to other Maps), so I assume that had something to do with a mutable variant not being included.Basically, it's probably because the underlying data structure isn't readily mutable so  isn't. So, to answer your question, it's a technical problem. It can definitely be done though, there's just not much of a use case for it.There may be performance reasons for a mutable , but usually you can use an immutable map in the same way as you would a mutable one. You just have to assign it to a  rather than a . It would be the same as for , which has mutable and immutable variants:"},
Scala

I wonder if there are any game engine written in Scala or easily accesible from Scala?All the Java gaming engines are easily accessible due to easy Java integration. There are several (not sorted in any way):A good presentation how to start coding a game in Java is  that applies as well.As  the ointerop should be easy. As mcherm pointed out, for . To have the nice Scala feel you could add some . I am currently working on a 3d engine in Scala: It still has a long way to go before it's a competitor to the major Java engines out there, but good progress is being made and more help is always appreciated. :) is an example of someone using a library like LWJGL from Scala. That seems like your best plan -- integrate with a good Java library. The integration betweeen Scala and Java is quite strong: in order to use such a library you need to integrate in \"both directions\": call Java code from your Scala (to do things like drawing to the screen) and also implement Java interfaces from your Scala code (to do things like responding to events). Fortunately, Scala makes it quite easy to do both.There is such engine in the works. Right now I am building a solid base with an easy to use math library to be optimized via compiler plugin. The math part is finished, including all the vectors, matrices, quaternions, rotations and projections for setting up the camera and ready to be plugged into opengl pretty much out of the box. A simple renderer will be done in a near feature. The compiler plugin will take time.Link: It's probably not a full fledged game engine though. (I dunno I have never written large games).There is a 2D game engine : For java, there is also Slick2d, which is pretty far developed and still active. Integration in Scala is easy as always."},
Scala

I've been working with Scala for a while now and have written a 10,000+ line program with it, but I'm still confused by some of the inner workings. I came to Scala from Python after already having intimate familiarity with Java, C and Lisp, but even so it's been slow going, and a huge problem is the frustrating difficulty I've often found when trying to investigate the inner workings of objects/types/classes/etc. using the Scala REPL as compared with Python. In Python you can investigate any object  (type, object in a global variable, built-in function, etc.) using  to see what the thing evaluates to,  to show its type,  to tell you the methods you can call on it, and  to get the built-in documentation.  You can even do things like  to find out the documentation on the package named  (which holds regular-expression objects and methods), even though there isn't an object associated with it.In Scala, you can try and read the documentation online, go look up the source code to the library, etc., but this can often be very difficult for things where you don't know where or even what they are (and it's often a big chunk to bite off, given the voluminous type hierarchy) -- stuff is floating around in various places (package , , various implicit conversions, symbols like  that are nearly impossible to Google). The REPL should be the way to explore directly, but in reality, things are far more mysterious.  Say that I've seen a reference to  somewhere, but I have no idea what it is.  There's apparently no such thing as a \"guide to systematically investigating Scala thingies with the REPL\", but the following is what I've pieced together after a great deal of trial and error:Example of failure using :Example of enlightening error message:OK, now let's try a simple example.Simple enough ...Now, let's try some real cases, where it's not so obvious:What does this mean?  Why is the type of  simply , whereas the class is ? I gather that the $ is the way that companion objects are shoehorned into Java ...  but Scala docs on Google tell me that  is  -- how can I deduce this from the REPL?  And how can I look into what's in it?OK, let's try another confusing thing:OK, this left me hopelessly confused, and eventually I had to go read the source code to make sense of this all.So, my questions are:Thanks for any enlightenment.You mentioned an important point which Scala lacks a bit: the documentation.The REPL is a fantastic tool, but it is not as fantastic at it can be. There are too much missing features and features which can be improved - some of them are mentioned in your post. Scaladoc is a nice tool, too, but is far away to be perfect. Furthermore lots of code in the API is not yet or too less documented and code examples are often missing. The IDEs are full ob bugs and compared to the possibilities Java IDEs show us they look like some kindergarten toys.Nevertheless there is a gigantic difference of Scalas current tools compared to the tools available as I started to learn Scala 2-3 years ago. At that time IDEs compiled permanently some trash in the background, the compiler crashed every few minutes and some documentation was absolutely nonexistent. Frequently I got rage attacks and wished death and corruption to Scala authors.And now? I do not have any of these rage attacks any more. Because the tools we currently have are great although the are not perfect!There is , which summarizes a lot of great documentation. There are Tutorials, Cheat-sheets, Glossaries, Guides and a lot of more great stuff. Another great tools is , which can find even the weirdest operator one can think of. It is Scalas  and even though it is not yet as good as his great ideal, it is very useful.Great improvements are coming with Scala2.10 in form of Scalas own Reflection library:Documentation for the new Reflection library is still missing, but in progress. It allows one to use scalac in an easy way inside of the REPL:This is even greater when we want to know how Scala code is translated internally. Formerly wen need to type  to get the internally representation. Furthermore some small improvements found there way to the new release, for example:Scaladoc will gain some  (click on type-hierarchy).With Macros it is possible now, to improve error messages in a great way. There is a library called , which does this:There is a tool which allows one to find libraries hosted on GitHub, called .The IDEs now have some semantic highlighting, to show if a member is a object/type/method/whatever. The semantic highlighting feature of .The javap feature of the REPL is only a call to the native javap, therefore it is not a very featue-rich tool. You have to fully qualify the name of a module:Some time ago I have written a , which offers a lot of things to know.And the best: This is all done in the last few months!So, how to use all of these things inside of the REPL? Well, it is not possible ... not yet. ;)But I can tell you that one day we will have such a REPL. A REPL which shows us documentation if we want to see it. A REPL which let us communicate with it (maybe like ). A REPL which let us do cool things we still cannot imagine. I don't know when this will be the case, but I know that a lot of stuff was done in the last years and I know even greater stuff will be done in the next years.Javap works, but you are pointing it to , which is a , not a . Point it instead to .Now, for the most part just entering a value and seeing what the result's type is is enough. Using  can be helpful sometimes. I find that use  is a really bad way of going about it, though.Also, you are sometimes mixing types and values. For example, here you refer to the object :And here you refer to the class :Objects and classes are not the same thing, and, in fact, there's a common pattern of objects and classes by the same name, with a specific name for their relationship: companions.Instead of , just use tab completion:If you enter the power mode, you'll get way more information, but that's hardly for beginners. The above shows types, methods, and method signatures. Javap will decompile stuff, though that requires you to have a good handle on bytecode.There's other stuff in there -- be sure to look up , and see what's available.Docs are only available through the scaladoc API. Keep it open on the browser, and use its  capability to quickly find classes and methods. Also, note that, as opposed to Java, you don't need to navigate through the inheritance list to get the description of the method.And they do search perfectly fine for symbols. I suspect you haven't spent much time on scaladoc because other doc tools out there just aren't up to it. Javadoc comes to mind -- it's awful browsing through packages and classes.If you have specific questions Stack Overflow style, use  to search with symbols.Use the  Scaladocs: they'll diverge from whatever version you are using, but they'll always be the most complete. Besides, right now they are far better in many respects: you can use TAB to alternate between frames, with auto-focus on the search boxes, you can use arrows to navigate on the left frame after filtering, and ENTER to have the selected element appear on the right frame. They have the list of implicit methods, and have class diagrams.I've made do with a far less powerful REPL, and a far poorer Scaladoc -- they do work, together. Granted, I skipped to trunk (now HEAD) just to get my hands on tab-completion.Note that  can facilitate the type exploration/discovery.It now includes:You need to pass fully qualified class name to .First take it using :Then use  (doesn't work from repl for me: \":javap unavailable on this platform.\") so example is from a command line, in repl, I believe, you don't need to specify classpath:But I doubt this will help you. Probably you're trying to use techniques you used to use in dynamic languages. I extremely rarely use repl in scala (while use it often in javascript). An IDE and sources are my all."},
Scala

 However, superficially, it seems that it can easily be encoded in an object-oriented language that supports abstract type members. For example, we can encode the elements of SML module system in Scala as follows:Are there any significant features such an encoding would miss? Anything that can be expressed in SML modules that encoding can't express? Any guarantees that SML makes that this encoding would not be able to make?There are a few fundamental differences that you cannot overcome easily:The differences become even more interesting when you move beyond SML, to higher-order, first-class, or recursive modules. We briefly discuss a few issues in Section 10.1 of our ."},
Scala

I am thinking about migrating to play 2.0 after play 1.2. One thing that bothers me is that people say Scala is more \"preferred\" for a play 2.0 application. I know the differences over 1.2 and 2.0, but I'm unsure if there are differences between Play 2.0 with Java and Play 2.0 with ScalaSo there are questions in my mind: I just finished a prototype using Play 2.0 with Java and now am considering to learn Scala just so I can switch to it for further development.It's not just the usual  discussion - the problem as I see it with the Play framework is that it forces Scala idioms onto Java. An example from the documentation about :It works but doesn't look like conventional Java. Those parentheses look really scary. Even Eclipse gets confused and never knows what generics I need or want to use - I always have to choose them manually.Also note that in the documentation they made this look pretty by removing  annotations, using just two spaces for indentation and overall choosing a very simple example without validation or error recovery so they don't use too many lines. I'm not even sure you could configure a code formatter to output it like this without messing up other code completely. In practice I ended up with an unreadable block of a horrible Java-Scala-abomination just for getting some data from another service.Unfortunately I can't find any example of combining responses in Scala. At least calling single  looks much shorter and easier to read.AFAIK, it is better to go with Scala, because it offers more functionnality.For instance (correct me if I'm wrong), you can directly using the  with Scala (aka reactive programming), but I don't know how to achieve that with Java.Also, the Java API of Play is an upper layer in the Play architecture, the core is written with Scala; so if you want to lean what's happening inside, go with Scala.And also note that you can mix Java and Scala in the same Play project, so you can move smoothly to Scala.I was new to Play and just wrote a small-mid sized Project with the Java side of it.It works and is powerful, but a lot of Features just seem to be very Scala centric and the Java support is sub-par.\nThe Java API Doc is virtually non existent, which takes away some comfort in the IDE (IntelliJ - I recommend it).\nThe integration in the Java world is not very \"natural\" (SBT..), It does not build as a war or maven module (but there seem to be plugins to do this). You kind of loose the benefits of the existing Java tooling.The concepts which differentiate Play from the other Frameworks almost all seem to be scala native and Java second.I stumbled onto some bugs and quirks and I always would end up in Scala code I had to read and understand to fix or work around it. (Actions, RequestBody stuff, Async, routes, template implicits and so on)So the Java side of things just feels very second tier to me, although they are clearly making an effort for them to be equally good.Now, after the Project, I would say it is very usable and would even use it again (in Java).As djangofan commented, when you google for Play help, you get examples in Scala.However, I haven't yet (still a beginner) found an equivalent of Ebean for Scala.  The Scala examples I've found all use direct SQL for persistence.  Where's the database abastraction?Since I haven't found a database abstraction for Play with Scala, I'm continuing with Java..."},
Scala

I am frequently getting an  from SBT.Sometimes it also exits abruptly with:Any solutions?This sometimes happens if you compile huge codebases - a lot of classes get loaded into the VM running sbt.You need to increase the  space for sbt - use the flag , where  you can change with the desired size of the permanent generation.Run:to locate you sbt startup script. Then edit it to include the flag with the  command that runs the sbt launcher in the similar way as it is  for modifying  and .Adding the  flag should also enable sbt to unload the classloaders with classes from the previous compilation runs that are no longer being used.EDIT:Alternatively, you can set these options in the  environment variable if you are using the ."},
Scala

I'm relatively new to Scala and am trying to define a generic object method.  However, when I refer to the parameterized type within the method I am getting \"No ClassTag available for T\".  Here is a contrived example that illustrates the problem.Thanks in advance for help in understanding what is wrong here and how to make this contrived example work.To instantiate an array in a generic context (instantiating an array of  where  is a type parameter), scala needs at runtime to have information about , in the form of an implicit value of type .\nConcretely, you just need to require from the caller of your method to (implicitly) pass this  value, which can conveniently be done using a :For a (torough) description of this situation, see this document:(To put it shortly, ClassTags are the reworked implementation of ClassManifests, so the rationale remains)"},
Scala

I have an immutable Set of a class, Set[MyClass], and I want to use the Set methods intersect and diff, but I want them to test for equality using my custom equals method, rather than default object equality testI have tried overriding the == operator, but it isn't being used.Thanks in advance.Edit:The intersect method is a concrete value member of GenSetLikespec: \nsrc: so the intersection is done using the filter method.Yet another Edit:filter is defined in TraversableLikespec: src: What's unclear to me is what it uses when invoked without a predicate, p. That's not an implicit parameter.equals and hashCode are provided automatically in case class only if you do not define them.  If what you want is reference equality, still write equals and hashCode, to prevent automatic generation, and call the version from AnyRefWith that: You cannot override the  from AnyRef, which is sealed and always calls equals. If you tried defining a new (overloaded) , it is not the one that  calls, so it is useless here and quite dangerous in general. As for the call to , the reason it works is that  is a . And yes,  is used, you will see that function implementation () is a synonymous for , and  most implementations of  use  in contains ( uses the  instead).  And  calls .Note: the implementation of my first  is quick and dirty and probably bad if MyClass is to be subclassed . If so, you should at the very least check type equality () or better define a  method (you may read  by Daniel Sobral)You'll need to override  as well. This is almost always the case when you override , as  is often used as a cheaper pre-check for ; any two objects which are equal  have identical hash codes. I'm guessing you're using objects whose default  does not respect this property with respect to your custom equality, and  the Set implementation is making assumptions based on the hash codes (and so never even calling your equality operation).See the Scala docs for  and : . It could be made immutable by replacing the internal store with a  and returning a modified copy of itself upon each operation\"It is not possible to override == directly, as it is defined as a final method in class Any. That is, Scala treats == as if were defined as follows in class Any:\" from Programming In Scala, Second Edition"},
Scala

Have somebody use both Buildr and Gradle and can make comparison of this build tools. From first look they are very similar. But what to choose. And also it is good to hear about Scala support and various IDE integration(IDEA, NetBeans, Eclipse).Thanks.I have tried using, both and I'd definitely recommend Gradle. While both of them have pretty much the same expressiveness, I found Gradle to be much more stable (since version 1.0), less effort to install, and better documented. Although Buildr is undoubtedly a great effort, at the moment Gradle is much more professionally made.The only problem I faced with Gradle is lack of native support for reusing ivy.xml (and ivysettings.xml), despite the fact that Gradle actually uses Ivy as its dependency engine. This feature has been promised for sometime in the future soon. Buildr, on the other hand has a ready-to-use plugin for that (it's not very configurable though).If you need to migrate from Maven, I'd do some investigation on both tools and their support for the features you need. For new projects I'd recommend Gradle.Neither have good support for Eclipse, but Gradle have a work-in-progress Eclipse plugin that works very much like the Ant plugin. Also, Gradle's generation of Eclipse settings files is highly customizable, so that's another way to integrate it with Eclipse.See if this helps (probably outdated): If compared to BuildR, I'd recommend Gradle:\n1. Groovy is much more \"native\" to the JVM ecosystem than Ruby. Even if you use JRuby, you'd still need to install a lot of gems\n2. BuildR's development is crawling. They have not added new features in a long timeHaving said that, I'd question using either one of these: With the power to script any task comes the risk that the build will have a lot of logic that people need to learn before being able to maintain it. Since this is not the main logic of the product, you have the risk of people that do not want to maintain the build or worse, doing it in copy&paste way that is not right (e.g., performance wise). With Maven, there's no logic in the pom. Also, using Gradle/BuildR means that to build the product, one needs to install Gradle/BuildR. Maven is much more standard here. I looked at both gradle and buildr and went for buildr in the end because of one huge disadvantage with gradle: start-up time of the build system. buildr is much snappier and gave me much faster incremental builds. Performance is something I found almost unbearable with gradle. Just consider how many times a build system is kicked off and add up the constant overhead.BTW I found the build server with both build systems (buildr and gradle) to be not very useful  and error prone (that is: I spent more time with troubleshooting than it actually sped up things)."},
Scala

I'm working on a Scala API (for Twilio, by the way) where operations have a pretty large amount of parameters and many of these have sensible default values. To reduce typing and increase usability, I've decided to use case classes with named and default arguments. For instance for the TwiML Gather verb:The parameter of interest here is . It is the only parameter which is  optional in the sense that if no value is supplied, no value will be applied (which is perfectly legal). I've declared it as an option in order to do the monadic map routine with it on the implementation side of the API, but this puts some extra burden on the API user:As far as I can make out, there are two options (no pun intended) to resolve this. Either make the API client import an implicit conversion into scope:Or I can redeclare the case class with a null default and convert it to an option on the implementation side:My questions are as follows:Here's another solution, partly inspired by .  It also involves a wrapper, but the wrapper is transparent, you only have to define it once, and the user of the API doesn't need to import any conversions:To address the larger design issue, I don't think that the interaction between Options and named default parameters is as much oil-and-water as it might seem at first glance.  There's a definite distinction between an optional field and one with a default value. An optional field (i.e. one of type ) might  have a value. A field with a default value, on the other hand, simply does not require its value to be supplied as an argument to the constructor. These two notions are thus orthogonal, and it's no surprise that a field may be optional and have a default value.That said, I think a reasonable argument can be made for using  rather than  for such fields, beyond just saving the client some typing.  Doing so makes the API more flexible, in the sense that you can replace a  argument with an  argument (or vice-versa) without breaking callers of the constructor[1].As for using a  default value for a public field, I think this is a bad idea. \"You\" may know that you expect a , but clients that access the field may not. Even if the field is private, using a  is asking for trouble down the road when other developers have to maintain your code. All the usual arguments about  values come into play here -- I don't think this use case is any special exception.[1] Provided that you remove the option2opt conversion so that callers must pass a  whenever an  is required.Don't auto-convert anything to an Option. Using , I think you can do this nicely but in a typesafe way.Then you can call it as you wanted to - obviously adding your  methods to  and  as appropriate. The main negative here is that it is a ton of boilerplatePersonally, I think using 'null' as default value is perfectly OK here. Using Option instead of null is when you want to convey to your clients that something may not be defined. So a return value may be declared Option[...], or a method arguments for abstract methods. This saves the client from reading documentation or, more likely, get NPEs because of not realizing something may be null.In your case, you are aware that a null may be there. And if you like Option's methods just do  at the start of the method.However, this approach only works for types of AnyRef. If you want to use the same technique for any kind of argument (without resulting to Integer.MAX_VALUE as replacement for null), then I guess you should go with one of the other answersI think as long as no language support in Scala for a real kind of void (explanation below) \u2018type\u2019, using  is probably the cleaner solution in the long run. Maybe even for all default parameters.The problem is, that people who use your API know that some of your arguments are defaulted might as well handle them as optional. So, they\u2019re declaring them asIt\u2019s all nice and clean and they can just wait and see if they ever get any information to fill this Option.When finally calling your API with a defaulted argument, they\u2019ll face a problem.I think it would be much easier then to do thiswhere the  would just be left out in case of . But this is not possible.So you really should think about who is going to use your API and how they are likely to use it. It may well be that your users already use  to store all variables for the very reason that they know they are optional in the end\u2026Defaulted parameters are nice but they also complicate things; especially when there is already an  type around. I think there is some truth in your second question.Might I just argue in favor of your existing approach, ? It's all of 6 more characters for the API user to type, shows them that the parameter is optional, and presumably makes the implementation easier for you.I think you should bite the bullet and go ahead with . I have faced this problem before, and it usually went away after some refactoring. Sometimes it didn't, and I lived with it. But the  is that a default parameter is not an \"optional\" parameter -- it's just one that has a default value.I'm pretty much in favor of  .I was also surprised by this.  Why not generalize to:Any reason why that couldn't just be part of Predef?"},
Scala

I use scala sbt console to test my methods. (commands :  then ) But the code changes done in eclipse or other external editor, are not getting reflected in the sbt console. Every time, I have to quit the console (using Crt + D) and again start it using  command to see the changes. Any one facing this problem? \nIs there any ways to reload the code from console? I am using Ubuntu 64-Bit, Not without using something like JRebel, mostly because class definitions could break in such a way as to make instances already loaded unusable. The only suggestion I have is to run the console with  so that if changes have been made they will be recompiled and the console re-entered.Also if you're regularly running a set of commands the initialCommands sbt setting configures commands to be run immediately after starting the console.One option is to use  in the console - this will reload it and replay all the commands you've entered so far.For a better solution you might want to read my  on incremental development with JRebel & Scala. You should modify the sbt startup script like this:When you start the REPL from inside SBT, for instance with the command:changes to the imported classes will be reflected automatically without the need to do a  or  the REPL - something reminiscent of the interactive Lisp programming.this will be rebuilding the app each time source code changes"},
Scala

I want to change  of a Spark job in dev/prod environment. It seems to me that the easiest way to accomplish this is to pass  to the job. Then Typesafe config library will do the job for me.Is there way to pass that option directly to the job? Or maybe there is better way to change job config at runtime?Change  command line adding three options:I Had a lot of problems with passing -D parameters to spark executors and the driver, I've added a quote from my blog post about it:\n\"\nThe right way to pass the parameter is through the property: \n\u201c\u201d and \u201c\u201d:\nI\u2019ve passed both the log4J configurations property and the parameter that I needed for the configurations. (To the Driver I was able to pass only the log4j configuration).\nFor example (was written in properties file passed in spark-submit with \u201c\u2014properties-file\u201d):\n\u201c\u201cYou can read  about overall configurations of spark.\nI'm am running on Yarn as well.Here is my spark program run with addition java optionas you can see \nthe custom config file\n the executor java options\n the driver java options.\n Hope it can helps.I am starting my Spark application via a spark-submit command launched from within another Scala application. So I have an Array likewhere  is:It is a bit tricky to understand where (not) to escape quotes and spaces, though. You can check the Spark web interface for system property values.if you write in this way, the later  will overwrite the previous one, you can verify this by looking at sparkUI after job started under  tab.so the correct way is to put the options under same line like this:\n\nif you do this, you can find all your settings will be shown under sparkUI."},
Scala

I'm hoping there is a way to define a type for a function in Scala.For example, say I want a function that takes two Ints and returns a Boolean, I could define a function that uses that like this:Is there a way to define the type of f? Then I could do something like:or "},
Scala

Consider the following Scala case class:Pattern matching allows me to extract one field and discard others, like so:What I would like to do, and what's more relevant when a case class has ~20 odd fields, is to extract only a few values in a way that does not involve typing out .I was hoping that named args could help here, although the following syntax doesn't work:Is there any hope here, or am I stuck typing out many, many ?: I understand that I can do , yet I'm still wondering whether there's even terser syntax that does what I need without having to introduce an extra .I don't know if this is appropriate, but you can also build an object just to match that field, or that set of fields (untested code):or evenYou can always fall back to guards. It's not really nice, but better than normal pattern matching for you monster case classes :-PThat said I think you should rethink your design. Probably you can logically group some parameters together using case classes, tuples, lists, sets or maps. Scala  support nested pattern matching:"},
Scala

I'm getting compile errors when running the  task as the sources reference new classes in  package that only appeared in Java 7.I have the following in :In sbt:It compiles and runs fine in Eclipse. How can I set up sbt to use Java 7 for compilation?The most reliable (perhaps only) way to do this at the moment it to start SBT with  in the JDK7 folder.Modify your  launcher script; or use  that allows you to specify Java Home (and so much more!) as command line options.Simply setting  changes the Java version used to compile and fork processes, but does not change the version of the Java standard library on the classpath, nor the version used to run tests, which are always run the the same JVM as SBT.If you use Linux or Mac, another possibility is to look at , a command line Java manager.It allows you to choose per project which JDK to use.I use , which is a tool from the Python ecosystem. In a nutshell, it is a shell script which allows you to change your PATH variable easily and get back to what it was before, if you need to.I'm assuming you want to change whatever you have set in JAVA_HOME by default, which you can do when invoking sbt:This works for me on OSX with sbt 0.13.8change javacOption to 1.7?  I don't think setting the javaHome is necessary."},
Scala

I couldn't find the answer to this in any other question. Suppose that I have an abstract superclass Abstract0 with two subclasses, Concrete1 and Concrete1. I want to be able to define in Abstract0 something likewhere Self would be the concrete subtype. This would allow chaining calls to setOption like this:and still get Concrete1 as the inferred type of obj.What I don't want is to define this:because it makes it harder for clients to handle this type. I tried various possibilities including an abstract type:but then it is impossible to implement setOption, because  in Abstract0 does not have type Self. And using  also doesn't work in Abstract0.What solutions are there to this issue?This is what  is for:As you can see setOption returns the actual type used, not Abstract0. If Concrete0 had  then  would work UPDATE: To answer JPP's followup question in the comment (how to return new instances:\nThe general approach described in the question is the right one (using abstract types). However, the creation of the new instances needs to be explicit for each subclass. One approach is:Another one is to follow the builder pattern used in Scala's collection library. That is, setOption receives an implicit builder parameter. This has the advantages that building the new instance can be done with more methods than just 'copy' and that complex builds can be done. E.g. a setSpecialOption can specify that the return instance must be SpecialConcrete.Here's an illustration of the solution:UPDATE 2: \nReplying to JPP's second comment. In case of several levels of nesting, use a type parameter instead of type member and make Abstract0 into a trait:This is the exact use case of . It would be like:"},
Scala

What's the difference between:andCan I declare parameters as s, and change their values later? For instance,For the first part the answer is scope: If you prefix parameters with ,  they will be visible from outside of class, otherwise, they will be private, as you can see in code above.And yes, you can change value of the var, just like usually.Thismakes the fields available externally to users of the class e.g. you can later doIf you specify the args as , then the scoping is the same as for , but the fields are mutable.If you are familiar with Java, you can get the idea from this example:is similiar toWhile is similar toThe intuition is that without var/val, the variable is only accessible inside the constructor. If var/val is added, the class will have the member variables with the same name.You could use a  and in that case the  class would have those variables available outside of the class. \n. Then the following code would work as expected. "},
Scala

In , is there a way to restrict messages to actors to be of a specific static type other than using the \"Typed Actor\" APIs that use an RPC style programming model?Can I use the message passing style with Akka without throwing away static type safety at the actor boundaries?For example, I'd like to use code like this:Perhaps one would have to extend some base trait or have a construct like  to allow for system level messages (, etc.).Then you'd have to encode the message type into the Actor ref, which would drastically decrease the value of something like the ActorRegistry.Also, with powerful mechanics like \"become\" (which is fundamental to the actor model) typing the messages is less valuable.Since Akka doesn't leak memory when a message is not matched to the current behavior, there is not the same risk of sending the \"wrong\" messages to the \"wrong\" actor.Also, Actors are by nature dynamic, so if you want to make them static, use TypedActor (which is not RPC, it's just as RPC as regular actors, void methods are ! calls, Future return type is !!! and other return types are based on !!)The common practice is to declare what messages an Actor can receive in the companion object of the Actor, which makes it very much easier to know what it can receive.Does that help?In Scala stdlib there was  for making basic actors untyped (which is not applicable to Akka, because it doesn't support nested receives, as I remember). Lift, in its turn, supports typed actors out-of-the-box.However, using channels, it's still possible to create strongly typed actors with stdlib:Actually restricting an Actor to have only single type as input is not very useful. What is more useful to my mind is to list possible inputs in a strictly typed manner.There is an approach for strictly typed inputs of actors ():In your case the interface consists of a single input contact:   Within SynapseGrid framework handling of signals is defined with Builder:Obviously one cannot construct Signal with incompatible types. Thus we have compile time checking. In SynapseGrid there is a DSL for working with signals and contacts. For instance, to send Foo or Bar from outside:Of course one may simply send the message:It sounds like Akka's  was to have addressed this, but (according to  ).In the documentation for Akka 2.2.3, there a good  section that discusses the difficulties in support typed message sends and responses.  There's also a good NEScala talk by Roland Kuhn,  ( / ), that discusses the implementation of typed channels."},
Scala

I am not sure what the difference is between specifying Unit as the return type of my scala method or leaving out the return type altogether. What is the difference?Can anyone please advise?Implicit  return type:Explicit  return type:Return type inferred from the last method expression, still  because this is the type of , but confusing:All the methods above are equivalent. I would prefer  because the lack of  operator after method signature alone is enough for me. Use explicit  when you want to extra document the method. The last form is confusing and actually treated as a warning in .The  operator is crucial. If it is present it means: \"\" in method body. Obviously you cannot use this syntax for  methods. If it is not,  is assumed.The special syntax for procedures (methods returning ) was a mistake. Don't use it. It is confusing and dangerous for beginners with a Java/C(++) background. And it is a unnecessary special treatment. Always use the equal sign, with and without type inference (the latter should only be used for private members):The Scala community is divided about it. On the one hand, not using explicit return types means you can easily forget the  sign, which results in errors that are often annoying to track. On the other hand, -returning methods having a different syntax puts them in a separate category, which pleases some people.Personally, I'd rather this syntax would go away -- the errors resulting from missing   annoying to track. But it's not even deprecated, so I'd rather take advantage of it than just suffer the problems of its existence.So, use whatever you wish. There's going to be people criticizing your choice either way, and people praising it either way."},
Scala

I have been toying with Scala and I was wondering if anyone had had any experience with using hibernate and mysql as a persistent store for scala objects? Does it work out of the box or is there a lot to do?Most of the time, Scala + Hibernate works quite well, with minor bumps which could be overcome easily. For exmaple, when dealing with collections, Hibernate requires the use of java.util interfaces. But you could import scala.collection.jcl.Conversions._ if you want to tap on Scala's more powerful library.You may want to check out ' post for more information.It is definitely not a lot of work. A simple hibernate + scala example can be defined in a few tens of lines. Scala and Java can be mixed up in the same project. In particular, the hibernate-scala combination makes possible to combine the JPA framework, and a very flexible orm layer with the elegance of immutable structures and functional programming as provided by scala. The easiest way to experiment with hibernate and scala is by using an in-memory hsqldb database via hibernate/jpa. First off, let\u2019s define the domain model. In this case, a scala class annotated according to hibernate style, about my buddies.Note how the scala class, is much more compact than the java class, since we don\u2019t need the typical getter/setter boilerplate code. Now let\u2019s make sure, that the jpa modules and the database model is loaded. According to the hibernate specification, let\u2019s add the well known hibernate configuration file: resources/META-INF/persistence.xml:After defining the persistency configuration, let\u2019s move on the main scala file:The code is quite straightforward. Once the JPA EntityManager is created via the factory, the data model is available for insertion, deletion, query, using the methods defined in the documentation of hibernate and jpa. This example has been set up using sbt. After retrieving the necessary packages, and compiling the source, running the tutorial will produce the following log:Scala Query is not Hibernate but may be interesting.There are issues.  Because some features of JPA leverage nested annotations, e.g. collections, you're in trouble because Scala does not yet support nested annotations.  That'll go away when 2.8 comes out.See  for more on this topic plus other incompatibilities.Note that Scala 2.8, now in RC5 and expected to release shortly, supports nested annotations.  The release has many other cool features as well.I have not used Hibernate with scala directly, but I am using JPA. Hibernate provides a JPA implementation, and the way you define JPA persistent classes or Hibernate ones is not much different, so I think using Hibernate without the JPA layer is possibleI am using hibernate with Scala. The real problem that I had to solve was how to persist Enumerations in hibernate. I've put my working solution on githubBasically one needs to define own UserTypeHave a look at  where there is full JPA adaptation for Scala."},
Scala

I tried Google search and could not find a decent  example. What does it do? Why does it take a boolean function?Please point me to a reference (except the Scaladoc).The  method takes a function  that returns a Boolean.  The semantics of  says: return  if for every  in the collection,  is true.So:means:  if 1, 2, and 3 are less than 3,  otherwise.  In this case, it will evaluate to  since it is not the case all elements are less than 3: 3 is not less than 3.There is a similar method  that returns  if there is  element  in the collection such that  is true.So: means:  if  1, 2, and 3 is less than 3,  otherwise.  In this case, it will evaluate to  since it is the case some element is less than 3: e.g. 1 is less than 3.A quick example of how you can play with this function using a  script.create a  file with and call it with "},
Scala

I'm using the following:I'm frequently running into this error:Currently I'm running into this when simply trying to call a  on my MongoDB collection.Upon Googling, it seems like it may be caused by dependency issues. The thing is, I'm using Scalatra just to serve an API and actually don't require any of the scalate stuff. I commented out all references to it, but I still get this. Could it be a dependency issue between the libraries I'm using?In my company we had this problem with CharSequence. This is due to Scala 2.10.x does not work with Java 8. This was described in Scalas . Switch back to Java 7.Switching to Scala 2.10.4 solved the problem for me.I have a similar problem on Java 1.8.0 working with Scala 2.10.4 and sbt 0.12.4. But when upgrading to sbt 0.13.7, the problem is solved.I am seeing the same issue with software requiring Scala 2.9.2+ and Java 1.7 running on Scala 2.10.4 and Java 1.8. Changed to Java 7 via sudo update-alternatives --config javaI solved this by using:My environment is:I hope a stable version of Scala will help you, Try 2.10.x with Java 1.7.x versions for better performance. I mean it worked for me also in the same.I had the same problem. However by switching to Java 7 my problem is resolved. \nSo now this configuration works for me:"},
Scala

Can command  run a compiled scala code? If so, why do we have an exclusive command ?You can run byte code generated by Scala if you include all necessary runtime libs for Scala (scala-library.jar, scala-swing.jar ...) in the classpath. The scala command does this automatically, and supports Scala specific command line arguments.Yes, it can. Scala is compiled down to Java bytecode. But remember that it depends on the Scala runtime classes, so you need to still have Scala's jar files on the classpath.Convenience wrapper.As long as you have installed the scala runtime you should be fine: compile classes with  and run them with .Just want to add my own answer as additional value for the future readers:those two can't be done using java"},
Scala

 says should import all classes from package , except  and . But it gives me this error: Is there still a way to do this?The   has to be put at the end - not at the beginning:See the detailed info in , page 50, paragraph 4.7"},
Scala

I have started work on FP recently after reading a lot of blogs and posts about advantages of FP for concurrent execution and performance. My need for FP has been largely influenced by the application that I am developing, My application is a state based data injector into another subsystem where timing is very crucial (close to a 2 million transactions per sec). I have a couple of such subsystems which needs to be tested. \nI am seriously considering using FP for its parallelism and want to take the correct approach, many posts on SO talk about disadvantages and advantages of Scala, Haskell and Clojure wrt language constructs, libraries and JVM support. From a language point of view I am ok to learn any language as long as it will help me achieve the result.Certain posts favor Haskell for pattern matching and simplicity of language, JVM based FP lang have a big advantage with respect to using existing java libraries. JaneStreet is a big OCAML supporter but I am really not sure about developer support and help forums for OCAML.If anybody has worked with handling such large data, please share your experience.Do you want  or do you want ?If you want fast, you should use C++, even if you're using FP principles to aid in correctness.  Since timing is crucial, the support for soft (and hard, if need be) real-time programming will be important.  You can decide exactly how and when you have time to recover memory, and spend only as much time as you have on that task.The three languages you've stated all are , and then only when used in a rather traditional imperative way.  They all use garbage collection, which will introduce uncontrolled random delays in your transactions.Now, that said, it's a  of work to get this running in bulletproof fashion with C++.  Applying FP principles requires considerably more boilerplate (even in C++11), and most libraries are mutable by default.  (Edit: Rust is becoming a good alternative, but it is beyond the scope of this answer to describe Rust in sufficient detail.)Maybe you don't have the time and can afford to scale back on other specifications.  If it is not  but  that is crucial, for example, then you  want Scala over Clojure (see the , where Scala wins every benchmark as of this writing  has lower code size in almost every case (Edit: CLBG is not helpful in this regard any more, though you may find archives supporting these statements on the Web Archive)); OCaml and Haskell should be chosen for other reasons (similar benchmark scores, but they have different syntax and interoperability and so on).As far as which system has the best concurrency support, Haskell, Clojure and Scala are all just fine while OCaml is a bit lacking.This pretty much narrows it down to Haskell and Scala.  Do you need to use Java libraries?  Scala.  Do you need to use C libraries?  Probably Haskell.  Do you need neither?  Then you can choose either on the basis of which one you prefer stylistically without having to worry overly much that you've made your life vastly harder by choosing the wrong one.I've done this with Clojure, which proved pretty effective for the following reasons:I can't speak with quite so much experience of the other languages, but my impression from some practical experience of Haskell and Scala is:Overall, I think you could be happy with any of these. It will probably come down to how much you care about the JVM and your view on type systems."},
Scala

I wonder how to get a class object for an object type in Scala. Ok, that is a mouth full because of the double meaning for object. So here an example which will fail:If  was class it works perfectly. Any ideas? The reason why  doesn't work is because  is not a .Classes and traits define types, objects do not.Since Main is an object, for your example to work, simply replace your assignment line with;"},
Scala

In Scala, I can make a caseclass, , and then put it in a list like so:Now, nothing strange here. The following is strange to me. The operator  is a function on a list, right? With any function with one argument in Scala, I can call it with infix notation.\nAn example is  is a function  on the object . The class  I just defined does not have the  operator, so how is the following possible?In Scala 2.8 RC1, I get the following output from the interactive prompt:I can go on and use it, but what is the explanation?From the Spec:You can always see how these rules are applied in Scala by printing the program after it has been through the 'typer' phase of the compiler:It ends with a . And that is the sign, that this function is defined in the class to the right (in  class here).So, it's , not  in your example.One aspect missing in the answers given is that to support  in pattern matching expressions: :so  would produce the same result. The expression  works because the default extractor  is defined for the case class and it can be used infix.If the method name ends with a colon () the method is invoked on the , which is the case here. If the method name doesn't end with colon, the method is invoked on the left operand. For example, ,  is invoked on .So, in your example,  is a method on its right operand, which is a ."},
Scala

there is an aspect of futures that I do not exactly understand from the official tutorial ref. Do futures in scala have a built in time-out mechanism of some kind? Let's say the example below was a 5 gigabyte text file... does the implied scope of \"Implicits.global\" eventually cause onFailure to fire in a non-blocking way or can that be defined? And without a default time-out of some kind, wouldn't that imply it's possible neither success nor failure would ever fire? You only get timeout behavior when you use blocking to get the results of the .  If you want to use the non-blocking callbacks ,  or , then you would have to roll your own timeout handling.  Akka has built in timeout handling for request/response () messaging between actors, but not sure if you want to start using Akka.  FWIW, in Akka, for timeout handling, they compose two  together via , one which represents the actual async task and one that represents the timeout.  If the timeout timer (via a ) pops first, you get a failure on the async callback.A very simplified example of rolling your own might go something like this.  First, an object for scheduling timeouts:Then a function to take a Future and add timeout behavior to it:Note that the  I am using here is from Netty.I've just created a  class for a coworker:You can specify the timeout when you wait on the future:For , the  method lets you specify a timeout.For ,  lets you specify a timeout.I do not think there is a timeout built-in the execution of a Future.Play framework contains Promise.timeout so you can write code like followingI'm quite surprise this is not standard in Scala. My versions is short and has no dependenciesUsage exampleNobody's mentioned , yet. The flows have an easy  method, and applying that on a single-source stream works like a Future.But, akka-streams also does cancellation so it can actually end the source from running, i.e. it signals the timeout to the source.If you want the writer (promise holder) to be the one who controls the timeout logic, use , in the following way:This way, if your promise completion logic never takes place, your caller's future will still be completed at some point with a failure."},
Scala

I like Scala's propose of operator precedence but in some rare cases, unmodified rules may be inconvenient, because you have restrictions in naming your methods. Are there ways to define another rules for a class/file, etc. in Scala? If not, would it be resolved in the future?Operator precedence is fixed in the  by the first character in the operator. Listed in increasing order of precedence:And it's not very probable that it will change. It will probably create more problems than it fixes. If you're used the normal operator precedence changing it for one class will be quite confusing.There is no such ability and there is little likelihood of it being added in the forseeable future.See Chapter 6 of the book  for \"Rational\" class example."},
Scala

I am trying to  convert all the Headers/ColumnNames of a DataFrame in Spark-scala. as of now i come up with following code which only replaces a single column name. Please help on this.If structure is flat:the simplest thing you can do is to use  method:If you want to rename individual columns you can use either  with :which can be easily generalized to multiple columns:or :which use with  to rename multiple columns:With nested structures () one possible option is renaming by selecting a whole structure:Note that it may affect  metadata. Another possibility is to rename by casting:or:For those of you interested in PySpark version:"},
Scala

For example, there is a Scala array . How to choose a random element from this array?A better answer that does not involve reshuffling the array at all would be this:This also works generically "},
Scala

Okay, fair warning: this is a follow-up to my  from last week.  Although I think this question isn't as ridiculous.  Anyway, here goes:Assume I have some base trait  with subclasses ,  and , I can declare a collection  for example, that can contain values of type ,  and . Making the subtyping more explicit, let's use the  type bound syntax.Now instead assume I have a typeclass  with members ,  and  (where \"member\" means the compiler can find some , etc. in implicit scope). Similar to above, I want to declare a collection of type , using context bound syntax.This isn't legal Scala, and attempting to emulate may make you feel like a .  Remember that context bound syntax (when used correctly!) desugars into an implicit parameter list for the class or method being defined, which doesn't make any sense here.So let's assume that typeclass instances (i.e. implicit values) are out of the question, and instead we need to use implicit conversions in this case.  I have some type  (the \"v\" is supposed to stand for \"view,\" fwiw), and implicit conversions in scope ,  and .  Now I can populate a , despite ,  and  being otherwise unrelated.But what if I want a collection of things that are implicitly convertible both to views  and ?  I can't say  because my implicit conversions don't magically aggregate that way.I solved my problem like this:Now I can write  like a boss.  For example:The implicit conversions from  and  to type  occur when the sequence is populated, and then the implicit conversions from  to  and  occur when calling  and ..  Not terrible, but there are two things I dislike there:I can give a partial answer for the point 4. This can be obtained by applying a technique such as :"},
Scala

In  he mentioned in section (5.1 Future Work) that one of the interesting areas of research would be to extend the framework with ambient references and he cited Van Cutsen's paper.Excerpt: And citated paper is: Is this what Akka did? If not, do you think it is still relevant to research this area given the fact that Akka exists today?Yes, this is possible with Akka.There are 2 ways to achieve this as far as I know:"},
Scala

I was wondering if scala had an equivalent to java's  that can be applied to a function or whatever to ignore any deprecation warnings[1] that function emits?1: Relevant warning in my case is:  I am aware of the problems with stop however there are still some cases where due to legacy code we have to use it.No, and an enhancement request [1] for such a feature was closed as . I agree it would be useful. I expect that the Scala core team aren't against the idea, but they have finite resources and many higher priorities.[1] There is a simple compiler plugin for this:  (a bit shameless plug)"},
Scala

I believe I understand the basics of inline functions: instead of a function call resulting in parameters being placed on the stack and an invoke operation occurring, the definition of the function is copied at compile time to where the invocation was made, saving the invocation overhead at runtime.So I want to know:Never  anything whose implementation might reasonably change and which is going to be a  part of a .When I say \"implementation change\" I mean that the logic actually might change. For example:Let's say the \"natural comparison\" then changed to be based on an atomic counter. You may find that an application ends up with 2 components, each built and inlined against different versions of the comparison code.Personally, I use @inline for alias:Now, I couldn't find a way to know if it does anything (I tried to jad the generated .class, but couldn't conclude anything). My goal is to explicit what I want the compiler to do. But let it decide what's best, or simply do what it's capable of. If it doesn't do it, maybe later compiler version will."},
Scala

I'm trying to write a CSV parser using Scala parser combinators. The grammar is based on . I came up with the following code. It almost works, but I cannot get it to correctly separate different records. What did I miss? The default RegexParsers ignore whitespaces including space, tab, carriage return, and line breaks using the regular expression . The problem of the parser above unable to separate records is due to this. We need to disable skipWhitespace mode. Replacing whiteSpace definition to just  does not solve the problem because it will ignore all spaces within fields (thus \"foo bar\" in the CSV becomes \"foobar\"), which is undesired. The updated source of the parser is thus What you missed is whitespace.  I threw in a couple bonus improvements.With Scala Parser Combinators library out of the Scala standard library starting from 2.11 there is no good reason not to use the much more performant Parboiled2 library.\nHere is a version of the CSV parser in Parboiled2's DSL:The default whitespace for  parsers is , which includes new lines. So ,  and  never get a chance to be processed, as it is automatically skipped by the parser. "},
Scala

How do you test reference equality in Scala?The function you are looking for is , which is a member of :"},
Scala

I have spent a while learning the topic of Scala execution contexts, underlying threading models and concurrency. Can you explain in what ways does   and  as described in the ?In , it is presented as a means to await api that doesn't implement Awaitable. (Perhaps also just long running computation should be wrapped?).What is it that it actually does? doesn't easily betray its secrets.  is meant to act as a hint to the  that the contained code is blocking and could lead to thread starvation. This will give the thread pool a chance to spawn new threads in order to prevent starvation. This is what is meant by . It's not magic though, and won't work with every .Consider this example:This is using the default global . Running the code as-is, you will notice that the 100 s are all executed immediately, but if you remove , they only execute a few at a time. The default  will react to blocking calls (marked as such) by spawning new threads, and thus doesn't get overloaded with running s.Now look at this example with a fixed pool of 4 threads:This  isn't built to handle spawning new threads, and so even with my blocking code surrounded with , you can see that it will still only execute at most 4 s at a time. And so that's why we say it --it's not guaranteed. As we see in the latter , it's not guaranteed at all.How does it work? As linked,  executes this code: retrieves the  from the current thread, seen . A  is usually just a  with the  trait mixed in. As seen in the source, it is either stored in a , or if it's not found there, it is pattern matched out of the current thread. If the current thread is not a , then the  is used instead.Next,  is called on the current .  is an abstract method in , so it's implementation is dependent on how the  handles it. If we look at the  (when the current thread is not a ), we see that  actually does nothing there. So using  in a non- means that nothing special is done at all, and the code is run as-is, with no side-effects.What about threads that are s? For instance, in the  context, seen ,  does quite a bit more. Digging deeper, you can see that it's using a  under the hood, with the  defined in the same snippet being used for spawning new threads in the . Without the implementation of  from the  (thread), the  doesn't know you're blocking, and won't try to spawn more threads in response.Scala's  too, uses  for its implementation."},
Scala

In the REPL, I define a function. Note the return type.And if I specify the return type as StringWhy the difference? I can also specify the return type as List[Any], so I guess String is just a wrapper supertype to java.lang.String. Will this have any practical implications or can I safely not specify the return type?This is a very good question! First, let me assure you that you can safely specify the return type.Now, let's look into it... yes, when left to inference, Scala infers , instead of just . So, if you look up \"String\" in the , you won't find anything, which seems to indicate it is not a Scala class either. Well, it has to come from someplace, though.Let's consider what Scala imports by default. You can find it by yourself on the REPL:The first two are packages -- and, indeed,  can be found on ! Is that it, then? Let's check by instantiating something else from that package:So, that doesn't seem to be it. Now, it can't be inside the  package, or it would have been found when looking up on the ScalaDoc. So let's look inside , and there it is!That means  is an  for  (which was imported previously). That looks like a cyclic reference though, but if you check the , you'll see it is defined with the full path:Next, you might want to ask  Well, I don't have any idea, but I suspect it is to make such an important class a little less dependent on the JVM."},
Scala

If I understand correctly, traits are the closest thing to Java interfaces and class constructors automatically set the variables.But what if I have a class that extends a trait and has a constructor which sets a variable from the trait, so something like:Where I want the  string of the trait been set when I make a  object.The compiler seems to give me errors about this. What is the correct way to achieve this? must define the abstract  in  (would be the same for a ). This can be done in the constructor(of course, it could be done in the body of  too). By default, constructor parameters will be turned to private  if need be, that is if they are used outside the initiailization code, in methods. But you can force the behavior by marking them  or , and possibly control the visibility as inHere you need a public  to implement . The trait declares an uninitialized var; the class then sets it equal to the input parameter.Alternatively,declares the getter/setter pair corresponding to a foo, which are set by the class."},
Scala

Are there any languages that target the LLVM that:Scala is all of these, but only targets the JVM. F# (and to some extent C#) is most if not all of these, but only targets .NET. What similar language targets the LLVM?There's a  targeting the LLVM.You could also try using F# through .Also, the  project is implementing both the JVM and the .NET CLI on top of LLVM; it's still in its early stages but once it matures you could use it with F#, or any JVM-targeting functional languages (Scala, Clojure, etc.)I'm not sure how far these have progressed, but they may be worth adding to the list:Scala for LLVM - \nTimber for LLVM - \nMono for LLVM - Yes... . C++ has everything on your list except for list comprehensions. It is also the flagship LLVM language.\"Are statically typed\"Yup\"Use type inference\"\"Are functional (i.e. lambda expressions, closures, list primitives, list comprehensions, etc.)\"Lambdas in c++ look like . You can either capture closed over variables by reference (similar to lisp) like so: [&]. Alternatively you can capture by value like so: [=].In C++ map, zip, and reduce are called std::transform and std::accumulate.You can also rig up list comprehensions using a macro and and a wrapper around std::transform if you really want...\"Have first class object-oriented features (inheritance, polymorphism, mixins, etc.)\"Of course. C++ allows virtual dispatch + multiple inheritance + implementation inheritance. Note: mixins are just implementation inheritance. You only need a special \"mixin\" mechanism if your language prohibits multiple inheritance.\"Have a sophisticated type system (generics, covariance and contravariance, etc.)\"C++ templates are the most powerful generics system in any language as far as I know."},
Scala

What benefits and limitations has  language comparing to , especially from the web applications developer point of view? Comparison charts and proof-links are strongly welcome.P. S. This is not a holy war question (-:I've been working with Ruby and Rails for over 2 years and I'm just about a month into learning Scala and Lift, so my opinion is probably biased, but here it is.Ruby makes you feel amazing. Every new thing I discovered about the language made me giggle like a little schoolgirl. Working with gems is really simple and with  it is probably the best library management system I've came across.There are loads of gems for everything, from API wrappers, to complex .Ruby also has amazing community that will make learning the language really really easy. Take  for example. If you watch them, .For me, Ruby is probably the best thing I've discovered in my whole programming life, because the way the community works made me change my whole approach to programming.On the other hand, I don't see this in the Scala world. I don't want to raise a flame war, but this is just my impression after just starting to learn the language. In Ruby community, everything felt so engaging and made me wanna learn more and more. But with Scala, I tend to run into a lot of obstacles and not as much documentation and tutorials, that would help me overcome them.There are tons of books devoted to very specific topis on Ruby, be it , , , and bunch of other stuff (yes Pragmatic Programmers rule). The best thing is, that the whole community feels like a family, it's not the same as in the Java world, where everything is distributed and nobody talks to eachother, at least that's my impression. So what this comes down to, at least for me, is how easy and engaging it is to get into the world of the language and start doing something, and Ruby is definitely a winner here, at least for me.On the performance side, Scala is faster, no doubt about it. That's one of the reasons I'm getting into Scala, as it has really great concurrency model and allows you to do things that Ruby just can't do. But for most web applications, you won't need to do this.Ruby is slow, that's the only downside there is. It is getting faster and faster, and for 98% of the cases you won't see it as a problem. But Scala is faster.Ruby community also embraces testing and beautiful code, which naturally leads to better apps. "},
Scala

thenI saw the book writes that when use  it also results . My Scala version is 2.9. prepends a single item whereas  prepends a complete list. So, if you put a  in front of  it is taken as one item, which results in a nested structure."},
Scala

What is the proper way to restart node in elasticsearch? (preferably via the REST API, java API might be ok too)The correct way to restart a node is to shut it down, using either the  or sending a  signal to the process (eg with ).Once shut down, you can start a new node using whatever you use to run elasticsearch, eg the service wrapper, or just starting it from the command line.If you are using the service wrapper, you can restart a node by passing it the  command: eg  but that is just a convenience wrapper for the above.The  API has been disabled since version 0.11 as it was problematic.There is a restart API analogous to the . Just replace \"shutdown\" with \"restart\". See also the .Every time a node goes down and/or and new node comes up, the cluster redistributes the shards, which may not be desired when you just need to restart a node, therefore you can make use of Rolling restart:More on this: "},
Scala

Is there an easy way to convert a case class into a tuple?I can, of course, easily write boilerplate code to do this, but I mean without the boilerplate.What I'm really after is a way to easily make a case class lexicographically Ordered. I can achieve the goal for tuples by importing scala.math.Ordering.Implicits._, and voila, my tuples have an Ordering defined for them. But the implicits in scala.math.Ordering don't work for case classes in general.How about calling  in the companion object?You might try extending the  trait, for N=1-22, which  extends. It will give you  a lot of Tuple semantics, like the , , etc. methods. Depending on you how you use your types, this might be sufficient without creating an actual Tuple. Came across this old thread while attempting to do this same thing. I eventually settled on this solution:"},
Scala

In python I can do this:Here the passed in tuple is being decomposed while its being passed to .Right now in scala right now I am doing this:Is there something I can do here so that the decomposition happens while the arguments are passed in?  Just curious.Thanks. You can create a function and match its input with pattern matching:Or match the input of the method with the  keyword:Another way is to use a function with two arguments and to \"tuple\" it:How about:The _1, _2 etc. access the different elements of the tuple.prints:"},
Scala

I know you can   with companion objects but I am wondering why as a language design were statics dropped out of class definitions.The O in OO stands for \"Object\", not class.  Being object-oriented is all about the objects, or the instances (if you prefer)Statics don't belong to an object, they can't be inherited, they don't take part in polymorphism.  Simply put, statics aren't object-oriented.Scala, on the other hand,  object oriented.  Far more so than Java, which tried particularly hard to behave like C++, in order to attract developers from that language.They are a hack, invented by C++, which was seeking to bridge the worlds of procedural and OO programming, and which needed to be backwardly compatible with C. It also admitted primitives for similar reasons.Scala drops statics, and primitives, because they're a relic from a time when ex-procedural developers needed to be placated.  These things have no place in any well-designed language that wishes to describe itself as object-oriented.Concerning  it's important to by truly OO, I'm going to shamelessly copy and paste this snippet from Bill Venners on the mailing list:Couldn't have put it better myself!So if you want to create just one of something, then both statics and singletons can do the job.  But if you want that one thing to inherit behaviour from somewhere, then statics won't help you.In my experience, you tend to use that ability far more than you'd have originally thought, especially after you've used Scala for a while.I also posted this question on scala users google group and Bill Venners one of the authors of \"Programming in scala\" reply had some insights.Take a look at this:  and Here is an excerpt:Also take a look at this interview with Martin Odersky (scroll down to Object-oriented innovations in Scala section) Here is an excerpt:From a functional programming perspective static members are generally considered bad (see this  by Gilad Bracha - the father of java generics. It mainly has to do with side effects because of global state). But scala had to find a way to be interoperable with Java (so it had to support statics) and to minimize (although not totally avoid) global states that is created because of statics, scala decided to isolate them into companion objects.Companion objects also have the benefit of being extensible, ie. take advantage of inheritance and mixin composition (separate from emulating static functionality for interop). These are the things that pop into my head when I think about how statics could complicate things: Inheritance as well as polymorphism would require special rules. Here is an example:If you are 100% sure about what gets printed out, good for you. The rest of us can safely rely on mighty tools like  annotation, which is of course optional and the friendly  warning. This leads us to The \"static way\" of accessing stuff is a further special rule, which complicates things. Static members cannot be abstract. I guess you can't have everything, right?And again, these are just things which came to my mind after I gave the matter some thought for a couple of minutes. I bet there are a bunch of other reasons, why statics just don't fit into the OO paradigm.It's true, static member don't exists, BUT, it's possible to associate a singleton    object to each class:to obtain similar resultsObject oriented programming is all about objects and its states(Not touching state full and stateless object). I\u2019m trying to stress  so it\u2019s rational to pull off from objects. "},
Scala

I have this issue that I have to work around every time. I can't map over something that is contained within a Future using a for comprehension.Example:This gives me the error:But if I do this it works fine: Should i not be able to do this by using a for comprehension, is the reason it works in my other example that I do not flatmap? I'm using Scala 2.10.0.Well, when you have multiple generators in a single for comprehension, you are  the resulting type. That is, instead of getting a , you get a :Now, how would you flatten a ? It can't be a , because you'll be getting multiple , and a  (as opposed to a ) can only store one of them. The same problem happens with , by the way:The easiest way around it is to simply nest multiple for comprehensions:In retrospect, this limitation should have been pretty obvious. The problem is that pretty much all examples use collections, and all collections are just , so they can be mixed freely. Add to that, the  mechanism for which Scala has been much criticized makes it possible to mix in arbitrary collections and get specific types back, instead of .And, to make things even more blurry,  can be converted into an , which makes it possible to combine options with collections as long as the option doesn't come first.But the main source of confusion, in my opinion, is that no one ever mentions this limitation when teaching for comprehensions.Hmm, I think I got it. I need to wrap within a future as the for comprehension adds a flatmap.This works:When I added above I did not see any answers yet. However to expand on this it is possible to do work within one for-comprehension. Not sure if it is worth the Future overhead though (edit: by using successful there should be no overhead).Another way to solve this is to simply use assignment  instead of  when you have another type than the initial map return type. When using assignment that line does not get flat-mapped. You are now free to do an explicit map (or other transformation) that returns a different type. This is useful if you have several transformation where one step that does not have the same return type as the other steps, but you still want to use the for-comprehension syntax because it makes you code more readable.Your original version doesn't compile because  and  are different monads. To see why this is a problem, consider what it desugars to:Clearly  is a list of  pairs, so the argument to our  is a function that maps lists of strings to lists of these pairs. But we need something that maps lists of strings to a  of some kind. So this doesn't compile.The version in your answer does compile, but it doesn't do what you want. It desugars to this:The types line up this time, but we're not doing anything interesting\u2014we're just pulling the value out of the , putting it back into a , and mapping over the result. So we end up with something of type , when we wanted a .What you're doing is a kind of double mapping operation with two (different) nested monads, and that's not something a -comprehension is going to help you with. Fortunately  does exactly what you want and is clear and concise.I find this form more readable than either the serial map or the serial yield:at the expense of the tupling map:or more precisely:"},
Scala

When creating a  in scala, I call , and I get:This is because the signature for  is: ,\nwhich requires a varargs style argument.Is there a way to convert the  so that it can be accepted via ?Try this: Explicitly typing it as a varargs using  seems to work.Or this should work too:"},
Scala

I have two strings in scala and I want to find out, if the bigger string () contains a smaller string ().What I found is doing it with regexps and matches like this ():which is (1) grossly overcomplicated for such a simple problem, but more importantly, (2) doesn't work for me, becausereturnsIf you want to do it with maximum efficiency, you may have to write it yourself (or find a good substring searching algorithm somewhere).  If you just want it to work at all, then in Scala:These are  regex searches.  You aren't using the regex match correctly either (edit: because that code asks for an exact match to the whole string, not to find a matching substring), but that's a different issue.  If you want a count of the number of matches, you can do something likeAlthough answered I thought I would also offer this regex style"},
Scala

I found myself writing something like this quite often:Is there a shorter way to check if some value matches a pattern? I mean, in this case I could just write , but what if the pattern is more complex? Like when matching against a list or any pattern of arbitrary complexity. I'd like to be able to write something like this:I'm relatively new to Scala, so please pardon, if I'm missing something big :)This is exactly why I wrote these functions, which are apparently impressively obscure since nobody has mentioned them.The  operator in Scala is most powerful when used in functional style. This means, rather than \"doing something\" in the  statements, you would return a useful value. Here is an example for an imperative style:It is very understandable that the \"do nothing\" above hurts a little, because it seems superflous. However, this is due to the fact that the above is written in imperative style. While constructs like these may sometimes be necessary, in many cases you can refactor your code to functional style:In this case, you use the whole  statement as a value that you can, for example, assign to a variable. And it is also much more obvious that the  statement must return a value in any case; if the last case would be missing, the compiler could not just make something up.It is a question of taste, but some developers consider this style to be more transparent and easier to handle in more real-world examples. I would bet that the inventors of the Scala programming language had a more functional use in mind for , and indeed the  statement makes more sense if you only need to decide whether or not a certain action needs to be taken. (On the other hand, you can also use  in the functional way, because it also has a return value...)This might help:Now, some explanation on the general nature of the problem. There are three places where pattern matching might happen: ,  and . The rules for them are:There is, however, another situation where  might appear, which is function and partial function literals. For example:Both functions and partial functions will throw an exception if called with an argument that doesn't match any of the case statements. However, partial functions also provide a method called  which can test whether a match can be made or not, as well as a method called , which will turn a  into a , which means non-matching values will result in  instead of throwing an exception.A match is a combination of many different tests:Now, extractors are the methods  or , the first returning  or , and the second returning , where  means no match is made, and  will try to match  as described above.So there are all kinds of syntactic alternatives here, which just aren't possible without the use of one of the three constructions where pattern matches may happen. You may able to emulate some of the features, like value equality and extractors, but not all of them.Patterns can also be used in for expressions. Your code samplecan then be expressed asThe trick is to wrap a to make it a valid enumerator. E.g. List(a) would also work, but I think Some(a) is closest to your intended meaning.The best I can come up with is this:This won't win you any style points though. can be \u201cimproved\u201d to better match your requirement:then:I wouldn't do it, however. The  sequence is really ugly here, and the whole code looks much less clear than a normal match. Plus, you get the compile-time overhead of looking up the implicit conversion, and the run-time overhead of wrapping the match in a  (not counting the conflicts you could get with other, already defined  methods, like the one in ).To look a little bit better (and be less verbose), you could add this def to :and use it like this:which saves you your  line, but requires double braces if you want a block instead of a single statement... Not so nice.Note that this construct is not really in the spirit of functional programming, as it can only be used to execute something that has side effects. We can't easily use it to return a value (therefore the  return value), as the function is partial \u2014 we'd need a default value, or we could return an  instance. But here again, we would probably unwrap it with a match, so we'd gain nothing.Frankly, you're better off getting used to seeing and using those  frequently, and moving away from this kind of imperative-style constructs (following )."},
Scala

What is the simplest method to remove the last character from the end of a String in Scala?I find Rubys String class has some very useful methods like . I would have used \"oddoneoutz\".headOption in Scala, but it is depreciated. I don't want to get into the overly complex:Please someone tell me there is a nice simple method like chop for something this common.How about using dropRight, which works in 2.8:-Which produces \"abc\" That's basically chop, right? If you're longing for a chop method, why not write your own  library and include it in your projects until you find a suitable, more generic replacement?Hey, look, it's in commons.."},
Scala

I've read that Scala'a  construct automatically generates a fitting  and  implementation. What does exactly the generated code look like?As my professor used to say, only the code tells the truth! So just take a look at the code that is generated for:We can instruct the Scala compiler to show us the generated code after the different phases, here after the typechecker:So you can see that the calculation of the hash code is delegated to  and the equality depends on the equality of the case class' members.The generated   just calls , which is defined as:So what you get is , where  is the arity of your case class and  are the members of that case class.As of scala 2.9  for case classes uses : .MurmurHash ."},
Scala

I've got a list of objects  which are all instantiated from the same class. This class has a field which must be unique . What is the cleanest way to iterate the list of objects and remove all objects(but the first) with the same property? Explanation: The groupBy method accepts a function that converts an element to a key for grouping.  is just shorthand for  (the compiler generates a unique name, something like ). So now we have a map . A  extends . So it can be traversed like a list, but elements are a tuple. This is similar to Java's . The map method creates a new collection by iterating each element and applying a function to it. In this case the function is  which is shorthand for .  is just a method of Tuple that returns the second element. The second element is List[Object] and  returns the first elementTo get the result to be a type you want:To explain briefly,  actually expects two arguments, a function and an object that is used to construct the result. In the first code snippet you don't see the second value because it is marked as implicit and so provided by the compiler from a list of predefined values in scope. The result is usually obtained from the mapped container. This is usually a good thing. map on List will return List, map on Array will return Array etc. In this case however, we want to express the container we want as result. This is where the breakOut method is used. It constructs a builder (the thing that builds results) by only looking at the desired result type. It is a generic method and the compiler infers its generic types because we explicitly typed l2 to be  or, to preserve order (assuming  is of type ): is a method that accepts an initial result and a function that accepts an element and returns an updated result. The method iterates each element, updating the result according to applying the function to each element and returning the final result. We go from right to left (rather than left to right with ) because we are prepending to  - this is O(1), but appending is O(N). Also observe the good styling here, we are using a pattern match to extract the elements.In this case, the initial result is a pair (tuple) of an empty list and a set. The list is the result we're interested in and the set is used to keep track of what properties we already encountered. In each iteration we check if the set  already contains the property (in Scala,  is translated to . In , the method  is . That is, accepts an element and returns true / false if it exists or not). If the property exists (already encountered), the result is returned as-is. Otherwise the result is updated to contain the object () and the property is recorded ()Update: @andreypopp wanted a generic method:to use: Also note that this is pretty efficient as we are using a builder. If you have really large lists, you may want to use a mutable HashSet instead of a regular set and benchmark the performance.Here is a little bit sneaky but fast solution that preserves order:Although it uses internally a var, I think it is easier to understand and to read than the foldLeft-solution.One more solutionI found a way to make it work with groupBy, with one intermediary step:Use it like this:Similar to IttayD's first solution, but it filters the original collection based on the set of unique values. If my expectations are correct, this does three traversals: one for , one for  and one for . It maintains the ordering of the original collection, but does not necessarily take the first value for each property. For example, it could have returned  instead.Of course, IttayD's solution is still faster since it does only one traversal. My solution also has the disadvantage that, if the collection has s that are actually the same, both will be in the output list. This could be fixed by removing  and returning  directly, with type . However, it seems like  does not exist... suggestions are welcome!With preserve order:I don't know which version of Scala you are using, but 2.8.2 definitely has "},
Scala

I am not sure what is the difference between  and  in Scala.The question  has an answer that talks about ordering. That is understandable. But I still don't understand why this works (from REPL):but this does not:What does this error message mean?This line from the documentation is also confusing to me.Why will it be added ? I thought folding works differently.As defined by Scala,  is a linear operation while  is allowed to be a tree operation.  For example:In order to allow arbitrary tree decompositions of a sequential list, you must have a zero that doesn't do anything (so you can add it wherever you need it in the tree) and you must create the same sort of thing that you take as your binary arguments so the types don't change on you depending on how you decompose the tree.(Being able to evaluate as a tree is nice for parallelization.  If you want to be able to transform your output time as you go, you need both a combination operator  a standard start-value-transforms-sequence-element-to-desired-type function just like  has.  Scala has this and calls it , but in some ways this is more like  than  is.)I am not familiar with Scala, but Scala's collection library has a similar design to Haskell's.  This answer is based on Haskell and is probably accurate for Scala as well.Because  processes its inputs from left to right, it can have different input and output types.  On the other hand,  can process its inputs in various orders and so the inputs and output must all have the same type.  This is easiest to see by expanding out the fold expressions.   operates in a specific order:Note that array elements are never used as the first parameter to the combining function.  They always appear on the right of the . does not guarantee a specific order.  It could do various things, such as:Array elements can appear in either parameter of the combining function.  But your combining function expects its first argument to be an int.  If you don't respect that constraint, you end up adding strings to ints!  This error is caught by the type system.The neutral element may be introduced multiple times because, generally, a parallel fold is implemented by splitting up the input and executing multiple sequential folds.  A sequential fold introduces the neutral element once.  Imagine one particular execution of  where the array is split into two separate arrays, and these are folded sequentially in two threads.  (Of course, the real  function does not spit the array into multiple arrays.)  One thread executes , computing .  The other thread executes , computing .  Finally, the partial sums from the two threads are added together.  Note that the neutral element, , appears twice.NOTE: I could be completely wrong here.  My scala is less than perfect.I think that the difference is in the signature of the methods:vsIn short, fold is defined as operating on some type A1 which is a supertype of the array's type, which for your string array the compiler defines as \"Any\" (probably because it needs a type that can store your String  an int- notice that the combiner method passed to fold Fold takes two parameters of the same type?)  That's also what the documentation means when it talks about z- the implementation of Fold could be such that it combines your inputs in parallel, for instance:On the other hand, foldLeft operates on type B (unconstrained) and only asks that you provide a combiner method that takes a parameter of type B and another of your array's type (String, in your case), and produces a B. You are getting a compile-time error because the signature of  only allows folding values of type which is the supertype of the type of the values in the collection, and the only supertype of  (your collection type) and  (the type of your provided zero element) is . So, the type of the fold result is inferred to be  - and  does not have a method .Note that the two versions of  have different signatures:Why do they have different signatures? This is because  could be implemented in parallel, as is the case with parallel collections. When multiple processors fold over the values in the collections, each one of the processors takes a subset of elements of type  and produces the folded value of type , by consecutively applying . The results produced by those processors must be combined together into a final folding value - this is done using the  function, which does exactly that.Now, note that this cannot be done using the  in , because each of the processors  produces a folded value of type . Several values of type  cannot be combined using , because  only combines value  with another value of type  - there is no correspondance between types  and . In your example, assume the 1st processor takes elements  and the 2nd takes element . The first one will produce the folded value , and the second will produce another folded value . Now they have to combine their results to get the final folded value - this is impossible, because the closure  only knows how to combine an  and , and not 2  values.For situations where these types differ, use , in which you have to define how to combine two values of type :The  above defines how to do the final step when the fold result and the elements in the collection have different types. As described above, multiple processors may fold over subsets of elements in the collection. Each one of them will start its folded value by adding the neutral element.In the following example:always returns .However,  should not be used with , as it is not a neutral element:The above may return  or . If you don't use the neutral element for the , the results are nondeterministic. In the same way, you can use the  as a neutral element, but not a non-empty list.As another answer points out, the  method is primarily there to support a parallel fold. You can see this as follows. First we can define a kind of wrapper for integers that allows us to keep track of the operations that have been performed on its instances.Next we can create a parallel collection of these things and an identity element:First we'll try :So our zero value is only used once, as we'd expect, since  performs a sequential fold. Next we can clear the log and try :So we can see that the fold has been parallelized in such a way that the zero value is used multiple times. If we ran this again we'd be likely to see different values in the log.Here are the prototypes of the methodsSo, for fold the result is of type instead of any . Moreover, as specified in the doc, for  the order is not When typing  you assume that , an  is a subtype of . This is why the compiler throws an error. Here we have to see the  of  to understand what happens. Here is what we get: So basically,  is an implementation of  with a constraint on the output type. \nWe can now see that  will in practice be used the same way as in . So we can just conclude that this comment was made because nothing assures that behavior in future implementations. We can already see it now, with : "},
Scala

Besides integration with dynamic languages on the JVM, what are the other powerful uses of a  in a statically typed language like Scala?I guess a dynamic type could be used to implement several of the features found in JRuby, Groovy or other dynamic JVM languages, like dynamic metaprogramming and method_missing.For example creating a dynamic query similar to Active Record in Rails, where a method name with parameters is translated to an SQL query in the background. This is using the method_missing functionality in Ruby. Something like this (in theory - have not tried to implement anything like this):Allowing usage like this, where you can call methods 'name' and 'findByName' without having them explicitly defined in the Person class:If dynamic metaprogramming was to be added, the Dynamic type would be needed to allow invoking methods that have been added during runtime..Odersky says the primary motivation was integration with dynamic languages: [edit] Martin further confirms this You might also use it for syntactic sugar on maps:To be honest this only saves you a couple of keystrokes from:"},
Scala

I am about to start a project for a web application that should run on a Tomcat server. I have decided to go for Scala - the other alternative where I work being Groovy - essentially for type safety. I am now faced with the task of choosing the right tools for the job.The project I will need to develop will be accessed only through a JSON API. It will interact both with its own database and with two external services, which expose respectively a JSON and XML API. I will also need to be able to schedule periodic jobs where my application will execute various synchronization tasks with these external services.For the database, I would like to be able to define my models in Scala and automatically generate the schema. If the need arises to change my models, I would like to have migrations to handle it.For this application, I am trying to evaluate Lift, Play! 2 and Scalatra.What do you think would be the best choice for my task?If you are coming from a MVC background then Play will feel the most familiar.   Lift is not MVC and it takes some time to wrap your head around it.There is no reason that you can't use Scala with a Java-based framework like Jersey, Spring MVC, , Restlet, RESTEasy, etc.   Or you could use Scala with Grails just like you can use Java with Grails.  Note - Groovy has type safety starting with version 2.0 so that's something to consider. If you are thinking about Scalatra then don't forget , , ...  Be sure to check out Matt Raible's .  And these other SO questions:\n,  Although you already gave some candidates I recommend to you this talk by Tim Perrett (author of Lift in Action, in which he compares scala webframeworks :\n "},
Scala

Is there already any collection of best practices for languages like Scala?I've found a work on design patterns for functional languages, . There's  design patterns for OO languages. But are there any patterns for functional-OO hybrids? All I've seen is  list. What is known?Two patterns from Bill Venners; I think both are heavily used in ScalaTest: (similar in structure to the decorator pattern, except it involves decoration for the purpose of class composition instead of object composition). (allows library designers to provide services that their clients can access either through mixins or imports). - just like the \"Scalable Component Abstraction\", it's not a pattern catalog, but it also deals with similar problems (e.g. the Visitor pattern) - an alternative to the Observer.We can also consider the Scala emulation of  type classes a design pattern. The first description (that I could find at least) is in\n. Quite some blog entries are also available with this topic.And I think I'm not completely wrong if I also mention the various monads. You can find a lot of resources dealing with them.While not directly a design pattern catalog itself, the paper \"\" (Martin Odersky; Matthias Zenger) examines three building blocks for reusable components:And it revisits several design pattern (publish/subscribe, subject/observer, Context/Component) to illustrate and understand what language constructs are essential to achieve systems of scalable and dynamic components.  One frequently observed pattern, which badly needs a name, is creating control abstractions with curried parameter lists and by-name parameters. yieldingIn as much as any Object-Functional language is quickly going to acquire an actor library,  a large number of actor-based patterns probably qualify for this question.  Almost any of the patterns in Bob Martin's  is recastable in terms of actors, with patterns like Load Balancer, Message Filter, Content-Based Router, and Content Enricher being especially common in systems architected around coarse-grained actors.Closely related, you might want to explore data structures as defined in  (or hybrid functional) languages. For one, the ability to treat functions as first-class values make some patterns (like ,  or ) unnecessary in some (not all) contexts. Secondly, data structures (and the algorithms that operate on them) are either the plumbing for design patterns, or present certain problems that design patterns attempt to address, see Wikipedia article . Better yet, I'd refer you to ."},
Scala

I upgraded from IntelliJ IDEA from 12 CE to 13 CE few days ago and it has been hogging up CPU. Every few minutes it'll peak to 450-500% and then come down to 100-200%. Also, I've upgraded my Scala plugin to 0.30.380. Not sure what's causing the issue!?I'm posting this comment by K P as an answer, because K P does not have enough reputation.Go to your home folder, then navigate to Edit the file  by changing the   and  as follows:It decreased the CPU usage to 50%.Try clean up cache and restart. In Intellij 14 go to menu File -> Invalidate Caches / Restart...If anyone's wondering the \"right\" way to edit the idea.vmoptions or idea64.vmoptions file, here it is: On *NIX, you want to copyto:and edit that file to increase the heap memory for IntelliJ IDEA(OP's example settings: Xms = 512m and Xmx = 2048)As other said,increasing memory heap of IDEA is work, my IDEA version is 2016.3.4, following is setting way"},
Scala

In Scala, the  class is derived from type  (see Scala Reference, 12.3.3). However, this seems counterintuitive to me, since a  (which needs to be defined for all ) has more stringent requirements than a , which can be undefined at some places.The problem I've came accross was that when I have a partial function, I cannot use a  to extend the partial function. Eg. I cannot do:(Hope the syntax is at least remotely right)Why is this subtyping done reversely? Are there any reasons that I've overlooked, like the fact that the  types are built-in?BTW, it would be also nice if  so I needn't have the dummy argument in the example above :-)The difference between the two approaches can be emphasized by looking at two examples. Which of them is right?One:Two:Because in Scala (as in any Turing complete language) there is no guarantee that a Function is total. That function is not defined at 0. A PartialFunction is just a Function that promises to tell you where it's not defined.  Still, Scala makes it easy enough to do what you wantIf you prefer, you can make func2Partial implicit. has methods which  does not, therefore it is the subtype.  Those methods are  and .Your real problem is that s are not inferred sometimes when you'd really like them to be.  I'm hopeful that will be addressed at some future date.  For instance this doesn't work:But this does:Of course you could always do this:And now it's more like you want:"},
Scala

I have an Akka Actor that makes a call to MyObject.foo().  MyObject is not an Actor.  How do I setup Logging in it?  With an Actor it's simple, because I can just mixin ActorLogging.  In MyObject, I don't have access to context.system.  Do I create an akka.event.Logging with AkkaSystem() and then what for the LogSource implicit?Actually I would redirect Akka logging to  and use this API directly in all unrelated classes. First add this to your configuration:Then choose some SLF4J implementation, I suggest . In your actors continue using  trait. In other classes simply rely on SLF4J API - or even better - try out  facade around SLF4J.Tip: try out the following logging pattern in Logback:The  will print actor path when available (just like standard logging).Using Akka 2.2.1, I was able to put this into my App to get logging outside of an actor:This seems like a simpler solution for unifying an application's logging.I've now settled on simply passing my central logging system around through DI constructor injection (Guice). And in my classes that do logging regularly (where asynchronicity is important), I take the injected ActorSystem and call the in the classes constructor.As has been mentioned, you're spoiled for options for non-actor logging within an actor system. I am going to attempt to provide a set of heuristics to help you determine how you should route logging for your work.You're welcome to mix and match the above behaviors as necessary to meet your requirements. For example, you might choose to bind to SLF4J for libraries and use Akka logging for everything else. Just note that mixing blocking and non-blocking logging could cause race conditions where causes (logged async via an actor) are logged after their effects (logged sync directly)."},
Scala

I am a big fan of Scala aesthetically, and of a lot of the conceptual work put into things like its typing system and libraries.However, as I have begun tinkering with Scala (and seen some of my coworkers tinker with it) i find myself having to dig for more and more Java knowledge (especially in the way of libraries).This presents me with a few problems:At this point though, i'm not sure whether i should bite the bullet and try and find the quickest and most comprehensive tour through Java to catch myself up on 20 years of Java developments, or whether its reasonable to continue trying to incrementally patch my knowledge as i wander around scala.Any wisdom that scala heads amongst us could offer would be greatly appreciated.P.S.\nI have no doubt in my ability to familiarize myself with Scala syntax, and i'm perfectly comfortable and happy with functional programming and the paradigms in the scala community.  But a programmer's competence is not just based on one's ability to teach oneself, but also one's ability to learn from, and adopt tools and skills from other people.You should take a  approach to learning Java. Learn it when you need it.In my opinion, much of the old Java knowledge is out of date, much of the new tutorials are redundant. You certainly don't want to bother yourself with Java's antiquated , for example. Many Java-based frameworks can be safely ignored. And the heavyweight JavaEE stack can be safely bypassed until you were forced to use a part of it.Many common patterns in Java are much simpler in Scala, with the former being burdened with much boilerplate code. Core logic should always be implemented in Scala. I believe you can do most of your work directly in Scala and only need to dip down into Java when building things like Swing or integrating with Spring, etc.In regard to choosing and using Java libraries, my personal guidelines are:That's a bit tounge-in-cheek, but is the impression I get about the maturity and stability of third party libraries after having done Java for the last 12 years.If you want to learn Spanish, start to learning Spanish, not Latin. Same for programming languages. There are two things from Java that are good to know: The first thing are APIs. But you need only a general overview about what exists. Even long time Java programmers don't know all the details. And finding the right API or lib for a problem is usually easy, as Java is so common, and even with weak Google Fu you shouldn't have any problems. The second thing you need to know are some basic principles and limitations of Java and the JVM (including how to build and run), that help you to understand some of Scala's problems and design decisions. One typical example would be \"type erasure\": If you don't understand this limitation of Java's generics, you'll run in problems when using generics in Scala.As you can see, the things you really need to know is limited. Everything else can be picked up on the way. It depends entirely on your definition of \"Competent Java Programmer\".A good understanding of the Java memory model and garbage collection strategies will help.  As will experience with a wide range of 3rd part libraries.On the other hand... if you're deeply indoctrinated into getter/setter dependency injection used by libraries like Spring, then you'll have to unlearn a lot of bad habits before you can properly deal with immutability  -  In this case, prior Java exposure is probably going to hinder you in learning Scala.There are lots of folk coming to scala and clojure from ruby/python, lisp/scheme, C#, who need to pick up on:primitives, autoboxingJVM startup options, how hotspot works, 32 vs. 64 bit, use openJDK?benchmarks, profiling, how to read stacktraces;zillions of test libs for every conceivable need. java.util.concurrentSwing API calls;  Classpath;  Maven, ant;  Hudson, Interfacesnamespaces/packages/directory layout, and all the other things automated by:intelliJ, netBean, or eclipse+UseConcMarkSweepGC -XX:+CMSIncrementalMode -XX:, EscapeAnalysis etc.\ncompressed oops, \n"},
Scala

Given the following constructs for defining a function in Scala, can you explain what the difference is, and what the implications will be?vs.Thanks for the quick responses.  These are great.  The only question that remains for me is:If I omit the parenthesis, is there still a way to pass the function around?  This is what I get in the repl:Here are some similar questions I noticed:If you include the parentheses in the definition you can optionally omit them when you call the method. If you omit them in the definition you can't use them when you call the method.Additionally, you can do something similar with your higher order functions:Here  will only take  and not . What use this is, I don't know. But it does show that the types are distinct.Let me copy my answer I posted on :A Scala method of 0-arity can be defined with or without parentheses . This is used to signal the user that the method has some kind of side-effect (like printing out to std out or destroying data), as opposed to the one without, which can later be implemented as .See :To answer your second question, just add an :"},
Scala

I'm developing on the standard Lift platform (maven and jetty). I'm repeatedly (once every couple of days) getting this:This is in my dev environment. It's not a problem because I can keep restarting the server. In deployment I'm not having these problems so it's not a real issue. I'm just curious.I don't know too much about the JVM. I think I'm correct in thinking that permanent generation memory is for things like classes and interned strings? What I remember is a bit mixed up with the .NET memory model...Any reason why this is happening? Are the defaults just crazily low? Is it to do with all the auxiliary objects that Scala has to create for Function objects and similar FP things? Every time I restart Jetty with newly written code (every few minutes) I imagine it re-loads classes etc. But even so, it cant' be that many can it? And shouldn't the JVM be able to deal with a large number of classes?CheersJoeFrom :May be this could help.Edit July 2012 (almost 3 years later): comments (and I have updated the answer above):See the full  for mroe.If you see this when running  ,\nset the . For Linux:For Windows:Should be fine now. If not, increase .You can also put these permanently to your environment.This is because of the reloading of classes as you suggested. If you are using lots of libraries etc. the sum of classes will rapidly grow for each restart. Try monitoring your jetty instance with VisualVM to get an overview of memory consumption when reloading.The mailing list () is the official support forum for Lift, and where you'll be able to get a better answer. I don't know the particulars of your dev setup (you don't go into much detail), but I assume you're reloading your war in Jetty without actually restarting it. Lift doesn't perform dynamic class generation (as suggested by VonC above), but Scala compiles each closure as a separate class. If you're adding and removing closures to your code over the course of several days, it's possible that too many classes are being loaded and never unloaded and taking up perm space. I'd suggest you enable the options JVM options mentioned by VonC above and see if they help.The permanent generation is where the JVM puts stuff that will probably not be (garbage) collected like custom classloaders.Depending on what you are deploying, the perm gen setting can be low. Some applications and/or containers combination do contain some memory leaks, so when an app gets undeployed sometimes some stuff like class loaders are not collected, resulting in filling the Perm Space thus generating the error you are having.Unfortunately, currently the best option in this case is to max up the perm space with the following jvm flag (example for 192m perm size):The other option is to make sure that either the container or the framework do not leak memory."},
Scala

When running the Scala interpreter in Ubuntu 14.04, I get the following message printed as the first line:Followed by the familiar \"Welcome to Scala\" message.I'm worried because I haven't seen that when running Scala before - what does it mean, is it dangerous, etc?Apparently the environment variable  is set to  - I didn't set that, but what did and why? Can I safely unset it?Additional info:You can disable jayatana just for the current shell session by unsetting  like so:That way it will still be enabled for applications needing it.This occurs if you have installed jayatana which allows the hidden global menu in eclipse to work with Unity:that puts JARs in the  folder which is echoed by the JVM when starting up.  If you remove that software, you will not see the message:You may have to delete:and restart your session so that the environment variable  is not set.This is because of Jayatana, which is added to Ubuntu 15.04 in order to enable global menu for Java Swing applications. You can safely remove this message by entering the following command in a terminal. This command will remove the auto-start configuration of Jayatana.However, removing this option will disable the global menu support of Java Swing applications like Netbeans, IntelliJ IDEA. I have shared my workaround to suppress the message without losing the global menu in this article: On Windows,\nset JAVA_TOOL_OPTIONS=Setting to null will remove it from the environment. If you don't want to uninstall anything you can create a key store from a terminal:(you should create it at project's forlder)And then in Android Studio click Build->Generate Signed APK and choose created keystore.If you are using Windows OS, goto environment variables and delete or set to null the varible JAVA_TOOL_OPTIONS. "},
Scala

I have played around with Scala for a while now, and I know that traits can act as the Scala equivalent of both interfaces and abstract classes.  How exactly are traits compiled into Java bytecode?I found some short explanations that stated traits are compiled exactly like Java interfaces when possible, and interfaces with an additional class otherwise. I still don't understand, however, how Scala achieves class linearization, a feature not available in Java.Is there a good source explaining how traits compile to Java bytecode?I'm not an expert, but here is my understanding:Traits are compiled into an interface and corresponding class.becomes the equivalent of...Which leaves the question: How does the static bar method in Foo$class get called?  This magic is done by the compiler in the class that the Foo trait is mixed into.becomes something like...Class linearization just implements the appropriate version of the method (calling the static method in the Xxxx$class class) according to the linearization rules defined in the language specification.For the sake of discussion, let's look the following Scala example using multiple traits with both abstract and concrete methods:At the moment (i.e. as of Scala 2.11), a single trait is encoded as:The primary advantage of this encoding is that a trait without concrete members (which is isomorphic to an interface) actually  compiled to an interface.However, Scala 2.12 requires Java 8, and thus is able to use default methods and static methods in interfaces, and the result looks more like this:As you can see, the old design with the static methods and forwarders has been retained, they are just folded into the interface. The trait's concrete methods have now been moved into the interface itself as  methods, the forwarder methods aren't synthesized in every class but defined once as  methods, and the static  method (which represents the code in the trait body) has been moved into the interface as well, making the companion static class unnecessary.It could probably be simplified like this:I'm not sure why this wasn't done. At first glance, the current encoding might give us a bit of forwards-compatibility: you can use traits compiled with a new compiler with classes compiled by an old compiler, those old classes will simply override the  forwarder methods they inherit from the interface with identical ones. Except, the forwarder methods will try to call the static methods on  and  which no longer exist, so that hypothetic forwards-compatibility doesn't actually work.A very good explanation of this is in:Quote:In the context of Scala 12 and Java 8, you can  see another explanation in :"},
Scala

Isn't toList a method that converts something into a List?If yes so why can't I use parenthesis with it? I must be missing something more fundamental here.Here is the example:If a method is defined asthen it must be called aswith no extra parentheses.  We say that this method has .We could also define a parameter list but put nothing in it:Now, we could call either ofsince Scala allows the shortcut of omitting parentheses on method calls.As far as the JVM is concerned, there is no difference between the first definition (\"zero parameter lists\") and the second (\"one empty parameter list\").  But Scala maintains a distinction.  Whether this is a good idea or not is debatable, but the motivation might be clearer when you realize that we can alsowhich is known as , and then call any ofand now, if we were to convert this into a function, we would type it aswhile the second definition would bewhich is clearly different conceptually, even if practically you use it the same way (put in nothing and sooner or later get out a ).Anyway,  doesn't need any parameters, and the Scala standard is to leave off the parens unless the method changes the object itself (rather than just returning something), so it's  without any parens afterwards.  And thus you can only call it as .Your second line is actually interpreted as since  is \"magic\" syntax for .That's why the complier complains about \"not enough arguments\", as the apply method on lists takes one argument.Thus you can write e.g.:Let me answer from Scala coding style perspective.Scala  says...Omit empty parenthesis, only be used when the method in question has no side-effects (purely-functional). In other words, it would be acceptable to omit parentheses when calling queue.size, but not when calling println(). Religiously observing this convention will dramatically improve code readability and will make it much easier to understand at a glance the most basic operation of any given method. Resist the urge to omit parentheses simply to save two characters!"},
Scala

In Scala, what's the best way to dynamically instantiate an object and invoke a method using reflection?I would like to do Scala-equivalent of the following Java code:In the above code, both the class name and the method name are passed in dynamically. The above Java mechanism could probably be used for  and , but the Scala types don't match one-to-one with that of Java. For example, a class may be declared implicitly for a singleton object. Also Scala method allows all sorts of symbols to be its name. Both are resolved by name mangling. See .Another issue seems to be the matching of parameters by resolving overloads and autoboxing, described in .  There is an easier way to invoke method reflectively without resorting to calling Java reflection methods: use Structural Typing.Just cast the object reference to a Structural Type which has the necessary method signature then call the method: no reflection necessary (of course, Scala is doing reflection underneath but we don't need to do it).The answers by  and  are quite good, so I'll just complement with one Scala 2.8 Experimental feature. In fact, I won't even bother to dress it up, I'll just copy the scaladoc.The instanciation part  use the : see this So the true type safe solution would be using a Factory.Note: as stated in , Manifest is here to stay, but is for now \"only use is to give access to the erasure of the type as a Class instance.\"You can then get a method through reflection:and invoke itWorking up from @nedim's answer, here is a  for a full answer, \nmain difference being here below we instantiate naive classes. This code does not handle the case of multiple constructors, and is by no means a full answer.Here is a  that would compile it:In case you need to invoke a method of a Scala 2.10 object (not class) and you have the names of the method and object as s, you can do it like this:This prints  to standard output.\nFurther details in ."},
Scala

I'm wondering how can I use multiple type pattern matching. I have:So I'd like to write something like:I saw similar construction in some tutorial, but it gives me error:So is there a way to define few different types in on case clause? I think it would make code prettier. As if I will have 5 of them, I will write same code 5 times (calling doSomething()).Thanks in advance!You are missing the parenthesis for your case classes.\nCase classes without parameter lists are deprecated.Try this:If you have too many params for your case classes and don't like having to write long  patterns, then maybe:Or just:But perhaps you just wanted singleton case objects?"},
Scala

I'm wondering if there is any ideomatic way to chain multiple InputStreams into one continual InputStream in Java (or Scala).What I need it for is to parse flat files that I load over the network from an FTP-Server. What I want to do is to take file[1..N], open up streams and then combine them into one stream. So when file1 comes to an end, I want to start reading from file2 and so on, until I reach the end of fileN. I need to read these files in a specific order, data comes from a legacy system that produces files in barches so data in one depends on data in another file, but I would like to handle them as one continual stream to simplify my domain logic interface. I searched around and found PipedInputStream, but I'm not positive that is what I need. An example would be helpful.It's right there in JDK! Quoting :You want to concatenate arbitrary number of s while  accepts only two. But since  is also an  you can apply it recursively (nest them):...you get the idea.This is done using SequencedInputStream, which is straightforward in Java, as Tomasz Nurkiewicz's answer shows.  I had to do this repeatedly in a project recently, so I added some Scala-y goodness via the \"pimp my library\" pattern.With that, I can do stream sequencing as followsor evenAnother solution: first create a list of input stream and then create the sequence of input streams:Here is a more elegant solution using Vector, this is for Android specifically but use vector for any Java"},
Scala

What's the purpose of Symbol and why does it deserve some special  syntax e. g. ?Symbols are used where you have a closed set of identifiers that you want to be able to compare quickly. When you have two  instances they are not guaranteed to be interned[1], so to compare them you must often check their contents by comparing lengths and even checking character-by-character whether they are the same. With  instances, comparisons are a simple  check (i.e.  in Java), so they are constant time (i.e. O(1)) to look up.This sort of structure tends to be used more in dynamic languages (notably Ruby and Lisp code tends to make a lot of use of symbols) since in statically-typed languages one usually wants to restrict the set of items by type.Having said that, if you have a key/value store where there are a restricted set of keys, where it is going to be unwieldy to use a static typed object, a -style structure might well be good for you.: Java s are interned in some cases anyway; in particular string literals are automatically interned, and you can call the  method on a  instance to return an interned copy. Not all s are interned, though, which means that the runtime still has to do the full check unless they are the same instance; interning makes comparing two equal interned strings faster, but does not improve the runtime of comparing different strings. s benefit from being  to be interned, so in this case a single reference equality check is both sufficient to prove equality or inequality.[1] Interning is a process whereby when you create an object, you check whether an equal one already exists, and use that one if it does. It means that if you have two objects which are equal, they are precisely the same object (i.e. they are reference equal). The downsides to this are that it can be costly to look up which object you need to be using, and allowing objects to be garbage collected can require complex implementation.s are interned.The purpose is that  are more efficient than s and s with the same name are refered to the same  object (so having the same hashcode).Have a look at this read about Ruby symbols: You can only get the name of a :It's not very useful in Scala and thus not widely used. In general, you can use a symbol where you'd like to designate an identifier.For example, the reflection invocation feature which was planned for 2.8.0 used the syntax  where 'o' was a method added to Any and Symbol was added the method apply(Any*) (both with 'pimp my library'). Another example could be if you want to create an easier way to create HTML documents, then instead of using \"div\" to designate an element you'd write 'div. Then one can imagine adding operators to Symbol to make syntactic sugar for creating elements"},
Scala

Suppose I have the traits Student, Worker, Underpaid, and Young.How could I declare a class (), CollegeStudent, with all these traits? I am aware of the simplests cases, such as CollegeStudent with one or two Traits:It is easy, when declaring a class you just use the \"with\" keyword as often as you wantthe order of the traits can be important if a trait is changing the behavior of the class, it all depends on traits you are using.Also if you don't want to have a class which always uses the same traits you can use them later:I think that it is very important to explain not only the syntax, but . I found the explanation in Jason Swartz's  (page 177) quite enlightning.And since it determines the shape of the inheritance tree, the linearization order is indeed one very important question to regard. As an example,  (where A is a class and B\nand C are traits) would become . The following few lines, also from the book, illustrate that perfectly:A call to  would have the REPL print the following:Which perfectly reflects the structure of the linearized inheritance graph."},
Scala

How do you declare and initialize a variable to be used locally in a Play2 Scala template?I have this:declared at the top of the template, but it gives me this error:basically, you have to wrap the block in which you are going to use itActually, @c4k 's solution is working (and quite convenient) as long as you don't try to change the variable's value afterwards, isn't it?You simply place this at the top of your template:or, if it's a more complicated expression, you do this:You can even work with things like lists like that:For the given example, this would beIn the comments you said, that it gets typed to HTML type. However, that is only relevant if you try to overwrite  again, isn't it?scala template supports this, you can define variable in template   if you want to change its in template value you can byexamplevirtualeyes' solution is the proper one, but there is also other possibility, you can just declare a view's param as usually with default value, in such case you'll have it available for whole template + you'll keep possibility for changing it from the :controller:Note that Java controller doesn't recognise templates' default values, so you need to add them each time:If you don't want to wrap all your content with @defining, you can do this :The @defining directive is really unreadable in a template...There is one obvious solution which looks quite clean and may be preferred sometimes: define a scope around the template, define your variable inside of it, and let the scope produce the html code you need, like this:This has some drawbacks:The generated code:"},
Scala

I am a newbie scala programmer and came across a weird behavior.Above basically I want to return true if  and . Otherwise, I want to return false. Now above I have read that there is no need to add a return statement in scala. So I have omitted  above. But it doesn't return the boolean. If I add a return statement as . it works perfectly. Why is it so?Also, why is it considered a bad practice to have return statements in scalaIt's not as simple as just omitting the  keyword.  In Scala, if there is no  then the last expression is taken to be the return value.  So, if the last expression is what you want to return, then you can omit the  keyword.  But if what you want to return is  the last expression, then Scala .An example:Here the last expression of the function  is an if/else expression that evaluates to a String.  Since there is no explicit  marked, Scala will infer that you wanted to return the result of this if/else expression: a String.Now, if we add something  the if/else expression:Now the last expression is an if/else expression that evaluates to an Int.  So the return type of  will be Int.  If we really wanted it to return the String, then we're in trouble because Scala has  that that's what we intended.  Thus, we have to fix it by either storing the String to a variable and returning it after the second if/else expression, or by changing the order so that the String part happens last.Finally, we can avoid the  keyword even with a nested if-else expression like yours:}This topic is actually a little more complicated as described in the answers so far. This  explains it in more detail and gives examples on when using return will actually break your code (or at least have non-obvious effects).At this point let me just quote the essence of the post. The most important statement is right in the beginning. Print this as a poster and put it to your wall :-)It gives one example, where it actually breaks something, when you inline a functionbecauseThis is only one of the examples given in the linked post and it's the easiest to understand. There're more and I highly encourage you, to go there, read and understand.When you come from imperative languages like Java, this might seem odd at first, but once you get used to this style it will make sense. Let me close with another quote:I don't program Scala, but I use another language with implicit returns (Ruby). You have code after your  block -- the last line of code is what's returned, which is why you're not getting what you're expecting.EDIT: Here's a simpler way to write your function too. Just use the boolean value of isEmpty and count to return true or false automatically:By default the last statement of a function will be returned.\nIn your example there is another statement after the point, where you want your return value.\nIf you want to return anything prior to your last statement, you still have to use .You could modify your example like this, to return a  from the first partDon't write  statements without a corresponding . Once you add the  to your fragment you'll see that your  and  are in fact the last expressions of the function."},
Scala

Let's say I have this code:I expected  to only return , but instead, it returned . I know I could use  to extract only that part, but I'd have to have a pattern for the entire string, something like:Is there another way of achieving this, without using the classes from  directly, and without using unapply? Here's an example of how you can access  of each match:This prints  ().Depending on the complexity of the pattern, you can also use lookarounds to  match the portion you want. It'll look something like this: The above also prints  ().You want to look at , you're currently looking at , which is \"the entire matched string\".See ."},
Scala

I find myself writing code like this when I want to repeat some execution n times:I'm looking for a shorter syntax like this:Does something like this exist in Scala already?I thought about using Range's foreach() method, but then the block needs to take a parameter which it never uses.You could easily define one using Pimp My Library pattern.The Range class has a foreach method on it that I think is just what you need. For example, this:produced With :With :And that works as you would expect with most types (more precisely, for ):You could also say  which only works if your  is a monadic value. It has better type-safety, since you can do this:but not this:Let me see you pull that off in Ruby.I'm not aware of anything in the library. You can define a utility implicit conversion and class that you can import as needed.Rahul just posted a similar answer while I was writing this...It can be as simple as this:"},
Scala

I've seen \"<:\" and \">:\" and \"<%\" etc, can someone give (or locate) a good description of these? What are the possible constraints, what do they do, and whats an example of when to use them? means that  is a subtype of . This is also called an . Similarly,  means that  is a supertype of , a . is a view bound, and expresses that  must come equipped with a  that maps its values into values of type .It's confusing for me too, and I have a Masters in programming languages from Berkeley.There are two different beasts here, but they're all know as \"bounds\" and not \"constraints\"...First are the type bounds:These are essentially the same as  and  in java, and will actually be encoded as such in the generated bytecode, which is good for interop :)Then comes the syntactic sugar:These are NOT encoded in a way that Java could possibly understand (although they are represented in the , an annotation that scala adds to all classes to help the compiler, and which would ultimately be the base of an Scala reflection library)Both of these are converted to implicit parameters:For this reason, you can't combine your own implicits with either view bounds or context bounds, as Scala only permits one block labelled as implicit for any function or constructor.If you do need to use your own implicits then you must first manually convert any such bounds to the unsugared version and add this to the implicit block."},
Scala

In Scala, for many (all?) types of collections you can create views.What exactly is a view and for which purposes are views useful?Views are non-strict versions of collections. This means that the elements are calculated at access and not eagerly as in normal collections.As an example take the following code:Just this will not print anything but every access to the list will perform the calculation and print the value, i.e. every call to  will result in  being printed. If you want to get a strict version of the collection again you can call  on it. In this case you will see all numbers printed out.One use for views is when you need to traverse a collection of values which are expensive to compute and you only need one value at a time. Also views let you build lazy sequences by calling  on them that will also cache the evaluated elements.See  from .One use case is when you need to collect first result of elements transformation:Prints: While: Prints: "},
Scala

There are claims that Scala's type system is Turing complete. My questions are:I guess this applies to languages and type systems in general.There is a blog post somewhere with a type-level implementation of the SKI combinator calculus, which is known to be Turing-complete.Turing-complete type systems have basically the same benefits and drawbacks that Turing-complete languages have: you can do anything, but you can prove very little. In particular, you cannot prove that you will actually eventually do something.One example of type-level computation are the new type-preserving collection transformers in Scala 2.8. In Scala 2.8, methods like ,  and so on are guaranteed to return a collection of the same type that they were called on. So, if you  a , you get back a  and if you  a  you get back a .Now, as you can see,  can actually transform the element type. So, what happens if the new element type cannot be represented with the original collection type? Example: a  can only contain fixed-width integers. So, what happens if you have a  and you map each number to its string representation?The result  be a , but that's impossible. So, Scala chooses the most derived supertype of , which can hold a , which in this case is a .All of this computation is going on during , or more precisely during , using type-level functions. Thus, it is statically guaranteed to be type-safe, even though the types are actually computed and thus not known at design time.My  on encoding the SKI calculus in the Scala type system shows Turing completeness.For some simple type level computations there are also some examples on how to encode the natural numbers and addition/. Finally there is a great  on type level programming over on Apocalisp's blog."},
Scala

Suppose I have a Java class with multiple constructors:How can I extend it in Scala and still provide access to all three of Base's constructors? In Scala, a subclass can only call one of it's superclass's constructors. How can I work around this rule?Assume the Java class is legacy code that I can't change.It's easy to forget that a trait may extend a class. If you use a trait, you can postpone the decision of which constructor to call, like this:Traits may not themselves have constructor parameters, but you can work around that by using abstract members instead. - Assuming that each of your constructors ultimately create the   of the object, create a companion object with \"static\" methods to create this stateThen create a private constructor taking the state and (public) overloaded constructors which defer to the primary constructorThis is a silly answer that would probably work somewhat but might be too much effort if the Java class has way too many constructors, but:Write a subclass in Java that implements a constructor that takes all the inputs the various other constructors would and calls the proper constructor of its superclass based on the presence or absence of inputs (via usage of \"null\" or some sort of sentinel values), then subclass that Java class in Scala and assign the sentinel values as default parameters.I would pick the most generic one (in this case, String) and do the internal conversion yourself if it meets the other criteria.Although I admit this is not the best solution and something strikes me as wrong about it. :-("},
Scala

Can please someone explain the differences between Functor and Monad in the Scala context?Scala itself really does not emphasize the  and  terms that much. I guess using  is the functor side, using  is the Monad side.For me looking and playing around with  has been so far the best avenue to get a sense of those functional concepts in the scala context (versus the haskell context). Two years ago when I started scala, the scalaz code was gibberish to me, then a few months ago I started looking again and I realized that it's really a clean implementation of that particular style of functional programming.For instance the  implementation shows that a monad is a pointed  because it extends the  trait (as well as the  trait). I invite you to go look at the code. It has linking in the source itself and it's really easy to follow the links.So functors are more general. Monads provide additional features. To get a sense of what you can do when you have a functor or when you have a monad, you can look at You'll see utility methods that need an implicit functor (in particular applicative functors) such as  and sometime methods that needs a full monad such as . Taking  as the reference point, a type  (that is, a type F which is parameterized by some single type) is a functor if a function can be lifted into it. What does this mean:That is, if I have a function , a functor , then I now have a function . This is really just the reverse-way of looking at scala's  method, which (ignoring the  stuff) is basically:What I find interesting about this is that you might immediately jump to the (incorrect) conclusion that a Functor is a \"container\" of s. This is an unnecesssary restriction. For example, think about a function . If I have a function  and a function  then clearly, by composition, I have a function . But now, look at it this way:So the type X => A for some fixed X is also a functor. In , functor is designed as a trait as follows:hence the  method above is implementedA couple of functor instances:In , a monad is designed like this:It is not particularly obvious what the usefulness of this might be. It turns out that the answer is \"very\". I found Daniel Spiewak's  extremely clear in describing why this might be and also Tony Morris's stuff on , a good practical example of what might be meant by .The best article laying out in details those two notions is \"\" from .It is the basic layer from which you define:All three elements are used to define a . A while ago I wrote about that:  (I'm no expert though) The first thing to understand is the type ' T[X] ' : It's a kind of \"context\" (is useful to encode things in types and with this you're \"composing\" them) But see the other answers :)Ok, now you have your types inside a context, say M[A] (A \"inside\" M), and you have a plain function f:A=>B ... you can't just go ahead and apply it, because the function expects A and you have M[A]. You need some way to \"unpack\" the content of M, apply the function and \"pack\" it again. If you have \"intimate\" knowledge of the internals of M you can do it, if you generalize it in a trait you end with And that's exactly what a functor is. It transforms a T[A] into a T[B] by applying the function f.A Monad is a mythical creature with elusive understanding and multiple metaphors, but I found it pretty easy to understand once you get the applicative functor:Functor allow us to apply functions to things in a context. But what if the functions we want to apply are already in a context? (And is pretty easy to end in that situation if you have functions that take more than one parameter).Now we need something like a Functor but that also takes functions already in the context and applies them to elements in the context. And that's what the applicative functor is. Here is the signature:So far so good.\nNow comes the monads: what if now you have a function that puts things in the context? It's signature will be g:X=>M[X] ... you can't use a functor because it expects X=>Y so we'll end with M[M[X]], you can't use the applicative functor because is expecting the function already in the context M[X=>Y] .So we use a monad, that takes a function X=>M[X] and something already in the context M[A] and applies the function to what's inside the context, packing the result in only one context. The signature is:It can be pretty abstract, but if you think on how to work with \"Option\" it shows you how to compose functions X=>Option[X]EDIT: Forgot the important thing to tie it: the >>= symbol is called  and is  in Scala. (Also, as a side note, there are some laws that functors, applicatives, and monads have to follow to work properly).I think this great blog post will help you first for . "},
Scala

I am starting to use  build my Scala code (and handle dependencies). As far as I know if I useon the command line this will run the main class of the main project.Is it possible to 'run' within any other project from the command line, i.e. not in the interactive session mode? (I'm thinking about something that might look like  or whatever...)What I would do in interactive mode is this:This seems to be straightforward enough, but I can not find any documentation describing this behavior. Hints would be much appreciated...You simply have to quote each command (as in the second example ), so in your case it would be: also workThis works:Worked for me:Also this may be of some help:"},
Scala

I'm using SBT (within IntelliJ IDEA) to build a simple Scala project.I would like to know what is the  to build an  file (aka Fat JAR, Super JAR).I'm currently using SBT but when I'm submiting my JAR file to  I get the following error:Or this error during compilation time:It  it is because some of my dependencies include signature files (META-INF) which needs to be removed in the final Uber JAR file.I tried to use the  plugin like that:/project/assembly.sbt/project/plugins.sbt/build.sbtWhen I click \"\" in IntelliJ IDEA I get a JAR file. But I end up with the same error...I'm new to SBT and not very experimented with IntelliJ IDE.Thanks.Finally I totally skip using IntelliJ IDEA to avoid generating noise in my global understanding :)I started reading the .I created my project with the following file structure :Added the   in my  file. Allowing me to build a fat JAR :My minimal  looks like :: The  means not to include the dependency in the final fat JAR (those libraries are already included in my workers): META-INF discarding .: Meaning of  and Now I can build my fat JAR using SBT () by running the following command in my  root folder:My fat JAR is now located in the new generated  folder :Hope that helps someone else.For those who wants to embeed SBT within IntelliJ IDE: 3 Step Process For Building Uber JAR/Fat JAR in IntelliJ Idea: : JAR file having all external libraray dependencies in it.\nVoila!!! Uber JAR is built. JAR will be in \nAdd the following line to your project/plugins.sbtAdd the following to your build.sbtThe Assembly merge strategy is used to resolve conflicts occurred when creating fat jar."},
Scala

I want to get the type of a variable at runtime.\nHow do I do this?So, strictly speaking, the \"type of a variable\" is always present, and can be passed around as a type parameter. For example:But depending on , that won't help you. For instance, may want not to know what is the type of the variable, but to know if the type of the  is some specific type, such as this:Here it doesn't matter what is the type of the variable, . What matters, what is checked is the type of , the value. In fact,  is useless -- you might as well have written it  instead. Also, this uses either  or a value's , which are explained below, and cannot check the type parameters of a type: you can check whether something is a  ( of something), but not whether it is, for example, a  or .Another possibility is that you want to  the type of the variable. That is, you want to convert the type into a value, so you can store it, pass it around, etc. This involves reflection, and you'll be using either  or a . For example:A  will also let you use type parameters you received on . This won't work:But this will:Here I'm using the  syntax, , which works just like the implicit parameter in the previous  example, but uses an anonymous variable.One can also get a  from a value's , like this:A  is limited in that it only covers the base class, but not its type parameters. That is, the  for  and  is the same, . If you need type parameters, then you must use a  instead. A  however, cannot be obtained from a value, nor can it be used on a pattern match, due to JVM's .Examples with  can get quite complex -- not even comparing two type tags is not exactly simple, as can be seen below:Of course, there are ways to make that comparison return true, but it would require a few book chapters to really cover , so I'll stop here.Finally, maybe you don't care about the type of the variable at all. Maybe you just want to know what is the class of a value, in which case the answer is rather simple:It would be better, however, to be more specific about what you want to accomplish, so that the answer can be more to the point.I think the question is incomplete. if you meant that you wish to get the type information of some typeclass then below: If you wish to print as you have specified then:If you are in repl mode then Or if you just wish to know what the class type then as @monkjack explains  might solve the purposeIf by  you mean the runtime class of the object that the variable points to, then you can get this through the class reference that all objects have.If you however mean the type that the variable was declared as, then you cannot get that. Eg, if you say then you will still get a  back from the above code."},
Scala

I seem to have a problem with performance of \"sbt test\" after upgrading to macOS Sierra. On a previous version of OS X it took about 40-50 seconds to finish. macOS Sierra times are much higher than that. Last run I did was around 15 minutes. Compile times are about the same as on 'El Capitan'.I'm the only one from my team to try this new macOS so I can't tell if it's only happening on my mac or is it a universal issue.My colleague had a similar issue on Ubuntu and it was related with random number generation slowing down the tests - Unfortunately, that didn't work for me. Originally I tried that on JDK 8u54 and then tried updating to JDK 8u102 and that didn't help as well.P.S. I'm running Macbook Pro Mid-2015 2.8GHz i7, 16GB ram, 1TB SSD.I had the same problem. Tomcat went from 15 seconds to 6 minutes to initialise spring context after the upgrade... disabling csrutils didn't solve the issue for me.I  the problem by adding my Mac hostname (i.e. Macbook.local, or whatever your Mac is called) on the  file mapped to the  address as well as the  like this:If you're interested you can find some details on the issue and solution here:\nOn the post I also link to a  to help troubleshooting the issue and validating the solution.The problem is related (I believe) on how the localhost name resolution works and how the java.net.InetAddr class is retrieving the addresses. I verified with few colleagues and apparently it doesn't happen to everyone who upgraded to Sierra, but I'm still investigating the roots of this change.The solution anyway was the same that  implemented and worked immediately.Correct answer: For the lazy people:I have the same problem. My spring-boot application take 60 seconds to start on Sierra against 25 seconds on Yosemite.While debugging, I realized that the problem comes from InetAddress.getLocalHost().\nI changed my host file to add my hostname for 127.0.0.1 and :: 1 and now the application starts as fast as before.I think it is a general problem with the new OS. I have a similar problem: I have a web application which is deployed to tomcat. On El Capitan it started up in 10 secs, now it takes 95 secs and the client (a Swing based desktop app) cannot connect to it (or at least it took lot of time). I think it is something around network communication, because a simple test console app runs well.Enabling e.g. System Preferences > Sharing > Remote Login, results in the hostname being automatically assigned an IP address.As people are seeing issues after the upgrade, it makes sense to assume that 10.12 changed how the hostname is resolved, i.e. at least with 10.11 the hostname is always resolved, while with 10.12 it is resolved only if a service is enabled in System Preferences > Sharing (someone with 10.11 could confirm this).It could be because of some bugs in the way Mac OS Sierra was set up. Try doing what is called a SMC reset or PRAM reset to see if it will fix your Mac. These are software resets and will not harm your user data. They might require you to just reset system time after a restart. But they can potentially fix your problems. You can also look at some of the tips mentioned about Mac OS Sierra troubleshooting here - "},
Scala

I sense that the Scala community has a little big obsession with writing \"concise\", \"cool\", , \"one-liner\" -if possible- code. This is immediately followed by a comparison to Java/imperative/ugly code.While this (sometimes) leads to easy to understand code, it also leads to inefficient code for 99% of developers. And this is where Java/C++ is not easy to beat.Consider this simple problem:  Ordering does not need to be preserved.Here is my version of the solution (It may not be the greatest, but it's what the average non-rockstar developer would do).It's Scala idiomatic, concise, and uses a few nice list functions. It's also very inefficient. It traverses the list at least 3 or 4 times.Here is my totally uncool, Java-like solution. It's also what a reasonable Java developer (or Scala novice) would write.Totally non-Scala idiomatic, non-functional, non-concise, but it's very efficient. It traverses the list only once!So, if 99% of Java developers write more efficient code than 99% of Scala developers, this is a huge \nobstacle to cross for greater Scala adoption. Is there a way out of this trap?I am looking for practical advice to avoid such \"inefficiency traps\" while keeping implementation clear ans concise. This question comes from a real-life scenario: I had to write a complex algorithm. First I wrote it in Scala, then I \"had to\" rewrite it in Java. The Java implementation was twice as long, and not that clear, but at the same time it was twice as fast. Rewriting the Scala code to be efficient would probably take some time and a somewhat deeper understanding of scala internal efficiencies (for vs. map vs. fold, etc)Let's discuss a fallacy in the question:This is presumed, with absolutely no evidence backing it up. If false, the question is moot.Is there evidence to the contrary? Well, let's consider the question itself -- it doesn't prove anything, but shows things are not that clear.Of the four claims in the first sentence, the first three are true, and the fourth, as shown by , is false! And why it is false? Because, contrary to what the second sentence states, it traverses the list more than once.The code calls the following methods on it:andLet's consider first .So let's consider this. When you resize, Java first clears the memory by storing 0 in each element, then Scala copies each element of the previous array over to the new array. Since size doubles each time, this happens log(n) times, with the number of elements being copied increasing each time it happens.Take for example n = 16. It does this four times, copying 1, 2, 4 and 8 elements respectively. Since Java has to clear each of these arrays, and each element must be read  written, each element copied represents 4 traversals of an element. Adding all we have (n - 1) * 4, or, roughly, 4 traversals of the complete list. If you count read and write as a single pass, as people often erroneously do, then it's still three traversals.One can improve on this by initializing the  with an initial size equal to the list that will be read, minus one, since we'll be discarding one element. To get this size, we need to traverse the list once, though.Now let's consider . To put it simply, it traverses the whole list to create a new list.So, we have 1 traversal for the algorithm, 3 or 4 traversals for resize, and 1 additional traversal for . That's 4 or 5 traversals.The original algorithm is a bit difficult to analyse, because ,  and  traverse a variable number of elements. Adding all together, however, it does the equivalent of 3 traversals. If  was used, it would be reduced to 2 traversals. With 2 more traversals to get the maximum, we get 5 traversals -- the same number as the non-functional, non-concise algorithm!So, let's consider improvements.On the imperative algorithm, if one uses  and , then all methods are constant-time, which reduces it to a single traversal.On the functional algorithm, it could be rewritten as:That reduces it to a worst case of three traversals. Of course, there are other alternatives presented, based on recursion or fold, that solve it in one traversal.And, most interesting of all, all of these algorithms are , and the only one which almost incurred (accidentally) in worst complexity was the imperative one (because of array copying). On the other hand, the  characteristics of the imperative one might well make it faster, because the data is contiguous in memory. That, however, is unrelated to either big-Oh or functional vs imperative, and it is just a matter of the data structures that were chosen.So, if we actually go to the trouble of benchmarking, analyzing the results, considering performance of methods, and looking into ways of optimizing it, then we can find faster ways to do this in an imperative manner than in a functional manner.But all this effort is very different from saying the average Java programmer code will be faster than the average Scala programmer code -- if the question is an example, that is simply false. And even discounting the question, we have seen no evidence that the fundamental premise of the question is true.First, let me restate my point, because it seems I wasn't clear. My point is that the code the average Java programmer writes may seem to be more efficient, but actually isn't. Or, put another way, traditional Java style doesn't gain you performance -- only hard work does, be it Java or Scala. Next, I have a benchmark and results too, including almost all solutions suggested. Two interesting points about it:The benchmark code is , and the results are .Here is a recursive method, which only iterates once. If you need performance, you have to think about it, if not, not. You can make it tail-recursive in the standard way: giving an extra parameter , which is per default the empty List, and collects the result while iterating. That is, of course, a bit longer, but if you need performance, you have to pay for it:I don't know what the chances are, that later compilers will improve slower map-calls to be as fast as while-loops. However: You rarely need high speed solutions, but if you need them often, you will learn them fast. Do you know how big your collection has to be, to use a whole second for your solution on your machine?As oneliner, similar to Daniel C. Sobrals solution: but that is hard to read, and I didn't measure the effective performance. The normal pattern is (x /: xs) ((a, b) => /* something */). Here, x and a are pairs of List-so-far and max-so-far, which solves the problem to bring everything into one line of code, but isn't very readable. However, you can earn reputation on CodeGolf this way, and maybe someone likes to make a performance measurement. An updated timing-method, to get the garbage collection out of the way, and have the hotspot-compiler warm up, a main, and many methods from this thread, together in an Object named I renamed all the methods, and had to modify uu2 a bit, to fit to the common method declaration (List [Int] => List [Int]). From the long result, i only provide the output for 1M invocations: The numbers aren't completly stable, depending on the sample size, and a bit varying from run to run. For example, for 100k to 1M runs, in steps of 100k, the timing for splitAt was as follows:The initial solution is already pretty fast.  is a modification from Daniel, often faster, but not always.The measurement was done on a single core 2Ghz Centrino, running xUbuntu Linux, Scala-2.8 with Sun-Java-1.6 (desktop). The two lessons for me are: First of all, the behavior of the methods you presented is not the same. The first one keeps the element ordering, while the second one doesn't.Second, among all the possible solution which could be qualified as \"idiomatic\", some are more efficient than others. Staying very close to your example, you can for instance use tail-recursion to eliminate variables and manual state management:or fold the list:If you want to keep the original insertion order, you can (at the expense of having two passes, rather than one) without any effort write something like:which is more clear than your first example.The biggest inefficiency when you're writing a program is worrying about the wrong things. This is usually the wrong thing to worry about. Why?The example you gave is not very functional, actually. Here's what you are doing:Mind you, it is not , but you know when functional code is at its best when it describes what you want, instead of how you want it. As a minor criticism, if you used  instead of  and  you could improve it slightly.Another way of doing it is this:Now, let's discuss the main issue. Is this code slower than the Java one? Most certainly! Is the Java code slower than a C equivalent? You can bet it is, JIT or no JIT. And if you write it directly in assembler, you can make it even faster!But the cost of that speed is that you get more bugs, you spend more time trying to understand the code to debug it, and you have less visibility of what the overall program is doing as opposed to what a little piece of code is doing -- which might result in performance problems of its own.So my answer is simple: if you think the speed penalty of programming in Scala is not worth the gains it brings, you should program in assembler. If you think I'm being radical, then I counter that you just chose the familiar as being the \"ideal\" trade off.Do I think performance doesn't matter? Not at all! I think one of the main advantages of Scala is leveraging gains often found in dynamically typed languages with the performance of a statically typed language! Performance matters, algorithm complexity matters a lot, and constant costs matters too.But, whenever there is a  between performance and readability and maintainability, the latter is preferable. Sure, if performance  be improved, then there isn't a choice: you have to sacrifice something to it. And if there's no lost in readability/maintainability -- such as Scala vs dynamically typed languages -- sure, go for performance.Lastly, to gain performance out of functional programming you have to know functional algorithms and data structures. Sure, 99% of Java programmers with 5-10 years experience will beat the performance of 99% of Scala programmers with 6 months experience. The same was true for imperative programming vs object oriented programming a couple of decades ago, and history shows it didn't matter.As a side note, your \"fast\" algorithm suffer from a serious problem: you use . That collection does not have constant time append, and has linear time . If you use  instead, you get constant time append  .For reference, here's how  is defined in  in the Scala standard library,It's not unlike your example code of what a Java programmer might come up with.I like Scala because, where performance matters, mutability is a reasonable way to go. The collections library is a great example; especially how it hides this mutability behind a functional interface. Where performance isn't as important, such as some application code, the higher order functions in Scala's library allow great expressivity and programmer efficiency.Out of curiosity, I picked an arbitrary large file in the Scala compiler () and counted something like 37 for loops, 11 while loops, 6 concatenations (), and 1 fold (it happens to be a ).What about this?A bit more ugly, but faster:Try this:Idiomatic, functional, traverses only once. Maybe somewhat cryptic if you are not used to functional-programming idioms.Let's try to explain what is happening here. I will try to make it as simple as possible, lacking some rigor.A  is an operation on a  (that is, a list that contains elements of type ) that will take an initial state  (that is, an instance of a type ) and a function  (that is, a function that takes the current state and an element from the list, and gives the next state, ie, it updates the state according to the next element).The operation will then iterate over the elements of the list, using each one to update the state according to the given function. In Java, it would be something like:For example, if you want to add all the elements of a , the state would be the partial sum, that would have to be initialized to 0, and the new state produced by a function would simply add the current state to the current element being processed:Try to write a fold to multiply the elements of a list, then another one to find extreme values (max, min).Now, the fold presented above is a bit more complex, since the state is composed of the new list being created along with the maximum element found so far. The function that updates the state is more or less straightforward once you grasp these concepts. It simply puts into the new list the minimum between the current maximum and the current element, while the other value goes to the current maximum of the updated state.What is a bit more complex than to understand this (if you have no FP background) is to come up with this solution. However, this is only to show you that it exists, can be done. It's just a completely different mindset.EDIT: As you see, the first and second  in the solution I proposed are used to  the fold. It is equivalent to what you see in other answers when they do . Note that the solutions proposed until now using  don't cover the case in which  is , and will throw an exception. The solution above will return  instead. Since you didn't specify the behavior of the function on empty lists, both are valid.Another contender.  This uses a ListBuffer, like Daniel's second offering, but shares the post-max tail of the original list, avoiding copying it."},
Scala

So I've been trying to puzzle through the various ways you can define stuff in Scala, complicated by my lack of understanding of the way  blocks are treated:Presumably some of these are equivalent, some of these are syntactic sugar for others, and some are things I should not use, but I can't for the life of me figure it out. My specific questions are:To answer your questions in order:As \"user unknown\" indicates, the braces are only important for scoping purposes and do not make any difference in your use case here.is sytactic sugar forSo if you omit the \"=\" the method will always return an object of type Unit.\nIn Scala, methods and expressions always return something.If you write def f() = () => 10, it's the same as writingSo that means f is returning a function object.\nYou could however writeWhen you call that with f() it returns 10\nFunction objects and methods can be used interchangingly in most cases, but there are a few syntactic differences.\ne.g.\nWhen you writeyou get \"10\", but when you writeyou get On the other hand when you have thisBoth println will print the same thingWhen you use the name of a method at a place where a function object is expected and the method signature matches the signature of the expected function object it is automatically converted.\nSo  gets automatically converted by the scala compiler intoThe second form does not use an assignment. Therefore you can think of it as an Procedure. It is not meant to return something, and returns therefore Unit, even if the last statement could be used to return something specific (but it could be an if-statement, which would only have something specific in one branch).You don't need braces here. You need them, for instance, if you define a val, so the scope of this val is restricted to the enclosing block. You need the curly braces to define val sqr here. If the val is declared in an inner branch, the curly braces don't need to be at the top-level of the method:For further investigation when two methods return the same result, you can compile them and compare the bytecode. Two binary identical methods will be identic."},
Scala

Following watching  on deriving , I got to looking at this example, which is just awesome:I was trying to understand what the  method was doing, here is the source code:OK, that is fairly confusing (!) - but it references the  method, which is declared thus:So I have a few questions: is a type parameter to one of Scalaz's main pimps, , that represents the Type Constructor (aka Higher Kinded Type) of the pimped value. This type constructor is used to look up the appropriate instances of  and , which are implicit requirements to the method .From the Scala Language Reference: is a type constructor. You can apply the type  to get a Value Type, , which can classify a value. Other type constructors take more than one parameter.The trait  requires that it's first type parameter must be a type constructor that takes a single type to return a value type, with the syntax . The type parameter definition describes the shape of the type constructor, which is referred to as its Kind.  is said to have the kind '.But how can  wrap a values of type ? The type  has a kind , and could only be passed as a type argument to a type parameter declared like . This implicit conversion in  converts a value of type  to a :Which in turn uses a trick with a type alias in  to partially apply the type constructor , fixing the type of the errors, but leaving the type of the success unapplied. would be better written as . I recently proposed to add such a syntax to Scala, it might happen in 2.9.Think of this as a type level equivalent of this:This lets you combine  with a , because the both share the type constructor . demands the the type constructor  must have associated instances of  and . This constitutes an Applicative Functor, which, like a Monad, is a way to structure a computation through some effect. In this case the effect is that the sub-computations can fail (and when they do, we accumulate the failures).The container  can wrap a pure value of type  in this 'effect'. The  operator takes two effectful values, and a pure function, and combines them with the Applicative Functor instance for that container.Here's how it works for the  applicative functor. The 'effect' here is the possibility of failure.In both cases, there is a pure function of type , being applied to effectful arguments. Notice that the result is wrapped in the same effect (or container, if you like), as the arguments.You can use the same pattern across a multitude of containers that have an associated Applicative Functor. All Monads are automatically Applicative Functors, but there are even more, like . and  are both Monads, so you could also used  (aka flatMap): is really similar to , but it provides the pure function for you to simply build a Tuple2 from the results.  is a shorthand for Here's our bundled examples for  and . I used a slightly different syntax to use the Applicative Functor, If any of the sub-computations fails, the provided function is never run. It only is run if all sub-computations (in this case, the two arguments passed to ) are successful. If so, it combines these into a . Where is this logic? This defines the  instance for . We require that the type X must have a  avaiable, which is the strategy for combining the individual errors, each of type , into an aggregated error of the same type. If you choose  as your error type, the  concatenates the strings; if you choose , the error(s) from each step are concatenated into a longer  of errors. This concatenation happens below when two  are combined, using the  operator (which expands with implicits to, for example, .Still reading? ()I've shown that sub-computations based on  or  can be combined with either  or with . When would you choose one over the other?When you use , the structure of the computation is fixed. All sub-computations will be executed; the results of one can't influence the the others. Only the 'pure' function has an overview of what happened. Monadic computations, on the other hand, allow the first sub-computation to influence the later ones.If we used a Monadic validation structure, the first failure would short-circuit the entire validation, as there would be no  value to feed into the subsequent validation. However, we are happy for the sub-validations to be independent, so we can combine them through the Applicative, and collect all the failures we encounter. The weakness of Applicative Functors has become a strength!"},
Scala

While looking for something else, quite out of mere coincidence I stumbled upon few comments about how diabolical case class inheritance is. There was this thing called  , wretches and kings, elves and wizards and how some kind of a very desirable property is lost with case classes inheritance. So what is so wrong with case class inheritance ?One word:    classes come with a supplied implementation of  and . The equivalence relation, known as  works like this (i.e. must have the following properties):As soon as you allow for equality within an inheritance hierarchy you can break 2 and 3. this is trivially demonstrated by the following example:Then we have:But You might argue that all class hierarchies may have this problem, and this is true. But case classes exist specifically to simplify equality from a developer's perspective (among other reasons), so having them behave  would be the definition of an own goal!There were other reasons as well; notably the fact that  and .That is not overall true. And this is worse than lie.As mentioned by  in any case class successor which constricts a definition area must redefine the equality because pattern matching must work exactly as equality (if try to match  as  then it will not matched since  is not exists).That give understanding to how the equality of case class hierarchy could be implemented.Eventually it is possible to satisfy requirements of the equality relation even for case class successor (without overriding of equality)."},
Scala

My method definition looks as followsSuppose I wish to know whether the second string is blankDoes not compile.  How do I go about doing this?If you want to pattern match on the array to determine whether the second element is the empty string, you can do the following:The  binds to any number of elements including none. This is similar to the following match on Lists, which is probably better known:Pattern matching may not be the right choice for your example. You can simply do:Pattern matching is more approriate for cases like:which print something for each token. if you want to check if there exist any token which is an empty string, you can also try: statement doesn't work like that. That should be:What is extra cool is that you can use an alias for the stuff matched by  with something like "},
Scala

NOTE: I am on Scala 2.8\u2014can that be a problem?Why can't I use the  function the same way as  or ?In the  it says that:But I see no type parameter  in the function signature:What is the difference between the  and , and how do I use the latter?EDIT: For example how would I write a fold to add all elements in a list? With  it would be:You're right about the old version of Scala being a problem. If you look at the  for Scala 2.8.1, you'll see no fold defined there (which is consistent with your error message).  Apparently,  was introduced in Scala 2.9.Short answer: associates to the right. I.e. elements will be accumulated in right-to-left order: associates to the left. I.e. an accumulator will be initialized and elements will be added to the accumulator in left-to-right order: is  in that the order in which the elements are added together is not defined. I.e. the arguments to  form a ., contrary to  and , does not offer any guarantee about the order in which the elements of the collection will be processed. You'll probably want to use , with its more constrained signature, with parallel collections, where the lack of guaranteed processing order helps the parallel collection implements folding in a parallel way. The reason for changing the signature is similar: with the additional constraints, it's easier to make a parallel fold.For your particular example you would code it the same way you would with foldLeft.Agree with other answers. thought of giving a simple illustrative example: "},
Scala

What is the difference between the  and  functions of ?Here is a pretty good explanation:Using  list as an example:Map's signature is: and flatMap's isSo flatMap takes a type [A] and returns an iterable type [B] and map takes a type [A] and returns a type [B]This will also give you an idea that flatmap will \"flatten\" lists.The above is all true, but there is one more thing that is handy:   turns a  into , with any  that drills down to , removed.  This is a key conceptual breakthrough for getting beyond using .From :You can see this better in for comprehensions:this translates into:Each iterator inside for will be translated into a \"flatMap\", except the last one, which gets translated into a \"map\". This way, instead of returning nested collections (a list of an array of a buffer of blah, blah, blah), you return a flat collection. A collection formed by the elements being yield'ed -- a list of Integers, in this case.Look here:\n\"Search for flatMap\"  - there is a really good explanation of it there.  (Basically it is a combination of \"flatten\" and \"map\" -- features from other languages)."},
Scala

I guess it is not possible to invoke methods implemented in Scala traits from Java, or is there a way? Suppose I have in Scala:and in Java if I use it as Java complains that From Java perspective  is compiled into  . Hence implementing  in Java is interpreted as implementing an interface - which makes your error messages obvious. Short answer: you can't take advantage of trait implementations in Java, because this would enable multiple inheritance in Java (!)Long answer: so how does it work in Scala? Looking at the generated bytecode/classes one can find the following code:Note that  is neither a member of , nor does  extend it. It simply delegates to it by passing .To continue the digression on how Scala works... That being said it is easy to imagine how mixing in multiple traits works underneath:translates to:Now it's easy to imagine how mixing in multiple traits overriding same method:Again  and  will become interfaces extending . Now if  comes last when defining :you'll get:However switching  and  (making  to be last) will result in:Now consider how traits as stackable modifications work. Imagine having a really useful class Foo:which you want to enrich with some new functionality using traits:Here is the new 'Foo' on steroids:It translates to:So the whole stack invocations are as follows:And the result is \"Foo, Trait1, Trait2\".If you've managed to read everything, an answer to the original question is in the first four lines...It's indeed not abstract since  is returning an empty  (a kind of NOP). Try:Then  will be a Java abstract method returning ."},
Scala

Given a typeclass where instance selection should be performed based on the return type:why does Scala (2.11.6) fail to resolve the proper instance:when it has no problems finding an implicit based on the return type when using the  function (we redefine it here as  to illustrate how similar it is to )The , instead of  in the error message is puzzling.I would assume many scalaz contributors to be familiar with this problem as it seems to limit the convenience of typeclasses in scala.EDIT: I'm looking into getting this working without forgoing type inference. Otherwise I'd like understand why that's not possible. If this limitation is documented as a Scala issue, I could not find it.1) After rewriting your code as follows:then becomes clearly why that works so.2) After you had to set mzero as  then you enabled additional type inference to resolve existencial type. Compiler got actual type from required return type. \nYou could check it with  if you want.3) Of course all that behaviour is just subtleties of compiler and I not think that such partial cases really required deep understanding."},
Scala

I'm only beginning to become familiar with the concept of kinds, so bear with me if I am not formulating my questions well...  Do they kinds have ilk, or genres, or breeds, or varieties?How far does this sequence of abstraction go?  Do we stop because we run out of words, or do we stop because going farther has no value?  Or, perhaps, because we quickly reach the limits of human cognition and just can't wrap our heads around higher-genred kinds?A related question:  languages give us value-constructors (like a cons operator) to make values. Languages also give us type-constructors like (,) or [] to make types.  Are there any languages that expose kind-constructors to make kinds?  Another edge case that I'm curious about:  We apparently have a type that has no value, denoted as \u22a5, called \"the bottom type\".  Is there a kind that has no type:  a bottom kind?The terminology  and  does not scale well.  Type theorists since Bertrand Russell have used a hierarchy of \"types.\"  One version of this has that   In dependently typed languages like Coq and Agda, one frequently needs these \"higher sorts.\"Levels like this are helpful for avoiding .  Using  tends to cause contradiction (see  for alternative designs).This use of numbers is the standard notation when we need it.  Some type theories have a notion of \"cumulative kinds\", \"cumulative levels\" or \"cumulative sorts\" which says \"if  then also \".Cumulative levels + \"level polymorphism\" give a theory almost as flexible as , but avoids paradoxes.  Coq makes the levels implicit mostly, although the sorts  and  are both typed , .  That is, you don't usually see the numbers, and most of the time it just works. Agda has a language pragma which provides level polymorphism, and makes things very flexible, but can be slightly bureaucratic (Agda is however usually less \"bureaucratic\" than Coq in other areas).  Another good word is \"universe.\"You should probably read Tim Sheard's paper about Omega, a dialect of Haskell with an infinite tower of types/kinds/sorts, but without full-blown dependent types.  It explains why you'd want this, and mentions that the levels above \"sort\" are in practice (at least so far) not directly used very much."},
Scala

I just recently started learning the Scala language and would like to do it in -way. Could you share your experiences on the unit testing frameworks there are for Scala and the pros/cons of them.I'm using IntelliJ IDEA for Scala development, so it would be nice to be able to run the tests with IDE-support.Have you looked at  ?I've not used it, but it comes from Bill Venners and co at Artima, and consequently I suspect it'll do the job. It doesn't appear to have IDE integration, however. is a little old, but suggests that TestNG is the best option for testing Scala. TestNG will certainly have IDE integrations.EDIT: I've just realised that I wrote this answer in 2009, and the world has moved on (!). I am currently using ScalaTest, the IDE integration works fine, and I can strongly recommend it. In particular the  works very nicelyI'm the author of specs. If you're a Intellij user, I advise you to mix-in in the org.specs.runner.ScalaTest trait to your specification and run it as a ScalaTest suite.If you have any issue with that, or anything else feel free to send a message to the  mailing list.You could also check out  it's fairly complete and IIRC is heavily used as part of Lift."},
Scala

I'm trying to find the 'right' actor implementation. I realized there is a bunch of them and it's a bit confusing to pick one. Personally I'm especially interested in remote actors, but I guess a complete overview would be helpful to many others. This is a pretty general question, so feel free to answer just for the implementation you know about.I know about the following Scala Actor implementations (SAI). Please add the missing ones.This is the most comprehensive comparison I have seen so far: via As of , scala actors is now deprecated and Akka Actors is now part of standard distributionScala 2.7.7. vs 2.8 after :New Reactors provide more lightweight, purely event-based actors with optional, implicit sender identification. Support for actors with daemon-style semantics was added. Actors can be configured to use the efficient JSR166y fork/join pool, resulting in significant performance improvements on 1.6 JVMs. Schedulers are now pluggable and easier to customize.There's also a design document of Haller: As far as I know, only Scala and Akka support remote actors.Akka is backed up by scalablesolutions, which offer commerical support and plug ins for akka. \nAkka seems like a heavyweight solution, which targets integration with existing frameworks (camel, AMQP, JTA, Comet, Spring, Redis) and additionally STMs and persistence.Akka compared to Scala doesn't support nested receives, but supports hotswapping the actors message loop and has both, thread based and event based actors and so called \"Event-based single-threaded\" ones.I realized that akka enforces exhaustive matches. So even if technically receive expects a partial function, the function must not be partial. This means you have to handle every message immediately."},
Scala

When I type  on the terminal to start the repl, it throws this errorWhen I hit  and type , it again throws thisI am using  and  givesEither update to a newer scala version (2.10.3+) or downgrade java to java 6/7. As you have seen in the output, 2.9.2 was here long before java 8 was introduced (), so they don't work well together. contains exact instructions on ubuntu's java downgrade.remove the scala 2.9.2 using terminal download the latest scala from Installation instruction are giving on this You might have to run it with JDK 7 or 6"},
Scala

My scala application will only run with Java 7 as it depends on libraries that only appeared in that version of the JDK.How do I enforce that in sbt, so that the correct error message is shown immediately to the user if she is using the wrong version of Java when starting sbt to run/compile the application?NOTE: There is  Java\u2122 source code to compile here. I  have Scala source code. The Scala code requires an  that's available from Java 7.Using  does not work if you have no Java sources.But you can set the target JVM for the Scala compiler in build.sbt or Build.scala:As a result it prints on a JDK 6:Note: Maybe it works only for the latest SBT/Scalac version.Being Scala code, you can put assertions in the build definition.  sbt defines the  as a common place for things like this, but you can use any setting, including a custom one.  For example,For anybody in the future, this is also a good way to do it. It halts execution immediately if it cannot find the right Java version:In SBT 0.13.6 there is a new  class and  trait. Tweaking the approach recommended by @MarkHarrah to use this one might do the following:In order to compile in Java 7, you should add the javac option to compile with source 1.7.You should add  to your SBT build config that can be found in the /project folder.Here's the reference from SBT:\nJust in-case if you use eclipse based scala-ide change settings in window --> pref -- scala compiler --> standard --> target --> jvm-1.7 "},
Scala

I have a scala Map and would like to test if a certain value exists in the map. There are several different options, depending on what you mean.If you mean by \"value\" , then you can use something likeIf you mean , then you canIf you wanted to just test , thenNote that although the tuple forms (e.g. ) end up being shorter, the slightly longer forms are more explicit about what you want to have happen.Do you want to know if the  exists on the map, or the key? If you want to check the key, use :you provide a test that one of the map values will pass, i.e.The ScalaDocs say of the method \"Tests whether a predicate holds for some of the elements of this immutable map.\", the catch is that it receives a tuple (key, value) instead of two parameters.What about this:Yields  if map contains  value.If you insist on using :Per answers above, note that exists() is significantly slower than contains() (I've benchmarked with a Map containing 5000 string keys, and the ratio was a consistent x100). I'm relatively new to scala but my guess is exists() is iterating over all keys (or key,value tupple) whereas contains uses Map's random access"},
Scala

I am doing a project in Scala, but am fairly new to the language and have a Java background.  I see that Scala doesn't have ArrayList, so I am wondering what Scala's equivalent of Java's ArrayList is called, and if there are any important differences between the Java and Scala versions.  I'm not looking for a specific behavior so much as an internal representation (data stored in an array, but the whole array isn't visible, only the part you use).I can think of 3 more specific questions to address yours:So here are the answers for these:Scala's equivalent of Java's  interface is the . A more general interface exists as well, which is the  -- the main difference being that a  may have operations processed serially or in parallel, depending on the implementation.Because Scala allows programmers to use  as a factory, they don't often bother with defining a particular implementation unless they care about it. When they do, they'll usually pick either Scala's  or . They are both immutable, and  has good indexed access performance. On the other hand,  does very well the operations it does well.That would be .Well, the good news is, you can just use  in Scala! In Java,  is often avoided because of its general incompatibility with generics. It is a co-variant collection, whereas generics is invariant, it is mutable -- which makes its co-variance a danger, it accepts primitives where generics don't, and it has a pretty limited set of methods.In Scala,  -- which is still the same  as in Java -- is invariant, which makes most problems go away. Scala accepts  (the equivalent of primitives) as types for its \"generics\", even though it will do auto-boxing. And through the \"enrich my library\" pattern,  of  methods are available to .So, if you want a more powerful , just use an .The default methods available to all collections all produce  collections. For example, if I do this:Then  will be a  collection, while  will still be the same as before this command. This is true no matter what  was: , , etc.Naturally, this has a cost -- after all, you  producing a new collection. Scala's immutable collections are much better at handling this cost because they are , but it depends on what operation is executed.No collection can do much about , but a  has excellent performance on generating a new collection by prepending an element or removing the head -- the basic operations of a stack, as a matter of fact.  has good performance on a bunch of operations, but it only pays if the collection isn't small. For collections of, say, up to a hundred elements, the overall cost might exceed the gains.So you can actually add or remove elements to an , and Scala will produce a   for you, but you'll pay the cost of a full copy when you do that.Scala mutable collections add a few other methods. In particular, the collections that can increase or decrease size -- without producing a new collection -- implement the  and  traits. They don't guarantee good performance on these operations, though, but they'll point you to the collections you want to check out.It's  from . You can find the scaladocs .Did you have a look at ?It's hard to say exactly what you should do because you haven't said what behavior of  you're interested in using. It's more useful to think in terms of which scala traits you want to take advantage of. Here's a good explanation: .That said, you probably want some sort of ."},
Scala

This is not about command-line compiler options. How do I programmatically obtain the Scala version inside code?Alternatively, where does the Eclipse Scala plugin v2 store the path to ?This will work without access to :There are three ways to get the Scala version -You can get the Scala version like this:I don't know the specifics of the plugin, though.We can also get installed Scala versionWelcome to Scala version 2.10.3 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_6\n0).\nType in expressions to have them evaluated.\nType :help for more information."},
Scala

I am trying to figure out how to make Eclipse recognize dependencies that are retrieved using SBT?  SBT download the correct dependencies and puts them in my ~/.ivy directory but eclipse doesn't see them.  Is there a way to do this?thanksThis is probably not the answer you are looking for and I admit it is not elegant but it currently works for me, meaning that I think it takes less time for me to periodically do the following instead of researching and finding a more elegant solution.I assume you are using the sbt-eclipse plugin (  ). When I add new dependencies to my project ( which is actually pretty rare ) I simply regenerate my eclipse project files from the plugin. The downside of this is that I have a multiple module project and after I refresh the projects in eclipse I need to re-add the inter-project dependencies in the eclipse build path editor. Like I mentioned it is pretty hacky but all in all I really don't loose that much time doing it. It's not pretty but it works.Best of luck,\nAndyIf you are using sbteclipse plugin it's achievable in a simple way. In sbt type: Then in eclipse, hit F5 on a project folder to refresh it. Or right-click and choose \"Refresh\". Just works.I use the  plugin for Eclipse, and I've had more luck with this approach. It's only , but works with sbt 0.11First, install the IvyDE plugin in Eclipse and restart.Run the sbt command  - this will create an XML ivy file of your dependencies.In Eclipse, under your Project/Properties - Java Build Path - Libraries, click \"Add Library\" and choose \"IvyDE Managed Dependencies\" then select the file target/scala-2.9.1/ivy-.xmlWhen you add a new dependency to build.sbt, run the sbt commands  and  again. Then right-click the Ivy library for your project in the Package Explorer - it will be called \"target/scala-2.9.1/ivy-.xml [compile,test]\", and click the second \"Refresh\" menu item (between \"Refresh\" and \"Reload Settings\" -  \"F5 Refresh\" ). In command prompt go to the project folder and typeThis should generate the appropriate  entries in eclipse project.Go back to eclipse, select the project and , this will reload the referenced libs.The following works for me:1) close project in Eclipse2) in my file explorer, browse to my Eclipse project, make sure hidden files are visible3) open .classpath in a simple text editor4) copy the bottom entry. For example, in my current project, it is 5) navigate to my .ivy folder, cache, then down to the library I have added via sbt6) right click on jar file, select properties, copy the path and jar file name and replace it in the entry I copied in step 47) save .classpath8) open my project on EclipseNew dependency is now available in Eclipse.All you need is execute from your project home:or enter  console and write:BTW: I don't know if from Jan '12 something has changed but now it seems much more simple."},
Scala

I really don't seem to be understanding Map and FlatMap. What I am failing to understand is how a for-comprehension is a sequence of nested calls to map and flatMap. The following example is from translates toThe mkMatcher method is defined as follows:And the pattern method is as follows:It will be great if someone could shed some light on the rationale behind using map and flatMap here.I'll try and recapThe  comprehension is a syntax shortcut to combine  and  in a way that's easy to read and reason about.Let's simplify things a bit and assume that every  that provides both aforementioned methods can be called a  and we'll use the symbol  to mean a  with an inner type .Some commonly seen monadsDefined in a generic monad e.g.As you can see, the  operation preserves the \"shape\" of the original , so the same happens for the  expression: a  remains a  with the content transformed by the operation in the On the other hand each binding line in the  is just a composition of successive , which must be \"flattened\" in order to maintain a single \"external shape\"Suppose for a moment that each internal binding was translated to a  call, but the right-hand was the same  function, you would end up with a  for each line in the comprehension.\nThe intent of the whole  syntax is to easily \"flatten\" the concatenation of successive monadic operations (i.e. operations that \"lift\" a value in a \"monadic shape\": ), with the addition of a final  operation that  performs a concluding transformationI hope this explains the logic behind the choice of translation, which is applied in a mechanical way, that is:   nested calls concluded by a single  call.\nMeant to show the expressiveness of the  syntaxCan you guess the type of ?As already said, the shape of the  is mantained through the comprehension, so we start with a  in , and must end with a .\nThe inner type instead changes and is determined by the  expression: which is  should be a The rationale is to chain monadic operations which provides as a benefit, proper \"fail fast\" error handling.It is actually pretty simple. The  method returns an  (which is a Monad).\nThe result of , the monadic operation, is either a  or a .Applying the  or  function to a  always returns a  - the function passed as a parameter to  and  is not evaluated.Hence in your example, if  returns a None, the flatMap applied to it will return a  (the second monadic operation  will not be executed) and the final will again return a .\nIn other words, if any of the operations in the for comprehension, returns a None, you have a fail fast behavior and the rest of the operations are not executed.This is the monadic style of error handling. The imperative style uses exceptions, which are basically jumps (to a catch clause)A final note: the  function is a typical way of \"translating\" an imperative style error handling (...) to a monadic style error handling using This can be traslated as:Run this for a better view of how its expandedresults are:This is similar to  - loop through each element in  and foreach element  it to each element in I'm not a scala mega mind so feel free to correct me, but this is how I explain the  saga to myself!To understand  and it's translation to  we must take small steps and understand the composing parts -  and .  But isn't  just  with  you ask thyself! if so why do so many developers find it so hard to get the grasp of it or of . Well, if you just look at scala's  and  signature you see they return the same return type  and they work on the same input argument  (at least the first part to the function they take) if that's so what makes a difference?scala map signature:But there is a big part missing when we look at this signature, and it's - where does this  comes from? our container is of type  so its important to look at this function in the context of the container - .  Our container could be a  of items of type  and our  function takes a function which transform each items of type  to type , then it returns a container of type  (or )Let's write map's signature taking into account the container:Note an  - it bundles  in the output container  you have no control over it.  Let's us stress it again:You see you did not specify how to  the item you just specified how to transform the internal items.  And as we have the same container  for both  and  this means  is the same container, meaning if you have  then you are going to have a  and more importantly  is doing it for you!Now that we have dealt with  let's move on to .Let's see its signature:You see the big difference from map to  in flatMap we are providing it with the function that does not just convert from  but also containerizes it into .So why do we so much care of the input function to map/flatMap does the containerization into  or the map itself does the containerization for us?You see in the context of  what's happening is multiple transformations on the item provided in the  so we are giving the next worker in our assembly line the ability to determine the packaging.  imagine we have an assembly line each worker does something to the product and only the last worker is packaging it in a container! welcome to  this is it's purpose, in  each worker when finished working on the item also packages it so you get containers over containers.Now let's looks into your for comprehension taking into account what we said above:What have we got here:First,  returns a function whose signature is , that's a regular java procedure which just run , as shown in the  function.\nThen, look at this lineThe  function is applied to the result of , which is , so the  in  is just the pattern you compiled. So, given a pattern , a new function is constructed, which takes a String , and check if  matches the pattern. Note, the  variable is bounded to the compiled pattern. Now, it's clear that how a function with signature  is constructed by .Next, let's checkout the  function, which is based on . To show how  works, we first look at this part:Since we got a function with signature  from , which is  in this context,  is equivalent to , which returns if the String s matches pattern . So how about , it's same as , the only difference is that, the first call of  uses , instead of ,  Why? Because  returns , you will get a nested result  if you use  for both call, that's not what you want ."},
Scala

Can Scala be used to script a Java application?I need to load a piece of Scala code from Java, set up an execution scope for it (data exposed by the host application), evaluate it and retrieve a result object from it. The Scala documentation shows how easy it is to call compiled Scala code from Java (because it gets turned into to regular JVM bytecode).But how can I evaluate a Scala expression on the fly (from Java or if that is easier, from within Scala) ? For many other languages, there is the javax.scripting interface. Scala does not seem to support it, and I could not find anything in the Java/Scala interoperability docs that does not rely on ahead-of-time compilation.Scala is not a scripting language.  It may  somewhat like a scripting language, and people may advocate it for that purpose, but it doesn't really fit well within the JSR 223 scripting framework (which is oriented toward dynamically typed languages).  To answer your original question, Scala does not have an  function just like Java does not have an .  Such a function wouldn't really make sense for either of these languages given their intrinsically static nature.My advice: rethink your code so that you don't need  (you rarely do, even in languages which have it, like Ruby).  Alternatively, maybe you don't want to be using Scala at all for this part of your application.  If you really need , try using JRuby.  JRuby, Scala and Java mesh very nicely together.  It's quite easy to have part of your system in Java, part in Scala and another part (the bit which requires ) in Ruby.it's now 2011, and you can do so with see Scala has added official support to JSR-223 in 2.11 ().So if you still need it after thinking about the considerations made in the currently accepted answer from Daniel Spiewak (about rethinking in a way it is not needed), this should be the official alternative.You can emulate \"eval\" by taking scala code, wrapping it in a class, compiling that class, using reflection to create a new instance, and then calling it. It's a little involved, and the scala compiler is very slow (on the order of 2 seconds) to initialize, but it works fine.There's a library for it here, called \"util-eval\": The code in question lives here: It works like this:I am not sure, if this is a good way, but I solved this problem with using  and  To have an eval in Scala you have to:You can always use scalac to compile a scala class and then load that class dynamically. But I guess that's not what you're after."},
Scala

I've seen questions about IDE's here --  and , but I've had mixed experiences with IDEs. Right now, I'm using the Eclipse IDE with the automatic workspace refresh option, and KDE 4's Kate as my text editor. Here are some of the problems I'd like to solve:I looked at Ant and Maven, though haven't employed either yet (I'll also need to spend time solving #3 and #4). I wanted to see if anyone has other suggestions before I spend time getting a suboptimal build system working. Thanks in advance! - I'm now using Maven, passing a project as a compiler plugin to it. It seems fast enough; I'm not sure what kind of jar caching Maven does. A current repository for Scala 2.8.0 is available []. The archetypes are very cool, and cross-platform support seems very good. However, about compile issues, I'm not sure if fsc is actually fixed, or my project is stable enough (e.g. class names aren't changing) -- running it manually doesn't bother me as much. If you'd like to see an example, feel free to browse the pom.xml files I'm using []. - from benchmarks I've seen, Daniel Spiewak is right that buildr's faster than Maven (and, if one is doing incremental changes, Maven's 10 second latency gets annoying), so if one can craft a compatible build file, then it's probably worth it...Points 2 and 4 are  difficult to manage with the current scalac.  The problem is that Scala's compiler is a little dumb about building files.  Basically, it will build whatever you feed it, regardless of whether or not that file really needs to be built.  Scala 2.8.0 will have some tremendous improvements in this respect, but until then...  Eclipse SDT actually has some very elaborate (and very hackish) code for doing change detection and dependency tracking.  On the whole, it does a decent job, but as you have seen, there are wrinkles.  Eclipse SDT 2.8.0 will rely on the aforementioned improvements to scalac itself.So, building only modified files is pretty much out of the question.  Aside from SDT, the only tool I know of which even tries this is SBT ().  It uses a compiler plugin to track files as they are compiled and query the dependency graph computed by the compiler itself.  In practice, this yields about a 50% improvement over the recompile-the-world approach.  Once again, this is a hack to get around deficiencies in pre-2.8.0 scalac.The good news is that reasonably fast compilation is still achievable even without worrying about change detection.  FSC uses the same technology (ooh, that sounded so \"Charlie Eppes\") that Eclipse SDT uses to implement fast incremental compilation.  In short, it's pretty snappy.Personally, I use .  Its configuration is significantly cleaner than either Maven's or SBT's and its startup time is orders of magnitude less (when running under MRI).  It integrates with FSC and attempts to do some basic change detection on its own (fairly primitive).  It also has auto-magical support for the major Scala test frameworks (ScalaTest, ScalaCheck and Specs) as well as support for joint compilation with Java sources and IDE meta generation for IntelliJ and Eclipse.  Oh, and it supports all of Maven's features (dependency resolution, etc) and then some.  I'm even working on an extension which would allow interactive shell support integrated with JavaRebel and supporting several shell providers (Scala, JIRB, Clojure REPL, etc).  It's not ready for the SVN yet, but I'll commit once it's ready (possibly in time for 1.3.5).As you can see, I'm very firmly of the opinion that Buildr is the best Scala build tool out there.  Its documentation is a little spotty where Scala is concerned, but that's because everything is so straightforward that it's hard to document without feeling verbose.  You can always check out one of  for examples.  Good luck!Have you looked at Intellij IDEA and its  ? Intellij has a loyal (fanatical?) following amongst Java developers, so you may find this is appropriate for your needs.Am also quite frustrated with the scala plugin on Eclipse and I can add a few more problems to the list: I'm glad to hear that Buildr sounds like a better alternative (on the build front anyhow), I'll give that a try - thanks!For the reasons of completeness, I have to say that there is also  -- the build tool that in use in Twitter (one of the early scala adopters)The main difference it that it is intended not only for scala (and written in python, by the way) and is modeled after .It's not so bloated as sbt, so for the freshmans it's much simplier, but I've never heard about Pants usage outside of twitter and foursquare.If you scared of SBT, maybe another no-so-popular build tool, , could be an  for you?I went down the same road, and here is where I am at:\n- After some initial investigation, I dropped Kate.  I love to use it for most things, but when it came to things like defining tab completions, I found it sorely lacking.  I would recommend that you look into gedit instead, which is much more robust for Scala development\n- With gedit as my editor, I use SBT and have found it to be a great build tool.  I can put it into a 'test' mode where when any code changes it recompiles the relevant files and runs my test suite.  This has been an extremely effective way to work.I have not taken a look at Buildr yet.  I would like to say that I will, but honestly with SBT at my disposal I don't really have a compelling need to look at another build tool.If you use Emacs, I think  is a pretty good IDE. I think at the time writing, Ensime is the only IDE that will give you fast and accurate autocompletion on both Scala and Java objects, including implicit conversions.There's code browsing support using Speedbar, code templates using the excellent Yasnippet, and code completion menu using Autocomplete. These are all very modern, actively maintained Emacs packages. There's also out of the box incremental building support for Maven and SBT. There's a lot more in there such as interactive debugging, refactoring, and the Scala interpreter in an inferior process. All the things you want in a modern IDE for Scala is already there in Ensime. Highly recommended for Emacsens.If you want to use Eclipse, but build the project using sbt, and still be able to debug, take a look at this post here:zikaprog.wordpress.com/2010/04/19/scala-eclipse-sbt-and-debugging/It also can be applied to builders other than sbt.The latest version of the Maven Scala plugin supports Zinc/Nailgun for faster start times and faster incremental builds.  See ."},
Scala

I saw a StackOverflow question regarding static analysis in Scala, but that  one was answered in 2009. As you know, the Scala tools are changing very rapidly. I was therefore wondering if someone familiar with the current state of static analysis tools in Scala could tell me if there's, say, a Findbugs equivalent for Scala. I found that Findbugs issues many unnecessary warnings for Scala, probably having to do with the way the \"object\" singleton compiles to bytecode, due to traits, etc. I heard that Scalastyle is not only a Scala version of Java's CheckStyle, that it also includes bits of Findbugs and PMD. But if it doesn't implement all of Findbugs and/or PMD, then are there other tools that supplement it? Or, is Scalastyle good not only for style checking, but is it good for improving code quality?Also, what about Scala's integration with, say, Sonar? Is the Scala Sonar plugin (which works with Scalastyle) reliable?Here is an updated answer as of August 2014 for some that are aimed or work well with Scala. Personally I think the JVM or Java ones end up with far too many false positives, or have inspections that are aimed mostly at Java specific classes. For example, since in Scala we don't tend to use the Java Collections, all the findbugs collection based inspections are not needed. Another example is the inspections for use of static fields which are irrelevant in Scala.Would the  be counted as an alternative? Also  and  command line parameters of scalac might help catching certain types of bugs. developed a easy to customize tool - scala-meta: take a lookand I think  has some support for scalaWhy don't you like to use a very powerful Scalac compiler? E.g. it has some useful options, e.g. ...etc.According to Codacy, following are the tools (updated till Oct 2015)Source: \n"},
Scala

I've searched for a half-hour, and still cannot figure it out.In  there are a number of features which will require explicit \"enabling\" in Scala 2.10 ().\nAmongst them there is , to which I just cannot find a reference anywhere. What exactly does this feature allow?It allows you to use operator syntax in postfix position. For examplerather thanIn this harmless example it is not a problem, but it can lead to ambiguities. This will not compile:And the error message is not very helpful:It tries to call the  method on the result of the  call, which is of type . This is likely not what the programmer intended. To get the correct result, you need to insert a semicolon after the first line. Dropping dot from methods without parameters is !OK to drop dot in methods that take one parameter of  like map, filter, count and be safe!\nAlso,  methods like zip. Postfix operator - is actually a method call with no parameters (a!==a.!) and without brackets. (considered not safe and deprecated) Postfix operator is method, that should end the line, or else it will be treated as infix. Infix operator is method with one parameter, that can be called without dot and parentheses. Only for  methods Method with one or more parameters will chain without dot if you call it with parameters. def a(), def a(x), def a(x,y)\nBut you should do this only for methods that use  as parameter!Sample warnings:It refers to the ability to call a nullary (with no arg list or empty arg list) method as a postfix operator:By example:See: "},
Scala

According to :and attempts to store custom type in a  lead to following error like:or:Are there any existing workarounds?Note this question exists only as an entry point for a Community Wiki answer. Feel free to update / improve both question and answer.Unfortunately, virtually nothing has been added to help with this. Searching for  in  or  finds things mostly to do with primitive types (and some tweaking of case classes). So, first thing to say: . With that out of the way, what follows is some tricks which do as good a job as we can ever hope to, given what we currently have at our disposal. As an upfront disclaimer: this won't work perfectly and I'll do my best to make all limitations clear and upfront.When you want to make a dataset, Spark \"requires an encoder (to convert a JVM object of type T to and from the internal Spark SQL representation) that is generally created automatically through implicits from a , or can be created explicitly by calling static methods on \" (taken from the ). An encoder will take the form  where  is the type you are encoding. The first suggestion is to add  (which gives you  implicit encoders) and the second suggestion is to explicitly pass in the implicit encoder using  set of encoder related functions.There is no encoder available for regular classes, sowill give you the following implicit related compile time error:However, if you wrap whatever type you just used to get the above error in some class that extends , the error confusingly gets delayed to runtime, soCompiles just fine, but fails at runtime withThe reason for this is that the encoders Spark creates with the implicits are actually only made at runtime (via scala relfection). In this case, all Spark checks at compile time is that the outermost class extends  (which all case classes do), and only realizes at runtime that it still doesn't know what to do with  (the same problem occurs if I tried to make a  - Spark waits until runtime to barf on ). These are central problems that are in dire need of being fixed:The solution everyone suggests is to use the  encoder.This gets pretty tedious fast though. Especially if your code is manipulating all sorts of datasets, joining, grouping etc. You end up racking up a bunch of extra implicits. So, why not just make an implicit that does this all automatically?And now, it seems like I can do almost anything I want (the example below won't work in the  where  is automatically imported)Or almost. The problem is that using  leads to Spark just storing every row in the dataset as a flat binary object. For , ,  that is enough, but for operations like , Spark really needs these to be separated into columns. Inspecting the schema for  or , you see there is just one binary column:So, using the magic of implicits in Scala (more in ), I can make myself a series of implicits that will do as good a job as possible, at least for tuples, and will work well with existing implicits:Then, armed with these implicits, I can make my example above work, albeit with some column renamingI haven't yet figured out how to get the expected tuple names (, , ...) by default without renaming them - if someone else wants to play around with this,  is where the name  gets introduced and  is where the tuple names are usually added. However, the key point is that that I now have a nice structured schema:So, in summary, this workaround:This one is less pleasant and has no good solution. However, now that we have the tuple solution above, I have a hunch the implicit conversion solution from another answer will be a bit less painful too since you can convert your more complex classes to tuples. Then, after creating the dataset, you'd probably rename the columns using the dataframe approach. If all goes well, this is  an improvement since I can now perform joins on the fields of my classes. If I had just used one flat binary  serializer that wouldn't have been possible.Here is an example that does a bit of everything: I have a class  which has fields of types , , and . The first takes care of itself. The second, although I could serialize using  would be more useful if stored as a  (since s are usually something I'll want to join against). The third really just belongs in a binary column.Now, I can create a dataset with a nice schema using this machinery:And the schema shows me I columns with the right names and with the first two both things I can join against.Related questions:In case of Java Bean class, this can be usefulNow you can simply read the dataFrame as custom DataFrame This will create a custom class encoder and not a binary one. Encoders work more or less the same in . And  is still the recommended  choice.You can look at following example with spark-shellTill now] there were no  in present scope so our persons were not encoded as  values. But that will change once we provide some  encoders using  serialization.I have been quite successful converting  to  using  and  as long as  is a simple .I'd stick to classes with primitive types and String as fields before the DataBricks folks beef up their Encoders.  Sure it's a little extra work, but I imagine it'll help a lot on performance working with a flat schema.And voila! Lather, rinse, repeat."},
Scala

I was thinking of making a new, light-weight database population framework. I absolutely hate dbunit. Before I do, I want to know if someone already did it.Things i dislike about dbunit:1) The simplest format to write and get started is deprecated. They want you to use formats that are bloated. Some even require xml schemas. Yeah, whatever.2) They populate rows not in the order you write them, but in the order tables are defined in the xml file. This is really bad because you can't order your data in such a way that foreign key constraints won't cause problems. This just forces you to go through the hassle of turning them off altogether. This also wastes time and bloats up your junit base classes to include code to disable the foreign key constraints. You will probably have to test for the database type (hsqldb, etc.) and disable them in database-specific ways. This is way bad.It could be better if dbunit helped in disabling foreign key constraints as part of their framework automatically, but they don't do this. They do keep track of dialects... so why not use them for this? Ultimately, all of this does is force the programmer to waste time and not get up and testing quickly.3) XML is a pain to write. I don't need to say more about this. They also offer so many ways to do it, that I think it just complicates matters. Just offer one really solid way and be done with it.4) When your data gets large, keeping track of the ids and their consistent/correct relationships is a royal pain. Also, if you don't work on a project for a month, how are you to remember that user_id 1 was an admin, user_id 2 was a business user, user_id 3 was an engineer and user_id 4 was something else? Going back to check this is wasting more time. There should be a meaningful way to retrieve it other than an arbitrary number.5) It's slow. I've found that unless hsqldb is used, it is painfully slow. It doesn't have to be. There are also numerous ways to mess up its configuration as it is not easy to do \"out of the box\". There is a hump that you must go through to get it working right. All this does is encourage people to not use it, or be pissed of when they do start to use it.6) Some values tend to repeat a lot, likes dates. It'd be nice to specify defaults, or even have the framework put defaults in automatically, even without you telling it to put defaults in there. That way you can create objects just with the values you want, and leave the rest off. This sure beats specifying every nook and cranny of a column if it's not required.7) Probably the most annoying thing is that the first entry must include ALL the values - even null placeholders - or future rows won't pick the columns that you actually specified.DBunit doesn't have a sensible default for translating [NULL] to a real null value either. You have to manually add it. Tell me, who hasn't done this with dbunit? Everyone has. It shouldn't be like this!What this means is that if you have a polymorphic object, you must declare all the foreign keys to the joining tables of each subclass in the first row, even though they are null. If you do a table for all subclasses pattern, you still have to specify all the fields on the first row. This is just awful.Anything out there to satisfy me, or should I become the next framework developer of a much better database testing framework?I'm not aware of any real alternative to DbUnit and none of the tools mentioned by  are in my eyes:That being said, I've personally used DbUnit successfully several times, on small and huge projects, and I find it pretty usable, especially when using  and its DbUnit module. This doesn't mean it's perfect and can't be improved but with decent tooling (either custom made or something like Unitils), using it has been a decent experience.So let me answer some of your points:DbUnit supports flat or structured XML, XLS, CSV. What revolutionary format would you like to use? By the way, a DTD or schema is not mandatory when using XML. But it gives you nice things like validation and auto-completion, how is that bad? And Unitils can generate it easily for you, see .They are waiting for your patch. Meanwhile, Unitils provides support to handle constraints transparently, see . I guess pain is subjective but I don't find it painful, especially when using a schema and autocompletion. What is the silver bullet you're suggesting?Keep them small, that's a know . You're going against a known best practice and then complain... Yes, task switching is counter productive. But since you're working with low level data, you have to know how they are represented, there is no magic solution unless you use a higher level API of course (but that's not the purpose of DbUnit).That's inherent to databases and JDBC, not DbUnit. Use a fast database like H2 if you want things to be as fast as possible (if you have a better agnostic way to do things, I'd be glad to learn about it).Not when using Unitils as mentioned in presentations like  or . If you think you can make things better, maybe contribute to existing solutions. If that's not possible and if you think you can create the killer database testing framework, what can I say, do it. But don't forget, ranting is easy, coming up with solutions using your own solutions is less so.As a DbUnit developer I'm grateful for criticism and I must partially agree with you. We are currently starting the design of the next DbUnit major release and I wish to invite you to participate both in the discussion and development.I'm not going to answer your points as your question is not really related to DbUnit, but to DbUnit alternatives. Anyway, I just want to highlight your point 7 is completely false: you do not need to specify all the columns on first row any more, the feature is called column sensing. I'm not going to tell you why it's not enabled by default as you are surely smart enough to understand it by yourself.I'll give scaladbtest a deep examination in the hope we can integrate their ideas.Faced with similar concerns using DBUnit I have found this :  which may address concerns. Such as instead of representing test data in separate files all DB content is contained within the java class itself.Here's a short list of a few tools in this vein (besides DBunit) that I particularly like, or find interesting. At the very least they may offer some inspiration:Note that none of these are really competitors to DBunit in terms of scope or feature sets. However, there are some interesting ideas there that might be worth taking a look at. Good luck!I use DBUnit, with a few wrappers to smooth over the rough edges. A nice tool that can either complement or overlap the functionality is . It can extract subsets of data from a reference database, and store this as either DBUnit compatible XML files, or as \"topologically sorted DML files\", which respect the foreign key constraints.You're making excellent point.   I've been working for a lot of web portals over the last years, mostly with PHP, but also some Java now and then.\nAnd like you I don't get that after all these years framework and unittesting developers don't seem to realize how much storage handling has changed in the last decade.\nIt's not enough to just send create/insert/truncate statements to some database!\nIf you're operating at large scale you end up employing all sorts of storage backends, organized in layers to push hot content out fast. Plus on the Database front there's the issue of data partitioning. If you don't have a proper foreign key abstraction provided you will certainly go nuts when your storage setup changes. And while we're at it: fixture ordering by foreign key precedence has many pitfalls and I have yet to see a real solution for that with .  Anyway, the point is having just a basic database storage in place for unittesting is not enough for complex storage setups, since they often fail to reproduce problems in the live environment and are a pain in the ass to maintain.  Without wanting to sound like a fanboy: one place where things are okay is .\nThat has a persistent model concept that people seem to have actually put some thought into. If you're dealing in ,  is the place to go. It is limited via the default inclusion of , with is also quite DB-centric, but it has clean interfaces and great extensibility and copied the rails fixture system completely. Professionally I need to stick to homebrew solutions for now, but they work okay.If you use the Spring Framework (or don\u2019t mind using it at least for testing), then  is currently the best (maintained) alternative to plain DBUnit that I know and use. Quoting their website:Spring DBUnit appears to be the \u2018somewhat official\u2019 Spring solution for DB unit testing (with DBUnit); at least the author/maintainer of the library, Phil Webb, is working at SpringSource/Pivotal.We are writing  as a wrapper around DbUnit to address some of the mentioned concerns. It allows populating a DB just within your unit test rather than relying on editing XML files. I too had similar issues with DBUnit. Especially for using it to populate local development data and exporting data from a real database. I ran into several cases where it would export a dataset that it couldn't then import.This inspired me to write a new library for it: This uses a groovy DSL to define the datasets which makes for a very compact representation of the data and makes it possible to do cool things like generate random data since it's just groovy code.An alternative using  configuration and  testing can be found I just released a groovy DSL based framework called pedal-loader available via . Documentation .It allows you to work with JPA entity level abstraction directly. Since it is a groovy script, you can use all of the groovy constructs. To insert rows into a table backed by a JPA entity called Student, with fields (not database columns, but mapped fields) called id, name and grade, you would do something like this:Grade is an enum in the Student class that is mapped to the database column (perhaps using JPA 2.1 @Convert annotation). allStudents is a list that will hold the rows and rowOfInterest is a reference to a particular row. These properties (allStudents and rowOfInterest) become available to your unit test.The situation of DBUnit is indeed sometimes frustrating. Some of the problem are solved from  with , specially if you combine it with the , which is in a very early stage. You can see it in action at .Disclaimer: All referenced github-resources are maintained by me.I just released a library called JDBDT (Java Database Delta Testing) that\nyou may use for database setup and validation in software tests.Have a look at  Best,\nEduardo"},
Scala

I'm having problems with a maven dependency which is in my local respository.SBT can't find it. Already set log level to debug, but not getting anything new.The files are in the repository. I copy paste paths from the console to file explorer and they are there.The output: like described in \"sbt can search your local Maven repository if you add it as a repository:\"That made sbt look in the local repository. Before it didn't.So the scala file looks like this:(I hardcoded Path.userHome to exclude possible error reason. As expected it didn't change anything).You need three slashes after the  specifier. This is because between the second and third slash, you have an optional hostname.  has a good explanation of  URL'sYou're having a problem because the typical pattern of  assumes a Unix filesystem, where the path begins with a , contains no , and usually contains no spaces.To have a non-hardcoded path that works on both Windows and Linux/Unix, use: Just add this line in the build.scala or build.sbt fileTo get this to work for newer versions of sbt, add the following to build.sbt:Watch out when you have a project defined, you'll need to include the resolver in the settings. Global resolver will not be identified.Example:"},
Scala

Are there any sane analogues to LINQ (.NET) exists for Scala? It depends on what exactly you mean by \"LINQ\". LINQ is many things.The most obvious answer would be: just use the .NET port of Scala. It gives you full native access to everything in .NET, which obviously includes LINQ.Unfortunately, the .NET port of Scala was dropped a couple of years ago. Fortunately, it was picked up again a couple of months ago, with official funding directly from Microsoft no less. You can expect a release sometime in the 2011/2012 timeframe.Anyway, what is LINQ?A couple of features where added to .NET and specifically C# and VB.NET  LINQ. They are not technically part of LINQ, but are necessary prerequisites: type inference, anonymous (structural) types, lambda expressions, function types ( and ) and expression trees. All of these have been in Scala for a long time, most have been there forever.Also not directly part of LINQ, but in C#, LINQ query expressions can be used to generate XML, to emulate VB.NET's XML literals. Scala has XML literals, like VB.NET.More specifically, LINQ isIn Scala, like in pretty much any other functional language (and in fact also pretty much any other object-oriented language, too), the query operators are simply part of the standard collections API. In .NET, they have a little bit weird names, whereas in Scala, they have the same standard names they have in other languages:  is ,  is  (or ),  is ,  is  or ,  is  or  or , and there are ,  and  and so on. So, that takes care of both the specification and the LINQ-to-Objects implementation. Scala's XML libraries also implement the collections APIs, which takes care of LINQ-to-XML.SQL APIs are not built into Scala, but there are third-party APIs which implement the collection API.Scala also has specialized syntax for those APIs, but unlike Haskell, which tries to make them look like imperative C blocks and C#, which tries to make them look like SQL queries, Scala tries to make them look like  loops. They are called  and are the equivalent to C#'s query comprehensions and Haskell's monad comprehensions. (They also replace C#'s  and generators ()).But if you  want to know whether or not there are analogues for LINQ in Scala, you will first have to specificy what exactly you mean by \"LINQ\". (And of course, if you want to know whether they are \"sane\", you will have to define that, too.)All LINQ  extensions are available in Scala. For example:Linq:scala:There are many situations in Scala where you can use monadic constructs as a sort of query language.For example, to query XML (in this case, extracting URLs from links in some XHTML):For an analogue of LINQ to SQL, the closest thing is probably . To lift an example right out of the docs: is a modern database query and access library for Scala. \n()"},
Scala

This might be the least important Scala question ever, but it's bothering me.  How would I generate a list of n random number.  What I have so far:Which works, but doesn't look very Scalarific to me.  I'm open to suggestions.Not because it's relevant so much as it's amusing and obvious in retrospect, the following looks like it works:But the index of each entry in the returned list is also the upper bound of that last.  The first number must be less than 1, the second less than 2, and so on.  I ran it three or four times and noticed \"Hmmm, the result always starts with 0...\"You can either use  or:Note that you don't need to create a new  object, you can use the default companion object Random, as stated above.How about:regarding your EDIT, can take an  argument as an upper bound for the random number, so  is the same as , rather than a more useful compilation error. does what you intended. But it's better to use  since that more accurately represents what you're doing."},
Scala

How can you write to multiple outputs dependent on the key using Spark in a single Job. I could of course use  for all the possible keys, but that is a horrible hack, which will fire up many jobs Related: E.g.would ensure  isand  would beI know that the answer to this question will involve using MultipleOutputFormat in Hadoop.UPDATE: Please do not place any limitations on the resulting output, e.g. supply a solution where the number of files is fixed, or where the number of keys must be known a priori, or where the compression type is limited.UPDATES: In Scalding this is now super easy thanks to  I want an answer just like that!I would do it like this which is scalableJust saw similar answer above, but actually we don't need customized partitions. The MultipleTextOutputFormat will create file for each key. It is ok that multiple  record with same keys fall into the same partition. new HashPartitioner(num), where the num is the partition number you want. In case you have a big number of different keys, you can set number to big. In this case, each partition will not open too many hdfs file handlers.If you use Spark 1.4+, this has become much, much easier thanks to the . (DataFrames were introduced in Spark 1.3, but , which we need, was .)If you're starting out with an RDD, you'll first need to convert it to a DataFrame:In Python, this same code is:Once you have a DataFrame, writing to multiple outputs based on a particular key is simple. What's more -- and this is the beauty of the DataFrame API -- the code is pretty much the same across Python, Scala, Java and R:And you can easily use other output formats if you want:In each of these examples, Spark will create a subdirectory for each of the keys that we've partitioned the DataFrame on:If you potentially have many values for a given key, I think the scalable solution is to write out one file per key per partition. Unfortunately there is no built-in support for this in Spark, but we can whip something up.(Replace  with your choice of distributed filesystem operation.)This makes a single pass over the RDD and performs no shuffle. It gives you one directory per key, with a number of files inside each.I have a similar need and found an way. But it has one drawback (which is not a problem for my case): you need to re-partition you data with one partition per output file.To partition in this way it generally requires to know beforehand how many files the job will output and find a function that will map each key to each partition.First let's create our MultipleTextOutputFormat-based class:With this class Spark will get a key from a partition (the first/last, I guess) and name the file with this key, so it's not good to mix multiple keys on the same partition.For your example, you will require a custom partitioner. This will do the job:Now let's put everything together:This will generate 3 files under prefix (named 1, 2 and 7), processing everything in one pass.As you can see, you need some knowledge about your keys to be able to use this solution.For me it was easier because I needed one output file for each key hash and the number of files was under my control, so I could use the stock HashPartitioner to do the trick.I was in need of the same thing in Java. Posting my translation of  to Spark Java API users:I had a similar use case where I split the input file on Hadoop HDFS into multiple files based on a key (1 file per key). Here is my scala code for sparkI have grouped the records based on key. The values for each key is written to separate file.saveAsText() and saveAsHadoop(...) are implemented based on the RDD data, specifically by the method:    which takes the data from the PairRdd where it's executed.\nI see two possible options: If your data is relatively small in size, you could save some implementation time by grouping over the RDD, creating a new RDD from each collection and using that RDD to write the data. Something like this:Note that it will not work for large datasets b/c the materialization of the iterator at  might not fit in memory.The other option I see, and actually the one I'd recommend in this case is: roll your own, by directly calling the hadoop/hdfs api.Here's a discussion I started while researching this question:\ngood news for python user in the case you have multi columns and you want to save all the other columns not partitioned in csv format which will failed if you use \"text\" method as Nick Chammas' suggestion .error message is \"AnalysisException: u'Text data source supports only a single column, and you have 2 columns.;'\"In spark 2.0.0 (my test enviroment is hdp's spark 2.0.0) package \"com.databricks.spark.csv\" is now integrated , and it allow us save text file partitioned by only one column, see the example blow:In my spark 1.6.1 enviroment ,the code didn't throw any error,however ther is only one file generated. it's not partitioned by two folders.Hope this can help ."},
Scala

I want to be able to use  and , the problem is that the compiler is triggering an error on the file which contains the play routes for my application:same goes for other routes.Is it possible maybe to tell scalac to ignore a file?Scala version is .A horrible \"solution\" could be to remove those unused imports after the routes are generated but before the compile task runs. Here's a sketch:You'll then want to sort out the task dependencies:You'll also likely need to set  to a conservative list before enabling . Something like this, depending on what types are used in your views:I also had to knock unused  imports out of Twirl templates (YMMV):If you do that, make sure the task dependencies are set up appropriately.This works for me. Scala 2.11.8, Play 2.5.10, both  and  enabled. It's hideous, but it works."},
Scala

I have a suite of scalatest tests that test different endpoints of a RESTful API.\nI really want them separated into different files for best organization.My problem is how to start something (an HTTP server in my case, but it doesn't matter what it is) before all the tests and shut it down after all the tests are done.I know about BeforeAndAfterAll, but that only accomplishes before/after inside one test file.  I need something like that, but for all tests, for example:-- start http server before tests\n-- run all test suites\n-- shut down http serverThe intended way to do this is to use nested suites. Suite has a nestedSuites method that returns an IndexedSeq[Suite] (in 2.0, in 1.9.1 it was a List[Suite]). Suite also has a runNestedSuites method that is responsible for executing any nested suites. By default runNestedSuites calls nestedSuites, and on each returned Suite either invokes run directly, or if a Distributor is passed, puts the nested suites in the distributor so that they can be run in parallel.So what you really probably want to do is make Foo and Bar into classes, and return instances of them from the nestedSuites method of EndpointTests. There's a class that makes that easy called Suites. Here's an example of its use:One potential problem, though, is that if you are using discovery to find Suites to run, all three of EndpointTests, Foo, and Bar will be discovered. In ScalaTest 2.0 you can annotate Foo and Bar with @DoNotDiscover, and ScalaTest's Runner will not discover them. But sbt still will. We are currently enhancing sbt so that it passes over otherwise discoverable Suites that are annotated with DoNotDiscover, but this will be in sbt 0.13, which isn't out yet. In the meantime you can get sbt to ignore them by adding an unused constructor parameter to Foo and Bar.Alternatively you can just use an object.When you access the object it will be initialised, starting the server.\nJust create a common trait in the body of which you access the object.\nThen mixin that trait into all your tests. Done.If your server runs in daemon mode (e.g. a Play! application in test mode) it will be automatically shut down after all tests are run.Ok, found a way.  It seems (unless someone here can correct me) that Scalatest does not have the facility of a \"master\" suite. But... you can kinda build one.You can compose a suite from traits. So using my endpoint example:Ok, but what about the tests?  Notice the with  with . I'm bringing the dependent tests in as traits.\nSee here:"},
Scala

I'm following the Scala course on Coursera.\nI've started to read the Scala book of Odersky as well.What I often hear is that it's not a good idea to throw exceptions in functional languages, because it breaks the control flow and we usually return an Either with the Failure or Success.\nIt seems also that Scala 2.10 will provide the Try which goes in that direction.But in the book and the course, Martin Odersky doesn't seem to say (at least for now) that exceptions are bad, and he uses them a lot.\nI also noticed the methods assert / require...Finally I'm a bit confused because I'd like to follow the best practices but they are not clear and the language seems to go in both directions...Can someone explain me what i should use in which case?The basic guideline is to use exceptions for something really exceptional**.  For an \"ordinary\" failure, it's far better to use  or .  If you are interfacing with Java where exceptions are thrown when someone sneezes the wrong way, you can use  to keep yourself safe.Let's take some examples.Suppose you have a method that fetches something from a map.  What could go wrong?  Well, something dramatic and dangerous like a * stack overflow, or something expected like the element isn't found.  You'd let the  stack overflow throw an exception, but if you merely don't find an element, why not return an  instead of the value or an exception (or )?Now suppose you're writing a program where the user is supposed to enter a filename.  Now, if you're not just going to instantly bail on the program when something goes wrong, an  is the way to go:Now suppose you want to parse an string with space-delimited numbers.So you have three ways (at least) to deal with different types of failure:  for it worked / didn't, in cases where not working is expected behavior, not a shocking and alarming failure;  for when things can work or not (or, really, any case where you have two mutually exclusive options) and you want to save some information about what went wrong; and  when you don't want the whole headache of exception handling yourself, but still need to interface with code that is exception-happy.Incidentally, exceptions make for good examples--so you'll find them more often in a textbook or learning material than elsewhere, I think: textbook examples are very often incomplete, which means that serious problems that normally would be prevented by careful design ought instead be flagged by throwing an exception.***So this is one of those places where Scala specifically trades off functional purity for ease-of-transition-from/interoperability-with legacy languages and environments, specifically Java.  Functional purity is broken by exceptions, as they break referential integrity and make it impossible to reason equationally.  (Of course, non-terminating recursions do the same, but few languages are willing to enforce the restrictions that would make those impossible.)  To keep functional purity, you use Option/Maybe/Either/Try/Validation, all of which encode success or failure as a referentially-transparent type, and use the various higher-order functions they provide or the underlying languages special monad syntax to make things clearer.  Or, in Scala, you can simply decide to ditch functional purity, knowing that it might make things easier in the short term but more difficult in the long.  This is similar to using \"null\" in Scala, or mutable collections, or local \"var\"s.  Mildly shameful, and don't do  to much of it, but everyone's under deadline.   "},
Scala

True ... it has been discussed quite a lot.However there is a lot of ambiguity and some of the answers provided ... including duplicating jar references in the jars/executor/driver configuration or options.Following ambiguity, unclear, and/or omitted details should be clarified for each option:I am aware where I can find the , and specifically about , the  available, and also the . However that left for me still quite some holes, although it answered partially too.I hope that it is not all that complex, and that someone can give me a clear and concise answer.If I were to guess from documentation, it seems that , and the   and  methods are the ones that will automatically distribute files, while the other options merely modify the ClassPath.Would it be safe to assume that for simplicity, I can add additional application jar files using the 3 main options at the same time:Found a nice article on . However nothing new learned. The poster does make a good remark on the difference between Local driver (yarn-client) and Remote Driver (yarn-cluster). Definitely important to keep in mind.ClassPath is affected depending on what you provide. There are a couple of ways to set something on the classpath:If you want a certain JAR to be effected on both the Master and the Worker, you have to specify these separately in BOTH flags.:This depends on the mode which you're running your job under:In , the Spark documentation does a good job of explaining the accepted prefixes for files:As noted, JARs are copied to the  for each Worker node. Where exactly is that? It is  under , you'll see them like this:And when you look inside, you'll see all the JARs you deployed along:The most important thing to understand is . If you pass any property via code, it will take precedence over any option you specify via . This is mentioned in the Spark documentation:So make sure you set those values in the proper places, so you won't be surprised when one takes priority over the other.Lets analyze each option in question:You can safely assume this only for Client mode, not Cluster mode. As I've previously said. Also, the example you gave has some redundant arguments. For example, passing JARs to  is useless, you need to pass them to  if you want them to be on your classpath. Ultimately, what you want to do when you deploy external JARs on both the driver and the worker is:Another approach in  is to use  during spark-submit which changes the priority of dependency load, and thus the behavior of the spark-job, by giving priority to the jars the user is adding to the class-path with the  option."},
Scala

Scala seems to have a .NET implementation too. I was wondering if it's a complete implementation with no loose ends or just a showcase thing.It's important, because the app we are about to develop should have Windows GUI besides the main implementation on web. Having a language where the core code can be ported between two implementations looks like a deal maker.Anyone worked on the .NET implementation of Scala? Any feedback?I have heard new funding has been acquired for the .NET side, but at the moment it is a great and increasing distance from \"production ready\" or even \"usable\".  There hasn't been a check-in which meaningfully touched the .NET side in a long time. A recent message to one of the scala lists.From: Lukas RytzOn Fri, Jan 15, 2010 at 03:18, Naftoli Gugenheim wrote:We're working on bootstrapping the compiler and we're fixing MSIL-Backend-Bugs along the way. EPFL will provide a compiler running on .NET (which uses IKVM.OpenJDK.Core.dll, at least in a first version)Right now, we have a cross-compiler running on the JVM, and a reduced version of scala-library.jar which runs on .NET.For some parts we will rely on the community (e.g. porting more of scala-library.jar to .NET).LukasMartin Odersky says in this  (January 2011): He starts talking about .NET at the 15 minute mark.The  claims:The  has this entry:The  talks about version 1.4, which is rather old by now. On the other hand, it looks like documentation was written as recently as 2008, including the  page which sounds pretty important.Without having any experience of it myself, it sounds like support is limping along, but that the .NET port isn't really a first-class citizen. The fact that there's no \"buzz\" around Scala on .NET (compared with the Java version) isn't encouraging either. It doesn't sound like something I'd want to use for commercial software at the moment. Of course, it's possible that it's fine, and just not well marketed. If you're really keen on the idea, I'd ask on a .Why not either use the  for a Java/Scala-based Windows client, or use .NET for the web app?In an interview on scala-lang.org on 18th July 2011:Link: \nLink: At the moment -- no, not really, which is a great pity, since it's quite a fun language.\"Hello world\" type programs, fine -- even fancy tricks like writing a simple stack where a small piece of Python (the same code under Jython or IronPython) drives the same piece of Scala.Anything moderately taxing -- the scalac-net compilation can and will throw, even if the code doesn't use anything outside the scala namespace, and builds and passes a fairly exhaustive set of unit tests on the JVM.  It can balk at building against even fairly simple assemblies (even if built using .net 1.0, to match the low spec of the mscorlib included in the scala-msil bundle).My test-sets for \"moderately taxing\" have included the following implementations intended to compensate for current lacks on .net As of Scala Days 2010 in April, Miguel Garcia was working on Scala.NET.  I believe he's working on a visual studio plugin and I'm not sure how far along things are, however you can find evidence of his work here:\n\nMiguel is now doing his postdoc at EPFL: Paul (extempore)'s answer probably has more up-to-date information, but if I were curious I might ask Miguel directly.Looking in the SVN repo, there's definitely some activity going on in the .net space.  In  there was a  directory, but that's gone in  and .  Instead there is a  directory which has had some non-trivial things going on as recently as .All the documentation available seems to be way out of date, but maybe it's worth asking one of the main contributors what the current status is.  Note that extempore (who as already answered this over a year ago) seems to be one of them."},
Scala

In Scala there is a Stream class that is very much like an iterator.  The topic  offers some insights into the similarities and differences between the two.Seeing how to use a stream is pretty simple but I don't have very many  use-cases where I would use a stream instead of other artifacts.  The ideas I have right now:So have I missed any big uses?  Or is it a developer preference for the most part?ThanksThe main difference between a  and an  is that the latter is mutable and \"one-shot\", so to speak, while the former is not.  has a better memory footprint than , but the fact that it  mutable can be inconvenient.Take this classic prime number generator, for instance:It can be easily be written with an  as well, but an  won't  the primes computed so far.So, one important aspect of a  is that you can pass it to other functions without having it duplicated first, or having to generate it again and again.As for expensive computations/infinite lists, these things can be done with  as well. Infinite lists are actually quite useful -- you just don't know it because you didn't have it, so you have seen algorithms that are more complex than strictly necessary just to deal with enforced finite sizes.In addition to Daniel's answer, keep in mind that  is useful for short-circuiting evaluations.  For example, suppose I have a huge set of functions that take  and return , and I want to keep executing them until one of them works:Well, I certainly don't want to execute the  list, and there isn't any handy method on  that says, \"treat these as functions and execute them until one of them returns something other than \".  What to do?  Perhaps this:This takes a list and treats it as a  (which doesn't actually evaluate anything), then defines a new  that is a result of applying the functions (but that doesn't evaluate anything either yet), then searches for the first one which is defined--and here, magically, it looks back and realizes it has to apply the map, and get the right data from the original list--and then unwraps it from  to  using .Here's an example:But does it work?  If we put a  into our functions so we can tell if they're called, we get(This is with Scala 2.8; 2.7's implementation will sometimes overshoot by one, unfortunately.  And note that you  accumulate a long list of  as your failures accrue, but presumably this is inexpensive compared to your true computation here.)I could imagine, that if you poll some device in real time, a Stream is more convenient. Think of an GPS tracker, which returns the actual position if you ask it. You can't precompute the location where you will be in 5 minutes. You might use it for a few minutes only to actualize a path in OpenStreetMap or you might use it for an expedition over six months in a desert or the rain forest. Or a digital thermometer or other kinds of sensors which repeatedly return new data, as long as the hardware is alive and turned on - a log file filter could be another example. is to  as  is to . Favouring immutability prevents a class of bugs, occasionally at the cost of performance.scalac itself isn't immune to these problems: As Daniel points out, favouring laziness over strictness can simplify algorithms and make it easier to compose them."},
Scala

I've a SBT multi-project where some projects have dependencies to each other. Like this:Now I have some test-code in the 'core' project in the test-folder. There are also stuff like mocks and test-utilities. Now I would like to use those test utilities in the tests of the extensions. For production code this works, since I've declared a dependency. However it seems that dependency doesn't hold for the tests. When I run the tests I get compilation error for missing classes. Those classes are from the test-code in the core-project.How can I tell sbt that the dependency also should include the test-code for the test-scope? So that I can reuse my mocks in the test-code of the 'exension'-project?Like so:This is discussed in the section \"Per-configuration classpath dependencies\" in then  guide.You can also do this with a  after the initial project declaration."},
Scala

I have two RDD's that I want to join and they look like this:It happens to be the case that the key values of  are unique and also that the tuple-key values of  are unique.  I'd like to join the two data sets so that I get the following rdd:What's the most efficient way to achieve this?  Here are a few ideas I've thought of.  Option 1:Option 2:Option 1 will collect all of the data to master, right?  So that doesn't seem like a good option if rdd1 is large (it's relatively large in my case, although an order of magnitude smaller than rdd2).  Option 2 does an ugly distinct and cartesian product, which also seems very inefficient.  Another possibility that crossed my mind (but haven't tried yet) is to do option 1 and broadcast the map, although it would be better to broadcast in a \"smart\" way so that the keys of the map are co-located with the keys of .Has anyone come across this sort of situation before?  I'd be happy to have your thoughts.Thanks!One option is to perform a broadcast join by collecting  to the driver and broadcasting it to all mappers; done correctly, this will let us avoid an expensive shuffle of the large  RDD:  The  tells Spark that this map function doesn't modify the keys of ; this will allow Spark to avoid re-partitioning  for any subsequent operations that join based on the  key.This broadcast could be inefficient since it involves a communications bottleneck at the driver.  In principle, it's possible to broadcast one RDD to another without involving the driver; I have a prototype of this that I'd like to generalize and add to Spark.Another option is to re-map the keys of  and use the Spark  method; this will involve a full shuffle of  (and possibly ):On my sample input, both of these methods produce the same result:A third option would be to restructure  so that  is its key, then perform the above join.Another way to do it is to create a custom partitioner and then use zipPartitions to join your RDDs."},
Scala

In the work that I do on a day to day in Java, I use builders quite a lot for fluent interfaces, e.g.: With a quick-and-dirty Java approach, each method call mutates the builder instance and returns . Immutably, it involves more typing, cloning the builder first before modifying it. The build method eventually does the heavy lifting over the builder state.What's a nice way of achieving the same in Scala?If I wanted to ensure that  was called only once, and then subsequently only  and  could be called, a-la a directed builder, how would I go about approaching this?Another alternative to the Builder pattern in Scala 2.8 is to use immutable case classes with default arguments and named parameters. Its a little different but the effect is smart defaults, all values specified and things only specified once with syntax checking...The following uses Strings for the values for brevity/speed...You can then also use existing immutable instances as kinda builders too...You have three main alternatives here.It's the same exact pattern.  Scala allows for mutation and side effects.  That said, if you'd like to be more of a purest, have each method return a new instance of the object that you're constructing with the element(s) changed.  You could even put the functions within the Object of a class so that there's a higher level of separation within your code.so that your code might look like(Note: I've probably screwed up some syntax here.)Case classes solve the problem as shown in previous answers, but the resulting api is difficult to use from java when You have scala collections in your objects. To provide a fluent api to java users try this:Then in java code the api is really easy to useusing Scala partial applies are feasible if you are building a smallish object that you don't need to pass over method signatures. If any of those assumptions don't apply, I recommend using a mutable builder to build an immutable object. With this being scala you could implement the builder pattern with a case class for the object to build with a companion as the builder.Given that the end result is a constructed immutable object I don't see that it defeats any of the Scala principles.  I think scala's Stackable Modification could be used here. Check this out : \nIt works for me, but I think it is write Java for Scala compiler. I`m still learning the scala way, functionnaly way.The usage is:The structure is:"},
Scala

As shown below, in Haskell, it's possible to store in a list values with heterogeneous types with certain context bounds on them:How can I achieve the same in Scala, preferably without subtyping?As @Michael Kohl commented, this use of forall in Haskell is an existential type and can be exactly replicted in Scala using either the forSome construct or a wildcard. That means that @paradigmatic's answer is largely correct.Nevertheless there's something missing there relative to the Haskell original which is that instances of its ShowBox type also capture the corresponding Show type class instances in a way which makes them available for use on the list elements even when the exact underlying type has been existentially quantified out. Your comment on @paradigmatic's answer suggests that you want to be able to write something equivalent to the following Haskell,@Kim Stebel's answer shows the canonical way of doing that in an object-oriented language by exploiting subtyping. Other things being equal, that's the right way to go in Scala. I'm sure you know that, and have good reasons for wanting to avoid subtyping and replicate Haskell's type class based approach in Scala. Here goes ...Note that in the Haskell above the Show type class instances for Unit, Int and Bool are available in the implementation of the useShowBox function. If we attempt to directly translate this into Scala we'll get something like,and this fails to compile in useShowBox as follows,The problem here is that, unlike in the Haskell case, the Show type class instances aren't propagated from the ShowBox argument to the body of the useShowBox function, and hence aren't available for use. If we try to fix that by adding an additional context bound on the useShowBox function,this fixes the problem within useShowBox, but now we can't use it in conjunction with map on our existentially quantified List,This is because when useShowBox is supplied as an argument to the map function we have to choose a Show instance based on the type information we have at that point. Clearly there isn't just one Show instance which will do the job for all of the elements of this list and so this fails to compile (if we had defined a Show instance for Any then there would be, but that's not what we're after here ... we want to select a type class instance based on the most specific type of each list element).To get this to work in the same way that it does in Haskell, we have to explicitly propagate the Show instances within the body of useShowBox. That might go like this,then in the REPL,Note that we've desugared the context bound on ShowBox so that we have an explicit name (showInst) for the Show instance for the contained value. Then in the body of useShowBox we can explicitly apply it. Also note that the pattern match is essential to ensure that we only open the existential type once in the body of the function.As should be obvious, this is a lot more vebose than the equivalent Haskell, and I would strongly recommend using the subtype based solution in Scala unless you have extremely good reasons for doing otherwise.As pointed out in the comments, the Scala definition of ShowBox above has a visible type parameter which isn't present in the Haskell original. I think it's actually quite instructive to see how we can rectify that using abstract types.First we replace the type parameter with an abstract type member and replace the constructor parameters with abstract vals,We now need to add the factory method that case classes would otherwise give us for free,We can now use plain ShowBox whereever we previously used ShowBox[_] ... the abstract type member is playing the role of the existential quantifier for us now,(It's worth noting that prior to the introduction of explict forSome and wildcards in Scala this was exactly how you would represent existential types.)We now have the existential in exactly the same place as it is in the original Haskell. I think this is as close to a faithful rendition as you can get in Scala.The  example you gave involves an . I'm renaming the  data constructor to  to distinguish it from the :We say  is \"existential\", but the  here is a universal quantifier that pertains to the  data constructor. If we ask for the type of the  constructor with explicit  turned on, this becomes much clearer:That is, a  is actually constructed from three things:Because the type  becomes part of the constructed , it is . If Haskell supported a syntax for existential quantification, we could write  as a type alias:Scala does support this kind of existential quantification and Miles's answer gives the details using a trait that consists of exactly those three things above. But since this is a question about \"forall in Scala\", let's do it exactly like Haskell does.Data constructors in Scala cannot be explicitly quantified with forall. However, every method on a module can be. So you can effectively use type constructor polymorphism as universal quantification. Example:A Scala type , given some , is then equivalent to a Haskell type .We can use this technique to add constraints to the type argument.A value of type  is like a value of the Haskell type . The instance of  is implicitly looked up by Scala if it exists.Now, we can use this to encode your  ...The  method is the universally quantified data constructor. You can see that it takes a type , an instance of , and a value of type , just like the Haskell version.Here's an example usage: in Scala might be to use a case class:Then:In this case, a  is basically equivalent to a , but you can use this technique with traits other than  to get something more interesting.This is all using the  typeclass from .I don't think a 1-to-1 translation from Haskell to Scala is possible here. But why don't you want to use subtyping? If the types you want to use (such as Int) lack a show method, you can still add this via implicit conversions.( : Adding methods to show, to answer comment. )I think you can get the same using implicit methods with context bounds:Why not:As the authorities' answers suggested,\nI'm often surprised that Scala can translate \"Haskell type monsters\" into very simple one."},
Scala

I'm trying to understand the advantages of currying over partial applications in Scala. Please consider the following code:So, if I can calculate partially applied function that easy, what are the advantages of currying?Currying is mostly used if the second parameter section is a function or a by name parameter. This has two advantages. First, the function argument can then look like a code block enclosed in braces. E.g.This reads better than the uncurried alternative:Second, and more importantly, type inference can usually figure out the function's parameter type, so it does not have to be given at the call site.\nFor instance, if I define a  function over lists like this:I can call it like this:or even shorter:If I defined  as an uncurried function, this would not work, I'd have to call it like this:If the last parameter is not a function or by-name parameter, I would not advise currying. Scala's  notatation is amost as lightweight, more flexible, and IMO clearer.I think it becomes clearer if you invert your curried example:It is more of an optical effect but you don\u2019t need to use any parentheses around the whole expression. Of course you can achieve the same result using partial application or by creating a helper method to invert the arguments, sure. The point is, that you don\u2019t have to do all of this if you start with a curried method in the first place. In that sense currying is more of an API and syntax sugar thing. It is not expected that you useanywhere in your code or that this is in any way especially meaningful to do. It is just that you get a nicely looking expression easily.(Well, and there are some advantages with respect to type inference\u2026)"},
Scala

It seems to me like the  syntax for partial functions require at least one :So, what's the best way to define an \"empty\" partial function? Is there a better way than \"manually\" overriding  and ?Map is a PartialFunction so you can do:Since Scala 2.10 you can use:As @didierd said in the comments, due to argument variances, a single instance can cover all possible argument types.Stealing from everyone, a possible mix of it all : Shortest one I can think of:A solution (which is more a hack) is to ensure that the case is never true: Simple curiosity, why do you need such a function?It may be interesting to know that it is planned to add an empty member to the scala library and to see how it is implemented:\n"},
Scala

With too many arguments,  easily gets too confusing. Is there a more powerful way to format a String. Like so:Or is this not possible because of type issues ( would need to take a Map[String, Any], I assume; don\u2019t know if this would make things worse).Or is the better way doing it like this:even though it pollutes the name space?While a simple pimping might do in many cases, I\u2019m also looking for something going in the same direction as Python\u2019s  (See: )In Scala 2.10 you can use .Well, if your only problem is making the order of the parameters more flexible, this can be easily done:And there's also regex replacement with the help of a map:Maybe the Scala-Enhanced-Strings-Plugin can help you. Look here:You can easily implement a richer formatting yourself (with pimp-my-library approach):If you're using 2.10 then go with built-in interpolation. Otherwise, if you don't care about extreme performance and are not afraid of functional one-liners, you can use a fold + several regexp scans:This the answer I came here looking for:  You might also consider the use of a template engine for really complex and long strings. On top of my head I have  which implements amongst others the  template engine. Might be overkill and performance loss for simple strings, but you seem to be in that area where they start becoming real templates."},
Scala

I have the following code which recursively operates on each element within a ListNow, ignoring that this functionality is available through  and , this works just fine. However, if I try to change it to accept any , I run into problems:Here is how I think the code should look, except it doesn't work:Edit: So many good answers! I'm accepting agilesteel's answer as his was the first that noted that :: isn't an operator in my example, but a case class and hence the difference.There are two  (pronounced cons) in Scala. One is an operator defined in  and one is a  (subclass of ), which represents a non empty list characterized by a head and a tail. is a constructor pattern, which is syntactically modified from . is a case class, which means there is an extractor object defined for it.Kind of cheating, but here it goes:Don't ask me why  doesn't work...As of the ides of March 2012, this works in 2.10+:More generally, two different head/tail and init/last decomposition objects mirroring append/prepend were added for  in :You can actually define an object for  to do exactly what you are looking for:Then your code works exactly as expected.This works because  is equivalent to  when used for patten matching.I don't think there is pattern matching support for arbitrary sequences in the standard library. You could do it with out pattern matching though:You can define your own extractor objects though. See  A simple tranformation from Seq to List would do the job:"},
Scala

I have a Scala data processing tool which is failing with a  exception. The tool needs to make a couple passes over a large data file (the one I'm working on is over 700MB), so it would be convenient if the entire thing could be stored in memory.I run the tool from the command line or from a Bash script using the \"scala\" runner. How do I increase the JVM heap size for this? I've tried passing , but it does not recognize this argument. I'm using a nightly build of Scala 2.8.0 (r18678).The JAVA_OPTS environment variable is used to specify the options passed to the java command. See the  for details.You can pass options to the JVM via -J.  E.g.,Based on Joe's suggestion, I looked at the scala program, which is a Bash script that calls java with various Scala specific arguments. It allows extra command line arguments to be passed to Java through the JAVA_OPTS environment variable. So you can increase the heap size like this:Edit .As a hack you can edit the  file to edit the parameters for the  command. Not pretty."},
Scala

Say I'm writing an extension methodShould you always include  in the class defininition? Under what circumstances would you not want to make an implicit class a value class?Let's look at the  and think when they may not be suitable for implicit classes:In addition, making your implicit class a value class could possibly change some behavior of code using reflection, but reflection shouldn't normally see implicit classes.If your implicit class does satisfy all of those limitations, I can't think of a reason not to make it a value class.I sense you're confusing  with . You'd rarely extend anything when defining an Implicit Class for an enhancement while Value Classes  extend ."},
Scala

I am trying to parse a CSV file, ideally using weka.core.converters.CSVLoader.\nHowever the file I have is not a valid UTF-8 file.\nIt is mostly a UTF-8 file but some of the field values are in different encodings,\nso there is no encoding in which the whole file is valid,\nbut I need to parse it anyway.\nApart from using java libraries like Weka, I am mainly working in Scala.\nI am not even able to read the file usin scala.io.Source:\nFor examplethrows:I am perfectly happy to throw all the invalid characters away or replace them with some dummy.\nI am going to have lots of text like this to process in various ways\nand may need to pass the data to various third party libraries.\nAn ideal solution would be some kind of global setting that would\ncause all the low level java libraries to ignore invalid bytes in text,\nso that that I can call third party libraries on this data without modification.SOLUTION:Thanks to +Esailija for pointing me in the right direction.\nThis lead me to \nwhich provides the core java solution. In Scala I can make this the default behaviour by making the codec implicit. I think I can make it the default behaviour for the entire package by putting it the implicit codec definition in the package object.This is how I managed to do it with java:The invalid file is created with bytes:Which is  in UTF-8 with 4 invalid bytes mixed in.With  you see the standard unicode replacement character being used:With , you see the invalid bytes ignored:Without specifying , you get The solution for scala's Source (based on @Esailija answer):Scala's Codec has a decoder field which returns a :The problem with ignoring invalid bytes is then deciding when they're valid again. Note that UTF-8 allows variable-length byte encodings for characters, so if a byte is invalid, you need to understand which byte to start reading from to get a valid stream of characters again.In short, I don't think you'll find a library which can 'correct' as it reads. I think a much more productive approach is to try and clean that data up first.I'm switching to a different codec if one fails.In order to implement the pattern, I got inspiration from .I use a default List of codecs, and recursively go through them.  If they all fail, I print out the scary bits:I'm just learning Scala, so the code may not be optimal.A simple solution would be to interpret your data stream as ASCII, ignore all non-text characters. However, you would lose even valid encoded UTF8-characters. Don't know if that is acceptable for you.EDIT: If you know in advance which columns are valid UTF-8, you could write your own CSV parser that can be configured which strategy to use on what column.Use  as the encoder; this will just give you byte values packed into a string.  This is enough to parse CSV for most encodings.  (If you have mixed 8-bit and 16-bit blocks, then you're in trouble; you can still read the lines in ISO-8859-1, but you may not be able to parse the line as a block.)Once you have the individual fields as separate strings, you can tryto generate the string with the proper encoding (use the appropriate encoding name per field, if you know it).Edit: you will have to use  if you want to detect errors.  Mapping to UTF-8 this way will just give you 0xFFFF in your string when there's an error."},
Scala

There is an Idris tutorial, an Agda tutorial and many other tutorial style papers and introductory material with never ending references to things yet to learn. I'm kind of crawling in the middle of all these and most of the time I'm stuck with mathematical notations and new terminology appearing suddenly with no explanation. Perhaps my math sucks :-)Is there any disciplined way to approach dependent type programming? Like when you want to learn Haskell, you start with \"Teach yourself a Haskell\", when you want to learn Scala, you start with Odersky's book, for Ruby you read that weird tutorial with mutated bugs in it. But I can't start Agda or Idris with their books. They are way above my head. I tried Coq and got stuck in its all-about-teorm-proving style. Agda requires a huge math background and Idris, well, let's leave that for now!I understand static type systems very well, I am kind of proficient with Scala and I can use Haskell if necessary. I understand the Functional Paradigm and use it day to day, I understand Algebraic Data Types and GADTs (quite smoothly actually) and I recently managed to comprehend the Lambda Cube. I'm lacking in the math and logic parts, though. I would highly recommend . This book is quite good at introducing you to Coq one step at a time. There is a lot of theorem proving, yes, but that's part of the deliciousness of dependent types. It's a great feeling when the line between \"programming\" and \"proving\" starts to blur.I think Software Foundations does a pretty good job of bringing you up to speed for the logic you need to know. Already being comfortable with the concept of implication helps, though.(Notice: This is a self advertisement)I am writing an  and my primary goal is to\nlet people to play with Agda without theoretical background.This tutorial may solve most of your problems:It is under development, but the first half is kind of ready."},
Scala

Given a trait :it can be mixed into a class with  or :It can also be mixed upon instantiating a new instance:But...can the trait (or any other if that makes a difference) be added to an existing instance?I'm loading objects using JPA in Java and I'd like to add some functionality to them using traits. Is it possible at all?I'd like to be able to mix in a trait as follows:I have a idea for this usage:you can use this trait as below:for your example code:I hope this can help you.UPDATEDbut this pattern has some restrict, you can't use some implicit helper method that defined already.An existing runtime object in the JVM has a certain size on the heap. Adding a trait to it would mean altering its size on the heap, and changing its signature.So the only way to go would be to do some kind of transformation at compile time.Mixin composition in Scala occurs at compile time. What compiler could potentially do is create a wrapper B around an existing object A with the same type that simply forwards all calls to the existing object A, and then mix in a trait T to B. This, however, is not implemented. It is questionable when this would be possible, since the object A could be an instance of a final class, which cannot be extended.In summary, mixin composition is not possible on existing object instances.UPDATED:Related to the smart solution proposed by Googol Shan, and generalizing it to work with any trait, this is as far as I got. The idea is to extract the common mixin functionality in the  trait. The client should then create a companion object extending  for each trait he wants to have the dynamic mixin functionality for. This companion object requires defining the anonymous trait object gets created ().I usually used a  to mix in a new method to an existing object.See, if I have some code as below:and then you can use  method with an already existing object Test.in your example, you can use like this:I am thinking out a prefect syntax to define this HelperObject:What about an implicit class? It seems easier to me compared to the way in the other answers with a final inner class and a \"mixin\"-function. "},
Scala

What are the available code coverage tools for Scala? I have Scala spec tests and a Hudson continuous integration set-up. Is there something I can hook-in to this setup to measure and track code coverage?SCCT is a compiler plugin which instruments the classes to gather coverage data:I use .  However, any Java coverage tool should work just fine.  The only catch is that you will end up with a large number of auto-generated classes in your coverage list.  This is because while Scala compiles down into very natural JVM bytecode, it is forced to produce an unnaturally large number of classes to accommodate common functional features like lazy evaluation. is little better.One problem with non-mainstream languages (such as Scala) is that tools are hard to find, because they are hard to build.This technical paper  (I'm the author) describes how to build test coverage tools for langauges in systematic way to help get around this problem, using a generic tool-building infrastructure.We've implemented  this way, including instrumenters, data collection and test coverage display and reporting.\nIt would be straightforward to implement Scala like this.The solutions posed by other answers produces confusing information from the implementation of Scala (\"auto genreated classes\").  What developers want to see is coverage data in terms of their code.   The approach we use instruments the source code, so the results are stated entirely and only in terms of the source code; even the test coverage viewer shows the source code covered with coverage information.I've put together a SBT plugin called  that uses scct under the hood, but publishes the results to .  Still, it's good if you want to code coverage reports to be publicly visible. Check out an example of the results I use jacoco. It does not require compile- or runtime- dependencies, instruments classes on the fly w/o special instrumentation phase. Also it integrated with Sonar and published on Maven Central. Here is example: I would like to add better reporting: more detailed branch coverage makrup, excluding of generated classes/methods, and to be handy like ScalaDoc (see SCCT reports for example)"},
Scala

I'm about to write a Scala command-line application that relies on a MySQL database. I've been looking around for ORMs, and am having trouble finding one that will work well.The  looks nice, but I'm not sure it can be decoupled from the entire Lift web framework. ActiveObjects also looks OK, but the author says that it may not work well with Scala.I'm not coming to Scala from Java, so I don't know all the options. Has anyone used an ORM with Scala, and if so, what did you use and how well did it work?There are several reasons why JPA-oriented frameworks (Hibernate, for instance) do not fit into idiomatic Scala applications elegantly:There are more reasons, I'm sure. That's why we have started the . This pure-Scala ORM tries it's best to eliminate the nightmares of classic Java ORMs. Specifically, you define your entities in pretty much way you would do this with classic DDL statements:As you can see, these declarations are a bit more verbose, than classic JPA POJOs. But in fact there are several concepts that are assembled together:The only things Circumflex ORM lacks are:P.S. I hope this post will not be considered an advertisement. It isn't so, really -- I was trying to be as objective as possible. I experimented with  and basic operations worked fine for me.  JPA is a Java standard and there are other implementations that may also work (, etc). Here is an example of what a JPA class in Scala looks like:I am happy to announce the 1st release of a new ORM library for Scala. MapperDao maps domain classes to database tables. It currently supports mysql, postgresql (oracle driver to be available soon), one-to-one, many-to-one, one-to-many, many-to-many relationships, autogenerated keys, transactions and optionally integrates nicely with spring framework. It allows freedom on the design of the domain classes which are not affected by persistence details, encourages immutability and is type safe. The library is not based on reflection but rather on good Scala design principles and contains a DSL to query data, which closely resembles select queries. It doesn't require implementation of equals() or hashCode() methods which can be problematic for persisted entities. Mapping is done using type safe Scala code.Details and usage instructions can be found at the mapperdao's site:The library is available for download on the above site and also as a maven dependency (documentation contains details on how to use it via maven)Examples can be found at:Very brief introduction of the library via code sample:Querying is very familiar:I encourage everybody to use the library and give feedback. The documentation is currently quite extensive, with setup and usage instructions. Please feel free to comment and get in touch with me at kostas dot kougios at googlemail dot com.Thanks,Kostantinos KougiosHere's basically the same example with @Column annotation: is a perfect match for a functional world. Traditional ORM's are not a perfect fit for Scala. Slick composes well and uses a DSL that mimics Scala collection classes and for comprehensions.Of course, any Java database access framework will work in Scala as well, with the usual issues that you may encounter, such as collections conversion, etc. jOOQ for instance, has been observed to work well in Scala. An example of jOOQ code in Scala is given in the manual:Taken from\n"},
Scala

Are there any advantages to using object-oriented programming (OOP) in a functional programming (FP) context?I have been using  for some time now, and I noticed that the more my functions are stateless, the less I need to have them as methods of objects. In particular, there are advantages to relying on type inference to have them usable in as wide a number of situations as possible.This does not preclude the need for namespaces of some form, which is orthogonal to being OOP. Nor is the use of data structures discouraged. In fact, real use of FP languages depend heavily on data structures. If you look at the F# stack implemented in , you will find that it is not object-oriented.In my mind, OOP is heavily associated with having methods that act on the state of the object mostly to  the object. In a pure FP context that is not needed nor desired.A practical reason may be to be able to interact with OOP code, in much the same way F# works with . Other than that however, are there any reasons? And what is the experience in the Haskell world, where programming is more pure FP?I will appreciate any references to papers or counterfactual real world examples on the issue.The disconnect you see is not of FP vs. OOP. It's mostly about immutability and mathematical formalisms vs. mutability and informal approaches.First, let's dispense with the mutability issue: you can have FP with mutability and OOP with immutability just fine. Even more-functional-than-thou Haskell lets you play with mutable data all you want, you just have to be explicit about what is mutable and the order in which things happen; and efficiency concerns aside, almost any mutable object could construct and return a new, \"updated\" instance instead of changing its own internal state.The bigger issue here is mathematical formalisms, in particular heavy use of algebraic data types in a language little removed from lambda calculus. You've tagged this with Haskell and F#, but realize that's only half of the functional programming universe; the Lisp family has a very different, much more freewheeling character compared to ML-style languages. Most OO systems in wide use today are very informal in nature--formalisms do exist for OO but they're not called out explicitly the way FP formalisms are in ML-style languages.Many of the apparent conflicts simply disappear if you remove the formalism mismatch. Want to build a flexible, dynamic, ad-hoc OO system on top of a Lisp? Go ahead, it'll work just fine. Want to add a formalized, immutable OO system to an ML-style language? No problem, just don't expect it to play nicely with .NET or Java.Now, you may be wondering, what  an appropriate formalism for OOP? Well, here's the punch line: In many ways, it's more function-centric than ML-style FP! I'll refer back to  for what seems to be the key distinction: structured data like algebraic data types in ML-style languages provide a concrete representation of the data and the ability to define operations on it; objects provide a black-box abstraction over  and the ability to easily replace components.There's a duality here that goes deeper than just FP vs. OOP: It's closely related to what some programming language theorists call : With concrete data, you can easily add new operations that work with it, but changing the data's structure is more difficult. With objects you can easily add new data (e.g., new subclasses) but adding new operations is difficult (think adding a new abstract method to a base class with many descendants).The reason why I say that OOP is more function-centric is that functions themselves represent a form of behavioral abstraction. In fact, you can simulate OO-style structure in something like Haskell by using records holding a bunch of functions as objects, letting the record type be an \"interface\" or \"abstract base class\" of sorts, and having functions that create records replace class constructors. So in that sense, OO languages use higher-order functions far, far more often than, say, Haskell would.For an example of something like this type of design actually put to very nice use in Haskell, read the source for , in particular the way that it uses an opaque record type containing functions and combines things only in terms of their behavior. A few final things I forgot to mention above.If OO indeed makes extensive use of higher-order functions, it might at first seem that it should fit very naturally into a functional language such as Haskell. Unfortunately this isn't quite the case. It is true that  as I described them (cf. the paper mentioned in the LtU link) fit just fine. in fact, the result is a more pure OO style than most OO languages, because \"private members\" are represented by values hidden by the closure used to construct the \"object\" and are inaccessible to anything other than the one specific instance itself. You don't get much more private than that!What doesn't work very well in Haskell is . And, although I think inheritance and subtyping are all too often misused in OO languages, some form of subtyping is quite useful for being able to combine objects in flexible ways. Haskell lacks an inherent notion of subtyping, and hand-rolled replacements tend to be exceedingly clumsy to work with.As an aside, most OO languages with static type systems make a complete hash of subtyping as well by being too lax with substitutability and not providing proper support for variance in method signatures. In fact, I think the only full-blown OO language that hasn't screwed it up completely, at least that I know of, is Scala (F# seemed to make too many concessions to .NET, though at least I don't think it makes any  mistakes). I have limited experience with many such languages, though, so I could definitely be wrong here.On a Haskell-specific note, its \"type classes\" often look tempting to OO programmers, to which I say: Don't go there. Trying to implement OOP that way will only end in tears. Think of type classes as a replacement for overloaded functions/operators, not OOP.As for Haskell, classes are less useful there because some OO features are more easily achieved in other ways.Encapsulation or \"data hiding\" is frequently done through function closures or existential types, rather than private members.  For example, here is a data type of random number generator with encapsulated state.  The RNG contains a method to generate values and a seed value.  Because the type 'seed' is encapsulated, the only thing you can do with it is pass it to the method.Dynamic method dispatch in the context of parametric polymorphism or \"generic programming\" is provided by type classes (which are not OO classes).  A type class is like an OO class's virtual method table.  However, there's no data hiding.  Type classes do not \"belong\" to a data type the way that class methods do.Dynamic method dispatch in the context of subtyping polymorphism or \"subclassing\" is almost a translation of the class pattern in Haskell using records and functions.I think that there are several ways of understanding what OOP means. For me, it is not about encapsulating , but more about organizing and structuring programs. This aspect of OOP can be used perfectly fine in conjunction with FP concepts.I believe that mixing the two concepts in F# is a very useful approach - you can associate  state with operations working on that state. You'll get the nice features of 'dot' completion for identifiers, the ability to easy use F# code from C#, etc., but you can still make your code perfectly functional. For example, you can write something like:In the beginning, people don't usually declare types in F# - you can start just by writing functions and later evolve your code to use them (when you better understand the domain and know what is the best way to structure code). The above example:"},
Scala

Is there a way to write an anonymous function that is recursive in Scala? I'm thinking of something like this:(Related question: )As described in the link you posted. You can use Y-combinator. Here is example:Note it doesn't work with big numbers. \nBe careful with tail call optimization.If you don't want to hit the \"Amazing mathematics\" you could just revert to the object aspects of scala.in order to make it look geekier you can also use this code style:Adding to the many good responses here in this thread, the fact that Scala is not giving us tail call optimizable Fixed-point combinator has been bothering me so much so that I've decided to write a macro to translate Y-combinator-like call to an ordinary, idiomatic recursive call (with tail call optimization, of course). The idea is that a call likeis readily translatable intoI've put up macro implementation targeting Scala 2.11 (with minor tweak should also work with 2.10) into . With this macro, we can perform ordinary recursive tasks in anonymous manner without fearing stack overflow e.g.givesA very simple approach:"},
Scala

I saw that there are two methods to cast an object in Scala:When I tried, I found that  doesn't use implicit conversion whereas the other one does. What are the differences of behavior between these two methods? And where is it recommended to use one over the other?Type ascriptions can also be used to trigger implicit conversions. For instance, you could define the following implicit conversion:and then ensure its use like so:Ascribing type  to a  would normally be a compile-time type error, but before giving up the compiler will search for available implicit conversions to make the problem go away. The particular implicit conversion that will be used in a given context is known at compile time.Needless to say, runtime errors are undesirable, so the extent to which you can specify things in a  manner (without using ), the better! If you find yourself using , you should probably be using  instead.Pelotom's answer covers the theory pretty nice, here are some examples to make it clearer:As you can see the type ascription can be used to resolve disambiguations. Sometimes they can be unresolvable by the compiler (see later), which will report an error and you must resolve it. In other cases (like in the example) it just uses the \"wrong\" method, not that you want.  does not compile, showing that the type ascription is not a cast. Compare it with the previous line, where the compiler is happy, but you get an exception, so the error is detected then with the type ascription.You will get an unresolvable ambiguity if you also add a methodIn this case the first and third invocation of foo will not compile, as the compiler can not decide if you want to call the foo with a single Any param, or with the varargs, as both of them seems to be equally good => you must use a type ascription to help the compiler. see also \"Programming in Scala\" covers this in a bit of detail in Chapter 15 - Case Classes and Pattern Matching.Basically the second form can be used as 'Typed Pattern' in a pattern match, giving the isInstanceOf and asInstanceOf functionality. Comparevs.The authors hint that the verbosity of the isInstance* way of doing things is intentional to nudge you into the pattern matching style.I'm not sure which pattern is more effective for a simple typecast without a test though.There is example of the difference:Example:We can also call method using multiple-dispatch:We can define implicit conversion:"},
Scala

E.g. why doeswork, butfails (because arrays are invariant). What is the desired effect behind this design decision?Because it would break type-safety otherwise.\nIf not, you would be able to do something like this:and the compiler cant catch it.On the other hand, lists are immutable, so you can't add something that is not This is because lists are immutable and arrays are mutable.The difference is that s are immutable while s are mutable.To understand why mutability determines variance, consider making a mutable version of  - let's call it . We'll also make use of some example types: a base class  and 2 subclasses named  and .Notice that  has one more method () than .Then, define a function that accepts a mutable list of animals and modifies the list:Now, horrible things will happen if you pass a list of cats into the function:If we were using a careless programming language, this will be ignored during compilation. Nevertheless, our world will not collapse if we only access the list of cats using the following code:But if we do this:A runtime error will occur. With Scala, writing such code is prevented, because the compiler will complain. The normal answer to give is that mutability combined with covariance would break type safety. For collections, this can be taken as a fundamental truth. But the theory actually applies to any generic type, not just collections like  and .The real answer has to do with the way function types interact with subtyping. The short story is if a type parameter is used as a return type, it is covariant. On the other hand, if a type parameter is used as an argument type, it is contravariant. If it is used both as a return type and as an argument type, it is invariant.Let's look at the . The two obvious methods to look at are for the ones for lookup and update:In the first method  is a return type, while in the second  is an argument type. The rules of variance dictate that  must therefore be invariant.We can compare the  to see why it is covariant. Confusingly, we would find these methods, which are analogous to the methods for :Since  is used as both a return type and as an argument type, we would expect  to be invariant just like  is for . However, unlike with , the documentation is lying to us about the type of . The lie is good enough for most calls to this method, but isn't good enough to decide the variance of . If we expand the documentation for this method and click on \"Full Signature\", we are shown the truth:So  does not actually appear as an argument type. Instead,  (which can be any supertype of ) is the argument type. This does not place any restriction on , so it really can be covariant. Any method on  which has  as an argument type is a similar lie (we can tell because these methods are marked as )."},
Scala

So say i have some list likeAnd then i want to filter one of them out, i can do something likeIs there any way i can \"unpack\" the tuple as the parameter to the lambda directly, instead of having this intermediate  variable?Something like the following would be ideal, but eclipse tells me Any help would be appreciated - using 2.9.0.1This is about the closest you can get:It's basically pattern matching syntax inside an anonymous . There are also the  methods in  object and traits, but they are just a wrapper around this pattern matching expression.Hmm although Kipton has a good answer. You can actually make this shorter by doing.There are a bunch of options:... is a type mismatch because that lambda defines aYou can convert between them like this:I've pondered the same, and came to your question today. I'm not very fond of the partial function approaches (anything having ) since they imply that there could be more entry points for the logic flow. At least to me, they tend to blur the intention of the code. On the other hand, I really do want to go straight to the tuple fields, like you.Here's a solution I drafted today. It seems to work, but I haven't tried it in production, yet.Output:Maybe this turns out to be useful. The  object should naturally be put aside in some tool namespace.Applied to your case:"},
Scala

Given:How can I get  from  and  from ?Or if you want only the name without the package:See the documentation of  for more information.You can use the property  of the case class:N.B.\nIf you pass to scala 2.8 extending a case class have been deprecated, and you have to not forget the left and right parent Here is a Scala function that generates a human-readable string from any type, recursing on type parameters:"},
Scala

What is the canonical way to get an empty array in Scala?  is too verbose.You can leave out the  part if it can be inferred (e.g. ). will be enough, most of the times. It will be of type .If you use implicit conversions, you might need to actually write Array[Nothing], due to :This will not work:  This will:But this is only a weird corner case of implicits. It's is quite possible that this problem will disappear in the future."},
Scala

I am new to Play framework and tried to mimic the  sample in my local machine but I encountered an error:I have Play 2.4 installed and created the project using IntelliJ Idea 14 via  template.After adding  parameters to views you can just add the following imports and use the old controller classes or even objects without any additional changes:Using view form helpers (such as ) requires you to pass an implicit  parameter to your view. You can do this adding  to the signature in your view. Your view becomes this:Then in your application controller you must make this parameter implicitly available in your scope. The simplest way to do this is to implement play's  trait.In your example, this would look like this:In your controller you can of course use your own implementation of . Since play knows out of the box how to inject a  you can simply annotate your controller with  and let play do the work for you.As Matthias Braun mentioned, you also have to setin your See  for more information about I18n."},
Scala

I am not sure whether mergestrategy or exclude jars is the best option here. Any help with how do I proceed further with this error will be great!// Here is where I start seeing errors:// Here are the error messages.Use the  configuration, which will scope your dependent library.For example:If needed, read more atAdd the code below to your build.sbt fileThis helped me a lot."},
Scala

given:why does the compiler complain I'm not sure about the error, but you can achieve what you want as follows:That is,  takes a function that takes a pair and returns , not a function that takes two arguments: here,  has type .Another way to write it is:In this case, the  block is a partial function.oops, read the doco wrong, map.foreach expects a function literal with a tuple argument!soworksThe confusing error message is a compiler bug, which should be :You need to patter-match on the  argument to assign variables to its subparts , . You can do with very few changes:Excellent question!\nEven when explicitly typing the foreach method, it still gives that very unclear compile error. There are ways around it, but I can't understand why this example does not work.Yet another way:However it requires explicit type annotations, so I prefer partial functions.Docs says argument is tuple -> unit, so We can easily do this"},
Scala

I've read a few questions such as Scala vs Haskell discussing the merits of both languages or which to learn, but I already know that I'd like to learn Scala. I was a Java programmer at uni and now mainly use PHP. I want to learn Scala as it looks like an improvement on Java for personal projects and I'd also like to learn a functional language to improve my knowledge as a programmer.I am wondering if it would be a good idea to learn Haskell as an introduction to functional programming as it is purely functional so I'd properly learn it rather than haphazard using bits of functional in Scala without knowing why? I'd also like to use Haskell for personal projects etc as it looks great, but I don't really see many real world applications of it, seems more used for academic stuff hence wanting to learn it to get the functional understanding then move on to Scala.Speaking as someone who came from Java, and for whom Scala was a gateway drug to Haskell, I happen to think this is a great idea (learn Haskell first)! Haskell is conceptually a much simpler language than Scala, and if your goal is to learn how to program functionally, you can't help but do so if you start with Haskell. By design, Scala supports a kind of \"legacy mode\" of coding in which you don't really have to change your Java (or PHP) habits too much if you don't want to. I think this is a strategic decision--and a good one!--meant to increase adoption amongst crusty Java stalwarts. But that's not you! You're actually  in learning something new... so why not go all-out? Learning functional programming in a pure setting, without the clutter and the temptation to regress into old habits, will crystallize the concepts in your brain.Then by all means return to Scala and learn how it differs from Haskell; it is both weaker in some respects and stronger in others, but you will then be on a much better foundation to appreciate these differences.I wouldn't do that. If you go straight to Scala (your final aim) you save time. You'll learn functional programming anyway, but as Scala is \"less pure\" you'll be able to start writing programs in Scala usign some Java-like constructs, which will make the transition simpler.Even if you go into Haskell, your first programs will be of less \"functional quality\" than later ones, as only practice improves that. Starting Scala your first programs will be of \"less quality\" as your first programs in Java or PHP were, but with practice you'll improve. Spending time in unrelated tasks hoping they MAY help, it can result in you wasting that time.Focus on your aim. If that's Scala, go for it. I believe  may be relevant to the question. It raises a point on productivity (deliver software) vs seeking \"pure knowledge\".I came to Scala from a Java background. Initially I just focused on Scala as a better Java. As time went on I started to use more and more functional concepts in Scala. Eventually I reached a point where I felt I needed a purer understanding of functional programming. It was at this point that I went away and learnt Haskell. When I cam back to Scala I found it much easier to use a functional style and some of the the concepts I struggled with previously made much more sense.You don't have to learn Haskell to become a good Scala developers, but I think once you get to a certain level in Scala that having a deeper understanding of functional programming concepts really helps.The risk of starting directly from Scala, without having played any purely functional programming language first, is that you'll probably be drawn to the procedural solutions a bit too often.I wouldn't try Haskell as an intro to functional programming, though: not that it's particularly hard - its syntax is amazingly terse - but it's definitely very peculiar (even in the peculiar world of functional programming) and I think you should try with a language you can port more easily to Scala, like Racket or plain Scheme.To better understand what I mean, look at list comprehensions in Haskell, Scala and Scheme.I learned Haskell first and then Scala and never regretted. You will gain a much deeper appreciation of FP if you learn Haskell first. Your understanding of the concepts behind FP and why they are important will be seared in. Much of Scala is taken from Haskell (IMHO). It will make more sense when you have the Haskell background. Don't shy away! Your efforts will be rewarded.For me, I want to learn Scala and functional programming; and, thus simply, I am learning Scala. My study material is . After I have read the early chapter on syntx and stuff, I have skipped chapter covering OO stuff and jumped to Chapter 8 which cover the functional programming stuff. There I let myself struggle with FP. I read  scala code, which is written in FP way and analyze . You want to learn Scala for \"...an improvement on Java for personal projects.\" and Haskell for FP intro. So, it seems that first of all, you want to be productive with your java project and then grasp FP as a side effect. To be productive, you have to master the language. There are much to learn and master the language and the only way to master the language is that you have to write the code in that language. As you learn/use Scala, you can't avoid FP out right even if you want to. I have been reading the Scala blogs(the book too) and the authors  go out of their way to do explanation when it comes to FP concept. You don't have to worry about not grasping FP by going Scala route. Yes, you can draw inspiration from Haskell like  when you are learning Scala. Or as  above have pointed out, you can delve into more FP when you are already productive with Scala. You wanna go to point A, why not go to point A directly? If you go via the route of point B (Haskell), you will have to postpone your productivity as  mentioned."},
Scala

is there a way in Scala to sort an array of tuples using and arbitrary comparison function? In particular I need to sort and array of tuples by their second element, but I wanted to know a general technique to sort arrays of tuples.Thanks!You can use this code:Unfortunetly, it seems that Scala cannot infer the type of the array passed to . I hope that's ok for you.In scala 2.8, there is a method sortBy. Here is a simple use case:If it's an , it's probably typical to use in-place sorting algorithms. However, in idiomatic Scala code, mutable collections are usually not encouraged/used. If that's the case and you have am immutable collection (or would like to not modify the  in place), use :sorting an  or any other collection of tuples:On Scala 2.8 (yes, again :), you can also do this:In the specific case of pairs, this can also work to sort  by the second element, and then by the first:2.7 and not in place:You probably want  from scala.util.Sorting.\nYour comparison function would be something like "},
Scala

In one of my first attempts to create functional code, I ran into a performance issue.I started with a common task - multiply the elements of two arrays and sum up the results:Here is how I reformed the work:When I benchmarked the two approaches, the second method takes 40 times as long to complete!  Why does the second method take so much longer? How can I reform the work to be both speed efficient and use functional programming style?The main reasons why these two examples are so different in speed are:Let's consider the slower one by parts. First:That creates a new array, an array of . It will copy all elements from both arrays into  objects, and then copy a reference to each of these objects into a third array. Now, notice that  is parameterized, so it can't store  directly. Instead, new instances of  are created for each number, the numbers are stored in them, and then a reference for each of them is stored into the . Now a fourth array is created. To compute the values of these elements, it needs to read the reference to the tuple from the third array, read the reference to the  stored in them, read the numbers, multiply, create a new  to store the result, and then pass this reference back, which will be -referenced again to be stored in the array (arrays are not type-erased).We are not finished, though. Here's the next part:That one is relatively harmless, except that it still do boxing/unboxing and  creation at iteration, since  receives a , which is parameterized.Scala 2.8 introduces a feature called specialization which will get rid of a lot of these boxing/unboxing. But let's consider alternative faster versions. We could, for instance, do  and  in a single step:We could use  (Scala 2.8) or  (Scala 2.7) to avoid creating intermediary collections altogether:This last one doesn't save much, actually, so I think the non-strictness if being \"lost\" pretty fast (ie, one of these methods is strict even in a view). There's also an alternative way of zipping that is non-strict (ie, avoids some intermediary results) by default:This gives much better result that the former. Better than the  one, though not by much. Unfortunately, we can't combined  with  because the former doesn't support the latter.The last one is the fastest I could get. Faster than that, only with specialization. Now,  happens to be specialized, but for ,  and . The other primitives were left out, as specialization increases code size rather dramatically for each primitive. On my tests, though  is actually taking longer. That might be a result of it being twice the size, or it might be something I'm doing wrong.So, in the end, the problem is a combination of factors, including producing intermediary copies of elements, and the way Java (JVM) handles primitives and generics. A similar code in Haskell using supercompilation would be equal to anything short of assembler. On the JVM, you have to be aware of the trade-offs and be prepared to optimize critical code.I did some variations of this with Scala 2.8. The loop version is as you write but the \nfunctional version is slightly different:I ran with Double instead of Float, because currently specialization only kicks in for Double. I then tested with arrays and vectors as the carrier type. Furthermore, I tested Boxed variants which work on java.lang.Double's instead of primitive Doubles to measure \nthe effect of primitive type boxing and unboxing. Here is what I got (running Java 1.6_10 server VM, Scala 2.8 RC1, 5 runs per test).The first thing to notice is that by far the biggest difference is between primitive array loops and primitive array functional reduce. It's about a factor of 15 instead of the 40 you have seen, which reflects improvements in Scala 2.8 over 2.7. Still, primitive array loops are the fastest of all tests whereas primitive array reduces are the slowest. The reason is that primitive Java arrays and generic operations are just not a very good fit. Accessing elements of primitive Java arrays from generic functions requires a lot of boxing/unboxing and sometimes even requires reflection. Future versions of Scala will specialize the Array class and then we should see some improvement. But right now that's what it is.If you go from arrays to vectors, you notice several things. First, the reduce version is now faster than the imperative loop! This is because vector reduce can make use of efficient bulk operations. Second, vector reduce is faster than array reduce, which illustrates the inherent overhead that arrays of primitive types pose for generic higher-order functions.If you eliminate the overhead of boxing/unboxing by working only with boxed java.lang.Double values, the picture changes. Now reduce over arrays is a bit less than 2 times slower than looping, instead of the 15 times difference before. That more closely approximates the inherent overhead of the three loops with intermediate data structures instead of the fused loop of the imperative version. Looping over vectors is now by far the slowest solution, whereas reducing over vectors is a little bit slower than reducing over arrays.So the overall answer is: it depends. If you have tight loops over arrays of primitive values, nothing beats an imperative loop. And there's no problem writing the loops because they are neither longer nor less comprehensible than the functional versions. In all other situations, the FP solution looks competitive.This is a microbenchmark, and it depends on how the compiler optimizes you code. You have 3 loops composed here,zip . map . foldNow, I'm fairly sure the Scala compiler cannot fuse those three loops into a single loop, and the underlying data type is strict, so each (.) corresponds to an intermediate array being created. The imperative/mutable solution would reuse the buffer each time, avoiding copies.Now, an understanding of what composing those three functions means is key to understanding performance in a functional programming language -- and indeed, in Haskell, those three loops will be optimized into a single loop that reuses an underlying buffer -- but Scala cannot do that.There are benefits to sticking to the combinator approach, however -- by distinguishing those three functions, it will be easier to parallelize the code (replace map with parMap etc). In fact, given the right array type, (such as a ) a sufficiently smart compiler will be able to automatically parallelize your code, yielding more performance wins.So, in summary:Don Stewart has a fine answer, but   I'll add to his answer that Scala compiles to JVM bytecodes, and not only does the Scala compiler not fuse the three loops into one, but the Scala compiler is almost certainly allocating all the intermediate arrays.  Notoriously, .  Allocation is a significant cost in functional programs, and that's one the loop-fusion transformations that Don Stewart and his colleagues have implemented for Haskell are so powerful: they eliminate lots of allocations.  When you don't have those transformations, plus you're using an expensive allocator such as is found on a typical JVM,  that's where the big slowdown comes from.Scala is a great vehicle for experimenting with the expressive power of an unusual mix of language ideas: classes, mixins, modules, functions, and so on.  But it's a relatively young research language, and it runs on the JVM, so it's unreasonable to expect great performance except on the kind of code that JVMs are good at.  If you want to experiment with the mix of language ideas that Scala offers, great\u2014it's a really interesting design\u2014but don't expect the same performance on pure functional code that you'd get with a mature compiler for a functional language, like  or ..  Stuff to do with first-class functions, pattern matching, and currying need not be especially slow.  But with Scala, more than with other implementations of other functional languages, you really have to \u2014they can be very expensive.The Scala collections library is fully generic, and the operations provided are chosen for maximum capability, not maximum speed.  So, yes, if you use a functional paradigm with Scala without paying attention (especially if you are using primitive data types), your code will take longer to run (in most cases) than if you use an imperative/iterative paradigm without paying attention.That said, you can easily create non-generic functional operations that perform quickly for your desired task.  In the case of working with pairs of floats, we might do the following:and then these operations will be much faster.  (Faster still if you use Double and 2.8.RC1, because then the functions  will be specialized, not generic; if you're using something earlier, you can create your own   and then call with  instead of .)Anyway, the point is that it's not the functional style that makes functional coding in Scala slow, it's that the library is designed with maximum power/flexibility in mind, not maximum speed.  This is sensible, since each person's speed requirements are typically subtly different, so it's hard to cover everyone supremely well.  But if it's something you're doing more than just a little, you can write your own stuff where the performance penalty for a functional style is extremely small.I am not an expert Scala programmer, so there is probably a more efficient method, but what about something like this. This can be tail call optimized, so performance should be OK.To answer the question in the title: Simple functional constructs may be slower than imperative on the JVM.But, if we consider only simple constructs, then we might as well throw out all modern languages and stick with C or assembler. If you look a the programming language shootout, C always wins.So why choose a modern language? Because it lets you express a cleaner design. Cleaner design leads to performance gains in the overall operation of the application. Even if some low-level methods can be slower. One of my favorite examples is the performance of BuildR vs. Maven. BuildR is written in Ruby, an interpreted, slow, language. Maven is written in Java. A build in BuildR is twice as fast as Maven. This is due mostly to the design of BuildR which is lightweight compared with that of Maven. Your functional solution is slow because it is generating unnecessary temporary data structures. Removing these is known as deforesting and it is easily done in strict functional languages by rolling your anonymous functions into a single anonymous function and using a single aggregator. For example, your solution written in F# using ,  and :may be rewritten using  so as to avoid all temporary data structures:This is a  faster and the same transformation can be done in Scala and other strict functional languages. In F#, you can also define the  as  in order to have the higher-order function inlined with its functional argument whereupon you recover the optimal performance of the imperative loop.Here is dbyrnes solution with arrays (assuming Arrays are to be used) and just iterating over the index:That needs about 1/40 of the time of the list-approach. I don't have 2.8 installed, so you have to test @tailrec yourself. :)"},
Scala

What changes to the JVM would most benefit the Scala compiler and runtime?The dynamic languages will benefit greatly in performance from the introduction of the  byte code scheduled to arrive in JVM 7 and Scala will probably benefit from tail recursion (not sure if it will appear in JVM 8 or later).What other changes could Scala, with its present feature set, benefit from in the JVM? Are these changes on the horizon?Specifically, are there changes to the JVM that would improve performance with closures and functions-as-objects?Basically, everything that John Rose has been campaigning for :)Reification is often quoted as something that would benefit Scala's pattern matching, but this would come at a high cost in terms of interop, given the different variance schemes that the two languages use.  At this point, I believe that reification may actually cause more harm than it would do good.I also think it unreasonable to expect anything that would break backwards compatibility in Java.  That just ain't gonna happen.There are a couple of features of Scala that would be better implemented in the JVM, such has:EDIT: Added declaration-site variance to list.Value types would help quite a bit performance wise for tuples and case classes. Escape analysis helps reduce heap allocations of such objects a bit, but at the moment the JVM can't inline some method calls aggressively enough thus can't eliminate heap allocations for these small immutable objects. This leads to heap trashing and 3-4x higher execution time.Value types also helps increase data locality and reduce memory usage. For example, in a simple Array[(Int, Int)] each array entry will have an overhead of one pointer + object header. With value types this overhead could be eliminated completely.People often focus on InvokeDynamic - without realizing that the MethodHandles framework has plenty of other advantages, even if the method references that MH provides are never dynamically invoked. MethodHandles are almost like a performant form of \"Reflection done right\".Any language which makes heavy use of reflection may well be able to get benefits from using MethodHandles inside the language runtime."},
Scala

When I'm working with libraries that support type-level programming, I often find myself writing comments like the following (from  presented by ):Or this, from  in the  repository:This is a very rough way of indicating some fact about the behavior of these methods, and we could imagine wanting to make these assertions more formal\u2014for unit or regression testing, etc.To give a concrete example of why this might be useful in the context of a library like Shapeless, a few days ago I wrote the following as a quick first attempt at an answer to :Where the intention is that this will compile:While this will not:I was surprised to find that this implementation of a type-level  for  didn't work, because Shapeless would happily find a  instance in the latter case. In other words, the following would compile, even though you'd probably expect it not to:In this case, what I was seeing was \u2014or at least something bug-ish\u2014and it .More generally, we can imagine wanting to check the kind of invariant that was implicit in my expectations about how   work with something like a unit test\u2014as weird as it may sound to be talking about testing type-level code like this, with all the recent debates about the relative merit of types  tests.The problem is that I don't know of any kind of testing framework (for any platform) that allows the programmer to assert that something must not .One approach that I can imagine for the  case would be to use the old :Which would let you write the following in your unit test:The following would be a heck of a lot more convenient and expressive, though:I want this. My question is whether anyone knows of any testing library or framework that supports anything remotely like it\u2014ideally for Scala, but I'll settle for anything.Not a framework, but Jorge Ortiz () mentioned some utilities he added to the tests for Foursquare's Rogue library at NEScala in 2012 which support tests for non-compilation: you can find examples . I've been meaning to add something like this to shapeless for quite a while.More recently, Roland Kuhn () has added a similar mechanism, this time using Scala 2.10's runtime compilation, to the .These are both dynamic tests of course: they fail at (test) runtime if something that shouldn't compile does. Untyped macros might provide a static option: ie. a macro could accept an untyped tree, type check it and throw a type error if it succeeds). This might be something to experiment with on the macro-paradise branch of shapeless. But not a solution for 2.10.0 or earlier, obviously.Since answering the question, another approach, due to Stefan Zeiger (), . This one is interesting because, like the untyped macro one alluded to above, it is a compile time rather than (test) runtime check, however it is also compatible with Scala 2.10.x. As such I think it is preferable to Roland's approach.I've now added implementations to shapeless for , for  and for . Examples of the corresponding tests can be found ,  and .The untyped macro tests are the cleanest, but Stefan's 2.10.x compatible approach is a close second.ScalaTest 2.1.0 has the following syntax for :And for :Do you know about  in the Scala project? E.g.  has the following doc:It is able to check for example whether this source  will have this result It's not a perfect fit for your question (since you don't specify your test cases in terms of asserts), but may be an approach and/or give you a head start.Based on the links provided by  I was able to use the akka versionThen in my tests I used it like thisThe  macro in \u00b5Test does just that:"},
Scala

I have the following setup of a Scala application and a common core library:\nrootI want to add a reference from ApplicationA to CoreLibrary \u00e0 la Eclipse project reference, so that every time CoreLibrary changes ApplicationA is built as well. I\u00b4ve tried the following contents of build.Scala for ApplicationA:However, when compiling ApplicationA SBT complains that a dependency can only be a subdirectory!!:This seems completely straightforward, what's the correct way of having this project dependency?You can do a source dependency on your project like that : I have a working example with a multimodule play build : But I think the proper way (it depends of your context) of doing it is to create a referencing the two projects and the dependencies between them.With sbt 0.12.1 it seems possible to get a simple reference to a project :I used  instead of sbt-eclipse also works.Since , you may create multi-project definitions directly in  without needing a  file.So adding the following to   would be sufficient."},
Scala

When I read the source of scalatra, I found there are some code like:There is an interesting class named . I've looked at the doc of this class, but I don't know when and why we should use it? It has a  which is usually be used.If we don't use it, then what code we should use instead, to solve the problem it solved?(I'm new to scala, if you can provide some code, that will be great) is an implementation of the loan and dynamic scope patterns. Use-case of  is pretty much similar to  in Java (as a matter of fact,  uses  behind the scenes) - it's used, when you need to do a computation within an enclosed scope, where every thread has it's own copy of the variable's value:Given that  uses an inheritable , value of the variable is passed to the threads spawned in the context: (and ) is used in Scalatra for the same reason it's used in many other frameworks (Lift, Spring, Struts, etc.) - it's a non-intrusive way to store and pass around context(thread)-specific information. Making  and  dynamic variables (and, thus, binding to a specific thread that processes request) is just the easiest way to obtain them anywhere in the code (not passing through method arguments or anyhow else explicitly).This is well answered by Vasil, but I'll add an additional simple example that might further help understanding.Suppose we must use some code that uses println() to write all over stdout.  We want this output to go to a log file, but we don't have access to the source.We can use this to simply fix our issue:This is a minimal snippet:The output will be:"},
Scala

I am trying to learn Scala now, with a little bit of experience in Haskell. One thing that stood out as odd to me is that all function parameters in Scala  be annotated with a type - something that Haskell does not require. Why is this? To try to put it as a more concrete example: an add function is written like this:But, this only works for doubles(well, ints work too because of the implicit type conversion). But what if you want to define your own type that defines its own  operator. How would you write an add function which works for any type that defines a  operator?Haskell uses Hindley-Milner type inference algorithm whereas Scala, in order to support Object Oriented side of things, had to forgo using it for now.In order to write an add function for all applicable types easily, you will need to use Scala 2.8.0:In order to solidify the concept of using  for myself, I wrote an example that does not require scala 2.8, but uses the same concept. I thought it might be helpful for some.\nFirst, you define an generic-abstract class :Now you can write the  function like this:This is used like a type class in Haskell. Then to  this generic class for a specific type, you would write(examples here for Int, Double and String):At this point you can call the  function with all three types:Certainly not as nice as Haskell which will essentially do all of this for you. But, that's where the trade-off lies.Haskell uses the  type inference. This kind of type-inference is powerful, but limits the type system of the language. Supposedly, for instance, subclassing doesn't work well with H-M.At any rate, Scala type system is too powerful for H-M, so a more limited kind of type inference must be used.I think the reason Scala requires the type annotation on the parameters of a newly defined function comes from the fact that Scala uses a more local type inference analysis than that used in Haskell.If all your classes mixed in a trait, say , that declared the  operator, you could write your generic add function as:This restricts the add function to types T that implement the Addable trait.Unfortunately, there is not such trait in the current Scala libraries. But you can see how it would be done by looking at a similar case, the  trait. This trait declares comparison operators and is mixed in by the , , etc. classes. Then you can write a sort function that can take, for example, a  where  to sort a list of elements that mix in the ordered trait. Because of implicit type conversions like  to , you can even use your sort function on lists of , or  or .As I said, unfortunately, there is no corresponding trait for the  operator. So, you would have to write out everything yourself. You would do the Addable[T] trait, create , , etc., classes that extend Int, Float, etc. and mix in the Addable trait, and finally add implicit conversion functions to turn, for example, and Int into an , so that the compiler can instantiate and use your add function with it.The function itself will be pretty straightforward:Better yet, you can just overload the + method:There's a missing piece, though, which is the type parameter itself.  As written, the method is missing its class. The most likely case is that you're calling the + method on an instance of T, passing it another instance of T.  I did this recently, defining a trait that said, \"an additive group consists of an add operation plus the means to invert an element\"Then, later, I define a Real class that knows how to add instances of itself (Field extends GroupAdditive):That may be more than you really wanted to know right now, but it does show both how to define generic arguments and how to realize them.Ultimately, the specific types aren't required, but the compiler does need to know at least the type bounds."},
Scala

Is there a way, only using the Scala collection API, to get an Option in a List when trying to get an element by its index?I'm looking for the equivalent of this function, does it exist?ThanksYes, you can lift your collection to a function :"},
Scala

I was taught about  at university, but I was disappointed how they didn't seem to be used in the real word.I like the idea of being able to know that some code (object, function, whatever) works, not by testing, but by .I'm sure we're all familiar with the parallels that don't exist between physical engineering and software engineering (steel behaves predictably, software can do anything - who knows!), and I would love to know if there are any languages that can be use in the real word (is asking for a web framework too much to ask?)I've heard interesting things about the testability of functional languages like scala.As software  what options do we have?Yes, there are languages designed for writing provably correct software. Some are even used in industry.  is probably the most prominent example. I've talked to a few people at Praxis Critical Systems Limited who used it for code running on Boings (for engine monitoring) and it seems quite nice. (Here is a great .) This language and accompanying proof system uses the second technique described below. It doesn't even support dynamic memory allocation!My impression and experience is that there are two techniques for writing correct software:Note that both approaches hinges on the fact you have a formal specification at hand (how else would you tell what is correct / incorrect behavior), and a formally defined semantics of the language (how else would you be able to tell what the actual behavior of your program is).Here are a few more examples of formal approaches. If it's \"real-world\" or not, depends on who you ask :-)I know of only one \"provably correct\" : . A Ur-program that \"goes through the compiler\" is guaranteed not to:In order to answer this question, you really need to define what you mean by \"provable\".  As Ricky pointed out, any language with a type system is a language with a built-in proof system which runs every time you compile your program.  These proof systems are almost always sadly impotent \u2014 answering questions like  vs  and avoiding questions like \"is the list sorted?\" \u2014 but they are proof systems none-the-less.Unfortunately, the more sophisticated your proof goals, the harder it is to work with a system which can check your proofs.  This escalates pretty quickly into undecidability when you consider the sheer size of the class of problems which are undecidable on Turing Machines.  Sure, you can theoretically do basic things like proving the correctness of your sorting algorithm, but anything more than that is going to be treading on very thin ice.Even to prove something simple like the correctness of a sorting algorithm requires a comparatively sophisticated proof system.  (note: since we have already established that type systems are a proof system built into the language, I'm going to talk about things in terms of type theory, rather than waving my hands still more vigorously)  I'm fairly certain that a full correctness proof on list sorting would require some form of dependent types, otherwise you have no way of referencing relative values at the type level.  This immediately starts breaking into realms of type theory which have been shown to be undecidable.  So, while you may be able to prove correctness on your list sorting algorithm, the only way to do it would be to use a system which will also allow you to express proofs which it cannot verify.  Personally, I find this very disconcerting.There is also the ease-of-use aspect which I alluded to earlier.  The more sophisticated your type system, the less pleasant it is to use.  That's not a hard and fast rule, but I think it holds true for the most part.  And as with any formal system, you will often find that expressing the proof is more work (and more error prone) than creating the implementation in the first place.With all that out of the way, it's worth noting that Scala's type system (like Haskell's) is Turing Complete, which means that you can  use it to prove any decidable property about your code, provided that you have written your code in such a way that it is amenable to such proofs.  Haskell is almost certainly a better language for this than Java (since type-level programming in Haskell is similar to Prolog, while type-level programming in Scala is more similar to SML).  I don't advise that you use Scala's or Haskell's type systems in this way (formal proofs of algorithmic correctness), but the option is theoretically available.Altogether, I think the reason you haven't seen formal systems in the \"real world\" stems from the fact that formal proof systems have yielded to the merciless tyranny of pragmatism.  As I mentioned, there's so much effort involved in crafting your correctness proofs that it's almost never worthwhile.  The industry decided a long time ago that it was easier to create ad hoc tests than it was to go through any sort of analytical formal reasoning process.Typed languages prove the absence of certain categories of fault.  The more advanced the type system, the more faults they can prove the absence of.For proof that a whole program works, yes, you're stepping outside the boundaries of ordinary languages, where mathematics and programming meet each other, shake hands and then proceed to talk using Greek symbols about how programmers can't handle Greek symbols.  That's about the \u03a3 of it anyway.You're asking a question a lot of us have asked over the years.  I don't know that I have a good answer, but here are some pieces:An interesting question to ask, I think, is what would sufficient conditions be to get formal approaches into practice?  I'd love to hear some suggestions.You can investigate  like Haskell, which are used when one of your requirements is . is a fun read if you're interested about functional programming languages and pure functional programming languages.real world uses of such provable languages would be incredibly difficult to write and understand afterwoods.\nthe business world needs working software, fast.\"provable\" languages just dont scale for writing/reading a large project's code base and only seem to work in small and isolated use cases.I'm involved in two provable languages. The first is the language supported by Perfect Developer, a system for specifying sotfware, refining it and generating code. It's been used for some large systems, including PD itself, and it's taught in a number of universities. The second provable language I'm involved with is a provable subset of MISRA-C, see  for more.Scala is meant to be \"real world\", so no effort has been made to make it provable. What you can do in Scala is to produce functional code. Functional code is much easier to test, which is IMHO a good compromise between \"real world\" and provability.EDIT =====\nRemoved my incorrect ideas about ML being \"provable\".Check out .This  contains a relatively painless implementation of AVL trees with included correctness proof.My (controversial) definition of \"real-world\" in the context of provably-correct code is:The above are relatively more universal requirements. Others, such as the ability to model imperative code, or the ability to prove higher-order functions correct, may be important or essential for some tasks, but not all.In view of these points, many of the tools listed in  may be useful - although they are nearly all either new and experimental, or unfamiliar to the vast majority of industry programmers. There are some very mature tools covered there though.How about  and ? Real world enough?As a good real life example, there's a project that aims to provide a verified HTTP REST library written in Agda, called Lemmachine: "},
Scala

In C# you can write:How would this simple  look like in Scala?The  pattern is the analogous construction:Per @Daniel Spiewak's comments, this will avoid reflection on method invocation, aiding performance:Since version 2.10 of Scala, it is possible to make an entire class eligible for implicit conversionIn addition, it is possible to avoid creating an instance of the extension type by having it extend AnyValFor more information on implicit classes and AnyVal, limitations and quirks, consult the official documentation:This would be the code after Daniel's  .In Scala we use the so-called (by the inventor of the language)  pattern, which is much discussed and pretty easy to find on the Web, if you use a string (not keyword) search."},
Scala

Suppose I have two arrays: Now for each element of , I want to first concatenate that element with the corresponding element of , and then print the result. One way to do would be something like:It would have been nicer if there was a  variant that would allow me to work directly with the indices of  instead of first constructing the integer list.Perhaps there is a better way?One very convenient way to do this is with the  method on tuples.  Put two collections in, get out two arguments to a function!This is both convenient to write and fast, since you don't need to build a tuple to store each pair (as you would with ) which you then have to take apart again.  Both forms of zip stop when the shorter of the two collections is exhausted.If you have something more complicated (e.g. you need to do math on the index), the canonical solution is to zip in the index:The method you are using is more rapidly and compactly done as follows, an can be useful:although this only works if the first collection is no longer than the second.  You can also specify your ranges explcitly:to get around this problem.  (You can see why  and  are preferred unless what you're doing is too complicated for this to work easily.)If it is not a parallel collection (and usually it is not unless you call ), it's also possible, though not recommended, to keep track with a mutable variable:There are a very limited number of cases where this is necessary (e.g. if you may want to skip or backtrack on some of the other collection(s)); if you can avoid having to do this, you'll usually end up with code that's easier to reason about.This is how you loop with an index in idiomatic Scala:And here is the idiomatic Scala way to do what you are trying to achieve in your code:I did not had the opportunity to test it, but this should do the trick: will do it:This will yield:Note that you don't need  generic type, will be infered by the compiler:"},
Scala

I am trying to put a Google map inside a scroll view, so that the user can scroll down other contents to see the map. The problem is that this scroll view is eating up all the vertical touching events, so the UI experience of map becomes very weird.I know that in V1 of the google map, you could override onTouch, or setOnTouchListener to call requestDisallowInterceptTouchEvent upon MotionEvent.ACTION_DOWN. I have tried to implement the similar trick with V2 to no avail.So far I have tried:None of these remedied the scrolling problem. Am I missing something here? If anyone has a working example of a map inside scrolling view, could you please kindly share code example?Apply a transparent image over the mapview fragment.Then set  for the main ScrollView. When the user touches the transparent image and moves disable the touch on the transparent image for  and  so that map fragment can take Touch Events.This worked for me. Hope it helps you..I encountered a similar problem and came up with a more general working solution based on In-Ho Yi and \u0414\u0430\u043d\u0430\u0438\u043b \u0414\u0438\u043c\u0438\u0442\u0440\u043e\u0432 answers above.Thank you for suggestions,After much try-and-error, pulling off my hairs and swearing at monitor and my poor Android test phone, I've figured that if I customise ScrollView, override onInterceptTouchEvent in which we return false when the event is on a map view no matter what, then the scrolling on a map does happen as expected.This code is in Scala but you get the idea. Note I've ended up using a raw map view (as shown in android-sdks\\extras\\google\\google_play_services\\samples\\maps\\src\\com\\example\\mapdemoRawMapViewDemoActivity.java). Guess you can do the pretty much same thing with fragments, I just never liked fragments in the first place.I think Google owes me an apology.I had the same issue, so here is how I used the solution as java code just in case anyone needs it. You just have to set the mapView field when using it.The accepted answer did not work in my case. The Guest's answer did neither (but almost). If this is the case for someone else try this edited version of the Guest's answer.I have commented out the action bar height if someone needs to use it when calculating the hitbox.Improving code if you do not need transparent Image again:Most of the options listed above did not work for me but the following proved to be a great solution to the problem for me:I also had to implement is slightly differently for my implementation, as I am using the map in a fragment which made things slightly more complicated but easy to get working."},
Scala

Am I right understanding thatYes, though for the 3rd one I would say \"when that statement is executed\", because, for example:This gives .  is never evaluated and its error is never thrown. But it is in scope as soon as control enters the block.Yes, but there is one nice trick: if you have lazy value, and during first time evaluation it will get an exception, next time you'll try to access it will try to re-evaluate itself.Here is example:One good reason for choosing  over , especially in abstract classes (or in traits that are used to mimic Java's interfaces), is, that you can override a  with a  in subclasses, but not the other way round.Regarding , there are two things I can see that one should have in mind. The first is that  introduces some runtime overhead, but I guess that you would need to benchmark your specific situation to find out whether this actually has a significant impact on the runtime performance. The other problem with  is that it possibly delays raising an exception, which might make it harder to reason about your program, because the exception is not thrown upfront but only on first use.I would like to explain the differences through the example that i executed in REPL.I believe this simple example is easier to grasp and explains the conceptual differences.Here,I am creating a val result1, a lazy val result2 and a def result3 each of which has a type String.Here, println is executed because the value of result1 has been computed here. So, now result1 will always refer to its value i.e \"returns val\".So, now, you can see that result1 now refers to its value. Note that, the println statement is not executed here because the value for result1 has already been computed when it was executed for the first time. So, now onwards, result1 will always return the same value and println statement will never be executed again because the computation for getting the value of result1 has already been performed.As we can see here, the println statement is not executed here and neither the value has been computed. This is the nature of lazyness.Now, when i refer to the result2 for the first time, println statement will be executed and value will be computed and assigned.Now, when i refer to result2 again, this time around, we will only see the value it holds and the println statement wont be executed. From now on, result2 will simply behave like a val and return its cached value all the time.In case of def, the result will have to be computed everytime result3 is called. This is also the main reason that we define methods as def in scala because methods has to compute and return a value everytime it is called inside the program.You are correct. For evidence from :From \"3.3.1 Method Types\" (for ):From \"4.1 Value Declarations and Definitions\": defines a method. When you call the method, the method ofcourse runs. defines a value (an immutable variable). The assignment expression is evaluated when the value is initialized. defines a value with delayed initialization. It will be initialized when it's first used, so the assignment expression will be evaluated then.A name qualified by def is evaluated by replacing the name and its RHS expression every time the name appears in the program. Therefore, this replacement will be executed every where the name appears in your program.A name qualified by val is evaluated immediately when control reaches its RHS expression. Therefore, every time the name appears in the expression, it will be seen as the value of this evaluation. A name qualified by lazy val follows the same policy as that of val qualification with an exception that its RHS will be evaluated only when the control hits the point where the name is used for the first timeShould point out a potential pitfall in regard to usage of val when working with values not known until runtime.Take, for example, If you were to say:You would get a null pointer exception as at the point of initialization of the , request has no foo (would only be know at runtime).So, depending on the expense of access/calculation, def or lazy val are then appropriate choices for runtime-determined values; that, or a val that is itself an anonymous function which retrieves runtime data (although the latter seems a bit more edge case)"},
Scala

I just wonder why there is no  to increase a number. As what I know, languages like Ruby or Python doesn't support it because they are dynamically typed. So it's obviously we cannot write code like  because maybe  is a string or something else. But Scala is statically typed - the compiler absolutely can infer that if it is legal or not to put  behind a variable.So, why doesn't  exist in Scala?Scala doesn't have  because it's a functional language, and in functional languages, operations with side effects are avoided (in a purely functional language, no side effects are permitted at all). The side effect of  is that  is now 1 larger than it was before. Instead, you should try to use immutable objects (e.g.  not ).Also, Scala doesn't really need  because of the control flow constructs it provides. In Java and others, you need  often to construct  and  loops that iterate over arrays. However, in Scala, you can just say what you mean:  or  or something along those lines.  is useful in imperative programming, but when you get to a higher level, it's rarely necessary (in Python, I've never found myself needing it once).You're spot on that   be in Scala, but it's not because it's not necessary and would just clog up the syntax. If you really need it, say , but because Scala calls for programming with immutables and rich control flow more often, you should rarely need to. You certainly could define it yourself, as operators are indeed just methods in Scala.Of course you can have that in Scala, if you really want:And here you go:No need to resort to violence against variables.Scala is perfectly capable of parsing  and, with a small modification to the language, could be made to modify a variable.  But there are a variety of reasons not to.First, it saves only one character,  vs. , which is not very much savings for adding a new language feature.Second, the  operator is widely used in the collections library, where  takes collection  and  and produces a new collection that contains both.Third, Scala tries to encourage you, without forcing you, to write code in a functional way.   is a mutable operation, so it's inconsistent with the idea of Scala to make it especially easy.  (Likewise with a language feature that would allow  to mutate a variable.)Scala doesn't have a  operator because it is not possible to implement one in it.: As just pointed out in response to this answer, Scala 2.10.0  implement an increment operator through use of macros. See  for details, and take everything below as being pre-Scala 2.10.0. Let me elaborate on this, and I'll rely heavily on Java, since it actually suffers from the same problem, but it might be easier for people to understand it if I use a Java example.To start, it is important to note that one of the goals of Scala is that the \"built-in\" classes must not have any capability that could not be duplicated by a library. And, of course, in Scala an  is a class, whereas in Java an  is a primitive -- a type entirely distinct from a class.So, for Scala to support  for  of type , I should be able to create my own class  also supporting the same method. This is one of the driving design goals of Scala.Now, naturally, Java does not support symbols as method names, so let's just call it . Our intent then is to try to create a method  such that  works just like .Here's a first pass at it:We can test it with this:Everything seems to work, too:And, now, I'll show what the problem is. Let's change our demo program, and make it compare  to :As we can see in the output,  and  are behaving differently:The problem is that we implemented  by mutating , which is not how primitives work.  needs to be immutable, which means that  must produce a  object. Let's do a naive change:However, this doesn't work:The problem is that, while,   a new object, that new object hasn't been  to . There's no existing mechanism in Java -- or Scala -- that would allow us to implement this method with the exact same semantics as .Now, that doesn't mean it would be impossible for Scala to make such a thing . If Scala supported parameter passing by reference (see \"call by reference\" in ), like C++ does, then we  implement it!Here's a fictitious implementation, assuming the same by-reference notation as in C++.This would either require JVM support or some serious mechanics on the Scala compiler.In fact, Scala  something similar to what would be needed that when it create closures -- and one of the consequences is that the original  becomes boxed, with possibly serious performance impact.For example, consider this method:The code being passed to , , is  part of this method. The method  takes an  of the type  whose  method implements that little code. That means  is not only on a different method, it is on a different class altogether! And yet, it can change the value of  just like a  operator would need to.If we use  to look at it, we'll see this:Note that instead of creating an  local variable, it creates an  on the heap (at 0), which is boxing the . The real  is inside , as we see on 25. Let's see this same thing implemented with a while loop to make clear the difference:That becomes:No object creation above, no need to get something from the heap.So, to conclude, Scala would need additional capabilities to support an increment operator that could be defined by the user, as it avoids giving its own built-in classes capabilities not available to external libraries. One such capability is passing parameters by-reference, but JVM does not provide support for it. Scala does something similar to call by-reference, and to do so it uses boxing, which would seriously impact performance (something that would most likely come up with an increment operator!). In the absence of JVM support, therefore, that isn't much likely.As an additional note, Scala has a distinct functional slant, privileging immutability and referential transparency over mutability and side effects. The  purpose of call by-reference is to cause side effects ! While doing so can bring performance advantages in a number of situations, it goes very much against the grain of Scala, so I doubt call by-reference will ever be part of it.Other answers have already correctly pointed out that a  operator is neither particularly useful nor desirable in a functional programming language. I would like to add that since Scala 2.10, you can add a  operator, if you want to. Here is how:You need an implicit macro that converts ints to instances of something that has a  method. The  method is \"written\" by the macro, which has access to the variable (as opposed to its value) on which the  method is called. Here is the macro implementation:Now, as long as the implicit conversion macro is in scope, you can writeRafe's answer is true about the rationale for why something like i++ doesn't belong in Scala. However I have one nitpick. It's actually not possible to implement i++ in Scala without changing the language.In Scala, ++ is a valid method, and no method implies assignment. Only  can do that.Languages like C++ and Java treat  specially to mean both increment and assign. Scala treats  specially, and in an inconsistent way.In Scala when you write  the compiler first looks for a method called  on the Int. It's not there so next it does it's magic on  and tries to compile the line as if it read . If you write  then Scala will call the method  on  and assign the result to... nothing. Because only  means assignment. You could write  but that kind of defeats the purpose.The fact that Scala supports method names like  is already controversial and some people think it's operator overloading. They could have added special behavior for  but then it would no longer be a valid method name (like ) and it would be one more thing to remember.Quite a few languages do not support the ++ notation, such as Lua. In languages in which it is supported, it is frequently a source of confusion and bugs, so it's quality as a language feature is dubious, and compared to the alternative of  or even just , the saving of such minor characters is fairly pointless.This is not at all relevant to the type system of the language. While it's true that most static type languages do offer and most dynamic types don't, that's a correlation and definitely not a cause.Scala encourages using of FP style, which  certainly is not.The question to ask is why there should be such an operator, not why there shouldn't be.  Would Scala be improved by it?The  operator is single-purpose, and having an operator that can change the value of a variable can cause problems.  It's easy to write confusing expressions, and even if the language defines what  means, for example, that's a lot of detailed rules to remember.Your reasoning on Python and Ruby is wrong, by the way.  In Perl, you can write  or  just fine.  If  turns out to be something that can't be incremented, you get a run-time error.  It isn't in Python or Ruby because the language designers didn't think it was a good idea, not because they're dynamically typed like Perl.You could simulate it, though. As a trivial example:Add some implicit conversions and you're good to go. However, this sort of changes the question into: why isn't there a mutable RichInt with this functionality?"},
Scala

I have a parser that was written using Scala's  - It had some serious performance problems when parsing a grammar which had deeply nested expressions. As such I have created a version where I mix in Scala's  - The Packrat version does not exhibit the same performance issue and correctly parses the grammar. However, when I provide an invalid grammar for testing, e.g. The old (non-packrat) parser used to correctly report the 'Invalid rule' failure, via the  parser combinator  here - When using the packrat-parser version, if I enable tracing I can see from the trace that the failure is created just as it is in the non-packrat version, however the PackratParser seems to ignore this and always return  instead.Is there something different about failure handling when using PackratParsers which I need to understand?Seems that you need to use  instead of , as it guarantees that no backtracking will be performed."},
Scala

I've seen quite a   recently of the new  pattern matcher for scala. I missed the memo explaining what it actually was...The  pattern matcher is a rewrite of the existing matcher. The motivation for doing this was to support virtualization of pattern matching for the , not relevant for 2.10.As Iulian says in the comments below: The \"polymorphic embedded DSLs\" are the idea that one might write programs in scala that are not supposed to be run on the JVM. That is,  will produce an output which describes what the program is doing. This may then be re-compiled against a specific architecture. Such things .This rewrite will eventually become the standard scala pattern matcher. The old pattern matcher was (as I understand it) unmaintainable.Sadly, the (sole) existing answer is low on juicy bits, and the links on the commentary are broken. So let me try to add some juice here, for, if no other reason, my own reference when I actually decide to do something with it in the future, seeing as this answer is on top of every google search I do.The virtualized pattern matcher, as mentioned, is a rewrite of how the Scala compiler handles pattern matching. It served many purposes, with the \"virtualization\" part of it meaning it is part of the virtualized scala effort. That effort is a bit the opposite of macros: it takes things that are \"run\" at compile time, and move then to run time.For example, given the presence of the proper definition in scope, a statement like this:instead of being compiled to bytecode branches and literals, or even optimized to the literal \"2\", actually gets compiled as the following statement:Please see the  for more information and some examples of what this can be useful for.I said, however, that the pattern matcher rewrite served many purposes. One other very important goal was to turn the spaghetti code that was the old pattern matcher, full or special and corner cases and bugs, into something that can be reasoned with, extended and improved more easily. This rewrite fixed so many problems that people just went through the issues list running sample code for issues related to the pattern matcher and marking the issues as \"fixed\" as they worked. It does have new bugs of its own, but on a much, much smaller scale.Now, there's very little information about how the new pattern matcher works, but, basically, it translates into a few method calls which are \"implemented\" in the compiler with the  monad. That then goes into an optimization phase that produces optimal bytecode.It is possible to introduce your own matcher, though that's locked behind an  flag. Try the following code, copied from Scala's test suite, with and without that flag:The result without the flag is just what you'd expect:With , however, the alternative matching \"engine\" gets compiled:See also, for more information, the scaladocs for  and the .Disclaimer: the above was extract and ran from a Scala version on the master branch, after 2.10.0, so there may be differences. I find myself sadly lacking in a pure 2.10.0 or 2.10.1 environment to test it out, though."},
Scala

Just now I am surprised to learn that  produces a view. The consequence is shown in the following example:The idea is that I have a distribution, which is perturbed with some randomness then I renormalize it. The code actually fails in its original intention: since  produces a ,  is always re-evaluated whenever  is used.I am now doing something like , but that's just a little bit verbose. So the purpose of this question is:Thanks.There's a ticket about this,  (by YT).The commit that introduces it has this to say:I have not been able to find the original suggestion by jrudolph, but I assume it was done to make  more efficient. Give the question, that may come as a surprise, but   more efficient if you are not likely to iterate over the values more than once.As a work-around, one can do  to produce a new .The scala doc say:So this should be expected, but this scares me a lot, I'll have to review bunch of code tomorrow. I wasn't expecting a behavior like that :-(Just an other workaround:You can call  to get a copy, and if you need it back to map , but this unnecessary create objects, and have a performance implication over using One can relatively easy write, a  which doesn't create a view, I'll do it tomorrow and post the code here if no one do it before me ;)I found an easy way to 'force' the view, use '.map(identity)' after mapValues (so no need of implementing a specific function):It's a shame the type returned isn't actually a view! othewise one would have been able to call 'force' ..."},
Scala

 has  method, which can interrupt the thread, which runs the  task. For example, if I wrap an  blocking call in a  I can interrupt it later. provides no  method. Suppose I wrap an  blocking call in a . How can I interrupt it? This is not yet a part of the s API, but may be added as an extension in the future.As a workaround, you could use the  to wrap 2 futures - the future you want to cancel and a future that comes from a custom . You could then cancel the thus created future by failing the promise:Now you can call this on any future to obtain a \"cancellable wrapper\". Example use-case:EDIT:For a detailed discussion on cancellation, see Chapter 4 in the  book.I haven't tested this, but this expands on the answer of Pablo Francisco P\u00e9rez Hidalgo. Instead of blocking waiting for the java , we use an intermediate  instead.By cancelling I guess you would like to violently interrupt the .Found this segment of code: Did a few tests and seems to work fine!Enjoy :)I think it is possible to reduce the complexity of the implementations provided by making use of the  and its implementations. can build a Java future which is the one to be cancelled by its  method. Another future can wait for its completion thus becoming the observable interface which is itself immutable in state:"},
Scala

Is it possible to implement in Scala something equivalent to the Python  statement where it remembers the local state of the function where it is used and \"yields\" the next value each time it is called?I wanted to have something like this to convert a recursive function into an iterator. Sort of like this:Except,  may be more complex and recurs through some acyclic object graph.\nLet me add a more complex example (but still simple):\nI can write a simple recursive function printing things as it goes along:Ideally I would like to have a library that allows me to easily change a few statements and have it work as an Iterator:It does seem continuations allow to do that, but I just don't understand the  concept. Will continuation eventually make it into the main compiler and would it be possible to extract out the complexity in a library?\ncheck  in that other thread.While Python generators are cool, trying to duplicate them really isn't the best way to go about in Scala. For instance, the following code does the equivalent job to what you want:In it the stream is generated lazily, so it won't process any of the elements until asked for, which you can verify by running this:The result can be converted into an  simply by calling  on the resulting :The  definition, using , would be rendered thus:Another alternative would be concatenating the various iterators, taking care to not pre-compute them. Here's an example, also with debugging messages to help trace the execution:This is pretty close to your code. Instead of , I have definitions, and then I just concatenate them as I wish.So, while this is a non-answer, I just think you are barking up the wrong tree here. Trying to write Python in Scala is bound to be unproductive. Work harder at the Scala idioms that accomplish the same goals.Another continuations plugin based solution, this time with a more or less encapsulated Generator type,To do this in a general way, I think you need the .A naive implementation (freehand, not compiled/checked):What is happening is that any call to  captures the control flow from where it is called to the end of the  block that it is called in.  This is passed as the  argument into the shift function.So, in the example above, each  returns the value of  (up to that point) and saves the rest of the computation in the  variable.  It is driven from outside by the  and  methods.Go gentle, this is obviously a terrible way to implement this.  But it best I could do late at night without a compiler handy.Scala's for-loop of the form  translates into a  call, and not directly into  / .In the  we don't need to linearize objects' creations and have them in one place, as it would be needed for iterator's . The consumer-function  can be inserted multiple times, exactly where it is needed (i.e. where an object is created).This makes implementation of use cases for generators simple and efficient with  /  in Scala.The initial Foo-example:The initial printClass-example:Or with indentation:Output:"},
Scala

In Scala 2.10 how do I generate a class from string (probably, using the Toolbox api) later to be instantiated with Scala's reflection?W.r.t compilation toolboxes can only run expressions = return values, but not resulting classes or files/byte arrays with compilation results. However it's still possible to achieve what you want, since in Scala it's so easy to go from type level to value level using implicit values:. In 2.10.0-RC1 some methods of  have been renamed.  is now just , and  is now called .Update #1. If you don't need a java.lang.Class and just need to instantiate the compiled class, you can write  directly in the string submitted to .Update #2. It is also possible to have  use custom mapping from variable names to runtime values. For example:In this example I create a free term that has a value of 2 (the value doesn't have to be a primitive - it can be your custom object) and bind an identifier to it. This value is then used as-is in the code that is compiled and run by a toolbox.The example uses manual AST assembly, but it's possible to write a function that parses a string, finds out unbound identifiers, looks up values for them in some mapping and then creates corresponding free terms. There's no such function in Scala 2.10.0 though."},
Scala

I was just comparing the performance of scala actors vs java threads.I was amazed to see the difference, I observed that with my system I was able to spawn maximum ~2000 threads (live at a time) only But with the same system I was able to spawn ~500,000 actors of scala. Both programs used around 81MB of Heap memory of JVM.Can you explain How java thread are this much heavy weight than scala / akka actors?\nWhat is the key factor which made scala-actor this much light weight? Thanks.Scala actors (including the Akka variety) use Java threads.  There's no magic: more than a few thousand threads running simultaneously is a problem for most desktop machines.The Actor model allows for awake-on-demand actors which do not occupy a thread unless they have work to do.  Some problems can be modeled effectively as lots of sleeping agents waiting to get some work, who will do it relatively quickly and then go back to sleep.  In that case, actors are a very efficient way to use Java threading to get your work done, especially if you have a library like Akka where performance has been a high priority.The  explain the basics pretty well.All reasonably scalable web servers have to solve this sort of problem one way or another; you probably ought not be basing your decision for web server primarily on whether actors are used under the hood, and regardless of what you use you can always add actors yourself.An Akka actor is not equivalent to a thread. It is more like a  that is executed on a threadpool.When a message is dispatched to an actor, that actor is placed on a threadpool to process the message. When it is done, the pooled thread can be used to execute other actors."},
Scala

I was working with a variable that I had declared as an Integer and discovered that > is not a member of Integer. Here's a simple example:Compare that to an Int:What are the differences between Integer and Int? I see the deprecation warning but it's unclear to me why it was deprecated and, given that it has been, why it doesn't have a > method.\"What are the differences between Integer and Int?\"Integer is just an alias for java.lang.Integer.  Int is the Scala integer with the extra capabilities.Looking in Predef.scala you can see this the alias:However, there is an implicit conversion from Int to java.lang.Integer if you need it, meaning that you can use Int in methods that take an Integer.As to why it is deprecated, I can only presume it was to avoid any confusion over which kind of integer you were working with.I think the problem you're seeing has has to do boxing/unboxing of value types and the use of the Java class Integer.I think the answer is here: .  There is no implict unboxing in Scala.  You've defined  as the Java class Integer but in the , the 3 is being treated and an int. Integer gets imported from java.lang.Integer and is only for compatibility with Java. Since it is a Java class, of course it can't have a method called \"<\".\nEDIT: You can mitigate this problem by declaring an implicit conversion from Integer to Int.You'll still get deprecation warning though.Integer gets imported from java.lang.Integer and is only for compatibility with Java. Since it is a Java class, of course it can't have a method called \"<\". EDIT: You can mitigate this problem by declaring an implicit conversion from Integer to Int. is a Java class, . It's different from Java's primitive type , which is not a class. It can't have  defined, because Java does not allow operators to be defined for classes.Now, you might wonder why such a type exist at all? Well, primitive types cannot be passed as references, so you can't pass an  to a method expecting , equivalent to Scala's , for example. To do that, you put that  inside an  object, and then pass the ."},
Scala

What is the different between the following Generics definitions in Scala:and My gut tells me they are about the same but that the latter is more explicit. I am finding cases where the former compiles but the latter doesn't, but can't put my finger on the exact difference.Thanks!Can I throw another into the mix?OK, I figured I should have my take on it, instead of just posting comments. Sorry, this is going to be long, if you want the TLDR skip to the end.As Randall Schulz said, here  is a shorthand for an existential type. Namely,is a shorthand forNote that contrary to what Randall Shulz's answer mentions (full disclosure: I got it wrong too in an earlier version fo this post, thanks to Jesper Nordenberg for pointing it out) this not the same as:nor is it the same as:Beware, it is easy to get it wrong (as my earlier goof shows): the author of the article referenced by Randall Shulz's answer got it wrong himself (see comments), and fixed it later. My main problem with this article is that in the example shown, the use of existentials is supposed to save us from a typing problem, but it does not. Go check the code, and try to compile  or . Yep, does not compile. Simply making  generic in  would make the code compile, and it would be much simpler.\nIn short, that's probably not the best article to learn about existentials and what they are good for (the author himself acknowledge in a comment that the article \"needs tidying up\").So I would rather recommend reading this article: , in particular the sections named \"Existential types\" and \"Variance in Java and Scala\".The important point that you you should get from this article is that existentials are useful (apart from being able to deal with generic java classes) when dealing with non covariant types.\nHere is an example.This class is generic (note also that is is invariant), but we can see that  really don't make use of the type parameter (unlike ), so if I get an instance of  I should always be able to call it, whatever  is.  If I want to define a method that takes a  instance and just calls its  method, I could try this:Sure enough, this does not compile, as  comes out of nowhere here.OK then, let's make the method generic:Great, this works. We could also use existentials here:Works too. So all in all, there is no real benefit here from using an existential (as in ) over type parameter (as in ).However, this changes if  appears itself as a type parameter to another generic class. Say by example that we want to store several instances of  (with different ) in a list. Let's try it:The last line does not compile because  is invariant, so a  and  cannot be treated as a  even though  and  both extends .OK, let's try with an existential, using the shorthand notation :This compiles fine, and you can do, as expected:Now, remember that the reason we had a type checking problem in the first place was because  is invariant. If it was turned into a covariant class () then everything would have worked out of the box and we would never have needed existentials.So to sum up, existentials are usefull to deal with generic invariant classes, but if the generic class does not need to appear itself as a type parameter to another generic class, chances are that you don't need existentials and simply adding a type parameter to your method will workNow come back(at last, I know!) to your specific question, regardingBecause  is covariant, this is for all intents and purpose the same as just saying:So in this case, using either notation is really just a matter of style.However, if you replace  with , things change: is invariant and thus we are in the same situation as with the  class from my example. Thus the above really is very different fromThe former is a shorthand for an existential type when the code doesn't need to know what the type is or constrain it:This form says that the element type of  is unknown to  rather than your second form, which says specifically that the 's element type is .Check out this brief explanatory  on Existential Types in Scala."},
Scala

'map' preserves the number of elements, so using it on a Tuple seems sensible.My attempts so far:It looks quite painful... And I haven't even begun to try to convert it back to a tuple.\nAm I doing it wrong? Could the library be improved? Supports mapping and folding over tuples via an intermediary  representation,Sample REPL session,Where the elements of the tuple are of different types you can map with a polymorphic function with type-specific cases,As of shapeless  mapping over tuples is supported directly. The above examples now look like this,In general, the element types of a tuple aren't the same, so map doesn't make sense. You can define a function to handle the special case, though:You could use the Pimp My Library pattern to call this as .Even when the types of the elements are not the same,  is a , which can be mapped with the  operation."},
Scala

One thing I find quite confusing is knowing which characters and combinations I can use in method and variable names. For instanceAs I understand it, there is a distinction between  and . You can mix an match one or the other but not both, unless separated by an underscore (a ).From  section 6.10,So we are excluded from using  and `I looked up Unicode mathematical symbols on , but the ones I found didn't include , ,  etc. Is there a definitive list somewhere of what the operator characters are?Also, any ideas why Unicode mathematical operators (rather than symbols) do not count as operators?Working from the EBNF syntax in the spec:But also taking into account the very beginning on Lexical Syntax that defines:Here is what I come up with. Working by elimination in the range , eliminating letters, digits, parentheses and delimiters, we have for ... (drumroll):\nand also  and  - except for parentheses and periods.(Edit: adding valid examples here:). In summary, here are some valid examples that highlights all cases - watch out for  in the REPL, I had to escape as :I found this Unicode  to figure out :Other operator-looking things that are reserved words:  and also  \u21d2 and  \u2190. gives the rule in Chapter 1, lexical syntax (on page 3):This is basically the same as your extract of Programming in Programming in Scala.  is not an Unicode mathematical symbol, but it is definitely an  not listed above (not a letter, including _ or $, a digit, a paranthesis, a delimiter).In your list:"},
Scala

I would like to disable the color escape codes logged from sbt/play. Is this possible? And if it is, is there a way to do it without making changes to the config - i.e. via a command line switch or system property.You can simply set the system property  to . If you want to e.g. use SBT inside Vim you can create a script like this:Since version  (and possibly earlier) you can now simply use the  option to sbt. e.g.This sounds like your platform does not match the actual jline.terminal property. I am just guessing here but when I pass the parameter as Daniel suggested on a Windows command line I see the color escape codes as well.Therefore, you have to make sure the property matches your platform, i.e. WindowsTerminal on Windows and UnixTerminal on Unix.If this does not help, then you might be on an unsupported platform in which case the  suggests to use:Well, you can  colors on Windows by installing Cygwin and passing this parameter:So I'd look up jline parameters to see what disables color coding.I was able to get colored output from SBT in Cygwin by adding:Additionally I figured out that I also needed to add the following line to Cygwin.bat:After that is added SBT gives very nice colored output. Additionally I would recommend looking into Console2 as it can hook through Cygwin, but provides a much better interface in my opinion:"},
Scala

By day I write C#. Everything I do goes through Microsoft code analysis and static analysis tools, so my C# has a very regular structure and layout. Obviously, I write code with a certain style. It is partially, because I have no choice (it won't compile if I miss out a space before that comma), but it's also nice to have regular looking code, knowing where to look for things, etc.At the weekends I'm getting into Scala. Looking at the Scala API and  web framework source, I can't obviously see any standardised style. One thing that jumps out at me, for example, is the lack of a separate file per class. The lack of consistency with brackets and braces is another example.I understand that there are probably a few reasons driving this: firstly, with open source (or hobby) code making sure that an obvious method isn't completely documented is less of a priority. Secondly, things like case classes cut down 20-line class declarations into a single line. Thirdly, C# is a much 'flatter' language: unless it's a complex  statement, the numbers of nested parens, braces and brackets isn't that deep. In Scala, things tend to get a little nested.Do regular Scala users have a specific style that they stick to? Am I just being stupid putting a one-line case-class in its own file for the sake of [alien] convention? Any tips?Having multiple classes and objects inside a single file is considered good form in Scala, as long as the classes are tightly related.While not necessary, the type returned by a method -- a named function declared on a trait, class or object -- is expected to be declared for non-private methods. Spaces are expected after , but not before it. Spaces are expected between keywords and parenthesis, but not between a method name and the following parenthesis, in dot notation. For operator notation, there doesn't seem to be an accepted style regarding parenthesis -- or when to use that notation, for that matter, but spaces are expected around non-alphanumeric methods in such notation.Exceptionally, when concatenating strings with , the recommended style is not to use spaces around it. For example:Declarations that can be one-liners are expected to be one-liners, unless the nesting isn't obvious.Methods that do not expect parameters, and do not have side effects, are supposed to be used without parenthesis, except for Java methods, which are expected to be used with parenthesis. Parameter-less methods with side effects are supposed to be used with parenthesis.Declarations which contains a single expression are expected not to be enclosed inside curly braces unless other syntactic considerations make that impossible. Enclosing an expression within parenthesis to enable multi-line expressions is accepted, but I have seen little use of that.In for-comprehensions, keeping generators and conditions vertically aligned seems to be an accepted style. As for , I have seen it both aligned with  and indented.It's also accepted style to vertically align parameters of a class declaration. Speaking of indentation, two-spaces is the accepted convention.Curly braces are expected to start on the same line of the declaration, and end vertically aligned with that line by itself.For procedures -- functions whose return type is  --, the expected style was supposed to be to leave out the type of the method and the equal sign:Some people think this style is error prone, however, as a missed equal sign will change a function returning something other than  into a procedure.Identifiers are written in camel case (eg: ), like in Java. For names of fields, method parameters, local variables and functions, start with a lower case letter. For classes,traits and types, start with an upper case letter.Departing from Java convention are constant names. In Scala, the practice is to use standard camel case starting with an upper case letter. For example  and not , XOffset and not . This rule is usually followed by any singleton. Having a constants and singletons be represented that way has a practical consequence, for case matches:Package names are written beginning with a lower case letter. This is particularly helpful when distinguishing in an import statement what is a package and what is not. In the previous example,  is not a package (it's a singleton), as it begins with an upper case letter.Using the underline character --  -- is not recommended, as that character has many special meanings in Scala. These rules for identifiers can be found on pages 141 and 142 of Programming in Scala, by Odersky, Spoon & Venners.Right now, I can't recall other situations, but feel free to ask for clarification on specific points. Some of these rules were explicitly stated, others are more of a community consensus. I tried to leave out my own preferences, but I may have failed.More importantly, perhaps, there just isn't really much of an unified convention. One reason for that may be that Scala is attracting people from many very different backgrounds, such as functional language mavens, Java programmers and web 2.0 enthusiasts.There is now a full Scala style guide which has been .  It isn't even remotely official yet, but it is the only (to my knowledge) codification of the community-accepted conventions.Now  is available. It's not 100% official (located on \"\" site) but seems the most standard style guide for Scala.This is a very important question.  Generally, Scala style seems to be picked up just by hanging out with other members of the Scala community, reading Scala source code, etc.  That's not very helpful for newcomers to the language, but it does indicate that some sort of de facto standard  exist (as chosen by the wisdom of the masses).  I am currently working on a fully-realized style guide for Scala, one which documents the community-chosen conventions and best-practices.  However, a) it's not finished yet, and b) I'm not sure yet that I'll be allowed to publish it (I'm writing it for work).To answer your second question (sort of): in general, each class/trait/object should get its own file named according to Java naming conventions.  However, in situations where you have a lot of classes which share a single common concept, sometimes it is easiest (both in the short-term and in the long-term) to put them all into the same file.  When you do that, the name of the file should start with a lower-case letter (still camelCase) and be descriptive of that shared concept.I don't really care for the typical style that many of the Scala coders use, so I just apply the same standard I would using in C#, Java or especially JavaScript.Scala  be very expressive, but using an unfamiliar format will increase your barrier to entry.  Especially considering internal , which could not possibly have a \"Standard\".So, I say to do whatever make your code more readable to you and your team."},
Scala

I'm new to Scala and don't know Java. I want to create a jar file out of a simple Scala file. So I have my HelloWorld.scala, generate a HelloWorld.jar. Manifest.mf:In the console I run:Sample directory structure:HelloWorld.scala:MANIFEST.MF:build.bat:In order to successfully use the  switch, you need two entries in the  file: the main class; relative URLs to any dependencies. The documentation notes:For completeness, an equivalent bash script:Because Scala scripts require the Scala libraries to be installed, you will have to include the Scala runtime along with your JAR.There are many strategies for doing this, such as , but ultimately the issue you're seeing is that the Java process you've started can't find the Scala JARs.For a simple stand-alone script, I'd recommend using jar jar, otherwise you should start looking at a dependency management tool, or require users to install Scala .You can also use maven and the maven-scala-plugin. Once you set up maven, you can just do mvn package and it will create your jar for you. I ended up using , it is really simple to use. I added a file called  into the  directory at the root of the project with a one liner (Note your version might need to be changed).Then just run the  task in :It will first run your tests and then it will generate the new jar into the  directory (given that my  already lists all my dependencies).In my case, I just make that  file executable, rename to remove the extension and it is ready to ship!Also, if you are doing a command line tool, don't forget to add a  (I hate scripts without proper manpages or with multi-page plain text documentation that is not even piped into a pager for you).I don't want to write why's and how's rather just show the solution which worked in my case (via Linux Ubuntu command line):1) 2)  3)  3) 4)  5)I modified the bash script adding some intelligence including auto-manifest generation.This script assumes that the main object is named the same as the file it is in (case sensitive).  Also, either the current directory name must equal to the main object name or the main object name should be provided as a command line parameter.  Launch this script from the root directory of your project.  Modify the variables at the top as required.Be aware that the script will generate the bin and dist folders and will ERASE any existing contents in bin.One thing which may cause a similar problem (although it's not the problem in the initial question above) is that the Java vm seems to demand that the main method returns . In Scala we can write something like ():where main actually returns a -object (i.e. it's not ), but the program will run nicely when we start it using the scala command.If we package this code into a jar-file, with  as the Main-Class, the Java vm will complain that there's no main function, since the return type of our main is not  (I find this complaint somewhat strange, since the return type is not part of the signature).We would have no problems if we left out the =-sign in the header of main, or if we explicitly declared it as .I tried to reproduce MyDowell's method. Finally I could make it work. However I find that the answer though correct a bit too complicated for a novice ( in particular the directory structure is unnecessarily complicated ).I can reproduce this result with very simplistic means. To start with there is only one directory which contains three files:helloworld.scalaMANIFEST.MF:first compile helloworld.scala:then create the jar:now you can run it with:I found this simple solution because the original one did not work. Later I found out that not because it is wrong, but because of a trivial error: if I don't close the second line in MANIFEST.MF with a newline, then this line will be ignored. This took me an hour to find out and I tried all other things before, in the process finding this very simple solution.If you do not wish to use sbt facilities I recommend the use of a makefile.Here is an example  where  package is replaced by  for completeness.makefile"},
Scala

I need to check if a string is present in a list, and call a function which accepts a boolean accordingly.Is it possible to achieve this with a one liner?The code below is the best I could get:I'm sure it's possible to do this with less coding, but I don't know how!Just use And if you didn't want to use strict equality, you could use exists:this should work also with different predicate    In your case I would consider using Set and not List, to ensure you have unique values only. unless you need sometimes to include duplicates.In this case, you don't need to add any wrapper functions around lists."},
Scala

I'm new to spark. I want to perform some operations on particular data in a CSV record.I'm trying to read a CSV file and convert it to RDD. My further operations are based on the heading provided in CSV file.(From comments)\nThis is my code so far:I can get the header values like this. I want to map this to each record in CSV file.I can get the header values like this. I want to map this to each record in CSV file.In java I\u2019m using  to get the particular value. I need to do something similar to that here.A simplistic approach would be to have a way to preserve the header.Let's say you have a file.csv like:We can define a header class that uses a parsed version of the first row:That we can use that header to address the data further down the road:Note that the  is not much more than a simple map of a mnemonic to the array index. Pretty much all this could be done on the ordinal place of the element in the array, like PS: Welcome to Scala :-)You can use the spark-csv library: This is directly from the documentation: Firstly I must say that it's much much simpler if you put your headers in separate files - this is the convention in big data.Anyway Daniel's answer is pretty good, but it has an inefficiency and a bug, so I'm going to post my own. The inefficiency is that you don't need to check every record to see if it's the header, you just need to check the first record for each partition.  The bug is that by using  you could get an exception thrown or get the wrong column when entries are the empty string and occur at the start or end of the record - to correct that you need to use .  So here is the full code:Final points, consider Parquet if you want to only fish out certain columns.  Or at least consider implementing a lazily evaluated split function if you have wide rows.We can use the new DataFrameRDD for reading and writing the CSV data.\nThere are few advantages of DataFrameRDD over NormalRDD:You will be required to have this library: Add it in build.sbtSpark Scala code for it:To convert to normal RDD by taking some of the columns from it and Saving the RDD to CSV format:Since the header is set to true we will be getting the header name in all the output files.I'd recommend reading the header directly from the driver, not through Spark. Two reasons for this: 1) It's a single line. There's no advantage to a distributed approach. 2) We need this line in the driver, not the worker nodes.It goes something like this:Now when you make the RDD you can discard the header.Then we can make an RDD from one column, for example:Here is another example using Spark/Scala to . For a more detailed description see this .Another alternative is to use the  method as you'll get the partition index number and a list of all lines within that partition. Partition 0 and line 0 will be be the headerHow about this? I would suggest you to tryYou have to have a class in this example person with the spec of your file header and associate your data to the schema and apply criteria like in mysql.. to get desired result I think you can try to load that csv into a RDD and then create a dataframe from that RDD, here is the document of creating dataframe from rdd:For spark scala I typically use when I can't use the spark csv packages... "},
Scala

Reading the Programming in Scala 2nd Ed and I came across this:literal identifier\n\"The idea is that you can put any string that's accepted by the runtime as an identifier between backtick\"I'm not entirely sure why I would use this? The book gave a use case of accessing the static yield method in Java's Thread class.So since in Scala, yield is a reserve word, if I use yield with backticks, it would ignore the Scala's yield and let me access the Java's Thread class's method yield instead? Thank you in advance.Exactly. Using backticks, you can more or less give any name to a field identifier. In fact, you can even saywhich defines a variable with name (one character of whitespace).The literal definition of identifiers is useful in two cases. The first case is, when there is already a reserved word of the same name in Scala and you need to use a Java library which does not care about that (and of course, why should it).The other use case comes with  statements. The convention is that lower case names refer to match variables, whereas upper case names refer to identifiers from the outer scope. So,prints  (if the compiler were dumb enough not to fail with saying  were unreachable). If you want to refer to the originally defined , you need to use backticks as a marker.Which prints . There is a more advanced use case in this recent question  where the backticks were needed to get the compiler to digesting the code for a setter method (which in itself uses some \u2018magic\u2019 syntax).Thank you @Debilski, it helps me to understand this code below from AKKA doc :The case :matches a message of type Terminated with ActorRef field equals to child which is defined earlier.With this statement :We match every Terminated messages with any reference of ActorRef mapped in ."},
Scala

How to catch multiple exceptions at once in Scala? Is there a better way than in C#: You can bind the whole pattern to a variable like this:See  called Pattern alternatives.As you have access to the full pattern matching capabilities of scala in the catch clause, you can do a lot : Note that if you need to write the same handlers time and time again you can create your own control structure for that : Some such methods are available in object . failing, failAsValue, handling may be just what you needUnfortunately, with this solution, you have no access to the exception where you use the alternative patterns. To my knowledge, you cannot bind on an alternative pattern with case . So if you need access to the exception, you have to nest matchers : You can also use :This specific example might not be the best example to illustrate how you can use it, but I find it pretty useful in many occasions."},
Scala

Is there a pattern-matching way to see if two arrays (or sequences) are equivalent?You need to change your last line toto do a deep comparison of the arrays.From :"},
Scala

I'm new to Scala, I'm using 2.9.1, and I'm trying to get my head around how to use partial functions.  I have a basic understanding of curried functions, and I know that partial functions are kind of like curried functions where they are only 2nary or some such.  As you can tell I'm a bit green at this.It does seem that in certain cases like XML filtering, being able to partial functions would be highly advantageous, so I'm hoping get a better understanding of how to use them.I have a function that uses the RewriteRule structure, but I need it to work with two arguments, whereas the RewriteRule structure only takes one, OR a partial function.  I think this is one of the cases I'm thinking about it being helpful.Any advice, links, words of wisdom etc. welcome!The answers so far are excellent, and have cleared up a few fundamental misconceptions I have.  I think they also explain where I'm struggling - I think maybe posting a new question being a bit more specific will help, so I'll do that too.A partial function is a function that is valid for only a subset of values of those types you might pass in to it.  For example:This is useful when you have something that knows how to check whether a function is defined or not.  Collect, for instance:This is  going to help you place two arguments where you really want one.In contrast, a  is a function where some of its arguments have already been filled in.Now you only need one argument--the thing to add 5 to--instead of two:You can see from this example how to use it.But if you need to specify those two arguments, this  won't do it--say you want to use , for instance, and you need to give it a function of one argument, but you want it to add two different things.  Well, then you canwhich will partially apply the function (really, just create a function out of the method, since nothing has been filled in) and then combine the separate arguments into a tuple.  Now you can use this in places that require a single argument (assuming that the type is correct):In contrast,  is different yet again; it turns functions of the form  into .  That is, given a function of multiple arguments, it will produce a chain of functions that each take one argument and return a chain one shorter (you can think of it as partially applying one argument at a time).Rex Kerr's explanation is very good -- and no surprise there either. The question is clearly mixing up  with . For whatever it is worth, I made the same confusion myself when I learned Scala.However, since the question does draw attention to partial functions, I'd like to speak of them a bit.Many people say that partial functions are functions that are not defined for all input, and that's true of mathematics, but not of Scala. In Scala, a function may not be defined for all input either. In fact, since partial function inherit from function, then function includes all partial functions as well, making that inevitable.Others mention the method , which is, indeed, a difference, but one mostly about implementation. That's so true that Scala 2.10 will probably be released with a \"fast partial function\", which does not rely on .And a few people even imply that the  method for partial functions do something different than the  method for functions, like only executing for the input that is defined -- which could not be farther from the truth. The  method is .What partial functions really come down to is another method: . That sums up all use cases for partial functions much better than , because partial functions are really about doing one of the following things:I'm not saying everything can be  implemented in terms of , mind you. I'm just saying that partial functions are about doing something else when an input isn't defined for it."},
Scala

In  I have set the  property of my Scala project to  where  is the location of my scala project.Now, if I am in a Scala file that implements a class/trait, when I type +, Eclipse opens the Scaladoc page of that class/trait. However, this does not work if it is an object since Eclipse tries to open  whereas the Scaladoc-generated file name is .Is there any workaround?Scaladoc is now integrated since  of the Scala-IDE plugin. You can just hover over your term, or press F2 while the cursor is on the identifier.Typesafe has  a plugin for the Scala compiler which generates  for your  API. The plugin and its documentation is available on . Maybe this helps as a workaround."},
Scala

Suppose I've got a type class that proves that all the types in a Shapeless coproduct are singleton types:We can show that it works with a simple ADT:And then:Now we want to combine this with Shapeless's  mechanism that'll give us a coproduct representation of our ADT:I'd expect  to work, but it doesn't. We can use  to get some information about why: obviously  a singleton type, though. We can try putting the  instances in scope manually just for fun:And somehow now it works:I don't understand why these instances would work in this context while the ones generated by the  macro method (which we used to create them) don't. What's going on here? Is there a convenient workaround that doesn't require us to enumerate the constructors manually?This works as written as of the most recent shapeless 2.1.0-SNAPSHOT."},
Scala

I started to program in Scala recently. I'm looking for a free Scala profiler. Reading from the language's official site led me to , but the program was not a free one.Googling \"scala profiler\" didnt give me any relevant result.So how do I profile my program written in Scala? I prefer a graphical plugin for Netbeans or Eclipse. But if there is no such thing, then a console one will be fine.Thanks :)Given that Scala runs on the Java Virtual Machine (), you can use the  tools  and  to profile the application. Alternatively  Java profiler should work (e.g. YourKit, as you've already mentioned) has been bundled with the JDK since  and it is based on the NetBeans profiler. You can capture memory usage, code performance hotspots etc:I have tried with jvisualvm (both inside and outside netbeans) but I cannot see any scala method call in the profiling reports (only the underlying java libraries method calls). To me it looks like a bug but I might have missed snomething obvious. Anyway here is a issue report I wrote on netbeans.org with the details:If anybody here has successfully used JVisualVM to CPU-profile Scala code please let me know."},
Scala

 monad is a great expressive way to deal with something-or-nothing things in Scala. But what if one needs to log a message when \"nothing\" occurs? According to the Scala API documentation,However, I had no luck to find best practices using Either or good real-world examples involving Either for processing failures. Finally I've come up with the following code for my own project:(Please note this is a snippet from a real project, so it will not compile on its own)I'd be grateful to know how you are using  in your code and/or better ideas on refactoring the above code.Either is used to return one of possible two meaningful results, unlike Option which is used to return a single meaningful result or nothing.An easy to understand example is given below (circulated on the Scala mailing list a while back):As the function name implies, if the execution of \"block\" is successful, it will return \"Right(<result>)\".  Otherwise, if a Throwable is thrown, it will return \"Left(<throwable>)\".  Use pattern matching to process the result:Hope that helps.Scalaz library has something alike Either named Validation. It is more idiomatic than Either for use as \"get either a valid result or a failure\".Validation also allows to accumulate errors.Edit: \"alike\" Either is complettly false, because Validation is an applicative functor, and scalaz Either, named \\/ (pronounced \"disjonction\" or \"either\"), is a monad. \nThe fact that Validation can accumalate errors is because of that nature. On the other hand, / has a \"stop early\" nature, stopping at the first -\\/ (read it \"left\", or \"error\") it encounters. There is a perfect explanation here:  See: As requested by the comment, copy/paste of the above link (some lines removed):The snippet you posted seems very contrived. You use Either in a situation where:Turning an exception into a Left is, indeed, a common use case. Over try/catch, it has the advantage of keeping the code together, which makes sense if the exception is . The most common way of handling Either is pattern matching:Another interesting way of handling  is when it appears in a collection. When doing a map over a collection, throwing an exception might not be viable, and you may want to return some information other than \"not possible\". Using an Either enables you to do that without overburdening the algorithm:Here we get a list of all authors in the library,  a list of books without an author. So we can then further process it accordingly:So, basic Either usage goes like that. It's not a particularly useful class, but if it were you'd have seen it before. On the other hand, it's not useless either."},
Scala

I see that traits in Scala are similar to interfaces in Java (but interfaces in Java extend other interfaces, they don't extend a class). I saw  where a trait extends a class.What is the purpose of this? Why can traits extend classes?Yes they can, a  that extends a  puts a restriction on what  can extend that  - namely, all  that mix-in that  must extend that ."},
Scala

The package \"scala\" has a number of classes named Product, Product1, Product2, and so on, up to Product22.The descriptions of these classes are surely precise. For example:Precise, yes. Communicative? Not so much. I expect that this is the perfect wording for someone who already understands the sense of \"cartesian product\" being used here. For someone who doesn't, it sounds a bit circular. \"Oh yes, well of course Product4 is the  product of 4 .\"Please help me understand the correct functional-language viewpoint.  What is the sense of \"cartesian product\" being used here?  What do the Product classes' \"projection\" members indicate?Perhaps better understanding can be gained by knowing who derives from it:Or by, knowing it \"\", know what other classes can make use of it, by virtue of extending  itself. I won't quote that here, though, because it's rather long.Anyway, if you have types A, B, C and D, then Product4[A,B,C,D] is a class whose instances are all possible elements of the cartesian product of A, B, C and D. Literally.Except, of course, that Product4 is a Trait, not a class. It just provides a few useful methods for classes that are cartesian products of four different sets.Everyone else has gone for the maths so I'll go for the silly answer just in case! You have a simple car which has a gearbox, a steering wheel, an accelerator and a number of passengers. These can each vary:  etc. The gearbox, steering, accelerator etc are therefore  and each has its own  of possible values. The cartesian product of each of these sets is basically . So a few possible values are:the size of the cartesian product is of course the product (multiplication) of the possibilities of each set. hence if you car has 5 gears (+ reverse + neutral), steering is left/straight/right, accelerator is on/off and up to 4 passengers, then there are 7 x 3 x 2 x 4 or 168 possible states.This last fact is the reason that the cartesian product (named after  by the way) has the multiplication symbol From :The projection allows to get the instance of the 'n' class referenced by the Product.A cartesian product is a product of sets. Given sets A and B, A x B (\"A cross B\") is the set of all tuples (x, y) such that x is in A and y is in B. A cartesian product may be analogously defined on types: given types A and B, A x B is the type of tuples (x, y) where x is of type A and y is of type B.So Product4 is the type of tuples (w, x, y, z), where w, x, y, z are components."},
Scala

Scala makes a big deal about how what seem to be language features are implemented as library features.Is there a list of types that are treated specially by the language?Either in the specification or as an implementation detail?That would include, for example, optimizing away matches on tuples.What about special conventions related to pattern matching, for comprehensions, try-catch blocks and other language constructs?Is String somehow special to the compiler? I see that String enhancement is just a library implicit conversion, and that String concatenation is supported by , but is that somehow special-cased by the language?Similarly, I see questions about  and  and , and it's not clear what is a magical intrinsic. Is there a way to tell the difference, either with a compiler option or by looking at byte code?I would like to understand if a feature is supported uniformly by implementations such as Scala.JS and Scala-native, or if a feature might actually prove to be implementation-dependent, depending on the library implementation.There is an incredible amount of types that are \"known\" of the compiler, and are special to varying degrees. You can find a complete list in scalac's .We can probably classify them according to the degree of specialness they bear.Disclaimer: I have probably forgotten a few more.The following types are crucial to Scala's type system. They have an influence on how type checking itself is performed. All these types are mentioned in the specification (or at least, they definitely should be).The following types are not crucial to the type system. They do not have an influence on type checking. However, the Scala language does feature a number of constructs which desugar into expressions of those types.These types would also be mentioned in the specification.This is probably the list that you care most about, given that you said you were interested in knowing what could go differently on different back-ends. The previous categories are handled by early (front-end) phases of the compiler, and are therefore shared by Scala/JVM, Scala.js and Scala Native. This category is typically known of the compiler back-end, and so potentially have different treatments. Note that both Scala.js and Scala Native do try to mimic the semantics of Scala/JVM to a reasonable degree.Those types might not be mentioned in the language specification per se, at least not all of them.Here are those where the back-ends agree (re Scala Native, to the best of my knowledge):And here are those where they disagree:Also, although not  per se, but  are also handled specifically by the back-ends.In addition to the types mentioned above, which are available on all platforms, non-JVM platforms add their own special types for interoperability purposes.See Plus, a dozen more .See "},
Scala

I have been looking for an explanation for why twitter had to migrate part of its middle ware from Rails to Scala. What prevented them from scaling the way facebook has, by adding servers as its user base expanded. More specifically what about the Ruby/Rails technology prevented the twitter team from taking this approach?It's not that Rails doesn't scale, but rather, requests for \"live\" data in Ruby (or any interpreted language) do not scale, as they are comparatively far more expensive both in terms of CPU & memory utilization than their compiled language counterparts.Now, were Twitter a different type of service, one that had the same enormous user base, but served data that changed less frequently, Rails could be a viable option via caching; i.e. avoiding live requests to the Rails stack entirely and offloading to front end server and/or in-memory DB cache. An excellent article on this topic: However, Twitter did not ditch Rails for scaling issues alone, they made the switch because Scala, as a language, provides certain built-in guarantees about the state of your application that interpreted languages cannot provide: if it compiles, time wasting bugs such as fat-fingered typos, incorrect method calls, incorrect type declarations, etc. simply cannot exist.For Twitter TDD was not enough. A quote from Dijkstra in  illustrates this point: \"testing can only prove the presence of errors, never their absence\".  As their application grew, they ran into more and more hard to track down bugs. The magical mystery tour was becoming a hindrance beyond performance, so they made the switch. By all accounts an overwhelming success, Twitter is to Scala what Facebook is to PHP (although Facebook uses their own ultra fast C++ preprocessor so cheating a bit ;-))To sum up, Twitter made the switch for both performance and reliability. Of course, Rails tends to be on the innovation forefront, so the 99% non-Twitter level trafficked applications of the world can get by just fine with an interpreted language (although, I'm now solidly on the compiled language side of the fence, Scala is just too good!)No platform can infinitely scale out whilst still dealing with complex sets of data that change moment to moment. \nLanguage and infrastructure matters, but how you build your site and the data access patterns matter more.If you've ever played games like Transport Tycoon or Settlers where you have to transport resources around, you'll know how you need to stay on top of upgrading infrastructure as usage increases. Scaling platforms like Facebook and Twitter is a never-ending task. \nYou have an ever increasing number of users, and you're being pushed to add more features and functionality. It's a continual process of upgrading one bit, which causes more stress on another bit. Throwing servers at the problem isn't always the answer, and sometimes can cause more problems.  links to a set of posts about the changes, including a decent history of the steps taken over time.The short version is that Ruby and Rails didn't deliver the performance and reliability they required for the service.  Given the scale, this isn't surprising; most COTS solutions are not satisfactory at the super-large end of scale.High Scalability covers a lot of questions about architecture at that top end, for other sites, so helps answer broader questions in the area too.They could have thrown more hardware at the problem, but it is a good deal more expensive then simply writing more efficient code. Like many high-level frameworks, Ruby on Rails is great at many things, but high-performance isn't one of them. Compiled languages will always be faster than interpreted languages.Facebook (and Google) scale by adding more servers, but at the same time they break their application out into various services.   Those services communicate via an agreed upon interface and type, and they are now free to build these services out in any technology they see fit.  Just because you read that facebook uses php doesn't mean that all their backend services are being served by php (and it doesn't make sense either since in SOA you can choose any tech stack).I think this video is the best answer to your question:\"From Ruby to the JVM\"\nI think one important bit missing here is the platform. Yes we had the compiled vs interpreted argument and a couple of others. \nBut one very important aspect was indeed the platform. There are different Ruby VMs but none did please twitter, although they tuned it quite a bit. But scala runs on the JVM and twitter engineers hat pretty goog experience with that. Why they they didnt try/choose JRuby? Well I guess the reasons mentioned above come here into play.Linear gains with parallelism (which is what multiple servers is) is exceedingly rare, and very application dependent. Yes, it exists -- that's how GPU do most of their work. If you are serving static pages, with no session state, that would also be the case.For the most part, however, adding servers do not increase performance linearly (ie, 10 servers are not 10 times faster than 1 server), and  means that any gains you can make on a single server will have much more impact than just adding servers. It's not like Twitter doesn't have a bunch of servers, now is it?"},
Scala

my Haskell* is a bit rusty, so i can imagine that I\u2019m missing the obvious:Does one of these properties apply to the it?*actually SML, but that\u2019s 99% the same, but known by nobody under the sun.Methods exist on the Traversable trait which are equivalent to  and :BTW, another function that I find missing is a  function.How about :It's on ."},
Scala

In Scala I can enforce type equality at compile time. For example:Is there a way to enforce that type A and type B should be different ?Riffing off of Jean-Philippe's ideas, this works:Then:I'd probably simplify this as follows, since the checks for \"cheating\" can always be circumvented anyway (e.g.  or ):I have a simpler solution, which also leverages ambiguity,The original use case,We can relate this to my  (thanks @jpp ;-) as follows,Sample REPL session,I liked the simplicity and effectiveness of Miles Sabin's first solution, but was a bit dissatisfied with the fact that the error we get is not very helpful:By example with the following definition:Attemtping to do  will fail to compile with:I'd rather have the compiler tell me something along the line of \"T is not different from String\"\nIt turns out that it's quite easy if add yet another level of implicits in such a way that we turn the  error\ninto an  error. From then we can use the  annotation to emit a custom error message:Now let's try to call :That's better. Thanks compiler.As a last trick for those that like the context bound syntactic sugar, one can define this alias (based on type lambdas):Then we can define  like this:Whether it is easier to read is highly subjective. In any case is definitly shorter than writing the full implicit parameter list.: For completeness, here the equivalent code for expressing that  is is not a sub-type of :And for expressing that  is not convertible to  :Based on 's idea, the following seems to work:Here's another attempt:Then, again:Like in my other proposal, the aim here is to introduce a compile-time ambiguity when  and  are the same. Here, we provide two implicits for the case where  is the same as , and an unambiguous implicit when this is not the case.Note that the problem is that you could still explicitly provide the implicit parameter by manually calling  or . I couldn't think of a way to prevent this at compile time. However, we can throw an exception at runtime, with the trick that  requires an evidence parameter itself indicating whether  is the same as . But wait... Aren't we trying to prove the exact opposite? Yes, and that's why that  implicit parameter has a default value of . And we expect it to be  for all legal uses \u2014 the only time where it would not be  is when a nasty user calls e.g. , and there we can prevent this cheating by throwing an exception.How about something like this, then?Then:The idea is to make resolution ambiguous when is the same as , and unambiguous when they are not the same. To further emphasize that the ambiguous methods should not be called, I added an implicit of type , which should never be around (and should certainly look wrong to the caller if they try to insert one explicitly). (The role of the  is just to give a different signature to the first two methods.)This is not an answer, just the beginnings of what I could think is an answer. The code below will return either an  or an  depending on whether the types are equal or not, if you ask for . How to go from there to actually making a check I haven't been able to figure out. Maybe the whole approach is doomed, maybe someone can make something out of it. Mind you,  will  return something, one can't use that. :-(Test:"},
Scala

Let's say I have a  instance which is not initialized:is this the proper way to initialize it to null?Use  as a last resort. As already mentioned,  replaces most usages of null. If you using  to implement deferred initialisation of a field with some expensive calculation, you should use a .That said, Scala does support . I personally use it in combination with Spring Dependency Injection.Your code is perfectly valid. However, I suggest that you use  to initialize  to it's default value. If  is a primitive, you get the default specific to the type. Otherwise you get .Not only is this more concise, but it is neccessary when you don't know in advance what  will be:Using  is an compile error if T is unbounded:You can add an implicit parameter as evidence that  is nullable -- a subtype of  not a subtype of  This isn't fully , even in Scala 2.8, so just consider it a curiousity for now. The canonical answer is . Instead, use an option type:When you want to set it:And when you want to read from it, test for None:As David and retronym have already mentioned, it's a good idea to use  in most cases, as  makes it more obvious that you have to handle a no-result situation.  However, returning  requires an object creation, and calling  or  can be more expensive than an if-statement.  Thus, in high-performance code, using  is not always the best strategy (especially in collection-lookup code, where you may look up a value very many times and do not want correspondingly many object creations).  Then again, if you're doing something like returning the text of an entire web page (which might not exist), there's no reason  to use Option.Also, just to add to retronym's point on generics with , you can do this in a fully-baked way if you really mean it should be :and this works in 2.7 and 2.8.  It's a little less general than the  method, because it doesn't obey  AFAIK, but it otherwise does exactly what you'd hope it would do.I came across this question since scalastyle told me to not use null when initialising an object within my test with . My solution without changing any type that satisfied scalastyle:"},
Scala

I'm novice in Scala. Recently I was writing a hobby app and caught myself trying to use pattern matching instead of if-else in many cases.instead ofAre these approaches equal? Is one of them more preferrable than another for some reason?I'm not sure why you'd want to use the longer and clunkier second version.And that's a lot more bytecode for the match also.  It's  efficient even so (there's no boxing unless the match throws an error, which can't happen here), but for compactness and performance one should favor /.  If the clarity of your code is greatly improved by using match, however, go ahead (except in those rare cases where you know performance is critical, and then you might want to compare the difference).Don't pattern match on a single boolean; use an if-else.Incidentally, the code is better written without duplicating .One arguably better way would be to pattern match on the string directly, not on the result of the comparison, as it avoids \"boolean blindness\". One downside is the need to use backquotes to protect the enteredPassword variable from being shadowed.Basically, you should tend to avoid dealing with booleans as much as possible, as they don't convey any information at the type level.Both statements are equivalent in terms of code semantics. But it might be possible that the compiler creates more complicated (and thus inefficient) code in one case (the ).Pattern matching is usually used to break apart more complicated constructs, like polymorphic expressions or deconstructing (ing) objects into their components. I would not advice to use it as a surrogate for a simple  statement - there's nothing wrong with . Note that you can use it as an expression in Scala. Thus you can writeI apologize for the stupid example.I'v came across same question, and had written tests:timeIf  : Long = 22\ntimeMatch  : Long = 1092                     For the large majority of code that isn't performance-sensitive, there are a lot of great reasons why you'd want to use pattern matching over if/else:Here's an equivalent if/else block implementation:Yes, you can argue that for something as simple as a boolean check you can use an if-expression.  But that's not relevant here and doesn't scale well to conditions with more than 2 branches.If your higher concern is maintainability or readability, pattern matching is awesome and you should use it for even minor things!"},
Scala

Scala's  trait has a methodBut I sometimes want a different type:Is there a simple way to do this which I am missing? Of course, this can be done with a fold. method iterates though all  pairs. You can use it like this:What about this code:Which produces:This can be packaged into utility method:Usage:With some Scalaz:I like @tenshi's solution better.You could create a utility class:Code not tested but it should work somehow simmilar like that."},
Scala

Given an Option, what is the idiomatic way to get its value or throw an exception trying?(EDIT: this is not the best or most idiomatic way to do it. I wrote it when I was not familiar with Scala. I leave it here for an example of how  to do it. Nowadays I would do as @TravisBrown)I think it really boils down to two things:If at that point in your code you  the value to be there, and in the remote case that it isn't you want your program to  fast, then I would only do a normal  and let Scala throw a  if there was no value:If you want to handle the case differently (throw your own exception) I think a more elegant way would look like this:And of course if you want to supply your own alternative value for the case that the  is  you would just use :A  \"statement\" is really an expression in Scala, and it has type , which is a subtype of every other type. This means you can just use plain old :You really, really shouldn't be doing this, though.Just use the .get method. It will throw a NoSuchElementException if o is an instance of None. Basically, I would work with options like this:to avoid your specific question.I think  will help you stay on the \"Functional\" side :)About  and "},
Scala

It seems like the support for printing arrays is somewhat lacking in Scala.  If you print one, you get the default garbage you'd get in Java:Furthermore, you cannot use the Java toString/deepToString methods from the java.util.Arrays class: (or at least I cannot figure it out)The best solution I could find for printing a 2D array is to do the following:Is there a more idiomatic way of doing this?  In Scala 2.8, you can use the  method defined on Array, that returns an IndexedSeq cointaining all of the (possibly nested) elements of this array, and call mkString on that:The IndexedSeq returned does have a stringprefix 'Array' by default, so I'm not sure whether this gives precisely what you wanted.How about this:Adding little more to Arjan's answer - you can use the mkString method to print and even specify the separator between elements.\nFor instance :The \"functional programming\" way to do this (as far as I concern) is:Or if you don't really care about the spacing:IMHO, functional programming can get a little messy, if it takes too long to make this, I'd say just go with the imperative way.You can get neat formatting of Array[Array[Somethings]] with custom separators for the inner as well as the outer array follows:This results in:Try simply this:"},
Scala

I recently gave up trying to use Scala in Eclipse (basic stuff like completion doesn't work). So now I'm trying IntelliJ. I'm not getting very far.I've been able to edit programs (within syntax highlighting and completion... yay!). But I'm unable to run even the simplest \"Hello World\".  This was the original error:But that was yesterday with IDEA 9.0.1. See below...Today I uninstalled IntelliJ 9.0.1, and installed 9.0.2 Early Availability, with the 4/14 stable version of the Scala plug-in.Then I setup a project from scratch through the wizards:Created a new class:For my efforts, I now have a brand-new error :)Here it is:Scalac internal error: class java.lang.ClassNotFoundException [java.net.URLClassLoader$1.run(URLClassLoader.java:202), java.security.AccessController.doPrivileged(Native Method), java.net.URLClassLoader.findClass(URLClassLoader.java:190), java.lang.ClassLoader.loadClass(ClassLoader.java:307), sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301), java.lang.ClassLoader.loadClass(ClassLoader.java:248), java.lang.Class.forName0(Native Method), java.lang.Class.forName(Class.java:169), org.jetbrains.plugins.scala.compiler.rt.ScalacRunner.main(ScalacRunner.java:72)]I uninstalled 9.0.2 EA and reinstalled 9.0.1, but this time went with the 2.7.3 version of Scala rather than the default 2.7.6, because 2.7.3 is the one shown in the screen-shots at the IntelliJ website (I guess the screen-shots prove that they actually tested this version!). Now everything works!!!I have encountered the same scalac error when trying to run a Scala project in Intellij Idea 9.0.2 and I've managed to find a solution by chance :). These are the steps I took in creating the project and running it.I have created a Scala project in Intellij Idea 9.0.2 final (it was released today). I have installed the Scala plugin, restarted the IDE and created a new Scala project (with the name \"TestScala\") with scala-2.8.0.Beta1 as project library. Once the project is created and the scala libraries downloaded, I have created a Test.scala file with the following content:After that, I created a launch configuration (\"Edit Configurations\"), choosing the \"Application\" template. I set as main class Test and choose the project name (\"TestScala\") in the \"Use classpath and JDK of module\" combo box. When I run the configuration I get the same error as you reported  (\"Scalac internal error: class java.lang.ClassNotFoundException\") .Now comes the freaky part :). I right click on the project, choose \"Module Settings\", have a look on all settings but  . Click \"apply\" and \"ok\", try to run configuration again and  :) .I use Intellij Idea 9.0.2 the final release (build 95-66); Ubuntu 9.10 and JDK 1.6.0_18. I also have to mention that I had a JDK configured in Intellij, otherwise there is an extra step to configure it. When checking the setting of the module, one needs to click on the  and  . Both of these settings are about the scala compiler and scala library location. I would guess these values are not properly set when the project is created but are saved once the user touches them and saves the settings.  To answer your question, it's difficult to get a working IDE for Scala for two reasons:\n(a) Scala is only just beginning to reach a wide audience and\n(b) due to (a), there is no business case for spending time on a Scala IDE.Also, if you are old enough to cast your mind back and young enough to still remember, you would know that for the first five or more years of Java, we were stuck with okay-ish tools like JBuilder that did little more than compile your code when you said so - no error highlighting, no auto-importing, and the word refactoring didn't even exist. If you want to pioneer, you need to be prepared to cut some of the road yourself, or at least bush-bash.I know it won't help you, but I have successfully used IDEA for Scala on Linux, Mac and Windows. I typically have the Scala SDK installed somewhere locally and point IDEA at that rather than using the 'download' option.Presently, I am mostly using an  on Mac OS X with Scala 2.8.0.Beta1-RC5 and it's working well (except that fsc doesn't seem to worked with mixed sources).You could try your luck over at the , though I haven't had a great lot of responses to my own postings there.Installing the plug-in is prerequisite one.The next thing you should do is define a library (global or project-specific; I use global) that holds the Scala library  compiler JAR files (at a minimum, that's  and ). Adding source JARs and a documentation JAR or URLs is a good idea, too. Then make this library a dependency of any modules in your project that include Scala code.Lastly, find the Scala facets in those modules and de-select both check-boxes there.I just did a fresh install and had exactly this same problem myself.\nIt turned out that, because I had created the file in the root package, IDEA had added a package statement at the top with naming a package. I assume that this then got compiled as \"package object Main\" - valid syntax in 2.8? Anyway, I deleted the line that said package and it all worked fine.I had the same problem yesterday while trying to set it up. Solution is pretty simple, you just have to set scala somewhere in project settings.You are mixing code compiled with two different Scala versions.I use Netbeans to write scala programs. So far it works very well with my codes. You can try the plugin here: .I was getting this error and also had to right click on the project and \"Open Module Settings\".  However, it was more than just hitting apply.  I had to make sure that my Content Root was correct for each project.  For some reason, there were some incorrect Source and Test Folders.My project uses maven as the main build tool and importing the project into Intellij is probably what created these incorrect settings.I had similar problem, following  blog post instructions solved the problem for me"},
Scala

I heard a lot of good things about  and the  Web framework recently, especially from  hence, I might use this technology in my next projects.  Share your experiences on the Scala/Lift Platform.I'm working on my second Lift app at the moment - it's very strongly in Lift's sweet spot - very realtime, lots of concurrency.The first one we wimped out after a few days of wrestling with the DB layer (it's better now, I am led to believe), and went to Play/Scala instead.  That maximized the existing knowledge of our team and made it possible to make deadline.  But the hot code reloading pretty much stopped happening once our project got moderately large (kept running out of PermGen - it's an ongoing problem with Scala compilation pretty much anywhere), and the manual juggling of things like method call parameters and location security in different places in the website got quite cumbersome.  We were glad when it was done - in the same way as I tended to find Rails 1, the speed increases shrank as the project size increased, and by the end it was every bit as tedious and error-prone as working in a Velocity/Spring/XML++ whatever).This time we've been committed to just working out how Lift does what it does, and the right ways to do things.  This has meant a lot of casual browsing through the mailing list (discussions that are several versions old are often still relevant), and most importantly a new ethos for the team.  It's been necessary to internalize very strongly the motto:\"This is feeling hard and repetitive.  I bet they made an easier way to do this.\"So far Lift has never disappointed us.  I'm not talking, by the way, about stuff like the Sitemap and list concatenation syntax - you MUST have a pretty good handle on functional Scala, or you just won't be able to read the source code or even configure your app.That said it's not crazy IO monads or anything, just some common idioms that you'd pick up in a few weeks of Scala anyway.The biggest problem for us has been a slow compile cycle.  It takes about 20 seconds to jetty:run our project, which is a different feeling to Play which (when it's working) hot compiles all your stuff.  On the other hand, we actually timed that the other day when one of our devs complained about it, and it worked out that although Play technically hot compiled it, the page still took 12 seconds to load in Dev mode.  So there's not a huge loss, it just feels a bit slow to have to hop out to the command line.Lift lets you do a great deal, and there are many places in our app where (because it's available), we've said \"Yeah, we really WOULD prefer to have that live updated immediately to all viewers of that page, instead of them discovering later that they're out of date (think of all the times you've posted simultaneously to someone on SO, with the same answer).  COMET is everywhere, it turns out - it's not a specialist use case, it's the way things should work.  And Lift makes it really easy.We also love the strong, programatically configurable, security model - once we switched our mindsets to \"We have to whitelist every location, and specify the necessary entrance conditions\", we never saw another session problem - you know, those ones where you assumed that the user would have traversed a certain path, and thus would know a whole bunch of parameters?  Like, a valid username, and an area of interest or whatever?  (I'm being intentionally vague).  That can be one of the awkward things about a stateful framework, that you're going to want to have usable state when the user hits a page, instead of (for instance) just demanding that all the state gets carried along at each request.My takeaway from this renewed shot at Lift:It's worth it.  Not just to build the app that you're trying to build, but to build the app that you didn't know you needed.There's a lot of head scratching, but not a lot of code.  And when it works it really works.  It's fast, and clean, and for all of the miracles that it's working between the browser and the server, I've never yet seen it get confused.I'm developing enterprise financial application in Lift for more than 6 months and I was JAVA programmer former. I have noticed a few points, which could help you:I can't imagine that I have to return to JAVA code now. But my little advice is to try to code some simple application and you will see."},
Scala

Are there any tools for performing static analysis of Scala code, similar to FindBugs and PMD for Java or Splint for C/C++? I know that FindBugs works on the bytecode produced by compiling Java, so I'm curious as to how it would work on Scala.Google searches (as of 27 October 2009) reveal very little.Google searches (as of 01 February 2010) reveal this question.FindBugs analyzes JVM byte codes, regardless of the tool that generated them. I've tried using FindBugs to check .class files generated by Scala. Unfortunately, FindBugs produced many warnings, even for trivial Scala programs.There is now  which does the job that Checkstyle does for Java. This includes not only formatting checks, but also some checks for known sources of bugs, such as a class which implements hashCode() but not equals.There are currently about 40 checks, but we're adding them all of the time.For more information, see .There is some work going on in that direction. Some links:There is also a discussion on scala mail list, archive available .Here is an updated answer as of August 2014 for some that are aimed or work well with Scala. Personally I think the JVM or Java ones end up with far too many false positives, or have inspections that are aimed mostly at Java specific classes. For example, since in Scala we don't tend to use the Java Collections, all the findbugs collection based inspections are not needed. Another example is the inspections for use of static fields which are irrelevant in Scala.Findbugs and other tools that are bytecode based will work, in the sense that they will find faults in your code.  Unfortunately, the bytecode based approaches have been tuned against the output of the javac compilers, meaning they are likely to produce very high false positive rates, and miss basic issues, because Scala will be producing different idioms than the javac compiler.   I'm having a lot of fun with Codacy (e.g. ) for Open Source projectsThere is a SBT plugin for PMD copy paste detector CPD. scala copy paste detector, based on AST. Looking for copy-pasted subtrees/ASTs, and inform about it.It's plugin for sbt. I don't know much about Scala but if is Java compatible Klocwork's Solo product might work.  You can find it here "},
Scala

Is it always more performant to use withFilter instead of filter, when afterwards applying       functions like map, flatmap etc.?Why are only map, flatmap and foreach supported? (Expected functions like forall/exists as well)  From the scala docs:So  will take the original collection and produce a new collection, but  will non-strictly (ie. lazily) pass unfiltered values through to later map/flatMap/withFilter calls, saving a second pass through the (filtered) collection. Hence it will be more efficient when passing through to these subsequent method calls.In fact,  is specifically designed for working with chains of these methods, which is what a for comprehension is de-sugared into. No other methods (such as /) are required for this, so they have not been added to the  return type of . Using for yield can be a work around, for example:As a workaround, you can implement other functions with only  and .Moreover, this optimisation is useless on small collections\u2026"},
Scala

There's not much info in the spec on what type ascription is, and there certainly isn't anything in there about the purpose for it.  Other than \"making passing varargs work\", what would I use type ascription for?  Below is some scala REPL for the syntax and effects of using it.Type ascription is just telling the compiler what type you expect out of an expression, from all possible valid types.A type is valid if it respects existing constraints, such as variance and type declarations, and it is either one of the types the expression it applies to \"\", or there's a conversion that applies in scope.So, , therefore any  is also an . In your example you declared you want the expression  to be treated as an , not a . Since there is no constraints preventing that and the desired type is one of the types  , it works.Now, why would you want that? Consider this:You could also have fixed this by type ascripting  at  declaration, or you could have declared 's type to be .However, type declarations achieve the same thing only as long as you are assigning a value to an identifier. Which one can always do, of course, if one doesn't care about littering the code with one-shot identifiers. For example, the following does not compile:But this does:It would be silly to use an identifier here in place of . And though I could just write  instead, that isn't always an option. Consider this, for instance:For the reference, this is what Scala 2.7 spec (march 15, 2009 draft) has to say about type ascription:One possibility is when network and serial protocol level stuff, then this:is far cleaner thanThe second form is also a runtime conversion (not handled by the compiler) and could lead to some interesting over/underflow conditions.I use type ascription to paper over holes in Scala's type inference. For example, foldLeft over a collection of type A takes an initial element of type B and a function (B, A) => B that is used to fold the elements of the collection into the initial element. The actual value of type B is inferred from the type of the initial element. Since Nil extends List[Nothing], using it as an initial element causes problems:Alternatively, you could just use List.empty[Int] instead of Nil:List[Int].edit: List.empty[A] is implemented as This is effectively a more verbose form of Nil:List[A]You may find  illuminating, if a bit convoluted to follow.  The important thing to note is that you're adding constraint hints to the type checker - it gives you a little more control over what that compilation phase is doing.Type Inference: We can skip Explicitly giving Name of Type of Something in source code, called Type Inference.(Although required in some exceptional cases.)Type Ascription: Being explicit about the type of something is called a Type Ascription.\nWhat Difference It can make?ex: val x = 2 : Bytealso see:\n1. We can explicitly give return type to our functionsAnother way of declaring this could be:Here we did not give  return type explicitly and Compiler inferred it as .\nWhy  is because we used type ascription in the definition.This time We did not explicitly tell the compiler anything(neither this defi). And It inferred our definition as Some[None.type]"},
Scala

I have a folder structure like below:and in that folders I have my files that I have to read.\nHere is the code:Resources in Scala work exactly as they do in Java. \nIt is best to follow the  and put all resources in  and .Example folder structure:To read resources the object  provides the method .To read resources you can use  and  .Keep in mind that  also works fine when the resources are part of a , , which returns a URL which is often used to create a file can lead to problems there. To avoid undebuggable Java NPEs (Java is so horrible), consider:To get meaningful FNFEs instead.For production code I would also suggest to make sure that the source is closed again.For Scala >= 2.12, use :"},
Scala

I used play2 before with java. It felt a little bit like boilerplate especially if you used akka with java. But that is not the fault of the framework.Yesterday I read \"Scala for the impatient\" and I really enjoy the language.Now I looked at both frameworks Lift 2.5 and Play 2.0.3. I think lift has a higher learning curve and I could not just do something with lift. This is not a con for me. From what I saw, Lift has a very nice and clean design. But for me it is hard to tell what the main differences are. I think both frameworks are great.Posting this after spending a week or two with Lift doesn't really\nserve anybody's interests. However, I want to spend some time correcting\nsome mistakes and mis-perceptions.You're dead wrong. Security is the job of the framework. It's critical that security\nis done by default rather than relying on each developer to understand every\nsecurity vulnerability and make sure every line of code takes that into account.All we have to do is look at what happened to \nto understand that even the best coders using well known technology\ncan make a critical mistake.Lift gives a solid security layer on top, so by default, there's no XSS, CSRF, etc.\nbut the developer can dig down as deep as he wants to the HTTP request and deal\nwith the bytes on the wire.Lift is very clear about where you need state and where you don't. Lift can support\nstateless, partially stateful, and completely stateful apps. On a page-by-page and\nrequest-by-request basis, a Lift app can be stateful or stateless (for example,\nin , the venue pages are stateless for\nsearch engine crawls, but stateful for browsers that are logged in.) For\nmore on the design decisions around state, please see .Lift uses Maven, sbt, Buildr, and even Ant. Lift is agnostic about the build environment\nand about the deploy environment (Java EE container, Netty, whatever). This is important\nbecause it make Lift easier to integrate with the rest of your environment.Lift has been around for 5+ years and has a lot of modules and stuff for it. The Lift web framework (as distinguished from the modules) is agnostic about persistence, authentication, etc., so you can use anything with Lift.Lift has had Async support for more than 5 years. It's baked into the framework. Lift's Comet support is  because,\namong other things, it multiplexes all the \"push\" requests on a page through a single request\nto the server which avoids connection starvation. How Lift does async is a whole lot\nless important because one of the core philosophies with Lift is that we remove the\nplumbing from the developer so the developer can focus on business logic.But for those who care, Lift has the best and lightest weight actors of any framework in\nScala-land. We were the first to break away from the Scala Actor's library and worked\nto blaze the trail for different Actor libraries that allowed Akka and ScalaZ Actors\nto flourish.This is part of Lift's commitment to security. It's .Lift apps can be as stateful or as stateless as you want. It's your choice and Lift\nmakes very clear how to make the decision.Also, as I pointed out in the Lift, State, and Scaling post, making the developer figure out\nhow to serialize state in a secure, scalable, performant way\n(because virtually every request on a web\napp that recognizes specific users is stateful) should be done in a predictable,\nsecure way by the framework with reasonable overrides for the developers.Play is a lot like Rails: it's quick to get a site knocked together and it's \nbased on MVC, so a lot of developers understand it. But Play lacks the\ndepth and breadth of Rails (community, plugins, expertise, talent, etc.) If you\nwant quick, easy MVC, then go with Rails and JRuby and write your\nback end in Scala (they work together extraordinarily well.)Lift is a different beast. There's a significant unlearning curve (stop thinking\nMVC and start thinking about user experience first that flows to business logic.)\nBut once you're up the unlearning curve, Lift sites are more secure, highly\nscalable, super-interactive, and much easier to maintain over time.To see what can be done with Play (it can be cool), have a look at the To get going quick with Lift, use a .For a sample of using Mongo with Play, look at .In summary, I don't think you will go wrong with either Lift or Play. Both are active projects, with good communities and good backing from the authors. It really depends on your business problem. If tool support are important to you, then you may want to look at using Play (it's well supported on IntelliJ Idea).Take note that Play, being part of the TypeSafe technology stack, will have builds up to the latest versions of Scala, so if using Scala 2.10 features are important to you, then you may want to keep that in mind. Lift is currently using Scala 2.9.2, which is fine also.For my current project I use lift-mapper for ORM (It's great and rock solid), with Spray for REST (which is simply amazing). This approach avoids frameworks altogether, but it depends on what you want to do. Frameworks are quite often the way to go."},
Scala

I'm following the great so i'm trying at 46m:00s to load the  but fail to what i'm doing is this:how can I load that ?Try explicitly specify . The error occurs when Hadoop environment is set. SparkContext.textFile internally calls , which in turn uses  if schema is absent. This method reads \"fs.defaultFS\" parameter of Hadoop conf. If you set HADOOP_CONF_DIR environment variable, the parameter is usually set as \"hdfs://...\"; otherwise \"file://\".gonbe's answer is excellent. But still I want to mention that  = , not . Hope this could save some time for newbs like me.You need just to specify the path of the file as example:This has been discussed into spark mailing list, and please refer this .You should use  copy the file into :  I have a file called NewsArticle.txt on my Desktop. In Spark, I typed:I needed to change all the \\ to / character for the filepath. To test if it worked, I typed:I'm running Windows 7 and I don't have Hadoop installed. This is the solution for this error that i was getting on Spark cluster that is hosted in Azure on a windows cluster:Load the raw HVAC.csv file, parse it using the functionWe use (wasb:///) to allow Hadoop to access azure blog storage file and the three slashes is a relative reference to the running node container folder.For example: If the path for your file in File Explorer in Spark cluster dashboard is:sflcc1\\sflccspark1\\HdiSamples\\SensorSampleData\\hvacSo to describe the path is as follows: sflcc1: is the name of the storage account. sflccspark: is the cluster node name.So we refer to the current cluster node name with the relative three slashes.Hope this helps.If the file is located in your Spark master node (e.g., in case of using AWS EMR), then launch the spark-shell in local mode first.Alternatively, you can first copy the file to HDFS from the local file system and then launch Spark in its default mode (e.g., YARN in case of using AWS EMR) to read the file directly.try "},
Scala

I frequently find myself working with Lists, Seqs, and Iterators of Tuples and would like to do something like the following,However, the compiler never seems to agree with this syntax.  Instead, I end up writing,Which is just silly.  How can I get around this?A work around is to use  :I like the tupled function; it's both convenient and not least, type safe:Why don't you use If you need the parameters multiple time, or different order, or in a nested structure, where _ doesn't work, seems to be a short, but readable form.Another option is"},
Scala

In Java you can write . However in Scala,  is hidden by  which lacks this function. It's easy enough to switch to using the original Java version of a boolean, but that just doesn't seem right.So what is the one-line, canonical solution in Scala for extracting  from a string?Ah, I am silly. The answer is .How about this:If the input string does not convert to a valid Boolean value  is returned as opposed to throwing an exception.  This behavior more closely resembles the Java behavior of .Note: Don't write  in Java - always use . Using the  variant unnecessarily creates a  object; using the  variant doesn't do this.The problem with  is that it will throw an exception if  isn't exactly one of  or  (even extra white space in the string will cause an exception to be thrown).If you want exactly the same behaviour as , then use it fully qualified, or import Boolean under a different name, eg, . Or write your own method that handles your own particular circumstances (eg, you may want  to be  as well).I've been having fun with this today, mapping a 1/0 set of values to boolean. I had to revert back to Spark 1.4.1, and I finally got it working with:where p(11) is the dataframe fieldmy previous version didn't have the \"Try\", this works, other ways of doing it are available ... "},
Scala

I have installed sbt on Ubuntu.However, whenever I try to launch sbt (from the same directory where sbt is located) it does not work:I am new to linux and I have no idea how to tackle this issue.It seems like you installed a zip version of sbt, which is fine. But I suggest you install the native debian package if you are on Ubuntu. That is how I managed to install it on my Ubuntu 12.04. Check it out here:\n\nOr simply directly download it from .The simplest way of installing SBT on ubuntu is the  package provided by Typesafe.Run the following shell commands:And you're done !It's saying that  is not on your path. Try to run  from  or wherever the  executable is to verify that it runs correctly. Also check that you have execute permissions on the  executable. If this works , then add  to your path and  should run from anywhere.See this  about adding a directory to your path.To verify the  use the  command on LINUX. The output will look something like this:Lastly, to verify  is working try running  or likewise. The output with -help will look something like this:As an alternative approach, you can save the  script to a file called sbt.sh and set the permission to executable. Then add this file to your path, or just put it under your ~/bin directory.The bonus here, is that it will download and use the correct version of SBT depending on your project properties. This is a nice convenience if you tend to compile open source projects that you pull from GitHub and other.My guess is that the directory ~/bin/sbt/bin is not in your PATH.To execute programs or scripts that are in the current directory you need to prefix the command with ./, as in:This is a security feature in linux, so to prevent overriding of system commands (and other programs) by a malicious party dropping a file in your home directory (for example).  Imagine a script called 'ls' that emails your /etc/passwd file to 3rd party before executing the ls command...  Or one that executes 'rm -rf .'...That said, unless you need something specific from the latest source code, you're best off doing what paradigmatic said in his post, and install it from the Typesafe repository."},
Scala

I'm trying to make a EnumListField in Lift/Record/Squeryl, similar to MappedEnumList in LiftMapper. The storage type should be Long/BIGINT. I understand that if I define:Then Squeryl will know it should create a BIGINT column. And I know it uses setFromAny() to set the value, passing in the Long. The one piece I don't get is:How will it read the field's value? If it uses valueBox, it will get a Seq[Enum#Value], and it won't know how to turn that into a Long. How do I tell Squeryl to convert my Seq[Enum#Value] to a Long, or define a \"getter\" that returns a Long, and that doesn't conflict with the \"normal\" getter(s)?"},
Scala

I am looking for a high-performance, concurrent, MultiMap. I have searched everywhere but I simply cannot find a solution that uses the same approach as ConcurrentHashMap (Only locking a segment of the hash array).The multimap will be both read, added to and removed from often.The multimap key will be a String and it's value will be arbitrary.I need O(1) to find all values for a given key, O(N) is OK for removal, but O(logN) would be preferred.It is crucial that removal of the last value for a given key will remove the container of values from the key, as to not leak memory.HERE'S THE SOLUTION I BUILT, availbable under ApacheV2:\nWhy not wrap ConcurrentHashMap[T,ConcurrentLinkedQueue[U]] with some nice Scala-like methods (e.g. implicit conversion to Iterable or whatever it is that you need, and an update method)?Have you tried Google Collections?  They have various  implementations.There is  although I haven't used it.I made a  mixin which extends the mutable.MultiMap mixin and has a concurrent.Map[A, Set[B]] self type.  It locks per key, which has O(n) space complexity, but its time complexity is pretty good, if you aren't particularly write-heavy.you should give  a try. here is the .I had a requirement where I had to have a  where insertion on the Map be concurrent and also on the corresponding Set, but once a Key was consumed from the Map, it had to be deleted, think if as a Job running every two seconds which is consuming the whole  from an specific Key but insertion be totally concurrent so that most values be buffered when the Job kicks in, here is my implementation: I use Guava's helper class Maps to create the concurrent Maps, also, this solution emulates :I am a bit late on this topic but I think, nowadays, you can use Guava like this:Have you taken a look to  which is intended for Real time etc. and of course high performance.It's late for the discussion, yet...When it comes to high performance concurrent stuff, one should be prepared to code the solution. \nWith Concurrent the statement  has a complete meaning. \nIt's possible to implement the structure fully concurrent and lock-free. Starting base would be the NonBlocking Hashtable  and then depending how many values per key and how often need to add/remove some copy on write Object[] for values or an array based Set with semaphore/spin lock."},
Scala

I am new to Scala started learning the language for fun and I am still trying to get my head around it. My understanding of Scala traits is that they are like java interfaces except that some methods can have an implementation.Java 8 is adding interfaces that can have default methods where an implementation can be provided. What are the similarities and differences between Java 8 interfaces and Scala traits?Motivations for  and  differ.The former was introduced to support safe API evolution and a limited form of multiple inheritance. With leveraging functional programming idioms in Project Lambda it's been beneficial to add, for example, a  method to  interface without altering all possible implementers (which is actually impossible to do without breaking backward compatibility). As a side effect this also offered a form of . were designed from scratch as building blocks for modular components composition. They are multiple inheritance friendly and don't have  by having strict rules on evaluation order of mix-ins due to linearization. They also support state, can reference the implementing class and place restrictions on which type can mix-in them. Look at Scala collections library where traits are used thoroughly.Note that with ,  now compiles to an interface.\nScala 2.12 is all about making optimal use of Java 8\u2019s new featuresSee  more the difference of implementation."},
Scala

I use 's iteratees in a number of projects, primarily for processing large-ish files. I'd like to start switching to Scalaz , which are designed to replace the iteratee package (which frankly is missing a lot of pieces and is kind of a pain to use).Streams are based on  (another variation on the iteratee idea), which have  in Haskell. I've used the Haskell machines library a bit, but the relationship between machines and streams isn't completely obvious (to me, at least), and the documentation for the streams library is .This question is about a simple parsing task that I'd like to see implemented using streams instead of iteratees. I'll answer the question myself if nobody else beats me to it, but I'm sure I'm not the only one who's making (or at least considering) this transition, and since I need to work through this exercise anyway, I figured I might as well do it in public.Supposed I've  got a file containing sentences that have been tokenized and tagged with parts of speech:There's one token per line, words and parts of speech are separated by a single space, and blank lines represent sentence boundaries. I want to parse this file and return a list of sentences, which we might as well represent as lists of tuples of strings:As usual, we want to fail gracefully if we hit invalid input or file reading exceptions, we don't want to have to worry about closing resources manually, etc.First for some general file reading stuff (that really ought to be part of the iteratee package, which currently doesn't provide anything remotely this high-level):And then our sentence reader:And finally our parsing action:We can demonstrate that it works:And we're done.More or less the same program implemented using Scalaz streams instead of iteratees.A scalaz-stream solution: We can demonstrate that it works:And we're done.The  function is a common Scalaz combinator. In this case it's being used to traverse, in the  monad, the sentence  generated by . It's equivalent to  followed by ."},
Scala

Where can differences between a class and a type be observed in Scala and why is this distinction important?Is it only a consideration from the language design point-of-view or has it \"practical\" impact when programming Scala?Or is it fundamental to \"securing the boundaries\" of the type system (,  come to my mind)?How many of the considerations/differences/problems mentioned above can also be recognized in Java?(See  as a language-agnostic introduction.)When you say \"type\" I'm going to assume you mean static type mostly.  But I'll talk about dynamic types shortly.A static type is a property of a portion of a program that can be statically proven (static means \"without running it\").  In a statically typed language, every expression has a type whether you write it or not.  For instance, in the Cish \"int x = a * b + c - d\", a,b,c,and d have types, a * b has a type, a * b + c has a type and a * b + c -d has a type.  But we've only annotated x with a type.  In other languages, such as Scala, C#, Haskell, SML, and F#, even that wouldn't be necessary.Exactly what properties are provable depends on the type checker.A Scala style class, on the other hand, is just the specification for a set of objects.  That specification includes some type information and includes a lot of implementation and representation details such as method bodies and private fields, etc.  In Scala a class also specifies some module boundaries.Many languages have types but don't have classes and many languages have classes but don't have (static) types.There are several observable differences between types and classes. List[String] is a type but not a class. In Scala List is class but normally not a type (it's actually a higher kinded type).  In C# List isn't a type of any sort and in Java it's a \"raw type\". Scala offers structural types.  {def foo : Bar} means any object that provably has a foo method that returns a Bar, regardless of class.  It's a type, but not a class.Types can be abstracted using type parameters.   When you write def foo[T](x : T) = ..., then inside the body of foo T is a type.  But T is not a class.Types can be virtual in Scala (i.e. \"abstract type members\"), but classes can't be virtual with Scala today (although there's a boilerplate heavy way to encode virtual classes )Now, dynamic types.  Dynamic types are properties of objects that the runtime automatically checks before performing certain operations.  In dynamically typed class-based OO languages there's a strong correlation between types and classes.  The same thing happens on JVM languages such as Scala and Java which have operations that can only be checked dynamically such as reflection and casting.  In those languages, \"type erasure\" more or less means that the dynamic type of most objects is the same as their class.  More or less.  That's not true of, e.g., arrays which aren't typically erased so that the runtime can tell the difference between Array[Int] and Array[String].  But remember my broad definition \"dynamic types are properties of objects that the runtime automatically checks.\"  When you use reflection it is possible to send any message to any object.  If the object supports that message then everything works out.  Thus it makes sense to talk of all objects that can quack like a duck as a dynamic type, even though it's not a class.  That's the essence of what the Python and Ruby communities call \"duck typing.\"  Also, by my broad definition even \"zeroness\" is a dynamic type in the sense that, in most languages, the runtime automatically checks numbers to make sure you don't divide by zero.  There are a very, very few languages that can prove that statically by making zero (or not-zero) a static type.Finally, as other's have mentioned, there are types like int which don't have a class as an implementation detail, types like Null and Any which are a bit special but COULD have classes and don't, and types like Nothing which doesn't even have any values let alone a class.Okay, I'll bite...  James has a good answer, so I'm going to try a different tact and give a more down-to-earth viewpoint.Broadly speaking, a class is . singleton objects (scala) traits (Scala) and interfaces (Scala) are also commonly considered to be classes.  This makes sense, as singletons are still instantiated (via compiler-generated code) and an interface can be instantiated as part of a subclass.Which brings us to the second point.  classes are the primary unit of design in most object-oriented languages (though not the prototype-based ones like javascript).  Polymorphism and subclassing are both defined in terms of classes.  classes also provide a namespace and visibility controls.types are a very different beast, every possible value that the system can express will have one or more types, and these can sometimes be equated to classes, for example:You also get some interesting differences between Scala and Java:and the really fun types that aren't classes at all.  For example,  always refers to the unique type of .  It's unique to a single instance and isn't even compatible with other instances of the same class.There are also abstract types and type parameters.  For example: is interesting as it's a class, but not a type.  More accurately, it's a \"type constructor\"; something that will construct a valid type when supplied with the necessary type parameter. Another term for type constructors is \"higher kinded types\", I personally don't like this term, as \"type constructor\" encourages me to think in terms of supplying types like any other form of argument - a mental model that has served me well for Scala.\"higher-kinded\" rightly implies that  has a \"kind\", which is , this notation states that  will take a single type and yield a single type (this is similar to curried notation for describing functions). By way of comparison, the kind of  is  because it takes two type parameters.A type can be useful by itself, without any instances. One example for this is called \"phantom type\". Here is an example for Java: In that example we have , where  and  take some types (represented by the abstract classes  and ), without ever beeing instantiated. I hope this shows that types and classes are something different, and that types can be useful by itself.(Java only) I'd say, a type is a set of objects. Object  is type , if  is a member of set . Type  is a  of , if set  is a  of . For every class C (not interface) there is a set of objects, created from . Interestingly, we rarely cares about this set. (but every object does belong to a set like this, a fact that may be useful)For every class C, there is a type , generally refered to as \"the type C\", which is the set of all objects that can be created from  where S is C or a subclass of C. Similarly, for every interface I, there is a type , \"the type I\", which is the set of all objects that can be created from  where S implements I.Obviously, if class  is a subclass of , type S is a subtype of type C. Similar for interface There is a null type, which is the empty set. The null type is a subtype of every type.There is a set of all objects, which is the type Object. It's a super type of every type.So far, this formalism is pretty useless. A type is basically the same as a class or an interface, and the subtype relation is basically the subclass/subinterface relation. The triviality is a good thing, the language was understandable! But entering generics, there are more complicated types, and operations like unions and intersections of types. Types are no longer only classes and interfaces, and subtype relations are much richer and harder to understand."},
Scala

I was going through the  and it mentions on slide 10 to never use  in a  for abstract members and use  instead. The slide does not mention in detail why using abstract  in a  is an anti-pattern. I would appreciate it if someone can explain best practice around using val vs def in a trait for abstract methods  A  can be implemented by either of a , a , a  or an . So it's the most abstract form of defining a member. Since traits are usually abstract interfaces, saying you want a  is saying  the implementation should do. If you ask for a , an implementing class cannot use a .A  is needed only if you need a stable identifier, e.g. for a path-dependent type. That's something you usually don't need.Compare:If you hadyou wouldn't be able to define  or .Ok, and to confuse you and answer @om-nom-nom\u2014using abstract s can cause initialisation problems:This is an ugly problem which in my personal opinion should go away in future Scala versions by fixing it in the compiler, but yes, currently this is also a reason why one should not use abstract s. (Jan 2016): You are allowed to override an abstract  declaration with a  implementation, so that would also prevent the initialisation failure.I prefer not use  in traits because the val declaration has unclear and non-intuitive order of initialization. You may add a trait to already working hierarchy and it would break all things that worked before, see my topic: You should keep all things about using this val declarations in mind which eventually road you to an error.But there are times when you could not avoid using . As @0__ had mentioned sometimes you need a stable identifier and  is not one.I would provide an example to show what he was talking about:This code produces the error:If you take a minute to think you would understand that compiler has a reason to complain. In the  case it could not derive return type by any means.  means that it could be implemented in broad way. It could return different holders for each call and that holders would incorporate different  types. But Java virtual machine expects the same type to be returned.Always using def seems a bit awkward since something like this won't work:You will get the following error:"},
Scala

When using Scala in Spark, whenever I dump result out using saveAsTextFile, it seems to split the output into multiple part. I'm just passing a parameter(path) to it. does the number of output correspond to the number of reducer it uses? \ndoes this mean the output is compressed? I know I can combine the output together using bash, but is there an option to store the output in a single text file, without splitting?? I looked at the API docs, but it doesn't say much about this.The reason it saves it as multiple files is because the computation is distributed. If the output is small enough such that you think you can fit it on one machine, then you can end your program with And then save the resulting array as a file, Another way would be to use a custom partitioner, , and make it so everything goes to one partition though that isn't advisable because you won't get any parallelization.If you require the file to be saved with  you can use . This basically means do the computation then coalesce to 1 partition. You can also use  which is just a wrapper for  with the shuffle argument set to true. Looking through the source of  is how I figured most of this stuff out, you should take a look.You could call  and then  - but it might be a bad idea if you have a lot of data. Separate files per split are generated just like in Hadoop in order to let separate mappers and reducers write to different files. Having a single output file is only a good idea if you have very little data, in which case you could do collect() as well, as @aaronman said.You will be able to do it in the next version of Spark, in the current version 1.0.0 it's not possible unless you do it manually somehow, for example, like you mentioned, with a bash script call. In Spark 1.6.1 the format is as shown below. It creates a single output file.It is best practice to use it if the output is small enough to handle.Basically what it does is that it returns a new RDD that is reduced into numPartitions partitions.If you're doing a drastic coalesce, e.g. to numPartitions = 1, this may result in your computation taking place on fewer nodes than you like (e.g. one node in the case of numPartitions = 1)As others have mentioned, you can collect or coalesce your data set to force Spark to produce a single file. But I prefer to let it create a hundred files in the output HDFS directory, then use  to extract the results into a single file in the local filesystem. This makes the most sense when your output is a relatively small report, of course.I also want to  mention that the documentation clearly states that users should be careful when calling coalesce with a real small number of  partitions  . this can cause upstream partitions to inherit this number of partitions.I would not recommend  using coalesce(1) unless really required. "},
Scala

In Martin Odersky's  in Scala, in the  section, he includes the term .These are not mentioned in . What are they?Early initializers are part of the constructor of a subclass that is intended to run before its superclass. For example:If the code was written instead asthen a null pointer exception would occur when  got initialized, because  is initialized before  in the normal ordering of initialization (superclass before class).For syntax and motivation look here:  (they are called \"early definitions\" there, but it's the same)As far as I can tell, the motivation (as given in the link above) is:\"Naturally when a val is overridden, it is not initialized more than once. So though x2 in the above example is seemingly defined at every point, this is not the case: an overridden val will appear to be null during the construction of superclasses, as will an abstract val.\"I don't see why this is natural at all. It is completely possible that the r.h.s. of an assignment might have a side effect. Note that such code structure is completely impossible in either C++ or Java (and I will guess Smalltalk, although I can't speak for that language). In fact you have to make such dual assignments implicit...ticilpmi...EXplicit in those languages via constructors. In the light of the r.h.s. side effect uncertainty, it really doesn't seem like much of a motivation at all: the ability to sidestep superclass side effects (thereby voiding superclass invariants) via ASSIGNMENT? Ick!Are there other \"killer\" motivations for allowing such unsafe code structure? Object-oriented languages have done without such a mechanism for about 40 years (30-odd years, if you count from the creation of the language), why include it now?It...just...seems...dangerous.On second thought, a year layer...This is just cake. Literally.Not an early ANYTHING. Just cake (mixins).Cake is a term/pattern coined by The Grand Pooh-bah himself, one that employs Scala's trait system, which is halfway between a class and an interface. It is far better than Java's decoration pattern.The so-called \"interface\" is merely an unnamed base class, and what used to be the base class is acting as a trait (which I frankly did not know could be done). It is unclear to me if a \"with'd\" class can take arguments (traits can't), will try it and report back.This question and its answer has stepped into one of Scala's coolest features. Read up on it and be in awe."},
Scala

I wrote this in scala and it won't compile:the compiler notify:I know JVM has no native support for generics so I understand this error.I could write wrappers for  and  but I'm lazy :)I'm doubtful but, is there another way expressing  is not the same type than ?Thanks.I like Michael Kr\u00e4mer's idea to use implicits, but I think it can be applied more directly:I think this is quite readable and straightforward.There is another easy way which seems to work:For every version you need an additional type parameter, so this doesn't scale, but I think for three or four versions it's fine.For exactly two methods I found another nice trick:Instead of inventing dummy implicit values, you can use the  defined in  which seems to be made exactly for that:Due to the wonders of type erasure, the type parameters of your methods' List get erased during compilation, thus reducing both methods to the same signature, which is a compiler error.To understand , it's necessary to recognize that the types of the implicit parameters are unimportant. What  important is that their types are distinct.  The following code works in the same way:At the bytecode level, both  methods become two-argument methods since JVM bytecode knows nothing of implicit parameters or multiple parameter lists. At the callsite, the Scala compiler selects the appropriate  method to call (and therefore the appropriate dummy object to pass in) by looking at the type of the list being passed in (which isn't erased until later).While it's more verbose, this approach relieves the caller of the burden of supplying the implicit arguments.  In fact, it even works if the dummyN objects are private to the  class.As Viktor Klang already says, the generic type will be erased by the compiler. Fortunately, there's a workaround:Thanks for  for the tip!If I combine s   and s response here  I get: I get a typesafe(ish) variant The logic may also be included in the type class as such (thanks to ): \n    @annotation.implicitNotFound(msg = \"Foo does not support ${T} only Int and String accepted\")\n    sealed trait Foo[T] { def apply(list : List[T]) : Unit }Which gives: Note that we have to write  since the compiler thinks that   means that we call  with parameters.There is (at least one) another way, even if it is not too nice and not really type safe:The implicit manifest paramenter can be used to \"reify\" the erased type and thus hack around erasure. You can learn a bit more about it in many blog posts,e.g. .What happens is that the manifest param can give you back what T was before erasure. Then a simple dispatch based on T to the various real implementation does the rest.Probably there is a nicer way to do the pattern matching, but I haven't seen it yet. What people usually do is matching on m.toString, but I think keeping classes is a bit cleaner (even if it's a bit more verbose). Unfortunately the documentation of Manifest is not too detailed, maybe it also has something that could simplify it. A big disadvantage of it is that it's not really type safe: foo will be happy with any T, if you can't handle it you will have a problem. I guess it could be worked around with some constraints on T, but it would further complicate it. And of course this whole stuff is also not too nice, I'm not sure if it worth doing it, especially if you are lazy ;-)Instead of using manifests you could also use dispatchers objects implicitly imported in a similar manner. I blogged about this before manifests came up: This has the advantage of type safety: the overloaded method will only be callable for types which have dispatchers imported into the current scope. I tried improving on Aaron Novstrup\u2019s and Leo\u2019s answers to make one set of standard evidence objects importable and more terse.But that will cause the compiler to complain that there are ambiguous choices for the implicit value when  calls another method which requires an implicit parameter of the same type.Thus I offer only the following which is more terse in some cases. And this improvement works with value classes (those that ).If the containing type name is rather long, declare an inner  to make it more terse.However, value classes do not allow inner traits, classes, nor objects. Thus also note Aaron Novstrup\u2019s and Leo\u2019s answers do not work with a value classes.Nice trick I've found from \nby Aaron Novstrup[...]I didn't test this, but why wouldn't an upper bound work?Does the erasure translation to change from foo( List[Any] s ) twice, to foo( List[String] s ) and foo( List[Int] i ):I think I read that in version 2.8, the upper bounds are now encoded that way, instead of always an Any.To overload on covariant types, use an invariant bound (is there such a syntax in Scala?...ah I think there isn't, but take the following as conceptual addendum to the main solution above):then I presume the implicit casting is eliminated in the erased version of the code.UPDATE: The problem is that JVM erases more type information on method signatures than is \"necessary\". I provided a link. It erases type variables from type constructors, even the concrete bound of those type variables. There is a conceptual distinction, because there is no conceptual non-reified advantage to erasing the function's type bound, as it is known at compile-time and does not vary with any instance of the generic, and it is necessary for callers to not call the function with types that do not conform to the type bound, so how can the JVM enforce the type bound if it is erased? Well  says the type bound is retained in metadata which compilers are supposed to access. And this explains why using type bounds doesn't enable overloading. It also means that JVM is a wide open security hole since type bounded methods can be called without type bounds (yikes!), so excuse me for assuming the JVM designers wouldn't do such an insecure thing.At the time I wrote this, I didn't understand that stackoverflow was a system of rating people by quality of answers like some competition over reputation. I thought it was a place to share information. At the time I wrote this, I was comparing reified and non-reified from a conceptual level (comparing many different languages), and so in my mind it didn't make any sense to erase the type bound."},
Scala

Why does this construction cause a Type Mismatch error in Scala?If I switch the Some with the List it compiles fine:This also works fine:For comprehensions are converted into calls to the  or  method. For example this one:becomes that:Therefore, the first loop value (in this case, ) will receive the  method call. Since  on a  returns another , the result of the for comprehension will of course be a . (This was new to me: For comprehensions don't always result in streams, not even necessarily in s.)Now, take a look at how  is declared in :Keep this in mind. Let's see how the erroneous for comprehension (the one with ) gets converted to a sequence of map calls:Now, it's easy to see that the parameter of the  call is something that returns a , but not an , as required.In order to fix the thing, you can do the following:That compiles just fine. It is worth noting that  is not a subtype of , as is often assumed.An easy tip to remember,  will try to return the type of the collection of the first generator, Option[Int] in this case. So, if you start with  you should expect a result of Option[T]. If you want a result of  type, you should start with a List generator.Why have this restriction and not assume you'll always want some sort of sequence? You can have a situation where it makes sense to return . Maybe you have an  that you want to combine with something to get a , say with the following function: ; you could then write this and get None when things don't \"make sense\":How  are expanded in the general case are in fact a fairly general mechanism to combine an object of type  with a function  to get an object of type . In your example, M can be Option or List. In general it has to be the same type . So you can't combine Option with List. For examples of other things that can be , look at .Why did combining  with  work though when you started with the List? In this case the library use a more general type where it makes sense. So you can combine List with Traversable and there is an implicit conversion from Option to Traversable.The bottom line is this: think about what type you want the expression to return and start with that type as the first generator. Wrap it in that type if necessary. It probably has something to do with Option not being an Iterable. The implicit  will handle the case where compiler is expecting second to be an Iterable. I expect that the compiler magic is different depending on the type of the loop variable."},
Scala

How can I convert an  to a 7-character long , so that  is turned into ?The Java library has pretty good (as in excellent)  which is accessible from  enriched String class:: as suggested by fommil, from 2.10 on, there is also a formatting string interpolator:Scala  (which contains a nice set of methods that Scala string objects have because of implicit conversions) has a  method, which appends a certain amount of characters to your string. For example:Will return \"alohaaaaaa\" (actually it will return a Vector but it's not important for this case).Your problem is a bit different since you need to  characters instead of  them. That's why you need to reverse the string, append the fill-up characters (you would be prepending them now since the string is reversed), and then reverse the whole thing again to get the final result.Hope this helps!huynhjl beat me to the right answer, so here's an alternative:The  is denoted by  for  to be prefixed to make the length :In case this Q&A becomes the canonical compendium,Do you need to deal with negative numbers? If not, I would just doorOtherwise, you can use :"},
Scala

How large is Scala's thread pool for futures?My Scala application makes many millions of s and I wonder if there is anything I can do to optimize them by configuring a thread pool.Thank you.You can specify your own ExecutionContext that your futures will run in, instead of importing the global implicit ExecutionContext.This answer is from monkjack, a comment from the accepted answer. However, one can miss this great answer so I'm reposting it here.If you just need to change the thread pool count, just use the global executor and pass the following system properties.best way to specify threadpool in scala futures:"},
Scala

I want to know the technical reasons why the lift webframework has high performance and scalability?  I know it uses scala, which has an actor library, but according to the install instructions it default configuration is with jetty. So does it use the actor library to scale?Now is the scalability built right out of the box.  Just add additional servers and nodes and it will automatically scale, is that how it works?  Can it handle 500000+ concurrent connections with supporting servers.  I am trying to create a web services framework for the enterprise level, that can beat what is out there and is easy to scale, configurable, and maintainable.  My definition of scaling is just adding more servers and you should be able to accommodate the extra load.ThanksLift's approach to scalability is within a single machine. Scaling across machines is a larger, tougher topic.  The short answer there is: Scala and Lift don't do anything to either help or hinder horizontal scaling.As far as actors within a single machine, Lift achieves better scalability because a single instance can handle more concurrent requests than most other servers. To explain, I first have to point out the flaws in the classic thread-per-request handling model.  Bear with me, this is going to require some explanation.A typical framework uses a thread to service a page request. When the client connects, the framework assigns a thread out of a pool. That thread then does three things: it reads the request from a socket; it does some computation (potentially involving I/O to the database); and it sends a response out on the socket.  At pretty much every step, the thread will end up blocking for some time.  When reading the request, it can block while waiting for the network. When doing the computation, it can block on disk or network I/O. It can also block while waiting for the database.  Finally, while sending the response, it can block if the client receives data slowly and TCP windows get filled up. Overall, the thread might spend 30 - 90% of it's time blocked.  It spends 100% of its time, however, on that one request.A JVM can only support so many threads before it really slows down. Thread scheduling, contention for shared-memory entities (like connection pools and monitors), and native OS limits all impose restrictions on how many threads a JVM can create.Well, if the JVM is limited in its maximum number of threads, and the number of threads determines how many concurrent requests a server can handle, then the number of concurrent requests will be determined by the number of threads.(There are other issues that can impose lower limits---GC thrashing, for example. Threads are a fundamental limiting factor, but not the only one!)Lift decouples thread from requests. In Lift, a request does  tie up a thread. Rather, a thread does an action (like reading the request), then sends a message to an actor. Actors are an important part of the story, because they are scheduled via \"lightweight\" threads.  A pool of threads gets used to process messages within actors. It's important to avoid blocking operations inside of actors, so these threads get returned to the pool rapidly.  (Note that this pool isn't visible to the application, it's part of Scala's support for actors.)  A request that's currently blocked on database or disk I/O, for example, doesn't keep a request-handling thread occupied. The request handling thread is available, almost immediately, to receive more connections.This method for decoupling requests from threads allows a Lift server to have many more concurrent requests than a thread-per-request server.  (I'd also like to point out that the Grizzly library supports a similar approach without actors.)  More concurrent requests means that a single Lift server can support more users than a regular Java EE server.at mtnyguard\"Scala and Lift don't do anything to either help or hinder horizontal scaling\"Ain't quite right. Lift is highly statefull framework. For example if a user requests a form, then he can only post the request to the same machine where the form came from, because the form processeing action is saved in the server state.And this is actualy a thing which hinders scalability in a way, because this behaviour is inconistent to the shared nothing architecture.No doubt that lift is highly performant but perfomance and scalability are two different things. So if you want to scale horizontaly with lift you have to define sticky sessions on the loadbalancer which will redirect a user during a session to the same machine.Jetty maybe the point of entry, but the actor ends up servicing the request, I suggest having a look at the twitter-esque example, 'skitter' to see how you would be able to create a very scalable service. IIRC, this is one of the things that made the twitter people take notice.I really like @dre's reply as he correctly states the statefulness of lift being a potential problem for horizontal scalability. The problem - \nInstead of me describing the whole thing again, check out the discussion (Not the content) on this post. Solution would be as @dre said sticky session configuration on load balancer on the front and adding more instances. But since request handling in lift is done in thread + actor combination you can expect one instance handle more requests than normal frameworks. This would give an edge over having sticky sessions in other frameworks. i.e. Individual instance's capacity to process more may help you to scale"},
Scala

Akka 2.x requires many commands to reference an .  So, to create an instance of an actor  you might say:Because of the frequent need for an : many code examples omit the creation from the code and assume that the reader knows where a  variable has come from. If your code produces actors in different places, you could duplicate this code, possibly creating additional  instances, or you could try to share the same  instance by referring to some global or by passing the  around.The Akka documentation provides a  under the heading 'Actor Systems', and there is .  But neither of these help a great deal in explaining why a user of Akka can't just rely on Akka to manage this under-the-hood.Creating an ActorSystem is very expensive, so you want to avoid creating a new one each time you need it. Also your actors should run in the same ActorSystem, unless there is a good reason for them not to. The name of the ActorSystem is also part the the path to the actors that run in it. E.g. if you create an actor in a system named  it will have a path like . If you are in an actor context, you always have a reference to the ActorSystem. In an Actor you can call . I don't know what akka-testkit expects, but you could take a look at the akka tests. So to sum it up, you should always use the same system, unless there is a good reason not to do so.Here are some materials which might be helpful to understand \"Why does document always suggest to use one ActorSystem for one logical application\" : Here is a  , if you have time, you can read it. They discuss a lot, ActorSystem, local or remote, etc. "},
Scala

I'm tearing my hair out trying to figure out how to do the following:There's a reason why I have to declare the method with an  and an   separately. Basically, I end up with the format method called with a single object parameter (of type ). Attempting:Gives me the type error:I've tried casting, which compiles but fails for pretty much the same reason as the first example. When I trythis fails to compile with implicit conversion ambiguity ( and )orI much prefer the latter, though it has no locale* support."},
Scala

I am exploring the Scala language. One claim I often hear is that Scala has a  type system than Java. By this I think what people mean is that:Am I right in thinking so? If so, please point to articles/blogs/papers which illustrate such examples.The main advantage of the Scala Type system is not so much being  but rather being far  (see \"\").\n(Java can define some of them, and implement others, but Scala has them built-in).\nSee also , commenting , where he \"disses\" Scala as \"Frankenstein's Monster\" because \"there are type types, and type type types\".The main safety problem with Java relates to variance. Basically, a programmer can use incorrect variance declarations that may result in exceptions being thrown at run-time in Java, while Scala will not allow it.In fact, the very fact that Java's  is co-variant is already a problem, since it allows incorrect code to be generated. For instance, as exemplified by :Then, of course, there are raw types in Java, which allows all sort of things.Also, though Scala has it as well, there's casting. Java API is rich in type casts, and there's no idiom like Scala's . Sure, one case use  to accomplish that, but there's no incentive to do it. In fact, Scala's  is intentionally verbose.These are the things that make Scala's type system stronger. It is also much richer, as  shows."},
Scala

I have a base abstract class (trait). It has an abstract method . It is extended and implemented by several derived classes. I want to create a trait that can be mixed into the derived classes so that it implements  and then calls the derived class's .Something like:I tried self types and structural types, but I can't get it to work.You were very close. Add the abstract modifier to M.foo, and you have the 'Stackable Trait' pattern: "},
Scala

So far implicit parameters in Scala do not look good for me -- it is too close to global variables, however since Scala seems like rather strict language I start doubting in my own opinion :-). could you show a real-life (or close) good example when implicit parameters really work. IOW: something more serious than , that would justify such language design.Or contrary -- could you show reliable language design (can be imaginary) that would make implicit not neccessary. I think that even no mechanism is better than implicits because code is clearer and there is no guessing.Thank you for all great answers. Maybe I clarify my \"global variables\" objection. Consider such function:you call it you could (!) do it like this:but in my eyes  works like this:it is not very different from such construct (PHP-like)This is great example, however if you can think of as flexible usage of sending message not using  please post an counter-example. I am really curious about purity in language design ;-).In a sense, yes, implicits represent global state. However, they are not mutable, which is the true problem with global variables -- you don't see people complaining about global constants, do you? In fact, coding standards usually dictate that you transform any constants in your code into constants or enums, which are usually global.Note also that implicits are  in a flat namespace, which is also a common problem with globals. They are explicitly tied to types and, therefore, to the package hierarchy of those types.So, take your globals, make them immutable and initialized at the declaration site, and put them on namespaces. Do they still look like globals? Do they still look problematic?But let's not stop there. Implicits  tied to types, and they are just as much \"global\" as types are. Does the fact that types are global bother you?As for use cases, they are many, but we can do a brief review based on their history. Originally, afaik, Scala did not have implicits. What Scala had were view types, a feature many other languages had. We can still see that today whenever you write something like , which means the type  can be viewed as a type . View types are a way of making automatic casts available on type parameters (generics).Scala then  that feature with implicits. Automatic casts no longer exist, and, instead, you have  -- which are just  values and, therefore, can be passed as parameters. From then on,  meant a value for an implicit conversion would be passed as parameter. Since the cast is automatic, the caller of the function is not required to explicitly pass the parameter -- so those parameters became .Note that there are two concepts -- implicit conversions and implicit parameters -- that are very close, but do not completely overlap.Anyway, view types became syntactic sugar for implicit conversions being passed implicitly. They would be rewritten like this:The implicit parameters are simply a generalization of that pattern, making it possible to pass  kind of implicit parameters, instead of just . Actual use for them then followed, and syntactic sugar for  uses came latter.One of them is , used to implement the  (pattern because it is not a built-in feature, just a way of using the language that provides similar functionality to Haskell's type class). A context bound is used to provide an adapter that implements functionality that is inherent in a class, but not declared by it. It offers the benefits of inheritance and interfaces without their drawbacks. For example:You have probably used that already -- there's one common use case that people usually don't notice. It is this:That uses a context bound of a class manifests, to enable such array initialization. We can see that with this example:You can write it like this:On the standard library, the context bounds most used are:The latter three are mostly used with collections, with methods such as ,  and . One library that makes extensive use of context bounds is Scalaz.Another common usage is to decrease boiler-plate on operations that must share a common parameter. For example, transactions:Which is then simplified like this:This pattern is used with transactional memory, and I think (but I'm not sure) that the Scala I/O library uses it as well.The third common usage I can think of is making proofs about the types that are being passed, which makes it possible to detect at compile time things that would, otherwise, result in run time exceptions. For example, see this definition on :That makes this possible:One library that makes extensive use of that feature is Shapeless.I don't think the example of the Akka library fits in any of these four categories, but that's the whole point of generic features: people can use it in all sorts of way, instead of ways prescribed by the language designer.If you like being prescribed to (like, say, Python does), then Scala is just not for you.Sure.  Akka's got a great example of it with respect to its Actors.  When you're inside an Actor's  method, you might want to send a message to another Actor.  When you do this, Akka will bundle (by default) the current Actor as the  of the message, like this:The  is implicit.  In the Actor there is a definition that looks like:This creates the implicit value within the scope of your own code, and it allows you to do easy things like this:Now, you can do this as well, if you like:ororBut normally you don't.  You just keep the natural usage that's made possible by the implicit value definition in the Actor trait.  There are about a million other examples.  The collection classes are a huge one.  Try wandering around any non-trivial Scala library and you'll find a truckload.One example would be the comparison operations on . E.g.  or :These can only be sensibly defined when there is an operation  on . So, without implicits we\u2019d have to supply the context  every time we\u2019d like to use this function. (Or give up type static checking inside  and risk a runtime cast error.)If however, an implicit comparison  is in scope, e.g. some , we can just use it right away or simply change the comparison method by supplying some other value for the implicit parameter.Of course, implicits may be shadowed and thus there may be situations in which the actual implicit which is in scope is not clear enough. For simple uses of  or  it might indeed be sufficient to have a fixed ordering  on  and use some syntax to check whether this trait is available. But this would mean that there could be no add-on traits and every piece of code would have to use the traits which were originally defined.\nI think you\u2019re correct that in a code snipped likeit may smell of rotten and evil global variables. The crucial point, however, is that there may be only one implicit variable  in scope. Your example with two s is not going to work.Also, this means that practically, implicit variables are employed only when there is a not necessarily unique yet distinct primary instance for a type. The  reference of an actor is a good example for such a thing. The type class example is another example. There may be dozens of algebraic comparisons for any type but there is one which is special.\n(On another level, the actual  in the code itself might also make for a good implicit variable as long as it uses a very distinctive type.)You normally don\u2019t use s for everyday types. And with specialised types (like ) there is not too much risk in shadowing them.Another good general usage of implicit parameters is to make the return type of a method depend on the type of some of the parameters passed to it. A good example, mentioned by Jens, is the collections framework, and methods like , whose full signature usually is:Note that the return type  is determined by the best fitting  that the compiler can find.For another example of this, see . There, the return type of the method  is determined according to a certain implicit parameter type ().It's easy, just remember:e.g.Implicit parameters are heavily used in the collection API. Many functions get an implicit CanBuildFrom, which ensures that you get the 'best' result collection implementation.Without implicits you would either pass such a thing all the time, which would make normal usage cumbersome. Or use less specialized collections which would be annoying because it would mean you loose performance/power.Based on my experience there is no real good example for use of implicits parameters or implicits conversion.The small benefit of using implicits (not needing to explicitly write a parameter or a type) is redundant in compare to the problems they create. I am a developer for 15 years, and have been working with scala for the last 1.5 years.I have seen many times bugs that were caused by the developer not aware of the fact that implicits are used, and that a specific function actually return a different type that the one specified. Due to implicit conversion.I also heard statements saying that if you don't like implicits, don't use them.\nThis is not practical in the real world since many times external libraries are used, and a lot of them are using implicits, so your code using implicits, and you might not be aware of that.\nYou can write a code that has either:or:Both codes will compile and run.\nBut they will not always produce the same results since the second version imports implicits conversion that will make the code behave differently.The 'bug' that is caused by this can occur a very long time after the code was written, in case some values that are affected by this conversion were not used originally.Once you encounter the bug, its not an easy task finding the cause.\nYou have to do some deep investigation.Even though you feel like an expert in scala once you have found the bug, and fixed it by changing an import statement, you actually wasted a lot of precious time.Additional reasons why I generally against implicits are:There is no option to compile scala without implicits (if there is please correct me), and if there was an option, none of the common community scala libraries would have compile. For all the above reasons, I think that implicits are one of the worst practices that scala language is using.Scala has many great features, and many not so great.When choosing a language for a new project, implicits are one of the reasons against scala, not in favour of it. In my opinion."},
Scala

As I understand from   \"type classes\" in Scala is just a \"pattern\" implemented with traits and implicit adapters.As the blog says if I have trait  and an adapter  then I can invoke a function, which requires argument of type , with an argument of type  without invoking this adapter explicitly.I found it nice but not particularly useful. Could you give a use case/example, which shows what this feature is useful for ? One use case, as requested...Imagine you have a list of things, could be integers, floating point numbers, matrices, strings, waveforms, etc.  Given this list, you want to add the contents.One way to do this would be to have some  trait that must be inherited by every single type that can be added together, or an implicit conversion to an  if dealing with objects from a third party library that you can't retrofit interfaces to.This approach becomes quickly overwhelming when you also want to begin adding other such operations that can be done to a list of objects.  It also doesn't work well if you need alternatives (for example; does adding two waveforms concatenate them, or overlay them?) The solution is ad-hoc polymorphism, where you  pick and chose behaviour to be retrofitted to existing types.For the original problem then, you could implement an  type class:You can then create implicit subclassed instances of this, corresponding to each type that you wish to make addable:The method to sum a list then becomes trivial to write...The beauty of this approach is that you can supply an alternative definition of some typeclass, either controlling the implicit you want in scope via imports, or by explicitly providing the otherwise implicit argument.  So it becomes possible to provide different ways of adding waveforms, or to specify modulo arithmetic for integer addition.  It's also fairly painless to add a type from some 3rd-party library to your typeclass.Incidentally, this is exactly the approach taken by the 2.8 collections API.  Though the  method is defined on  instead of on , and the type class is  (it also contains a few more operations than just  and )Reread the first comment there:I think this is the most important advantage of type classes.Also, they handle properly the cases where the operations don't have the argument of the type we are dispatching on, or have more than one. E.g. consider this type class:I think of type classes as the ability to add type safe metadata to a class. So you first define a class to model the problem domain and then think of metadata to add to it. Things like Equals, Hashable, Viewable, etc. This creates a separation of the problem domain and the mechanics to use the class and opens up subclassing because the class is leaner. Except for that, you can add type classes anywhere in the scope, not just where the class is defined and you can change implementations. For example, if I calculate a hash code for a Point class by using Point#hashCode, then I'm limited to that specific implementation which may not create a good distribution of values for the specific set of Points I have. But if I use Hashable[Point], then I may provide my own implementation.[Updated with example]\nAs an example, here's a use case I had last week. In our product there are several cases of Maps containing containers as values. E.g.,  or . Adding to these collections can be verbose:So I wanted to have a function that wraps this so I could writeThe main issue is that the collections don't all have the same methods for adding elements. Some have '+' while others ':+'. I also wanted to retain the efficiency of adding elements to a list, so I didn't want to use fold/map which create new collections.The solution is to use type classes:Here I defined a type class  that can add an element C to a collection CC. I have 2 default implementations: For Lists using  and for other collections, using the builder framework.Then using this type class is:The special bit is using  to add the elements and  to create new collections for new keys. To compare, without type classes I would have had 3 options:\n1. to write a method per collection type. E.g.,  and  etc. This creates a lot of boilerplate in the implementation and pollutes the namespace\n2. to use reflection to determine if the sub collection is a List / Set. This is tricky as the map is empty to begin with (of course scala helps here also with Manifests)\n3. to have poor-man's type class by requiring the user to supply the adder. So something like , which is plain uglyYet another way I find this blog post helpful is where it describes typeclasses:  Search the article for typeclass.  It should be the first match.  In this article, the author provides an example of a Monad typeclass.One way to look at type classes is that they enable  or .  There are a couple of great posts by  and  that show examples of using Type Classes in Scala to achieve this.Here's a \n that explores various methods in scala of , a kind of retroactive extension, including a typeclass example.The forum thread \"\" makes some interesting points:I don't know of any other use case than  which is explained  the best way possible.Both  and  are used for . The major use-case for both of them is to provide (i.e) on classes that you can't modify but expect inheritance kind of polymorphism. In case of implicits you could use both an implicit def or an implicit class (which is your wrapper class but hidden from the client). Typeclasses are more powerful as they can add functionality to an already existing inheritance chain(eg: Ordering[T] in scala's sort function). \nFor more detail you can see  is an important difference (needed for functional programming):consider :  received is the same that is returned, this cannot be done with subtypingIn scala type classesBehavior can be extended\n - at compile-time\n - after the fact\n - without changing/recompiling existing codeScala ImplicitsThe last parameter list of a method can be marked implicitBelow Example extension on String class with type class implementation extends the class with a new methods even though string is final :) "},
Scala

This weekend I decided to try my hand at some Scala and Clojure.  I'm proficient with object oriented programming, and so Scala was easy to pick up as a language, but wanted to try out functional programming.  This is where it got hard.  I just can't seem to get my head into a mode of writing functions.  As an expert functional programmer, how do you approach a problem?Given a list of values and a defined period of summation, how would you generate a new list of the simple moving average of the list?For example: Given the list  (2.0, 4.0, 7.0, 6.0, 3.0, 8.0, 12.0, 9.0, 4.0, 1.0), and the  4, the function should return: (0.0, 0.0, 0.0, 4.75, 5.0, 6.0, 7.25, 8.0, 8.25, 6.5)After spending a day mulling it over, the best I could come up with in Scala was this:I know this is horribly inefficient, I'd much rather do something like:  Now that would be easily done in a imperative style, but I can't for the life of me work out how to express that functionally.Interesting problem. I can think of many solutions, with varying degrees of efficiency. Having to add stuff repeatedly isn't really a performance problem, but let's assume it is. Also, the zeroes at the beginning can be prepended later, so let's not worry about producing them. If the algorithm provides them naturally, fine; if not, we correct it later.Starting with Scala 2.8, the following would give the result for  by using  to get a sliding window of the List:Nevertheless, although this is rather elegant, it doesn't have the best performance possible, because it doesn't take advantage of already computed additions. So, speaking of them, how can we get them?Let's say we write this:We have a list of the sum of each two pairs. Let's try to use this result to compute the moving average of 4 elements. The above formula made the following computation:So if we take each element and add it to the second next element, we get the moving average for 4 elements:We may do it like this:We could then compute the moving average for 8 elements, and so on. Well, there is a well known algorithm to compute things that follow such pattern. It's most known for its use on computing the power of a number. It goes like this:So, let's apply it here:So, here's the logic. Period 0 is invalid, period 1 is equal to the input, period 2 is sliding window of size 2. If greater than that, it may be even or odd.If odd, we add each element to the  of the next  elements. For example, if 3, we add each element to the  of the next 2 elements.If even, we compute the  for , then add each element to the one  steps afterwards.With that definition, we can then go back to the problem and do this:There's a slight inefficiency with regards to the use of , but it's O(period), not O(values.size). It can be made more efficient with a tail recursive function. And, of course, the definition of \"sliding\" I provided is horrendous performance-wise, but there will be a much better definition of it on Scala 2.8. Note that we can't make an efficient  method on a , but we can do it on an .Having said all that, I'd go with the very first definition, and optimize only if a critical path analysis pinpointed this as a big deal.To conclude, let's consider how I went about the problem. We have a moving average problem. A moving average is the sum of a moving \"window\" on a list, divided by the size of that window. So, first, I try to get a sliding window, sum everything on it, and then divide by the size.The next problem was to avoid repetition of already computed additions. In this case, I went to the smallest addition possible, and tried to figure out how to compute bigger sums reusing such results.Finally, let's try to solve the problem the way you figured it, by adding and subtracting from the previous result. Getting the first average is easy:Now we make two lists. First, the list of elements to be subtracted. Next, the list of elements to be added:We can add these two lists by using . This method will only produce as many elements as the smaller list has, which avoids the problem of  being bigger than necessary:We finish by composing the result with a fold:which is the answer to be returned. The whole function looks like this:I know Clojure better than Scala, so here goes. As I write this the other Clojure entry here is imperative; that's not really what you're after (and isn't idiomatic Clojure). The first algorithm that comes to my mind is repeatedly taking the requested number of elements from the sequence, dropping the first element, and recurring. The following works on any kind of sequence (vector or list, lazy or not) and gives a lazy sequence of averages---which could be helpful if you're working on a list of indefinite size. Note that it takes care of the base case by implicitly returning nil if there aren't enough elements in the list to consume.Running this on your test data yieldsIt doesn't give \"0\" for the first few elements in the sequence, though that could easily be handled (somewhat artificially). The easiest thing of all is to see the pattern and be able to bring to mind an available function that fits the bill.  gives a lazy view of portions of a sequence, which we can then map over:Someone asked for a tail recursive version; tail recursion vs. laziness is a bit of a tradeoff. When your job is building up a list then making your function tail recursive is usually pretty simple, and this is no exception---just build up the list as an argument to a subfunction. We'll accumulate to a vector instead of a list because otherwise the list will be built up backwards and will need to be reversed at the end. is a way to make an anonymous inner function (sort of like Scheme's named let);  must be used in Clojure to eliminate tail calls.  is a generalized , appending in the manner natural for the collection---the beginning of lists and the end of vectors.Here is another (functional) Clojure solution: The zeros at the beginning of the sequence must still be added if that is a requirement.Here's a purely functional solution in Clojure. More complex than those already provided, but it is  and . It's actually slower than a simple solution which calculates a new average at each step if the period is small; for larger periods, however, it experiences virtually no slowdown, whereas something doing  will perform worse for longer periods.Here's a partially  one line Haskell solution:First it applies  to the list to get the \"tails\" lists, so:Reverses it and drops the first 'p' entries (taking p as 2 here):In case you aren't familiar with the  symbol, it is the operator for 'functional composition', meaning it passes the output of one function as the input of another, \"composing\" them into a single function. (g . f) means \"run f on a value then pass the output to g\", so ((f . g) x) is the same as (g(f x)). Generally its usage leads to a clearer programming style.It then maps the function ((/ (fromIntegral p)) . sum . take p) onto the list. So for every list in the list it takes the first 'p' elements, sums them, then divides them by 'p'. Then we just flip the list back again with \"reverse\".This all looks a lot more inefficient than it is; \"reverse\" doesn't physically reverse the order of a list until the list is evaluated, it just lays it out onto the stack (good ol' lazy Haskell). \"tails\" also doesn't create all those separate lists, it just references different sections of the original list. It's still not a great solution, but it one line long :)Here's a slightly nicer but longer solution that uses mapAccum to do a sliding subtraction and addition:First we split the list into two parts at \"p\", so:Sum the first bit:Zip the second bit with the original list (this just pairs off items in order from the two lists). The original list is obviously longer, but we lose this extra bit:Now we define a function for our mapAccum(ulator).  is the same as \"map\", but with an extra running state/accumulator parameter, which is passed from the previous \"mapping\" to the next one as map runs through the list. We use the accumulator as our moving average, and as our list is formed of the element that has just left the sliding window and the element that just entered it (the list we just zipped), our sliding function takes the first number 'x' away from the average and adds the second number 'y'. We then pass the new 's' along and return 's' divided by 'p'. \"snd\" (second) just takes the second member of a pair (tuple), which is used to take the second return value of mapAccumL, as mapAccumL will return the accumulator as well as the mapped list.For those of you not familiar with the , it is the \"application operator\". It doesn't really do anything but it has a has \"low, right-associative binding precedence\", so it means you can leave out the brackets (take note LISPers), i.e. (f x) is the same as f $ xRunning (ma 4 [2.0, 4.0, 7.0, 6.0, 3.0, 8.0, 12.0, 9.0, 4.0, 1.0]) yields [4.75, 5.0, 6.0, 7.25, 8.0, 8.25, 6.5] for either solution.Oh and you'll need to import the module \"List\" to compile either solution.Here are 2 more ways to do moving average in Scala 2.8.0(one strict and one lazy).  Both assume there are at least  Doubles in .The J programming language facilitates programs such as moving average. Indeed, there are fewer characters in  than in their label, 'moving average.'For the values specified in this question (including the name 'values') here is a straightforward way to code this:We can describe this by using labels for components.Both examples use exactly the same program. The only difference is the use of more names in the second form. Such names can help readers who don't know the J primaries.Let's look a bit further into what's going on in the subprogram, .  denotes summation (\u03a3) and  denotes division (like the classical sign \u00f7). Calculating a tally (count) of items is done by  . The overall program, then, is the sum of values divided by the tally of values: The result of the moving-average calculation written here does not include the leading zeros expected in the original question. Those zeros are arguably not part of the intended calculation.The technique used here is called tacit programming. It is pretty much the same as the point-free style of functional programming.Here is Clojure pretending to be a more functional language.  This is fully tail-recursive, btw, and includes leading zeroes.Usually I put the collection or list parameter last to make the function easier to curry.  But in Clojure...... is so cumbersome, I usually end up doing this ...... in which case, it doesn't really matter what order the parameters go.Here's a clojure version:Because of the lazy-seq, it's perfectly general and won't blow stack;; To help see what it's doing:;; ExampleThis example makes use of state, since to me it's a pragmatic solution in this case, and a closure to create the windowing averaging function:It is still functional in the sense of making use of first class functions, though it is not side-effect free.  The two languages you mentioned both run on top of the JVM and thus both allow for state-management when necessary.  This solution is in Haskell, which is more familiar to me:Scala translation:A short Clojure version that has the advantage of being O(list length) regardless of your period:This exploits the fact that you can calculate the sum of a range of numbers by creating a cumulative sum of the sequence (e.g. [1 2 3 4 5] -> [0 1 3 6 10 15]) and then subtracting the two numbers with an offset equal to your period.I know how I would do it in python (note: the first 3 elements with the values 0.0 are not returned since that is actually not the appropriate way to represent a moving average). I would imagine similar techniques will be feasible in Scala. Here are multiple ways to do it.It looks like you are looking for a recursive solution. In that case, I would suggest to slightly change the problem and aim for getting (4.75, 5.0, 6.0, 7.25, 8.0, 8.25, 6.5, 0.0, 0.0, 0.0) as a solution.In that case, you can write the below elegant recursive solution in Scala:Being late on the party, and new to functional programming too, I came to this solution with an inner function:I adopted the idea, to divide the whole list by the period (len) in advance. \nThen I generate the sum to start with for the len-first-elements.\nAnd I generate the first, invalid elements (0.0, 0.0, ...) .Then I recursively substract the first and add the last value.\nIn the end I listify the whole thing. In Haskell pseudocode:or pointfree(Now one really should abstract the 4 out ....)Using Haskell:The key is the tails function, which maps a list to a list of copies of the original list, with the property that the n-th element of the result is missing the first n-1 elements.SoWe apply fmap (avg . take n) to the result, which means we take the n-length prefix from the sublist, and compute its avg.  If the length of the list we are avg'ing is not n, then we do not compute the average (since it is undefined).  In that case, we return Nothing.  If it is, we do, and wrap it in \"Just\".  Finally, we run \"catMaybes\" on the result of fmap (avg . take n), to get rid of the Maybe type.I was (surprised and) disappointed by the performance of what seemed to me the most idiomatic Clojure solutions, @JamesCunningham 's  .So here's a combination of James' solution with @DanielC.Sobral 's  of adapting  to moving sums : this one -based on @mikera 's - is even faster."},
Scala

I'm trying to incorporate ScalaTest into my Java project, replacing all JUnit tests by ScalaTests. At one point, I want to check if Guice's Injector injects the correct type. In Java, I have a test like this:But I have a problem doing the same with ScalaTest:It complaints that the value instanceof is not a member of Door/Window/Roof. Can't I use instanceof that way in Scala? Scala is not Java. Scala just does not have the operator  instead it has a parametric method called .If you want to be less JUnit-esque and if you want to use ScalaTest's matchers, you can write your own property matcher that matches for type (bar type erasure).I found this thread to be quite useful: You can then write assertions like:instead of With Scalatest 2.2.x (maybe even earlier) you can use:The current answers about isInstanceOf[Type] and junit advice are good but I want to add one thing (for people who got to this page in a non-junit-related capacity).  In many cases scala pattern matching will suit your needs.  I would recommend it in those cases because it gives you the typecasting for free and leaves less room for error.Example:Consolidating Guillaume's ScalaTest discussion reference (and another discussion linked to by James Moore) into two methods, updated for ScalaTest 2.x and Scala 2.10 (to use ClassTag rather than manifest):"},
Scala

I am new to Scala and I really like it, but sometimes it surprises me. For instance:Could anyone tell me what  and  mean in Scala? is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class.For example, the type , is equivalent to the type  i.e. a function that takes an argument of type  and returns a .Here  is binded to the argument value passed to  and . is the type of a function that takes no arguments and returns a . It is equivalent to .  is called a zero parameter list I believe. has several meanings in Scala, all related to its mathematical meaning as implication. means: So if you declare a value  to be a function that takes no parameters and returns nothing its type would be: Since this is a  you have to assign a value, for instance a function that prints That reads: *\"f is a function that takes no parameters and returns nothing initialized with the code Since in Scala you can use type inference you don't have to declare the type so the following would be equivalent: To invoke it you can just: Or, since the functions are also objects you can invoke the  method:That's why in your declaration you're saying   hence  List[()=>Unit]I hope this helps.  is the \"function arrow\". It is used both in function type signatures as well as anonymous function terms.  is a shorthand for , which is the type of functions which take no arguments and return nothing useful (like  in other languages).As the most simplified answer, you can substitute whatever is on the left-hand side of => with the word \"LEFT\" and whatever is on the right-hand side with the word \"RIGHT\".Then, the meaning of \"\" becomes:This means that if you have a \"()=>\" that you can take nothing (that is, no parameters) and then do whatever is on the right-hand side.This is the most common meaning."},
Scala

In his talk , Rick Hickey talks about \"\" (about 30:00 into the video). In the same context, he also mentions Haskell's  and Clojure's  (and protocols).Since I am not very familiar with these concepts, I would like to understand its usefulness when trying to achieve . I am particularly interested in any examples or showcases of this concept in . You can take  as . Clojure community are proud of the term  because of the fact that Clojure support multiple polymorphism strategies. Some of them are: means \"Select whatever polymorphism strategy best for your case. They're all in your toolbox.\"You can implement  pattern in Scala using implicits. Read  if you want real world examples. Scala does not support multimethods at language level, but I guess it is possible with the help of the upcoming 2.10 macro. As for the benefits, advanced polymorphism strategies such as TypeClass and Multimethod can help solve the . BTW, this question is too big to fit into a single StackOverflow question. My suggestion is to get familiar with these concepts, and then you'll understand their usefulness.   "},
Scala

I came across the  method, and according to the Scala documentation this is...I have some doubts:EDIT:Consider taking a look at Chapter 4 in the .I always found the official documentation a little bit poor in regard to the blocking construct; therefore I tried to explain it more clearly in this  with examples of how you could implement your own and how it works under the hood."},
Scala

I am trying to create a generic method for object updates using scala / java but I can't get the class for a type parameter.Here is my code:The error i get is I know in java you can't do it but is this possible in scala at all?Thanks!Due  is  (Since Scala 2.10.0) this is the updated answer -You should use  instead of \nand  instead of \nYes, you can do that using manifests:Vasil's and Maxim's answer helped me.Personally, I prefer the syntax where  is used for adding such parameters (the presented  is shorthand for it. So here, in case someone else also sees this to be a better way:Disclaimer: I did not compile the above, but my own similar code works this way. "},
Scala

I'm new to the Akka framework and I'm building an HTTP server application on top of Netty + Akka.My idea so far is to create an actor for each type of request. E.g. I would have an actor for a POST to /my-resource and another actor for a GET to /my-resource.Where I'm confused is how I should go about actor creation? Should I:Thanks for any feedback.Well, you create an Actor for each instance of mutable state that you want to manage. In your case, that might be just one actor if  is a single object and you want to treat each request serially - that easily ensures that you only return consistent states between modifications.If (more likely) you manage multiple resources, one actor per resource instance is usually ideal unless you run into many thousands of resources. While you can also run per-request actors, you'll end up with a strange design if you don't think about the state those requests are accessing - e.g. if you just create one Actor per POST request, you'll find yourself worrying how to keep them from concurrently modifying the same resource, which is a clear indication that you've defined your actors wrongly. I usually have fairly trivial request/reply actors whose main purpose it is to abstract the communication with external systems. Their communication with the \"instance\" actors is then normally limited to one request/response pair to perform the actual action.If you are using Akka, you can create an actor per request. Akka is extremely slim on resources and you can create literarily millions of actors on an pretty ordinary JVM heap. Also, they will only consume cpu/stack/threads when they actually do something.A year ago I made a  between the resource consumption of the thread-based and event-based standard actors. And Akka is even better than the event-base.One of the big points of Akka in my opinion is that it  you to design your system as \"one actor per usage\" where earlier actor systems often forced you to do \"use only actors for shared services\" due to resource overhead.I would recommend that you go for option 1.Options 1) or 2) have both their drawbacks. So then, let's use options  Router is an element which act as a Akka providers different Router implementations with different logic to route a message (for example SmallestMailboxPool or RoundRobinPool).Every Router may have several children and its task is to supervise their Mailbox to further decide where to route the received message.This procedure is well explained in .For scaling up the serial requests handling, add a master actor () which in turn will delegate to the worker actors () ()."},
Scala

I know that  can be expressed in Scala as follows:I see why it is useful. For example, given two functions:I can easily write function  since  is a monad:...Now I see  in Scala:I wonder when I should use it  monad . I guess both Option and List are . Could you give simple examples of using  with Option and List and explain  I should use it   ?To :To expand a bit on the first paragraph: sometimes you don't have a choice between monadic and applicative code. See the rest of  for a discussion of why you might want to use Scalaz's  (which doesn't and can't have a monad instance) to model\nvalidation.About the optimization point: it'll probably be a while before this is generally relevant in Scala or Scalaz, but see for example :Writing applicative code allows you to avoid making unnecessary claims about dependencies between computations\u2014claims that similar monadic code would commit you to. A sufficiently smart library or compiler  in principle take advantage of this fact.To make this idea a little more concrete, consider the following monadic code:The -comprehension desugars to something more or less like the following:We know that  doesn't depend on  (assuming these are well-behaved methods that aren't changing some mutable state behind the scenes), but the compiler doesn't\u2014from its perspective it needs to know  before it can start computing .The applicative version (using Scalaz) looks like this:Here we're explicitly stating that there's no dependency between the two computations.(And yes, this  syntax is pretty horrible\u2014see  for some discussion and alternatives.)The last point is really the most important, though. Picking the  powerful tool that will solve your problem is a tremendously powerful principle. Sometimes you really do need monadic composition\u2014in your  method, for example\u2014but often you don't.It's a shame that both Haskell and Scala currently make working with monads so much more convenient (syntactically, etc.) than working with applicative functors, but this is mostly a matter of historical accident, and developments like  are a step in the right direction.Functor is for lifting computations to a category.And it works perfectly for a function of one variable.But for a function of 2 and more, after lifting to a category, we have the following signature:And it is the signature of a applicative functor. And to apply the\u00a0following  value to a function  \u2014 an aplicative functor is needed.And finally:Applicative functor is a functor for applying a special value (value in category) to a lifted function."},
Scala

I'm building a few Java-only projects using simple-build-tool.  When I publish the artifacts from the projects using, say, sbt publish-local then the resulting artifacts have the Scala version appended to their name.  With a Scala project this would make sense, but since these are Java only projects it doesn't.  How would I disable this postfixing of the Scala version?  Or can I?For reference I'm using sbt 0.11.1, Scala 2.9.1 and a .sbt file for build configuration (though moving to a full project config would be no problem).After looking around how Artifact.artifactName is implemented and ultimately used it seems that the way to turn this off is to specify false for the crossPath setting.  This is documented in one of the quick configuration examples on the xsbt wiki.This is documented on the xsbt wiki under . From that page:While the accepted answer is strictly correct, you should  set  to  on publicly published Scala artifacts. The embedded scala version is an important compatibility feature, since different versions of the Scala libraries may not be binary compatible.Only set  to  for projects, like those in the question, that are strictly Java only."},
Scala

So here's the situation.  I want to define a case class like so:and I want to define an object to ensure that when I create instances of the class, the value for 's' is always uppercase, like so:However, this doesn't work since Scala is complaining that the apply(s: String) method is defined twice.  I understand that the case class syntax will automatically define it for me, but isn't there another way I can achieve this?  I'd like to stick with the case class since I want to use it for pattern matching.The reason for the conflict is that the case class provides the exact same apply() method (same signature).First of all I would like to suggest you use require:This will throw an Exception if the user tries to create an instance where s includes lower case chars. This is a good use of case classes, since what you put into the constructor also is what you get out when you use pattern matching ().If this is not what you want, then I would make the constructor  and force the users to  use the apply method:As you see, A is no longer a . I am not sure if case classes with immutable fields are meant for modification of the incoming values, since the name \"case class\" implies it should be possible to extract the (unmodified) constructor arguments using . \nWhile the answer I wrote below remains sufficient, it's worth also referencing another related answer to this regarding the case class's companion object. Namely,  which occurs when one only defines the case class itself. For me, it turned out to be counter intuitive.\nYou can alter the value of a case class parameter before it is stored in the case class pretty simply while it still remaining a valid(ated) ADT (Abstract Data Type). While the solution was relatively simple, discovering the details was quite a bit more challenging.   \nIf you want to ensure only valid instances of your case class can ever be instantiated which is an essential assumption behind an ADT (Abstract Data Type), there are a number of things you must do.  For example, a compiler generated  method is provided by default on a case class. So, even if you were very careful to ensure only instances were created via the explicit companion object's  method which guaranteed they could only ever contain upper case values, the following code would produce a case class instance with a lower case value:  Additionally, case classes implement . This means that your careful strategy to only have upper case instances can be subverted with a simple text editor and deserialization.  So, for all the various ways your case class can be used (benevolently and/or malevolently), here are the actions you must take:  Here's your code modified with the above actions:  And here's your code after implementing the require (suggested in the @ollekullberg answer) and also identifying the ideal place to put any sort of caching:And this version is more secure/robust if this code will be used via Java interop (hides the case class as an implementation and creates a final class which prevents derivations):  While this directly answers your question, there are even more ways to expand this pathway around case classes beyond instance caching. For my own project needs, I have  which I have  (a StackOverflow sister site). If you end up looking it over, using or leveraging my solution, please consider leaving me feedback, suggestions or questions and within reason, I will do my best to respond within a day.I don't know how to override the  method in the companion object (if that is even possible) but you could also use a special type for upper case strings:The above code outputs:You should also have a look at this question and it's answers: Another idea while keeping case class and having no implicit defs or another constructor is to make the signature of  slightly different but from a user perspective the same. \nSomewhere I have seen the implicit trick, but can\u00b4t remember/find which implicit argument it was, so I chose  here. If someone can help me out and finish the trick...It works with var variables:This practice is apparently encouraged in case classes instead of defining another constructor. . When copying an object, you also keep the same modifications.I faced the same problem and this solution is ok for me:And, if any method is needed, just define it in the trait and override it in the case class.I think this works exactly how you want it to already.  Here's my REPL session:This is using Scala 2.8.1.final"},
Scala

I am learning Scala now and I want to write some silly little app like a console Twitter client, or whatever. The question is, how to structure application on disk and logically. I know python, and there I would just create some files with classes and then import them in the main module like  or  (strongly hoping you wouldn't mind that names, they are just for reference). But how  I do this stuff using Scala? Also, I have not much experience with JVM and Java, so I am a complete newbie here.I'm going to disagree with , here, though not all that much.My own suggestion is that you model your efforts on . Previous versions of SBT (before SBT 0.9.x) would create it automatically for you:So you'll put your source files inside , for the main program, or , for the tests.Since that doesn't work anymore, there are some alternatives:Install , clone ymasory's  template and adapt it to your necessities, and use that. See below, for example, this use of unmodified ymasory's sbt.g8 template. I think this is one of the best alternatives to starting new projects when you have a good notion of what you want in all your projects.Use softprops's  for sbt. In the example below, the plugin is configured on , and its settings on , with standard sbt script. If you use paulp's sbt-extras, you'd need to install these things under the right Scala version subdirectory in , as it uses separate configurations for each Scala version. In practice, this is the one I use most often.You could simply create it with :Now, about the source layout. Jens recommends following Java style. Well, the Java directory layout is a  -- in Java. Scala does not have the same requirement, so you have the option of following it or not.If you do follow it, assuming the base package is , then source code for that package would be put inside , and so on for sub-packages.Two common ways of diverging from that standard are:And this deals with directory layout.Next, let's talk about files. In Java, the practice is separating each class in its own file, whose name will follow the name of the class. This is good enough in Scala too, but you have to pay attention to some exceptions.First, Scala has , which Java does not have. A  and  of the same name are considered , which has some practical implications, but  if they are in the same file. So, place companion classes and objects in the same file.Second, Scala has a concept known as  (or ), which limits subclasses (or implementing s) to those declared in the same file. This is mostly done to create algebraic data types with pattern matching with exhaustiveness check. For example:If  was not , then anyone could extend it, making it impossible for the compiler to know whether the match was exhaustive or not. Anyway,  classes go together in the same file.Another naming convention is to name the files containing a  (for that package) .The most basic rule is that stuff in the same package see each other. So, put everything in the same package, and you don't need to concern yourself with what sees what.But Scala also have relative references and imports. This requires a bit of an explanation. Say I have the following declarations at the top of my file:Everything following will be put in the package . Also, not only everything inside that package will be visible, but everything inside  will be visible as well. If I just declared  instead, then  would not be visible.The rule is pretty simple, but it can confuse people a bit at first. The reason for this rule is relative imports. Consider now the following statement in that file:This import may be relative -- all imports can be relative unless you prefix it with . It can refer to the following packages: , ,  and . It could also refer to an object named  inside . Or it could be an absolute import refering to a package named .If more than one such package exists, it will pick one according to some precedence rules. If you needed to import something else, you can turn the import into an absolute one.This import makes everything inside the  package (wherever it is) visible in its scope. If it happens inside a , and  or a , then the visibility will be restricted to that. It imports everything because of the , which is a wildcard.An alternative might look like this:In that case, the   and  would be visible, but you'd have to name them explicitly when using them:Or you could use further relative imports:The  statement also enable you to rename stuff, or import everything but something. Refer to relevant documentation about it for more details.So, I hope this answer all your questions.Scala supports and encourages the package structure of Java /JVM and pretty much the same recommendation apply:"},
Scala

How can I convert a list with (say) 3 elements into a tuple of size 3?For example, let's say I have  and I want to convert this into . How can I do this?You can't do this in a typesafe way. Why? Because in general we can't know the length of a list until runtime. But the \"length\" of a tuple must be encoded in its type, and hence known at compile time. For example,  has the type , which is sugar for . The reason tuples have this restriction is that they need to be able to handle a non-homogeneous types.an example using  :You can do it using scala extractors and pattern matching ():Which returns a tupleAlso, you can use a wildcard operator if not sure about a size of the List changed some syntax. Here's the updated solution using shapeless.The main issue being that the type for  has to be specified ahead of time. More generally, since tuples are limited in their arity, the design of your software might be better served by a different solution.Still, if you are creating a list statically, consider a solution like this one, also using shapeless. Here, we create an HList directly and the type is available at compile time. Remember that an HList has features from both List and Tuple types. i.e. it can have elements with different types like a Tuple and can be mapped over among other operations like standard collections. HLists take a little while to get used to though so tread slowly if you are new.Despite the simplicity and being not for lists of any length, it is type-safe and the answer in most cases:Another possibility, when you don't want to name the list nor to repeat it (I hope someone can show a way to avoid the Seq/head parts):You can't do this in a type-safe way. In Scala, lists are  sequences of elements of some type. As far as the type system knows,  could be a list of arbitrary length.In contrast, the arity of a tuple must be known at compile time. It would violate the safety guarantees of the type system to allow assigning  to a tuple type.In fact, for technical reasons, Scala tuples , but the limit no longer exists in 2.11 The case class limit has been lifted in 2.11 It would be possible to manually code a function that converts lists of up to 22 elements, and throws an exception for larger lists. Scala's template support, an upcoming feature, would make this more concise. But this would be an ugly hack.FWIW, I wanted a tuple to  and wanted to use the syntactic sugar of tuple assignment.\nEG:It turns out that there is syntactic sugar for assigning the contents of a list too...So no need for tuples if you've got the same problem.as far as you have the type:you can do this either2015 post.\nFor the   to be more , here is a real example.At first, I got confused about it. Because I come from Python, where you can just do .\nIs it short of Scala language ? (the answer is -- it's not about Scala or Python, it's about static-type and dynamic-type.)   That's causes me trying to find the crux why Scala can't do this .The following code example implements a  method, which has type-safe  and type-unsafe . The  method get the type-length information at run-time, i.e no type-length information at compile-time, so the return type is  which is very like the Python's  indeed (no type at each position, and no length of types).\nThat way is proned to runtime error like type-mismatch or . (so Python's convenient list-to-tuple  is not free lunch. )Contrarily , it is the length information user provided that makes  compile-time safe.If you are very sure that your list.size<23 use it:"},
Scala

What's the difference between and in Scala? means that class  can take any class  that is a subclass of . means that  can take  class, but if  is a subclass of , then  is considered to be a subclass of . means that class  can only take subclasses of  as well as propagating the subclass relationship.The first is useful when you want to do something generic, but you need to rely upon a certain set of methods in .  For example, if you have an  class with a  method, you could use that method in any class that could be passed into .The second is useful when you want to make collections that behave the same way as the original classes.  If you take  and you make a subclass , then you can pass  in anywhere where  is expected.  But if you take a  of , , is it true that you can always pass in  instead?  In general, no; there are cases when this would be the wrong thing to do.  But you can say that this is the right thing to do by using  (covariance;  covaries--follows along with--'s subclasses' inheritance relationship).I would like to extend  with some more examples:\nLet's say we have four classes: As you can see . The developers of List did not enforce that e.g. only Cars can go inside Lists. Additionally: If a function expects a  parameter you can also pass a  as an argument to the function instead.    due to the covariance of List. It would not work if List was invariant.As you can see . No cars allowed in here.for my Understanding:The first is a parameter type bound, there a upper and lower typebounds in our case its a \"type parameter A that is a subtype of B (or B itself).The second is a Variance Annotation for a class defintion, in our case a covariance subclassing of BScala: +  Java: ? extends T    Covariant subclassingScala: -  Java: ? super T      Contravariant subclassingI found this blog post while researching this question.  Gives an even deeper explanation of Scala variance including its theoretical basis in  Category Theory"},
Scala

Since Scala does not have old Java style  loops with index, How can we iterate efficiently, and without using 's?You could do thisbut the list is traversed twice - not very efficient.Much worse than traversing twice, it creates an intermediary array of pairs. \nYou can use . When you do , you can think of subsequent calls as acting lazily, during the iteration. If you want to get back a proper fully realized collection, you call  at the end. Here that would be useless and costly. So change your code toIt has been mentioned that Scala  have syntax for  loops:or simplyHowever, you also asked for efficiency. It turns out that the Scala  syntax is actually syntactic sugar for higher order methods such as , , etc. As such, in some cases these loops can be inefficient, e.g. (The good news is that the Scala team is working on improving this. Here's the issue in the bug tracker: ) For utmost efficiency, one can use a  loop or, if you insist on removing uses of , tail recursion:Note that the   annotation is useful for ensuring that the method is actually tail recursive. The Scala compiler translates tail-recursive calls into the byte code equivalent of while loops.One more way:Actually, scala has old Java-style loops with index:Where  or  is a  method which returns  suitable for looping.Also, you can try loop with :How about this?Output:There's nothing in the stdlib that will do it for you without creating tuple garbage, but it's not too hard to write your own.  Unfortunately I've never bothered to figure out how to do the proper CanBuildFrom implicit raindance to make such things generic in the type of collection they're applied to, but if it's possible, I'm sure someone will enlighten us. :)Some more ways to iterate:foreach, and similar, map, which would return something (the results of the function, which is, for println, Unit, so a List of Units)work with the elements, not the indexfoldingThe carry-part is just some example, to do something with i and j. It needn't be an Int. for simpler stuff, closer to usual for-loops:or without order:A simple and efficient way, inspired from the implementation of  in Looping in scala is pretty simple.\nCreate any array of your choice for ex.Types of loops,Indeed, calling  on a collection will traverse it and also create a new collection for the pairs.  To avoid this, you can just call  on the iterator for the collection.  This will just return a new iterator that keeps track of the index while iterating, so without creating an extra collection or additional traversing.This is how  is currently implemented in 2.10.3:This should even be a bit more efficient than creating a view on the collection.I have the following approachesThe proposed solutions suffer from the fact that they either explicitly iterate over a collection or stuff the collection into a function. It is more natural to stick with the usual idioms of Scala and put the index inside the usual map- or foreach-methods. This can be done using memoizing. The resulting code might look likeHere is a way to achieve this purpose. Consider the following utility:This is already all you need. You can apply this for instance as follows:which results in the listThis way, you can use the usual Traversable-functions at the expense of wrapping your effective function. Enjoy!"},
Scala

As suggested to me, I've run through a few articles describing how to make IntelliJ Idea and Android and Scala work together, but it turned out they were all written 1 or 2 years ago. And likely, something has changed since that time and now there are other solutions to achieve this goal. Concretely, there is a new solution  for  which I don't know if it works well or not.I have IntelliJ Idea 12, Android SDK, Scala, SBT and all other stuff installed and set up. The only thing remaining is to setup IntelliJ Idea 12 to make it work with Scala instead of Java for creating Android applications. Please don't close the question. I saw the previous questions similar to mine, but, as I said, they were outdated.The question is, how do I do it ?P.S. I tried Android Development Studio but I even wasn't able to launch it due to many errors. You can read the  I wrote about the upcoming new version of SBT-Android (0.7). Most of your concerns should be addressed there. If they are not, then that's a problem. For fairness's sake, there's also a great work in progress :  by @pfn on GitHub.Regarding ProGuard and build times :I've been contributing to  for a few months now, so I know it a lot better than the other solutions.As of now, the plugin is evolving rapidly, with :The current version doesn't have most of these niceties, but they're coming up in the following weeks. Some documentation is of course going to follow very soon afterwards, with examples and everything I'll think of.I encourage you to join the  Google Group and share your thoughts, by the way. There's also a  channel on Freenode if you're into IRC.Just wanted to chime in on this.  I used , although I found the instructions to be vague, not having ever used IntelliJ before this.You've probably got it all sorted out by now and are happy with SBT, but for my purposes I just wanted to test Scala on Android without all the extra bells and whistles. So, here are some little things I had to do to get the no-sbt-plugin stuff working:I ended up including the scala-compiler.jar (along with the scala-library.jar and scala-reflect.jar) as a Global Library:\nThat way, the compiler has access to the library & reflection code, otherwise I was getting errors. If you don't include the library, the IDE complains that the compiler needs an associated library, and if you don't include reflect it spits out a bunch of errors at compile time that it cannot find reflect class definitions.I had to include scala-library.jar as a module dependency as well (which had the side effect of including it under the Libraries section also):\nBefore doing all that, I had the Scala plugin installed, created an Android project, and simply added a Scala facet (ignore the memory settings, I was fooling around):\nFinally, I had to resolve some remaining compilation errors by adding a few \"-dontwarn\" lines to the proguard txt file. Simple enough.Works like a charm. Haven't done anything substantial with it yet, but am looking forward to using Scala on my next Android project.I wrote the  library that makes Android development more concisely with Scala.For a quick starting point, I wrote a  maven project for Scala+Android.I use Intellij as a main IDE, and it imports the project with a charm.I've gone through this about a month ago and I managed to make it work quite nicely using Gradle. Here is the outcome: This is a simple client-server project using Scala and Akka, with client-side on Android, developed with IntelliJ IDEA. I know that client-server doesn't really make sense with Akka, but that's just a simple university project to prove that these technologies can work together.Note however that gradle script in this project is meant only to generate IDEA project, it has to be further extended to be able to perform proper Android application build.I have been watching this thread for several months, finally got some time to do the real tests.Using IntelliJ 13 with SBT 0.13 and Scala 2.10.3."},
Scala

What is the difference between and The App trait is a convenient way of creating an executable scala program. The difference to the main method altenative is (apart from the obvious syntactic differences) that the App trait uses the delayed initalization feature.From the release notes for 2.9 (see  )These two cases is not same on the scala scripting. was not executed by \"\" command,\nbut the object containing the  method was executed by \"\" command.\nWhich was described as scala looking for object with main method for scripting.When using REPL or scala workseet of Eclipse, \nneed to call  explicitly for both cases.This simple tip be helpful for beginner like me."},
Scala

I just read  and found it absolutely fascinating.What's the status of the Scala.React package described in the document? I found one tarball of a snapshot of Scala.React but there doesn't seem to be much documentation or active maintenance. I also found ScalaFX, which looks like it might be related to reactive programming, but is similarly unmaintained.Are there any projects out there that build on the ideas in this paper to create a GUI framework based on reactives?: As , there is recent progress!Like you, I have an intense interest in the project, so I creep these pages every few weeks. :)Good news!  It looks like  Ingo Maier and Martin Odersky published a new technical report this year (2012) with some updates to Scala.React.  The new code has been available on GitHub for about two weeks.Relevant links:Technical Report (2012):  GitHub:  Some similar projects:The only project that I currently know of is Naftoli Gugenheim's  project, which he announced in  on the scala mailing list. The code is hosted at "},
Scala

Or does it just clutter up the code for something the JIT would take care of automatically anyway.I have yet to find a case where it improves performance, and I've tried in quite a few different spots.  The JVM seems to be quite good at inlining when it's possible, and even if you ask for @inline in Scala, it can't always do it (and sometimes I've noticed that it doesn't even when I think it ought to be able to).The place where you expect to see a bytecode difference is in something like this:when compiled with .  And you do see the difference, but it generally doesn't run any faster since the JIT compiler can notice that the same optimizations apply to .So it may be worth a try in the final stages of optimization, but I wouldn't bother doing it routinely without checking to see if it makes a difference in performance."},
Scala

I'm running on a 32-bit  (Squeeze) system (a 2.5\u00a0GHz  CPU), sun-java6 6.24-1 but with the Scala 2.8.1 packages from Wheezy.This code, compiled with , takes over 30\u00a0seconds to run:But if I make the trivial change of moving the  one line down and inside the scope of , then it runs in just 1\u00a0second, which is much more like I was expecting to see and comparable with the performance of equivalent C++. Interestingly, leaving the  where it is but qualifying it with  also has the same accelerating effect.What's going on here? Why is performing the calculation outside function scope so much slower?The JVM doesn't optimize static initializers (which is what this is) to the same level that it optimizes method calls.  Unfortunately, when you do a lot of work there, that hurts performance--this is a perfect example of that.  This is also one reason why the old  trait was considered problematic, and why there is in Scala 2.9 a  trait that gets a bit of compiler help to move stuff from the initializer into a method that's called later on.(Edit: fixed \"constructor\" to \"initializer\".  Rather lengthy typo!)Code inside a top-level object block is translated to a static initializer on the object's class.  The equivalent in Java would be The HotSpot JVM doesn't perform any optimizations on code encountered during static initializers, under the reasonable heuristic that such code will only be run once.    "},
Scala

I have some Scala functions defined in a file, not in a class, and I would like to use them in the Scala interpreter. I know I can say  to simply run the file and exit the interpreter, but I would like to run the file and then stay in the interpreter so I can do some testing. Can anyone tell me how to simply load a file into the interpreter so I can use the functions defined within it?type  in Scala REPL.You can get complete list of available commands by typing On occasions,  might be your better friend (than ). Here is an example on how to use .One can also use  to load a file using following command Just reminder, put the complete path. I found problem in Linux by doing like this:to get rid of error \"That file does not exist\" I did"},
Scala

In theory, Dalvik executes any virtual machine byte code, created for example with the compilers of Are there already working versions of bytecode compilers for Dalvik available for other languages than Java?Scala works very well.I'm programming my Android application projects in Scala (, ), and it is pretty easy to setup the evnviroment (without IDE, using SBT as build tool).It could access every API in Android SDK, so anything you could do in Java, you could do it in Scala too.You may check this  to see how to build Android application with Scala and SBT. is a lovely but little known variant of Scheme that has existed quietly for many years and runs on both the JVM and Dalvik, .  Therefore, its output includes no extra VM and only includes explicitly imported libraries.  To the end-programmer, this means Kawa's performance and executable size are nearly identical to standard Java (ProGuard not required).Kawa also includes lots of macros (including some specific to Android APIs) that make for a nice clean syntax (assuming one is not averse to parentheses), and adds some tasty goodies on top of Scheme, like \"promises\" (lazy eval and futures in one).  The language is quite robust and well-documented, and has been actively maintained and evolving since the early days of Java. summarizes Kawa's merits with some informative examples and links.I haven't played with it but I know that Scala works.Another JVM language that works on Android is  with , both from .  also works on Android, using its Java backend.  I've written a  that should help someone get started (there are still few other examples), and  also for this purpose (although at this exact moment, it's short a few commits.  And neither are using ProGuard yet, so the  size is shocking.)Although the other posts here are cheerful about Scala-on-Android, posters in Scala forums are more concerned by Scala's ability to blow through some of Dalvik's limitations, and people who do use it say they reserve it for non-production code.  (Some discussion about Scala's problems .)  I can't say yet if Mercury has its own problems with Dalvik, but I've switched to it from Scala for the time being.The dynamically typed languages wont be possible until Dalvik supports JIT (Just In Time) compiling. I believe there is JIT support in one of the experimental Eclair branches, but it is not yet officially available/supported in Android.There is a  compiler available now which creates executables for the Android platform.With this solution, developers have access to practically the entire  and Android toolsets. This includes not only the complete set of Android widgets and a graphical designer for laying them out, but also access to the complete Android runtime. The Eclipse IDE will also build the executable and launch the Android emulator (using Run As | Android Application)."},
Scala

My data could exist in rdds of two forms, either or as As you can see, in the second example the \"mapping\" of the data is enforced by the first element of the tuple being the key. Consider two entries in my rdd, call them R1 and R2. I'll be merging by keys in R1 and R2. When R1 and R2 both contain the same key, I do further merging on those values. As an example, say that both R1 and R2 contain an entrythen the resulting merge will produce So, my question is which data structure is faster and more memory efficient for spark to reduce by outer and inner key? Maps of maps or lists of (key, list_of_tuple). My intuition is that maps would be faster at reducing by key, given their 0(1) lookup. However, given the way that most maps are implemented, I'm sure that there is a decent amount of wasted memory for the map based RDDS. As a real life example of this type of merging, my RDDs are representing I think you have mis-understood about the concept of RDD's. You need to transform your data into appropriate structure to leverage the power of RDD's.SO, you need to think about what you want to compute for deciding your RDD's.As per my understanding of your question. You have 2 data source and you want to merge the data that you got from these 2 data sources. So you create your 2 RDD's from these sources then you merge them."},
Scala

The following code is the recursive code for splitting a list into two parts.I want to convert this recursive function to an iterative one using a stack.I've tried to solve the problem using stack But It just brings a chaos and complexity in the code In case you want just a simple solution, this is the answerHere's a version using queues.We can change  to a stack, at the expense of a reversebut the problem for  is that we want to add things to one end and remove things from the other end. This isn't a stack, but a queue.So I think you should tell your professor it works better with queues :)"},
Scala

this is my code:and i want this result:thanks.this is my code:"},
Scala

Given a file like this: Is it possible to produce this from command line:When asking how to transform data in one form to data in another form it is generally better to be very explicit about what exactly the transformation consists of.  In this case it seems obvious, but who knows?This ---- will give the transformation you show.  It assumes your input data is always in exactly 4 rows.  You don't say, so who knows?  It assumes a particular transformation, but others might be possible -- i.e., it assumes that the third column in the output is the zero-indexed number of the column of the previous item in the input data, not counting the first column. to the rescue!"},
Scala

Processing distinct and some other operations for a 5MB data using scala writes the output to multiple files. I can see the output in HDFS in 100's of 1kb files. why?Why even for a 5 MB data scala uses two executors? I studied executors are launched based on the partition and partition is based on the block size. My default block size is set to 128MB. So Normally there should be only one executor.According to  the number of executors could be set by enabling: and setting  to the number of executors that is desired."},
Scala

In Scala, how do I declare a Java List that can hold anything? List[Object] gets upset if I try and put a tuple in it, Scala errors saysI don't know what this means, how do I declare the list to hold a triple (or a tuple, or )My code looks like this (it is twirl, so it has @, but it is just Scala code):Use a Scala (not Java) collection, e.g. . If it needs to be mutable, look at If you insist on using Java collections, you can try , as suggested by the error message.\nAlso note that you  pass Scala collections to a Java app, because at runtime the Scala code is represented by compiled bytecode that is compatible with the JVM."},
Scala

I have to create an array or list which contains large numbers ( long ) , but I am unable to create one in an elegant way.\nI am currently doing this :How can i do this in an better way like :"},
Scala

Being new to spark and scala. I need to check how I can achieve this:input:o/p after collecting:I guess this is what you are looking forThanksOutputs :I think this helps you to understand as per your question.OutputOutput"},
Scala

I'm new to the Scala langauge, I don't know how to install Scala for Android in Eclipse.Try the  from .And you need code editing support to Eclipse for Android install the Scala-IDE plugin. You can get it from ."},
Scala

I'm using Intellij to do some scala development. I normally use Eclipse but was convinced by a friend to give IntelliJ a go. Finding the lack of a 'Problems' view a real pain. But have another problem.I've got the following code fragement in a test:So firstly I get a red bar on the right hand side of the editor screen (shame there's no 'problem view'), and when I hover the mouse over it it says .Can anyone help me understand this?If I change the ArrayList import to  and remove the prefixs in the code I then get 3 error messages:this is all on the line:So can anyone help me understand this collection of errors? There is no useful help from IntelliJ and a google search didn't shed any light. Lastly if there is anyone out there who has used IntelliJ and Eclipse for scala+java development could you give me an opinion. It seems to me that IntelliJ is a bit s**t. Or maybe I'm just not getting it...Thanks All.Regarding the prefix: withyou import the util namespace i.e. to access a class within util you have to write util.ArrayList. If you want to import everything within util, you need to writeto specifically import ArrayList"},
Scala

I'm new to Scala but I do know JAVA. Can Scala projects be compiled into web apps and deployed to Webservers like JAVA?Thanks!Scala code is converted into byte code after compilation, hence yes it can be done. this should help for starting"},
Scala

this code could be very long and ugly, is there a way of me shortening it down using a while loop or anything else? im new to scala programming   Here you go. No explanation of the actual code deliberately, you're after an answer to an assignment. But some general hints - if you find yourself repeating code that's the same apart from the data operated on, then, yes, a while loop might be a possibility but in a language like Scala with a rich selection of functional programming features and a extensive collections library, there are other alternatives.You want to iterate over the various coin sizes. You can do this with an array, and a loop over that array. I have a rule of thumb that if I'm using an index solely to retrieve the current element of the array (that is, the value of the index isn't significant in any other way) then there's probably a more elegant way to do it.In Scala, we have many ways of iterating over a collection.  is suggestive, since it allows us to iterate over an array collecting something as we go, and here we want to collect the coins to use.Another perspective: once I've processed the largest coin, I have some smaller amount of money left, and a smaller set of coins. So I have a smaller problem. Eventually, I have no coins and no money, and nothing more to do.  This divide-and-conquer approach suggests a recursive solution.and an alternative approach"},
Scala

This is my code:only the first line is getting written but the other lines is not getting written.I am getting the error asMost likely is that your problem is that  Has type  and are calling the  method on Option which pretty much should never be called. The world would be a better place if this method didn't even exist. I digress. If this call to  returns , then the call to  throws an exception that there is no value to get.It seems that is returning a  which will throw an exception when calling .this should never be done! Use a combination of  and  to avoid unexpected behaviour. For instance:or you can even make the  inside the map.If you are not aware, the  method executes when the Option is defined (it's a ) and ignores when the Option is a "},
Scala

Can you recommend a better way to do this?file lifehow wholife filenow wonsaw waswas sawwho howwon nowFirst, remove the duplicate anagram pairs.Second, alternative to the for ... for ... if ... if structure?Thank you.Here's a short version using for- (which are not equivalent to for loops, and are actually common in Scala):Which prints:As we all know that functional programming paradigm in scala, usually for loop should not be used in scala because it is in imperative way.I am also new in scala. I think you can make a list of key-value pairs that is (array of word)-word and group by key(array of word). Then extract two words in the list and generate a new list.Sorry my answer seems no very clear because english is not my first language. You can use 3 println() statements to see my thought.At last, argsSeq_3 is List(now,won, the,the, file,life, saw,was, how,who)."},
Scala

can some help me to under stand this code and operator types used or may be used hereThis code executes   times (i expected this variables to be defined in your code). Basically  is a function which will be executed given () number of times.\nTo read more about call-by-name: "},
Scala

I have a polygon file in ^ separated format I have a case class I want to parse the file in to the class. My file is on HDFS. Can anyone guide me on this? Assuming that a line  means that it is a polygon shape with  and its has five vertices ,,, and .Now you can do the following,"},
Scala

I have a Array of Objects that I need to apply filter.This code is not getting complied by Scala compiler. I am getting error like \n1) value ? is not a member of boolean\n2) type toUpperCase is not a member of string.Can anyone please help me how to write this ternary operator inside the filter function in scala.I agree that I can write a custom function to handle this as mentioned @  \nHowever, I am interested in why there is compilation error for this statement.\nBecause, this is valid statement in Java.The main issue is that Scala does not support the ternary operator you described. That is supported Java but there's no need for it in Scala.In Java the main difference between the   and the ternary operator is that the latter is an expression, meaning that it's evaluated to a result, while  is (as I previously suggested) a statement that relies on side-effects within its scope to make things happen.In Scala  is already an expression, hence there is no need for a ternary operator.Your code would be structured as follows:As suggested in a comment you can further improve the readability by not relying on s to express simple boolean conditions.Furthermore, in your case,  seems to be external to the list itself, so maybe pulling it out of the  (which has  complexity on ) can save you some cycles:It also looks like you are trying to make a case-insensive equality check on the two string, in which case you may be interested in using a  and not converting  to upper case at every loop:"},
Scala

Given is data by joining two tables.When I am trying to get following \n val data = joinDataRdd.map(x=>(x._1,x._2._1.split(\",\")(3)))It's is throwing an error :\nvalue split is not a member of (String, String, String, String, String)You are trying to split the tuple so that is why the error message. At the given position  , \n(41234,(,(2014-04-04 00:00:00.0,3182,PENDING_PAYMENT))), the highlighted data is the result. So if you are looking to dig inside the tuple, then you need to advance one position.  It looks like the values are already in a tuple, so you don't need to split the string. Is what you are looking for?"},
Scala

Pattern matching in SCALAI have 2 lists, one of which contains 20k elements and another contains 200k elements.\nI am performing pattern matching where each of the list_1 elements are matched in list_2. I have written a FOR loop which gives me correct answers but it takes more than 2 hours for complete execution.Is there any other alternative way to perform this task? How can I speed up the process?The code:Just a more scala-fashioned way to do that:Note: I'm assuming that matching at least one (1+) is acceptable, and that you need to not collect unmatched  instead of .Maybe we could improve this by knowing more about your data and eventually also choose a different  library."},
Scala

I want to call a  with different parameters and calling to this function should happen in parallel.Also my function is not returning anything. So how to know execution is running in parallel or how many threads has been created. Please provide full code for such scenario in Scala. It's quite simple, scala gives you  and  for this reasonThey both roughly work the same way, by converting any collection of the kind  to a collection of , but they are used differently.Now  is semantically different because you feed it an , or a collection of elements, and then a function that converts those elements to a future. For instance:In terms of execution semantics, both constructs execute all futures in parallel and fail if any of the futures fail. There's no guarantee the futures are executed in order.Off topic, but fortunately it's pretty easy to write a \"one at a time logic \nyourself. This works by moving the function that produces the  from an element \"inside\" the for block. Futures in Scala are always created in an already started state, which makes them harder to reason about.Building on the excellent answer of @flavian:"},
Scala

I need to use akka and actors, what IDE should I use? Do you have any links to add some plugin? I have scala installed but I don't know what I should install. ThanksAs vitalli wrote, when you use Akka you use a library, so you can use any of the popular scala ides ( Eclipse, Intellij, ENSIME ... ) or anything else ( vim, emacs ... )You should check TypeSafe Activator for very good Akka starter / template projects here:"},
Scala

How could I write function below in regular Recursion and Tail Recursion.Here's a basic recursive version.Here's a tail recursive version.And this is what you do after you've studied the Standard Library.@The Archetypal Paul makes a good point (as he often does) and has offered an alternative.What we're all dancing around, without actually pointing it out, is the defining difference between basic and tail recursion: if there's any more \"work\" to be done after the recursive call returns (calculations/evaluations/etc.) then it is  tail recursive.Here is the tail recursive version of the . The idea is to call the function recursively until the list is over and return  if test fails."},
Scala

to All!i have this data structure:all List[String] are the same size, it looks like:i need to summarize columns in this lists like this:with such algorithm...help, please!You're looking for the  method:"},
Scala

When I tried to split a string based on the space as a delimiter, and then apply the contains method on it like belowFor that string when I tried using string_var.contains(\"JAVA\") then it returns true, but when I tried it using then it returns false, is the Array[String] searches the complete elements of the array or matches substrings insides the individual elements?A simple test in the REPL demonstrates the problem.The  method on a  will look for any sub-string, but the  method on an  will only match on individual elements of the array, not sub-strings within the elements.It is returning all the split strings. The reason it does not find \"JAVA\" is because no element in the array containing the split strings is equal to  . Although, if you type:, you will get:"},
Scala

When trying to import a class that is in a different package, I am getting a the type cannot be resolvedsrc/foo/Foo.scala:src/bar/Bar.java: methods could be accessed in a  way and  methods like  class members."},
Scala

I'm trying to understand every piece of the implementation of class OWritesOps explained here: The way scala / play doc is structured doesn't really help (in this area Java(doc) beats Scala(doc) hands down).Let's start with: addField:I could only guess that the  is an equivalent of \"and\" (I gather it from here:  )Alright, so let's just take it this way:  create a new instance of  (combo). What about  ? After a lot of digging Play Doc, I came to a (shaky) conclusion that it produces an instance of JsPath? How did I arrive to that conclusion? It's for that  that follows;  has that method.Beside, I read somewhere that  is a shortcut for  (I forgot where, I guess it's in Play Doc as well, but using Scala doc it's almost impossible to find my way back to that page).Ok..., so  produces an instance of . Next: what's this?: Oh..., it's for the apply the parameter to the \"apply\" method of OWrites; it takes an lambda function with the following signature Ok...., so....  is supposed to create an instance of . So, I opened the play doc, . Hmm..., I guess it's this constructor (?):  .... But,... I really doubt it.... I'm lost here.Anyway, let's see an example how it is used: So...,  is supposed to map to a block with the following signature:   ... But..., if that's really the case, I was expecting  .... so I guess  is a syntactic-sugar provided by Scala (?).So... back to the definition of :  executes the block \"_.isAdult\". I can infer here that  is an instance of  then.Can you help me decipher all this?Scala is cool, but it's doc system (still) sucks :( is the name of a method invoked on the instance of .  is the same as .  the brackets around the argument of . There are two things relevant to this equivalent form: However,  has no method called  in its interface. If you import , there's an implicit conversion and  defines the method and an alias for it: The package  defines a value , so the double underscores are just an alias for the singleton object . The singleton object  is not to be confused with the equally-named class. This construct is called a companion object in Scala. While Java puts static members next to the regular members in a class, Scala puts them inside the companion object. Apparently, the object  is at the same time the companion object of the case class  and an instance of .  is of type  and  defines a method which is equivalent to The default apply method of a case class' companion object creates a new instance, so this is equivalent to As our singleton object  is an instance of  with the empty list for , this returns us a , where It's a function taking an instance of . The function maps the argument  to the tuple , where  is a function provided as argument to your method . It has the signature , so it is a function that takes an instance of  and returns an instance of . This may be a bit confusing, so let me give you an example function that does not operate on generics. Say you want to define a function  that squares an integer number. For example,  should be ,  should be . As it takes an integer and returns an integer, its signature is . It's implementation is . Actually, this is not correct - the signatures do not match. The given lambda function is of type . Also, as pointed out in the first part of the answer, the method  returns an instance of . Unfortunatly, I am lost on what the called -method does, because it is highly generic and uses implicit arguments of a generic type. Yes, the underscore in lambda functions is syntactic sugar for capturing the arguments. For example,  is syntactic sugar for , meaning the following two values are equivalent:So  really just translates to  and in the example, .The idea behind this write builder seems to be to provide means of defining a mapping from one of your Scala classes to JSON. Let's take a look again at the . Now, let's assume we have an instance of :  and want to serialize the instance to the following JSON: The key is always a string, but the value can be of a different type. So, basically, the serialization is a function taking a  and returning a tuple of key-value pairs where the value is always a string, i.e., . Or, in the general case where we do not know what we are going to serialize, simply that it has two fields, it is  for arbitrary types , , and . This is what  emulates - the  standing for the number of members to serialize. There's also a ,  and so on. We can instantiate a  that is appropriate to our example, by calling Here, the type of  is Now, the apply method of  can be used to generate an instance of the first generic argument - . The argument to the apply method is a function that maps an instance of our type to serialize (here ) to a tuple of the desired value types, here  and  (representing  and ). This writer can now be used to generate a JSON string from any instance of . So we can pass our person and get the desired output: "},
Scala

I am using java.text.SimpleDateFormat in Scala to convert string to date.How to fix this ? Are there any alternative?Your problem is that you have \"22\" in the month position.  The date format you set is day/month/year, but it looks like the date you sent is in the format month/day/year.The formatting is different between the dates. You have mixed the month and Day up in your statements. try this:goodluck with the code."},
Scala

I got this problem when writing a recursive function that calculates the number of points where two general functions f1 and f2 are equal(Assuming only Integer values).And this is what compiler says :Thank you!The  construct in Scala is an expression. As the others already said, there's no ternary operator because there's  - the if being already an expression.I rewrote your function to a tail-recursive version (to avoid s), let's see how it looks:Notice how the result of the if expression is assigned to  - here you would normally use the ternary operator. Anyway, I hope this helps you.the  operator doesn't exist in scalaScala does not use the ternary operator, "},
Scala

I have a following list-I want to find a string  in above list.\nLike first string in list contains given string .I  given string with list elementsHow do I find string in list using scala??Looking for a substringIf you need an exact match, just replace  with ."},
Scala

I got a assignment for balancing parentheses using scala. I wrote this code:but this code fails in  \nany idea to implement this code correct?Not giving any code away, just clarifying the likely spec.  All your code is doing is counting the number of right and left parens, and making sure they are equal.  That's a necessary condition, but not sufficient.   For balanced parentheses, you also need to show that as you scan through the string, the number of '('s you have seen must always be greater than or equal to the number of ')'s seen."},
Scala

I have just written this code for some fun and I have a question why it isn't working out? Seems like nothing is written to the list, but why is that so? Do I have to make it mutable? And why is here the  operator not working properly?Because  returns a new list, where the first element is , followed by .So, to make your code , make list a  and re-assign it inside the loop:However, the idiomatic way of doing this in Scala is to not use mutations at all (local mutable state is fine sometimes though). \"While\" loops can usually be replaced with a recursive function:This particular scenario can also be solved using  instead"},
Scala

I have an RDD of Array[Int] and I want the sum of all elements in each array in the form of RDD[Int].\nWhat is the best way to achieve thisThe answer may be as simple as "},
Scala

I want to know what exactly the .get method does in scala. getParam() is already returning the parameters to the post hit . I know that .get will make it easier as we dont have to \"match\" to check for null values as it will automotically thrown an exception in the former case.\nIs there more to it than meets the eye?It's usually  a function on Options (i.e. Some or None). It gets you the contained element if it exists, otherwise it throws a NoSuchElementException.As a side note, you should try to avoid using  because it lands you back in the land of null-pointer exceptions. Instead, try to use , or continue to use your Option value through higher-order functions like , , ,  etc.Here is an example of how you can use it to your advantage:You can just pretend that the value is always specified if you don't \"touch\" it directly.I suppose that's some  related code, if that's the case,  return an . s are a wrapper around types that allow you to avoid having to check for s (and other kind of utilities too), in fact a value wrapped in an  can be , in which case you can use get to access the value, e.g.Or can be a  in which case when calling  you get an exception, wether a value is a  or  can be determined via param matchOr using  which returns true if it's , false if it's .Note that your code could throw exceptions since you call  without knowing if it's a  or , you should use  which returns the value the Option holds if there's any, or a default specified parameter:"},
Scala

I want to apply preprocessing phase on a large amount of text data in Spark-Scala such as  , there is any way to implement them in Spark - Scala ? for example here is one sample of my data: after preprocessing:and they have POS tags e.g there is a POS tagging (sister.arizona) is it applicable in Spark?  Anything is possible. The question is what YOUR preferred way of doing this would be. For example, do you have a stop word dictionary that works for you (it could just simply be a Set), or would you want to run TF-IDF to automatically pick the stop words (note that this would require some supervision, such as picking the threshold at which the word would be considered a stop word). You can provide the dictionary, and Spark's MLLib .The POS tags step is tricky. Most NLP libraries on the JVM (e.g. Stanford CoreNLP) don't implement java.io.Serializable, but you can perform the map step using them, e.g.On the other hand, don't emit an RDD that contains non-serializable classes from that NLP library, since steps such as collect(), saveAsNewAPIHadoopFile, etc. will fail. Also to reduce headaches with serialization, use Kryo instead of the default Java serialization. There are numerous posts about this issue if you google around, but see  and .Once you figure out the serialization issues, you need to figure out which NLP library to use to generate the POS tags. There are plenty of those, e.g. ,  and  for Java,  for Scala, etc. Note that you can of course use the Java NLP libraries with Scala, including with wrappers such as the University of Arizona's  around Stanford CoreNLP, etc.Also, why didn't your example lower-case the processed text? That's pretty much the first thing I would do. If you have special cases such as iPod, you could apply the lower-casing except in those cases. In general, though, I would lower-case everything. If you're removing punctuation, you should probably first split the text into sentences (split on the period using regex, etc.). If you're removing punctuation in general, that can of course be done using regex.How deeply do you want to stem? For example, the Porter stemmer (there are implementations in every NLP library) stems so deeply that \"universe\" and \"university\" become the same resulting stem. Do you really want that? There are less aggressive stemmers out there, depending on your use case. Also, why use stemming if you can use lemmatization, i.e. splitting the word into the grammatical prefix, root and suffix (e.g. walked = walk (root) + ed (suffix)). The roots would then give you better results than stems in most cases. Most NLP libraries that I mentioned above do that.Also, what's your distinction between a stop word and a non-useful word? For example, you removed the pronoun in the subject form \"I\" and the possessive form \"my,\" but not the object form \"me.\" I recommend picking up an NLP textbook like \"Speech and Language Processing\" by Jurafsky and Martin (for the ambitious), or just reading the one of the engineering-centered books about NLP tools such as  for Java,  for Python, etc., to get a good overview of the terminology, the steps in an NLP pipeline, etc.There is no built-in NLP capability in Apache Spark. You would have to implement it for yourself, perhaps based on a non-distributed NLP library, as described in marekinfo's excellent answer.I would suggest you to take a look in spark's ml pipeline. You may not get everything out of the box yet, but you can build your capabililties and use pipeline as a framework.."},
Scala

Groovy has a nice GUI Console in which I can enter any java/groovy code and run.\nThis is distributed with groovy.As for as I know Scala does not have anything like that except for REPL.Is there any third party Scala GUI Console that I can download and install and run from command line and not from a JNLP file using webstart?One use case:Suppose I have Scala program:In Groovy Console (which is a full blown GUI) I can easily copy and paste above program. I can easily modify the program in GUI and quickly hit the run button and quickly see the result. I can even easily copy and paste the results and post it somewhere else. I can easily copy lines of Scala code from somewhere else and copy into GUI Console and hit the run button and I can also copy certain jars into a location that is in the classpath of Groovy Console and so on and on long list of lot more features. Can you do that in REPL or is there another tool you can use?For the kind of exploratory coding that you're talking about, you should check out .  Just ignore the parts designed for teaching children how to program (e.g. drag the border between the turtle window and the rest until it's as small as it can get), and you find that you have a full-fledged GUI with syntax highlighting and everything that lets you run code with a press of a button (or two presses of the keyboard).  Or maybe you want to use the turtle to do the drawing, given the example you gave.You might also be interested in  or .You definitely looking for an .There is plugin for theses IDE:My personal favourite is using a simple text editor with , you can use for example:For whatever it is worth, if you don't want to try out swing stuff, you might even go with ."},
Scala

The below code words perfectly fine in Pyspark (Spark 1.6.2). Can any one please help me with the relevant code in Scala Output :"},
Scala

i want to run the streaming k-means-example.scala code source (mllib) on spark , someone tell me how i can how I can display the content of clusters after clustering (for example i want to clustering data into 3 clusters , how i can display the cntent of the 3 clusters in 3 files and the content of centers in file.txt)You would have to use the predict method on your RDD( )\nThen you could zip your Rdd containing values and your RDD of predicted clusters they fall in.i am a new in this field so can you please be more clear , how can i traduct this ( use the predict method on your RDD Then you could zip your Rdd containing values and your RDD of predicted clusters they fall in ) in source code with scala !!"},
Scala

Given these two collections :How can I check if  contains a tuple with the same elements as  ?This should work:because set are unordered dont use But use instead a tuple And then you could do"},
Scala

Occasionally I want to print values, arrays, expressions, etc. quickly and be able to locate the print statements. How do I do this in Scala, short of \"println\"?Use this tool: ^ It's really handy for tracing values, containers, expressions, etc. ^If you want something a little more plain text editor friendly, try: or It's good for debugging things like multiple threads, separate processes, or anywhere else where debuggers tend to choke. Combine it with a debugger/logger."},
Scala

I am new to Scala facing  in below codeif (cell != null && cell.getCellType != Cell.CELL_TYPE_BLANK) formatting was wrong..Thanks @Tzach Zohar"},
Scala

I'm a new Scala programmer, and i would like to iterate and call another method passing the Something by parameter, but i really don't know how to do it."},
Scala

 the  Programming Language run internally ?\n of using Scala over Java?Scala is compiled to Java bytecode, executed by the same JVM that runs Java programs, using the same JDK class library plus a small extra Scala runtime library.The advantages are mostly for the programmer."},
Scala

Has anyone successfully used sonar-scala plugin when using \"maven sonar:sonar\"?  I got NullPointerException caused by As of today (March 12th, 2014), the Scala plugin has not been released yet as you can see it on . Note that this effort is only driven by the community, so you have to periodically check this page (or subscribe to announcements on the user mailing list) to know if/when you can use this plugin."},
Scala

I am using MVC architecture in Play Framework in which the view part is a mix of scala and html. Now, I need to sort a Map coming from the controller layer in my view. As scala has no memory its being really hard to create a sort function to sort my map by timestamp.\nCan anybody please help i'm really not able to solve this one as i am new to scala.This is my First Question. Any help would be Appreciated.Assuming the timestamps are the  of the map (i.e. it's a ):That is, you're converting the map to a  first, so that element ordering will be preserved (maps are normally s, with an unpredictable ordering), then sorting that sequence by the first element of the key-value tuple.If the timestamps are the values, replace the  with .Note that if you convert the intermediate  back to a  (e.g. with ), you'll be back in  land again, and your sort will be gone.So, this might be more like what you want:Here, we convert  to a  just so that it can be passed to the varargs factory method of ."},
Scala

This is my scalatest file which tests savedat method.savedat enters an Employeeentry object in my table and returns number of rows saved which is 1 in my case:This works : The error was Play frequently requires a running Application as context which WithApplication object provides."},
Scala

I have a  and I want to iterate through each object and check if one of its boolean properties are true/false. I've tried to use  followed by  but it's not working:Assuming an object like the followingand a sequence like thisYou would then use the following logic to filter out false boolean conditions on boolPropThis operation return a new sequence with only the objects that have a boolProp of true. Note, this does not  the sequence, but instead returns a new one.Imagine you have the following:And you create a list of these guys:Now if you want to find out if one of them has  set to , you just do:This is my code snippet, i am new to scala ..i am getting a error for type mismatch here ...saying that expected is boolean.. Child has property of expandable reservation is it is true then only extract that child from the sequence of childs"},
Scala

I have a list:I will do the list that it will create the number of children equal to the dog's age. Could you help me?  Thanks!!!Result that I want is: List[Dog] = List[Dog(5),Dog(5),Dog(5),Dog(5),Dog(5), Dog(2),Dog(2), Dog(2),Dog(2)),Dog(4),Dog(4),Dog(4),Dog(4),Dog(4),Dog(4),Dog(4),Dog(4),Dog(4),Dog(4),Dog(4),Dog(4), Dog(8),Dog(8),Dog(8),Dog(8), Dog(8),Dog(8),Dog(8),Dog(8)]Your question is a bit unclear, so you might want to clean it up, but I think I understand what you mean - assuming your Dog is defined something likeThen you can create a map like thisBTW, you can create your list like this if you like:I've seen you've changed your question, you want thisres13: List[Dog] = List(Dog(5), Dog(5), Dog(5), Dog(5), Dog(5), Dog(2), Dog(2), Dog(2), Dog(2), Dog(4), Dog(4), Dog(4), Dog(4), Dog(4), Dog(4), Dog(4), Dog(4), Dog(4), Dog(4), Dog(4), Dog(4), Dog(8), Dog(8), Dog(8), Dog(8), Dog(8), Dog(8), Dog(8), Dog(8))where List.fill(n)(e) will create a list of e f'spretty simple I guess:list.flatMap(dog => {for (i <- (0 to dog.age) ) yield dog.clone} )"},
Scala

Wordcount program is easy, but how to get word list of items based on key.(Not number of count)\nLet eg:\nLocation, Items\nBangalore,TV\nBangalore,Mobile\nHyderabad,LaptopNow I need output like this:\nBangalore, (TV, Mobile)\nHyderabad, Laptop\nIt may Json or csv or any format.Cityitems.csv:\nCity,Items\nBangalore,Mobile\nBangalore,Laptop\nBangalore,Mobile\nBangalore,Desktop\nHyderabad,Cooker\n    val data=sc.textFile(\"s3://path/Cityitems.csv\").cache()\n    val rows = data.map(line => line.split(\",\"))"},
Scala

I want to generate Sequence of Numbers column(Seq_No) as Product_IDs changes in table. In my input table I have only Product_IDs and want output with Seq_No. We can not use GropuBy or Row Number over partition in SQL as Scala does not support.So I want to generate Seq_No as current Product_Id is not equal to previous Product_Ids. Input table has only one column Product_IDs and we want Product_IDs with Seq_No using Spark Scala.I would probably just write a function to generate the sequence numbers:UPDATE:I'm not quite clear on what you want beyond that, Nikhil, and I am not a Spark expert, but I imagine you want something like"},
Scala

Let me first say that I have quite a lot of Java experience, but have only recently become interested in functional languages. Recently I've started looking at Scala, which seems like a very nice language.However, I've been reading about Scala's Actor framework in , and there's one thing I don't understand. In chapter 30.4 it says that using  instead of  makes it possible to re-use threads, which is good for performance, since threads are expensive in the JVM.Does this mean that, as long as I remember to call  instead of , I can start as many Actors as I like? Before discovering Scala, I've been playing with Erlang, and the author of  boasts about spawning over 200,000 processes without breaking a sweat. I'd hate to do that with Java threads. What kind of limits am I looking at in Scala as compared to Erlang (and Java)?Also, how does this thread re-use work in Scala? Let's assume, for simplicity, that I have only one thread. Will all the actors that I start run sequentially in this thread, or will some sort of task-switching take place? For example, if I start two actors that ping-pong messages to each other, will I risk deadlock if they're started in the same thread?According to , writing actors to use  is more difficult than with . This sounds plausible, since  doesn't return. However, the book goes on to show how you can put a  inside a loop using . As a result, you getwhich, to me, seems pretty similar towhich is used earlier in the book. Still, the book says that \"in practice, programs will need at least a few 's\". So what am I missing here? What can  do that  cannot, besides return? And why do I care?Finally, coming to the core of what I don't understand: the book keeps mentioning how using  makes it possible to discard the call stack to re-use the thread. How does that work? Why is it necessary to discard the call stack? And why can the call stack be discarded when a function terminates by throwing an exception (), but not when it terminates by returning ()?I have the impression that  has been glossing over some of the key issues here, which is a shame, because otherwise it's a truly excellent book.First, each actor waiting on  is occupying a thread. If it never receives anything, that thread will never do anything. An actor on  does not occupy any thread until it receives something. Once it receives something, a thread gets allocated to it, and it is initialized in it.Now, the initialization part is important. A receiving thread is expected to return something, a reacting thread is not. So the previous stack state at the end of the last  can be, and is, wholly discarded. Not needing to either save or restore the stack state makes the thread faster to start.There are various performance reasons why you might want one or other. As you know, having too many threads in Java is not a good idea. On the other hand, because you have to attach an actor to a thread before it can , it is faster to  a message than  to it. So if you have actors that receive many messages but do very little with it, the additional delay of  might make it too slow for your purposes.The answer is \"yes\" - if your actors are not blocking on anything in your code and you are using , then you can run your  program within a single thread (try setting the system property  to find out).One of the more obvious reasons why it is  is that otherwise the  method would end in a . As it is, the framework rather cleverly ends a  by throwing a , which is caught by the looping code which then runs the  again via the  method.Have a look at the  method in  and then the  method to see how the loop reschedules itself - terribly clever stuff!Those statements of \"discarding the stack\" confused me also for a while and I think I get it now and this is my understanding now. In case of \"receive\" there is a dedicated thread blocking on the message (using object.wait() on a monitor) and this means that the complete thread stack is available and ready to continue from the point of \"waiting\" on receiving a message. \nFor example if you had the following code the thread would wait in the receive call until the message is received and then would continue on and print the \"after receive and printing a 10\" message and with the value of \"10\" which is in the stack frame before the thread blocked. In case of react there is no such dedicated thread, the whole method body of the react method is captured as a closure and is executed by some arbitrary thread on the corresponding actor receiving a message. This means only those statements that can be captured as a closure alone will be executed and that's where the return type of \"Nothing\" comes to play. Consider the following codeIf react had a return type of void, it would mean that it is legal to have statements after the \"react\" call ( in the example the println statement that prints the message \"after react and printing a 10\"), but in reality that would never get executed as only the body of the \"react\" method is captured and sequenced for execution later (on the arrival of a message). Since the contract of react has the return type of \"Nothing\" there cannot be any statements following react, and there for there is no reason to maintain the stack. In the example above variable \"a\" would not have to be maintained as the statements after the react calls are not executed at all. Note that all the needed variables by the body of react is already be captured as a closure, so it can execute just fine. The java actor framework  actually does the stack maintenance by saving the stack which gets unrolled on the react getting a message. Just to have it here:These papers are linked from the scala api for Actor and provide the theoretical framework for the actor implementation. This includes why react may never return.I haven't done any major work with scala /akka, however i understand that there is a very significant difference in the way actors are scheduled. \nAkka is just a smart threadpool which is time slicing execution of actors... \nEvery time slice will be one message execution to completion by an actor unlike in Erlang which could be per instruction?!This leads me to think that react is better as it hints the current thread to consider other actors for scheduling where as receive \"might\" engage the current thread to continue executing other messages for the same actor. "},
Scala

What are the differences among Streams, Views (SeqView), and Iterators in scala? This is my understanding:So if I want to save heap space, should I use iterators (if I won't traverse the list again) or views? Thanks. First, they are all . That has a particular mathematical meaning related to functions, but, basically, means they are computed on-demand instead of in advance. is a lazy list indeed. In fact, in Scala, a  is a  whose  is a . Once computed, a value stays computed and is reused. Or, as you say, the values are cached.An  can only be used once because it is a   into a collection, and not a collection in itself. What makes it special in Scala is the fact that you can apply transformation such as  and  and simply get a new  which will only apply these transformations when you ask for the next element.Scala used to provide iterators which could be reset, but that is very hard to support in a general manner, and they didn't make version 2.8.0.Views are meant to be viewed much like a database view. It is a series of transformation which one applies to a collection to produce a \"virtual\" collection. As you said, all transformations are re-applied each time you need to fetch elements from it.Both  and views have excellent memory characteristics.  is nice, but, in Scala, its main benefit is writing infinite sequences (particularly sequences recursively defined). One  avoid keeping all of the  in memory, though, by making sure you don't keep a reference to its  (for example, by using  instead of  to define the ).Because of the penalties incurred by views, one should usually  it after applying the transformations, or keep it as a view if only few elements are expected to ever be fetched, compared to the total size of the view."},
Scala

On the surface Groovy and Scala look pretty similar, aside from Scala being statically typed, and Groovy dynamic.They're both object oriented languages for the JVM that have lambdas and closures and interoperate with Java.  Other than that, they're extremely different.Groovy is a \"dynamic\" language in not only the sense that it is dynamically typed but that it supports dynamic meta-programming.Scala is a \"static\" language in that it is statically typed and has virtually no dynamic meta-programming beyond the awkward stuff you can do in Java.  Note, Scala's static type system is substantially more uniform and sophisticated than Java's.Groovy is syntactically influenced by Java but semantically influenced more by languages like Ruby.Scala is syntactically influenced by both Ruby and Java.  It is semantically influenced more by Java, SML, Haskell, and a very obscure OO language called gBeta. Groovy has \"accidental\" multiple dispatch due to the way it handles Java overloading.Scala is single dispatch only, but has SML inspired pattern matching to deal with some of the same kinds of problems that multiple dispatch is meant to handle.  However, where multiple dispatch can only dispatch on runtime type, Scala's pattern matching can dispatch on runtime types, values, or both.  Pattern matching also includes syntactically pleasant variable binding.  It's hard to overstress how pleasant this single feature alone makes programming in Scala.Both Scala and Groovy support a form of multiple inheritance with mixins (though Scala calls them traits).Scala supports both partial function application and currying at the language level, Groovy has an awkward \"curry\" method for doing partial function application.Scala does direct tail recursion optimization.  I don't believe Groovy does.  That's important in functional programming but less important in imperative programming.Both Scala and Groovy are eagerly evaluated by default.  However, Scala supports call-by-name parameters. Groovy does not - call-by-name must be emulated with closures.Scala has \"for comprehensions\", a generalization of list comprehensions found in other languages (technically they're monad comprehensions plus a bit - somewhere between Haskell's do and C#'s LINQ).Scala has no concept of \"static\" fields, inner classes, methods, etc - it uses singleton objects instead.  Groovy uses the static concept.Scala does not have built in selection of arithmetic operators in quite the way that Groovy does.  In Scala you can name methods very flexibly.Groovy has the elvis operator for dealing with null.  Scala programmers prefer to use Option types to using null, but it's easy to write an elvis operator in Scala if you want to.Finally, there are lies, there are damn lies, and then there are benchmarks.  The computer language benchmarks game ranks Scala as being between substantially faster than Groovy (ranging from twice to 93 times as fast) while retaining roughly the same source size. .  I'm sure there are many, many differences that I haven't covered.  But hopefully this gives you a gist.Is there a competition between them?  Yes, of course, but not as much as you might think. Groovy's real competition is JRuby and Jython.Who's going to win?  My crystal ball is as cracked as anybody else's.Scala has Actors, which make concurrency much easier to implement. And Traits which give true, typesafe multiple inheritance.scala is meant to be an oo/functional hybrid language and is  well planned and designed. groovy is more like a set of enhancements that many people would love to use in java.\ni took a closer look at both, so i can tell :)neither of them is better or worse than the other. groovy is very good at meta-programming, scala is very good at everything that does not need meta-programming, so...i tend to use both.You've hit the nail on the head with the static and dynamic typing.  Both are part of the new generation of dynamic languages, with closures, lambda expressions, and so on.  There are a handful of syntactic differences between the two as well, but functionally, I don't see a huge difference between Groovy and Scala.Scala implements Lists a bit differently; in Groovy, pretty much everything is an instance of java.util.List, whereas Scala uses both Lists and primitive arrays.  Groovy has (I think) better string interpolation.Scala is faster, it seems, but the Groovy folks are really pushing performance for the 2.0 release.  1.6 gave a huge leap in speed over the 1.5 series.I don't think that either language will really 'win', as they target two different classes of problems.  Scala is a high-performance language that is very Java-like without having quite the same level of boilerplate as Java.  Groovy is for rapid prototyping and development, where speed is less important than the time it takes for programmers to implement the code.We have extensively used Groovy and can say with confidence that it is extremely good in developing production quality web applications, not just for prototyping. It is very easy to use and allows fast development, so much so that it is hard to wean away developers from Groovy to plan Java after they have used it for sometime, in my experience.I haven't used Scala much and so can't say much about it.Scala has a much steeper learning curve than Groovy. Scala has much more support for functional programming with its pattern matching and tail based recursion, meaning more tools for pure FP. Scala also has dynamica compilation and I have done it using twitter eval lib ( ). I kept scala code in a flat file(without any extension) and using eval created scala class at run time. \nI would say scala is meta programming and has feature of dynamic complication "},
Scala

These lines of code outputs , even though  was successfully executed. I found that this happens because I used def in . If I use var or val the output is . I understand the default is val in scala. This:...gives a compilation error because it is a val by default. Why do the first set of lines above not work properly, and yet also don't error?There are three ways of defining things in Scala:Looking at your code:This defines a new method called . You can call this method only without  because it is defined as parameterless method. For empty-paren method, you can call it with or without '()'. If you simply write:then you are calling this method (and if you don't assign the return value, it will just be discarded). In this line of code:what happens is that you first call the  method, and on the return value (an instance of class ) you are changing the  member variable. And the last line:Here you are again calling the  method, which returns a new instance of class  (with  set to 12). It's the same as this:I'd start by the distinction that exists in Scala between ,  and .  According to above, labels from  and  cannot be reassigned, and in case of any attempt an error like the below one will be raised:When the class is defined like:and then instantiated with:an  is created for that specific instance of Person (i.e. 'personA'). Whenever the mutable field 'age' needs to be modified, such attempt fails:as expected, 'age' is part of a non-mutable label. The correct way to work on this consists in using a mutable variable, like in the following example:as clear, from the  (i.e. 'personB') it is possible to modify the class mutable field 'age'.I would still stress the fact that everything comes from the above stated difference, that has to be clear in mind of any Scala programmer.With you are defining a function/lazy variable which always returns a new Person instance with name \"Kumar\" and age 12. This is totally valid and the compiler has no reason to complain. Calling person.age will return the age of this newly created Person instance, which is always 12.When writingyou assign a new value to the age property in class Person, which is valid since age is declared as . The compiler will complain if you try to reassign  with a new Person object likeTo provide another perspective, \"def\" in Scala means something that will  when it's used, while val is something that is . Here, the expression  entails that whenever we use \"person\" we will get a  call. Therefore it's natural that the two \"person.age\" are non-related.This is the way I understand Scala(probably in a more \"functional\" manner). I'm not sure ifis really what Scala intends to mean though. I don't really like to think that way at least...As Kintaro already says, person is a method (because of def) and always returns a new Person instance. As you found out it would work if you change the method to a var or val:Another possibility would be:However,  in your code is allowed, as you get back a  instance from the  method, and on this instance you are allowed to change the value of a . The problem is, that after that line you have no more reference to that instance (as every call to  will produce a new instance).This is nothing special, you would have exactly the same behavior in Java:Let's take this:and rewrite it with equivalent codeSee,  is a method. It will execute each time it is called, and each time it will return (a) . And these is no error in the \"assignment\" because it isn't really an assignment, but just a call to the  method (provided by )."},
Scala

I wonder if there is a way to make asynchronous calls to a database?For instance, imagine that I've a big request that take a very long time to process, I want to send the request and receive a notification when the request will return a value (by passing a Listener/callback or something). I don't want to block waiting for the database to answer.I don't consider that using a pool of threads is a solution because it doesn't scale, in the case of heavy concurrent requests this will spawn a very large number of threads.We are facing this kind of problem with network servers and we have found solutions by using select/poll/epoll system call to avoid having one thread per connection. I'm just wondering how to have a similar feature with database request?Note:\nI'm aware that using a FixedThreadPool may be a good work-around, but I'm surprised that nobody has developed a system really asynchronous (without the usage of extra thread).** Update **\nBecause of the lack of real practical solutions, I decided to create a library (part of finagle) myself: . It basically decodes/decodes mysql request/response, and use Finagle/Netty under the hood. It scales extremely well even with huge number of connections.I don't understand how any of the proposed approaches that wrap JDBC calls in Actors, executors or anything else can help here - can someone clarify.Surely the basic problem is that the JDBC operations block on socket IO. When it does this it blocks the Thread its running on - end of story. Whatever wrapping framework you choose to use its going to end up with one thread being kept busy/blocked per concurrent request.If the underlying database drivers (MySql?) offers a means to intercept the socket creation (see SocketFactory) then I imagine it would be possible to build an async event driven database layer on top of the JDBC api but we'd have to encapsulate the whole JDBC behind an event driven facade, and that facade wouldn't look like JDBC (after it would be event driven).  The database processing would happen async on a different thread to the caller, and you'd have to work out how to build a transaction manager that doesn't rely on thread affinity.Something like the approach I mention would allow even a single background thread to process a load of concurrent JDBC exec's. In practice you'd probably run a pool of threads to make use of multiple cores.(Of course I'm not commenting on the logic of the original question just the responses that imply that concurrency in a scenario with blocking socket IO is possible without the user of a selector pattern - simpler just to work out your typical JDBC concurrency and put in a connection pool of the right size).Looks like MySql probably does something along the lines I'm suggesting --- \nIt's impossible to make an asynchronous call  via JDBC, but you can make asynchronous calls  with  (e.g., actor makes calls to the DB via JDBC, and sends messages to the third parties, when the calls are over), or, if you like CPS, with  (a good implementation is  )Scala actors by default are event-based (not thread-based) - continuation scheduling allows creating millions of actors on a standard JVM setup. If you're targeting Java,  is an Actor model implementation that has a good API both for Java and Scala.Aside from that, the synchronous nature of JDBC makes perfect sense to me. The cost of a database session is far higher than the cost of the Java thread being blocked (either in the fore- or background) and waiting for a response. If your queries run for so long that the capabilities of an executor service (or wrapping Actor/fork-join/promise concurrency frameworks) are not enough for you (and you're consuming too many threads) you should first of all think about your database load. Normally the response from a database comes back very fast, and an executor service backed with a fixed thread pool is a good enough solution. If you have too many long-running queries, you should consider upfront (pre-)processing - like nightly recalculation of the data or something like that.Perhaps you could use a JMS asynchronous messaging system, which scales pretty well, IMHO:There is no direct support in JDBC but you have multiple options like MDB, Executors from Java 5.\"I don't consider that using a pool of threads is a solution because it doesn't scale, in the case of heavy concurrent requests this will spawn a very large number of threads.\"I am curious why would a bounded pool of threads is not going to scale? It is a pool not thread-per-request to spawn a thread per each request. I have been using this for quite sometime on a heavy load webapp and we have not seen any issues so far.The  might come handy.You can have a fixed number of threads to handle long-running operations. And instead of  you can use , which return a result. The result is encapsulated in a  object, so you can get it when it is back.Ajdbc project  seems to answer this problem There is currently 2 experimental natively async drivers for mysql and postgresql.Just a crazy idea : you could use an Iteratee pattern over JBDC resultSet wrapped in some Future/PromiseHammersmith does that for MongoBd.An old question, but some more information.  It is not possible to have JDBC issue asynchronous requests to the database itself, unless a vendor provides an extension to JDBC and a wrapper to handle JDBC with.  That said, it is possible to wrap JDBC itself with a processing queue, and to implement logic that can process off the queue on one or more separate connections.  One advantage of this for some types of calls is that the logic, if under heavy enough load, could convert the calls into JDBC batches for processing, which can speed up the logic significantly.  This is most useful for calls where data is being inserted, and the actual result need only be logged if there is an error.  A great example of this is if inserts are being performed to log user activity.  The application won't care if the call completes immediately or a few seconds from now.As a side note, one product on the market provides a policy driven approach to allowing asynchronous calls like those I described to be made asynchronously ().  Disclaimer:  I am co-founder of this company.  It allows regular expressions to be applied to data transformation requests such as insert/update/deletes for any JDBC data source, and will automatically batch them together for processing.  When used with MySQL and the rewriteBatchedStatements option () this can significantly lower overall load on the database.You have three options in my opinion: I am one of the developers of CoralMQ.The commons-dbutils library has support for an  which you provide an  to and it returns a . Worth checking out as it's simple to use and ensure you won't leak resources.I am just thinking ideas here. Why couldn't you have a pool of database connections with each one having a thread. Each thread has access to a queue. When you want to do a query that takes a long time, you can put on the queue and then one of threads will pick it up and handle it. You will never have too many threads because the number of your threads are bounded. Edit: Or better yet, just a number of threads. When a thread sees something in a queue, it asks for a connection from the pool and handles it. "},
Scala

I have such a piece of code from :Everything in it is pretty clear, except this piece: \nWhat does it do? I under stand there is Seq[Node] concatenated with another Node, and then? What does  do?Thanks in advanceIt \"splats\" the sequence.Look at the constructor signaturewhich is called asbut here there is only a sequence, not , , etc. so this allows the result sequence to be used as the input to the constructor.Happy coding. This doesn't have a cutesy-name in the SLS, but here are the details. The important thing to get is that it changes how Scala binds the arguments to the method with repeated parameters (as denoted with  above).The  is covered in \"4.6.2 Repeated Parameters\" of the SLS. expands  to  (tells the compiler that we're rather working with a varargs, than a sequence). Particularly useful for the methods that can accept only varargs."},
Scala

How in the world do you get just an element at index  from the List in scala?I tried , and   - nothing works. Googling only returns how to \"find\" an element in the list. But I already know the index of the element!Here is the code that does not compile:Looking at the  does not help, as my eyes just cross.Use parentheses:But you don't really want to do that with lists very often, since linked lists take time to traverse.  If you want to index into a collection, use  (immutable) or  (mutable) or possibly  (which is just a Java array, except again you index into it with  instead of ).Safer is to use  so you can extract the value if it exists and fail gracefully if it does not.This will return None if the list isn't long enough to provide that element, and Some(value) if it is.Whenever you're performing an operation that may fail in this way it's great to use an Option and get the type system to help make sure you are handling the case where the element doesn't exist.This works because List's  (which sugars to just parentheses, e.g. ) is like a partial function that is defined wherever the list has an element. The  method turns the partial  function (a function that is only defined for some inputs) into a normal function (defined for any input) by basically wrapping the result in an Option.Why parentheses? Here is the quote from the book . Here are a few examples how to pull certain element (first elem in this case) using functional programming style. "},
Scala

Say I have got following two es:and the following instance of  class:Now if I want to update  of  then I will have to do:With more levels of nesting this gets even more uglier. Is there a cleaner way (something like Clojure's ) to update such nested structures? provides convenient traversal and 'mutation' of an immutable data structure. Scalaz provides Zippers for  (), and  (). It turns out that the structure of the zipper is automatically derivable from the original data structure, in a manner that resembles symbolic differentiation of an algebraic expression.But how does this help you with your Scala case classes? Well, Lukas Rytz recently  an extension to scalac that would automatically create zippers for annotated case classes. I'll reproduce his example here:So the community needs to persuade the Scala team that this effort should be continued and integrated into the compiler.Incidentally, Lukas recently  a version of Pacman, user programmable through a DSL. Doesn't look like he used the modified compiler, though, as I can't see any  annotations.In other circumstances, you might like to apply some transformation across the entire data structure, according to some strategy (top-down, bottom-up), and based on rules that match against the value at some point in the structure. The classical example is transforming an AST for a language, perhaps to evaluate, simplify, or collect information.  supports , see the examples in , and watch this . Here's a snippet to whet your appetite:Note that Kiama  the type system to achieve this.Funny that no one added lenses, since they were MADE for this kind of stuff. So,  is a CS background paper on it,  is a blog which touch briefly on lenses use in Scala,  is a lenses implementation for Scalaz and  is some code using it, which looks surprisingly like your question. And, to cut down on boiler plate,  a plugin that generate Scalaz lenses for case classes.For bonus points,  another S.O. question which touches on lenses, and a  by Tony Morris.The big deal about lenses is that they are composable. So they are a bit cumbersome at first, but they keep gaining ground the more you use them. Also, they are great for testability, since you only need to test individual lenses, and can take for granted their composition.So, based on an implementation provided at the end of this answer, here's how you'd do it with lenses. First, declare lenses to change a zip code in an address, and an address in a person:Now, compose them to get a lens that changes zipcode in a person:Finally, use that lens to change raj:Or, using some syntactic sugar:Or even:Here's the simple implementation, taken from Scalaz, used for this example:Just want to add that the  and  projects, based on Scala 2.10 macros, provides Dynamic Lens Creation.I've been looking around for what Scala library that has the nicest syntax and the best functionality and one library not mentioned here is  which for me has been really good. An example follows:These are very nice and there are many ways to combine the lenses. Scalaz for example demands a lot of boilerplate and this compiles quick and runs great.To use them in your project just add this to your dependencies:Shapeless does the trick:with: Note that whilst some other answers here let you compose lenses to go deeper into a given structure these shapless lenses (and other libraries/macros) let you combine two unrelated lenses such that you can make lens that sets an arbitrary number of parameters into arbitrary positions in your structure. For complex data structures that additional composition is very helpful.  Due to their composable nature, lenses provide a very nice solution to the problem of heavily nested structures. However with a low level of nesting, I sometimes feel lenses are a bit too much, and I don't want to introduce the whole lenses approach if there is only few places with nested updates. For sake of completeness, here is a very simple/pragmatic solution for this case:What I do is to simply write a few  helper functions in the top level structure, which deal with the ugly nested copy. For instance:My main goal (simplifying the update on client side) is achieved:Creating the full set of modify helpers is obviously annoying. But for internal stuff it is often okay to just create them the first time you try to modify a certain nested field.Perhaps  matches your question better. QuickLens uses macro's to convert an IDE friendly expression into something that is close to the original copy statement.Given the two example case classes:and the instance of Person class:you can update zipCode of raj with:"},
Scala

I have to say I don't understand Scala enumeration classes. I can copy-paste the example from documentation, but I have no idea what is going on.the  trait has a type member  representing the individual elements of the enumeration (it's actually an inner class, but the difference doesn't matter here).Thus  inherits that type member. The line  is just a . It is useful, because after you import it elsewhere with , you can use that type, e.g.:Instead, a minimal version would just be:and you do not  import the contents of , but then you would need to use type  and to qualify individual members. So the example would becomeThe second question is about the meaning of . This is indeed very confusing if you don't look into the implementation of . This is not the assignment of a type! It is instead calling a protected , , which returns a concrete instance of type .It so happens that you can write  in Scala, and for each value , , and  the method  will be called again and again.  uses this trick to increment an internal counter so that each value is individual.If you open the Scala API docs for  and click on , you will see that method appearing."},
Scala

Dependent method types, which used to be an experimental feature before, has now been , and apparently this seems to have created  in the Scala community. After first look, it's not immediately obvious what this could potentially be useful for. Heiko Seeberger posted a simple example of dependent method types , which as can be seen in the comment there can easily be reproduced with type parameters on methods. So that wasn't a very compelling example. (I might be missing something obvious. Please correct me if so.)What are some practical and useful examples of use cases for dependent method types where they are clearly advantageous over the alternatives? What interesting things can we do with them that weren't possible/easy before? What do they buy us over the existing type system features?Thanks! Are dependent method types analogous to / draw inspiration from any features found in the type systems of other advanced typed languages such as Haskell, OCaml?More or less any use of member (ie. nested) types can give rise to a need for dependent method types. In particular, I maintain that without dependent method types the classic cake pattern is closer to being an anti-pattern.So what's the problem? Nested types in Scala are dependent on their enclosing instance. Consequently, in the absence of dependent method types, attempts to use them outside of that instance can be frustratingly difficult. This can turn designs which initially seem elegant and appealing into monstrosities which are nightmarishly rigid and difficult to refactor.I'll illustrate that with an exercise I give during my ,It's an example of the classic cake pattern: we have a family of abstractions which are gradually refined through a heirarchy (/ are refined by / which are in turn refined by /). It's a toy example, but the pattern is real: it's used throughout the Scala compiler and was used extensively in the Scala Eclipse plugin.Here's an example of the abstraction in use,Note that the path dependency means that the compiler will guarantee that the  and  methods on  can only be called with arguments which correspond to it, ie. it's own , and nothing else.That's undeniably a desirable property, but suppose we wanted to move this test code to a different source file? With dependent method types it's trivially easy to redefine those methods outside the  hierarchy,Note the uses of dependent method types here: the type of the second argument () depends on the value of the first argument ().It is possible to do this without dependent method types, but it's extremely awkward and the mechanism is quite unintuitive: I've been teaching this course for nearly two years now, and in that time, noone has come up with a working solution unprompted.Try it for yourself ...After a short while struggling with it you'll probably discover why I (or maybe it was David MacIver, we can't remember which of us coined the term) call this the Bakery of Doom. consensus is that Bakery of Doom was David MacIver's coinage ...For the bonus: Scala's form of dependent types in general (and dependent method types as a part of it) was inspired by the programming language  ... they arise naturally from Beta's consistent nesting semantics. I don't know of any other even faintly mainstream programming language which has dependent types in this form. Languages like Coq, Cayenne, Epigram and Agda have a different form of dependent typing which is in some ways more general, but which differs significantly by being part of type systems which, unlike Scala, don't have subtyping.Somewhere else we can statically guarantee that we aren't mixing up nodes from two different graphs, e.g.: Of course, this already worked if defined inside , but say we can't modify  and are writing a \"pimp my library\" extension for it.About the second question: types enabled by this feature are  weaker than complete dependent types (See  for a flavor of that.) I don't think I've seen an analogy before.This new feature is needed when  . When type parameters are used, the  type dependency can be expressed in the latest and some older versions of Scala, as in the following simplified example.I'm  for the interoption of a form of declarative programming with environmental state. The details aren't relevant here (e.g. details about callbacks and conceptual similarity to the Actor model combined with a Serializer).The relevant issue is state values are stored in a hash map and referenced by a hash key value. Functions input immutable arguments that are values from the environment, may call other such functions, and write state to the environment. But functions are  values from the environment (so the internal code of the function is not dependent on the order of state changes and thus remains declarative in that sense). How to type this in Scala?The environment class must have an overloaded method which inputs such a function to call, and inputs the hash keys of the arguments of the function. Thus this method can call the function with the necessary values from the hash map, without providing public read access to the values (thus as required, denying functions the ability to read values from the environment).But if these hash keys are strings or integer hash values, the static typing of the hash map element type  to Any or AnyRef (hash map code not shown below), and thus a run-time mismatch could occur, i.e. it would be possible to put any type of value in a hash map for a given hash key.Although I didn't test the following, in theory I can get the hash keys from class names at runtime employing , so a hash key is a class name instead of a string (using Scala's backticks to embed a string in a class name).So static type safety is achieved."},
Scala

Is it possible to match on a comparison using the pattern matching system in Scala?\nFor example:The second case statement is illegal, but I would like to be able to specify \"when a is greater than\".You can add a guard, i.e. an  and a boolean expression after the pattern:Edit: Note that this is more than superficially different to putting an   the , because a pattern  match if the guard is not true.As a non-answer to the question's spirit, which asked how to incorporate predicates into a match clause, in this case the predicate can be factored out before the :Now,  promises only that the non-equal outcomes will be  or . Java's  is specified similarly to Scala's. It happens to be conventional to use 1 and -1 for the positive and negative values, respectively, as Scala's  does, but one can't make such an assumption without some risk of the implementation changing out from underneath.A solution that in my opinion is much more readable than adding guards:Notes:Use guards:"},
Scala

According to the :In practice what are the limits? Also, are there different limits that apply to inferred expression types than to parameter type bounds, and what are those limits?When inferring types, the compiler often needs to calculate the Least Upper Bound (LUB) of a list of types. For example, the type of  is the LUB of the types of  and .These types can get quite large, for example try this in a REPL:This  introduced some sanity checks to limit the depth of such inferred types.There has been some recent work to plugin to the compilation process to detect inferred types that take a long time to calculate, and suggest places where an explicit type annotation might be prudent."},
Scala

Getting strange behavior when calling function outside of a closure:The problem is I need my code in a class and not an object. Any idea why this is happening? Is a Scala object serialized (default?)?This is a working code example:This is the non-working example :I don't think the other answer is entirely correct. , so this is not what's causing your task to fail. Spark is a distributed computing engine and its main abstraction is a resilient distributed dataset (), which can be viewed as a distributed collection. Basically, RDD's elements are partitioned across the nodes of the cluster, but Spark abstracts this away from the user, letting the user interact with the RDD (collection) as if it were a local one.Not to get into too many details, but when you run different transformations on a RDD (, ,  and others), your transformation code (closure) is:You can of course run this locally (as in your example), but all those phases (apart from shipping over network) still occur. [This lets you catch any bugs even before deploying to production]What happens in your second case is that you are calling a method, defined in class  from inside the map function. Spark sees that and since methods cannot be serialized on their own, Spark tries to serialize   class, so that the code will still work when executed in another JVM. You have two possibilities:Either you make class testing serializable, so the whole class can be serialized by Spark:or you make  function instead of a method (functions are objects in Scala), so that Spark will be able to serialize it:Similar, but not the same problem with class serialization can be of interest to you and you can read on it .As a side note, you can rewrite  to , they are exactly the same. Usually, the second is preferred as it's less verbose and cleaner to read.EDIT (2015-03-15):  introduced  and Spark 1.3.0 is the first version to use it. It adds serialization path to a . When a NotSerializableException is encountered, the debugger visits the object graph to find the path towards the object that cannot be serialized, and constructs information to help user to find the object.In OP's case, this is what gets printed to stdout: is great in explaining why the original code does not work and two ways to fix the issue. However, this solution is not very flexible; consider the case where your closure includes a method call on a non- class that you have no control over. You can neither add the  tag to this class nor change the underlying implementation to change the method into a function.  presents a great workaround for this, but the solution can be made both more concise and general:This function-serializer can then be used to automatically wrap closures and method calls:This technique also has the benefit of not requiring the additional Shark dependencies in order to access , since Twitter's Chill is already pulled in by core SparkComplete talk fully explaining the problem, which proposes a great paradigm shifting way to avoid these serialization problems: The top voted answer is basically suggesting throwing away an entire language feature - that is no longer using methods and only using functions. Indeed in functional programming methods in classes should be avoided, but turning them into functions isn't solving the design issue here (see above link). As a quick fix in this particular situation you could just use the  annotation to tell it not to try to serialise the offending value (here,  is a custom class not Spark's one following OP's naming):You can also restructure code so that rddList lives somewhere else, but that is also nasty.In future Scala will include these things called \"spores\" that should allow us to fine grain control what does and does not exactly get pulled in by a closure.  Furthermore this should turn all mistakes of accidentally pulling in non-serializable types (or any unwanted values) into compile errors rather than now which is horrible runtime exceptions / memory leaks.When using kyro, make it so that registration is necessary, this will mean you get errors instead of memory leaks:\"Finally, I know that kryo has kryo.setRegistrationOptional(true) but I am having a very difficult time trying to figure out how to use it. When this option is turned on, kryo still seems to throw exceptions if I haven't registered classes.\"Of course this only gives you type-level control not value-level control.... more ideas to come.I solved this problem using a different approach. You simply need to serialize the objects before passing through the closure, and de-serialize afterwards. This approach just works, even if your classes aren't Serializable, because it uses Kryo behind the scenes. All you need is some curry. ;)Here's an example of how I did it:Feel free to make Blah as complicated as you want, class, companion object, nested classes, references to multiple 3rd party libs.KryoSerializationWrapper refers to: I'm not entirely certain that this applies to Scala but, in Java, I solved the  by refactoring my code so that the closure did not access a non-serializable  field.I faced similar issue, and what I understand from  is your  method is trying to serialize  method, but as method are not serializable, it tries to serialize class  which is again not serializable.So make your code work, you should define  inside  method. For example:And if there are multiple functions coming into picture, then all those functions should be available to the parent context."},
Scala

I am really interested in finding out where the differences are, and more generally, to identify canonical use cases where HLists cannot be used (or rather, don't yield any benefits over regular lists).(I am aware that there are 22 (I believe)  in Scala, whereas one only needs a single HList, but that is not the kind of conceptual difference I am interested in.)I've marked a couple of questions in the text below. It might not actually be necessary to answer them, they are more meant to point out things that are unclear to me, and to guide the discussion in certain directions.I've recently seen a couple of answers on SO where people suggested to use HLists (for example, as provided by ), including a deleted answer to . It gave rise to , which in turn sparked this question.It seems to me, that hlists are only useful when you know the number of elements and their precise types statically. The number is actually not crucial, but it seems unlikely that you ever need to generate a list with elements of varying but statically precisely known types, but that you don't statically know their number.  Could you even write such an example, e.g., in a loop? My intuition is that having a statically precise hlist with a statically unknown number of arbitrary elements (arbitrary relative to a given class hierarchy) just isn't compatible.If this is true, i.e, you statically know number and type -  why not just use an n-tuple? Sure, you can typesafely map and fold over an HList (which you can also, but  typesafely, do over a tuple with the help of ), but since number and type of the elements are statically known you could probably just access the tuple elements directly and perform the operations.On the other hand, if the function  you map over an hlist is so generic that it accepts all elements -  why not use it via ? Ok, one interesting difference could come from method overloading: if we had several overloaded 's, having the stronger type information provided by the hlist (in contrast to the productIterator) could allow the compiler to choose a more specific . However, I am not sure if that would actually work in Scala, since methods and functions are not the same.Building on the same assumption, namely, that you need to know number and types of the elements statically -  can hlists be used in situations where the elements depend on any kind of user interaction? E.g., imagine populating an hlist with elements inside a loop; the elements are read from somewhere (UI, config file, actor interaction, network) until a certain condition holds. What would the type of the hlist be? Similar for an interface specification getElements: HList[...] that should work with lists of statically unknown length, and that allows component A in a system to get such a list of arbitrary elements from component B.Addressing questions one to three: one of the main applications for  is abstracting over arity. Arity is typically statically known at any given use site of an abstraction, but varies from site to site. Take this, from shapeless's ,Without using  (or something equivalent) to abstract over the arity of the tuple arguments to  it would be impossible to have a single implementation which could accept arguments of these two very different shapes and transform them in a type safe way.The ability to abstract over arity is likely to be of interest anywhere that fixed arities are involved: as well as tuples, as above, that includes method/function parameter lists, and case classes. See  for examples of how we might abstract over the arity of arbitrary case classes to obtain type class instances almost automatically,There's no runtime  here, but there is , which the use of  (or equivalent structures) can eliminate. Of course, if your tolerance for repetitive boilerplate is high, you can get the same result by writing multiple implementations for each and every shape that you care about.In question three you ask \"... if the function f you map over an hlist is so generic that it accepts all elements ... why not use it via productIterator.map?\". If the function you map over an HList really is of the form  then mapping over  will serve you perfectly well. But functions of the form  aren't typically that interesting (at least, they aren't unless they type case internally). shapeless provides a form of polymorphic function value which allows the compile to select type-specific cases in exactly the way you're doubtful about. For instance,With respect to your question four, about user input, there are two cases to consider. The first is situations where we can dynamically establish a context which guarantees that a known static condition obtains. In these kinds of scenarios it's perfectly possible to apply shapeless techniques, but clearly with the proviso that if the static condition  obtain at runtime then we have to follow an alternative path. Unsurprisingly, this means that methods which are sensitive to dynamic conditions have to yield optional results. Here's an example using s,The type of  doesn't capture the length of the list, or the precise types of its elements. However, if we expect it to have a specific form (ie. if it ought to conform to some known, fixed schema), then we can attempt to establish that fact and act accordingly,There are other situations where we might not care about the actual length of a given list, other than that it is the same length as some other list. Again, this is something that shapeless supports, both fully statically, and also in a mixed static/dynamic context as above. See  for an extended example.It is true, as you observe, that all of these mechanism require static type information to be available, at least conditionally, and that would seem to exclude these techniques from being usable in a completely dynamic environment, fully driven by externally provided untyped data. But with the advent of the support for runtime compilation as a component of Scala reflection in 2.10, even this is no longer an insuperable obstacle ... we can use runtime compilation to provide a form of  and have our static typing performed at runtime in response to dynamic data: excerpt from the preceding below ... follow the link for the full example,I'm sure  will have something to say about that, given his  ;-)Just to be clear, an HList is essentially nothing more than a stack of  with slightly different sugar on top.So your question is essentially about the differences between using nested tuples vs flat tuples, but the two are isomorphic so in the end there really is no difference except convenience in which library functions can be used and which notation can be used.There are a lot of things you can't do (well) with tuples:You can do all of that with tuples of course, but not in the general case. So using HLists makes your code more DRY.I can explain this in super simple language:The tuple vs list naming isn't significant. HLists could be named as HTuples. The difference is that in Scala+Haskell, you can do this with a tuple (using Scala syntax):to take an input tuple of exactly two elements of any type, append a third element, and return a fully typed tuple with exactly three elements. But while this is completely generic over types, it has to explicitly specify the input/output lengths.What a Haskell style HList lets you do is make this generic over length, so you can append to any length of tuple/list and get back a fully statically typed tuple/list. This benefit also applies to homogeneously typed collections where you can append an int to a list of exactly n ints and get back a list that is statically typed to have exactly (n+1) ints without explicitly specifying n."},
Scala

I have seen a function named  used in Scala examples. What is it, and how is it used?:Note that we have to write  since the compiler thinks that   means that we call  with parameters.Also see  and Here are a few reasons to use the delightfully simple method .An Implicit View can be triggered when the prefix of a selection (consider for example,  does not contain a member  that is applicable to  (even after trying to convert  with Implicit Views). In this case, the compiler looks for implicit members, locally defined in the current or enclosing scopes, inherited, or imported, that are either Functions from the type of that  to a type with  defined, or equivalent implicit methods.Implicit Views can also be triggered when an expression does not conform to the Expected Type, as below:Here the compiler looks for this function:Implicit parameters are arguably a more important feature of Scala than Implicit Views. They support the type class pattern. The standard library uses this in a few places -- see  and how it is used in . Implicit Parameters are also used to pass Array manifests, and  instances.Scala 2.8 allows a shorthand syntax for implicit parameters, called Context Bounds. Briefly, a method with a type parameter  that requires an implicit parameter of type :can be rewritten as:But what's the point of passing the implicit parameter but not naming it? How can this be useful when implementing the method ?Often, the implicit parameter need not be referred to directly, it will be tunneled through as an implicit argument to another method that is called. If it is needed, you can still retain the terse method signature with the Context Bound, and call  to materialize the value:Suppose you are calling a method that pretty prints a person, using a type class based approach:What if we want to change the way that the name is output? We can explicitly call , explicitly pass an alternative , but we want the compiler to pass the . is avaliable in Scala 2.8 and is  defined in  as: It is commonly used to  if so is the case. Simple example  from ) A \"teach you to fish\" answer is to use the alphabetic member index currently available in the . The letters (and the , for non-alphabetic names) at the top of the package / class pane are links to the index for member names beginning with that letter (across all classes). If you choose , e.g., you'll find the  entry with one occurrence, in , which you can visit from the link there."},
Scala

What's the standard way to work with dates and times in Scala? Should I use Java types such as java.util.Date or there are native Scala alternatives?From Java SE 8 onwards, users are asked to migrate to java.time (JSR-310). There are efforts on creating scala libraries  wrapping java.time for scala such as . If targeting lower than SE 8 use one of the below. Also see . This project forked from scala-time since it seems that scala-time is no longer maintained. is a good Java library, there is a Scala wrapper / implicit conversion library avaliable for Joda Time at  created by . (Note implicits have a performance hit, but it depends on what you do if you will notice. And if you run into a performance problem you can just revert to the Joda interface)From the README:If you are using Java 8, then there is no need to use  anymore. The Joda-Time library has been moved into Java 8 under the  package (JSR-310). Just import that package into your Scala project.MOTIVATION:The Java Date and Calendar libraries are largely inadequate. They are mutable,\nnot thread-safe, and very inconvenient to use.The Joda Time library is a great replacement for Java's Date and Calendar\nclasses. They're immutable by default, have a much richer and nicer API, and\ncan easily be converted to Java's Date and Calendar classes when necessary.This project provides a thin layer of convenience around the Joda Time\nlibraries, making them more idiomatic to use within Scala.(copied from )There is no  way to work with dates in Scala. The options available are:I would avoid using java.util.Date due to the well-documented issues surrounding it.Everyone uses JodaTime, these Scala helper/wrapper libraries may need re-compilation with new versions of Scala. Jodatime is the only time library that's been around for a long time, and is stable and works reliably with every version of Scala."},
Scala

I am upgrading existing code from  to  and  from .I'm having difficulty writing  that contains a scala enum, that I really could use some help with.For example,When we try to write to this field, we get the following error:We used to have this working in Rogue 1.1.8, by using our own version of the , which made the #formats method overridable. But that feature was included into lift-mongodb-record in 2.5-RC6, so we thought this should just work now?Answer coming from :  Sorry, I should have chimed in here sooner.One of the long-standing problems with Rogue was that it was too easy to\naccidentally make a field that was not serializable as BSON, and have it\nfail at runtime (when you try to add that value to a DBObject) rather than\nat compile time.I introduced the BSONType type class to try to address this. The upside is\nit catches BSON errors at compile time. The downside is you need to make a\nchoice when it comes to case classes.If you want to do this the \"correct\" way, define your case class plus a\nBSONType \"witness\" for that case class. To define a BSONType witness, you\nneed to provide serialization from that type to a BSON type. Example:That said, this can be quite burdensome if you're doing it for each case\nclass. Your second option is to define a generic witness that works for any\ncase class, if you have a generic serialization scheme:Hope this helps,"},
Scala

Sometime I stumble into the semi-mysterious notation of in Scala blog posts, which give it a \"we used that type-lambda trick\" handwave.While I have some intutition about this (we gain an anonymous type parameter  without having to pollute the definition with it?), I found no clear source describing what the type lambda trick is, and what are its benefits. Is it just syntactic sugar, or does it open some new dimensions?Type lambdas are vital quite a bit of the time when you are working with higher-kinded types.Consider a simple example of defining a monad for the right projection of Either[A, B]. The monad typeclass looks like this:Now, Either is a type constructor of two arguments, but to implement Monad, you need to give it a type constructor of one argument. The solution to this is to use a type lambda:This is an example of currying in the type system - you have curried the type of Either, such that when you want to create an instance of EitherMonad, you have to specify one of the types; the other of course is supplied at the time you call point or bind.The type lambda trick exploits the fact that an empty block in a type position creates an anonymous structural type. We then use the # syntax to get a type member.In some cases, you may need more sophisticated type lambdas that are a pain to write out inline. Here's an example from my code from today:This class exists exclusively so that I can use a name like FG[F, G]#IterateeM to refer to the type of the IterateeT monad specialized to some transformer version of a second monad which is specialized to some third monad. When you start to stack, these kinds of constructs become very necessary. I never instantiate an FG, of course; it's just there as a hack to let me express what I want in the type system.The benefits are exactly the same as those conferred by anonymous functions.An example usage, with Scalaz 7. We want to use a  that can map a function over the second element in a .Scalaz provides some implicit conversions that can infer the type argument to , so we often avoid writing these altogether. The previous line can be rewritten as:If you use IntelliJ, you can enable Settings, Code Style, Scala, Folding, Type Lambdas. This then , and presents the more palatable:A future version of Scala might directly support such a syntax.To put things in context: This answer was originally posted in another thread. You are seeing it here because the two threads have been merged. The question statement in the said thread was as follows:The one underscore in the boxes after  implies that it is a type constructor takes one type and returns another type. Examples of type constructors with this kind: , .Give  an , a concrete type, and it gives you , another concrete type. Give  a  and it gives you . Etc.So, ,  can be considered to be type level functions of arity 1. Formally we say, they have a kind . The asterisk denotes a type.Now  is a type constructor with kind  i.e. you need to give it two types to get a new type. Since their signatures do not match, you cannot substitute  for . What you need to do is   on one of its arguments, which will give us a type constructor with kind , and we can substitue it for .Unfortunately Scala has no special syntax for partial application of type constructors, and so we have to resort to the monstrosity called type lambdas. (What you have in your example.) They are called that because they are analogous to lambda expressions that exist at value level.The following example might help:More value level and type level parallels.In the case you have presented, the type parameter  is local to function  and so you cannot simply define , because there is simply no place where you can put that synonym.To deal with such a case, I use the following trick that makes use of type members. (Hopefully the example is self-explanatory.) causes that whatever we put in  in  the  is always true I guess."},
Scala

So Scala is supposed to be as fast as Java. I'm revisiting some  problems in Scala that I originally tackled in Java. Specifically Problem 5: \"What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?\"Here's my Java solution, which takes 0.7 seconds to complete on my machine:Here's my \"direct translation\" into Scala, which takes 103 seconds (147 times longer!)Finally here's my attempt at functional programming, which takes 39 seconds (55 times longer)Using Scala 2.9.0.1 on Windows\u00a07 64-bit. How do I improve performance? Am I doing something wrong? Or is Java just a lot faster?The problem in this particular case is that you return from within the for-expression. That in turn gets translated into a throw of a NonLocalReturnException, which is caught at the enclosing method. The optimizer can eliminate the foreach but cannot yet eliminate the throw/catch. And throw/catch is expensive. But since such nested returns are rare in Scala programs, the optimizer did not yet address this case. There is work going on to improve the optimizer which hopefully will solve this issue soon.The problem is most likely the use of a  comprehension in the method .  Replacing  by an equivalent  loop should eliminate the performance difference with Java.As opposed to Java's  loops, Scala's  comprehensions are actually syntactic sugar for higher-order methods; in this case, you're calling the  method on a  object. Scala's  is very general, but sometimes leads to painful performance.You might want to try the  flag in Scala version 2.9. Observed performance may depend on the particular JVM in use, and the JIT optimizer having sufficient \"warm up\" time to identify and optimize hot-spots.Recent discussions on the mailing list indicate that the Scala team is working on improving  performance in simple cases:Here is the issue in the bug tracker:\n:As a follow-up, I tried the -optimize flag and it reduced running time from 103 to 76 seconds, but that's still 107x slower than Java or a while loop.Then I was looking at the \"functional\" version:and trying to figure out how to get rid of the \"forall\" in a concise manner. I failed miserably and came up with whereby my cunning 5-line solution has balooned to 12 lines. However, this version runs in , the same speed as the original Java version, and 56 times faster than the version above using \"forall\" (40.2 s)! (see EDIT below for why this is faster than Java)Obviously my next step was to translate the above back into Java, but Java can't handle it and throws a StackOverflowError with n around the 22000 mark.I then scratched my head for a bit and replaced the \"while\" with a bit more tail recursion, which saves a couple of lines, runs just as fast, but let's face it, is more confusing to read:So Scala's tail recursion wins the day, but I'm surprised that something as simple as a \"for\" loop (and the \"forall\" method) is essentially broken and has to be replaced by inelegant and verbose \"whiles\", or tail recursion. A lot of the reason I'm trying Scala is because of the concise syntax, but it's no good if my code is going to run 100 times slower!: (deleted): Former discrepancies between run times of 2.5s and 0.7s were entirely due to whether the 32-bit or 64-bit JVMs were being used. Scala from the command line uses whatever is set by JAVA_HOME, while Java uses 64-bit if available regardless. IDEs have their own settings. Some measurements here: The answer about for comprehension is right, but it's not the whole story. You should note note that the use of  in  is not free. The use of return inside the , forces the scala compiler to generate a non-local return (i.e. to return outside it's function).This is done through the use of an exception to exit the loop. The same happens if you build your own control abstractions, for example:This prints \"Hi\" only once.Note that the  in  exits  (which is what you would expect). Since the bracketed expression is a function literal, which you can see in the signature of  this forces the compiler to generate a non local return, that is, the  forces you to exit , not just the .In Java (i.e. the JVM) the only way to implement such behavior is to throw an exception.  Going back to :The  is a function literal that has a return, so each time the return is hit, the runtime has to throw and catch an exception, which causes quite a bit of GC overhead.Some ways to speed up the  method I discovered:The original: Pre-instantiating the range, so we don't create a new range every time: Converting to a List instead of a Range: I tried a few other collections but List was fastest (although still 7x slower than if we avoid the Range and higher-order function altogether).While I am new to Scala, I'd guess the compiler could easily implement a quick and significant performance gain by simply automatically replacing Range literals in methods (as above) with Range constants in the outermost scope. Or better, intern them like Strings literals in Java. :\nArrays were about the same as Range, but interestingly, pimping a new  method (shown below) resulted in 24% faster execution on 64-bit, and 8% faster on 32-bit. When I reduced the calculation size by reducing the number of factors from 20 to 15 the difference disappeared, so maybe it's a garbage collection effect. Whatever the cause, it's significant when operating under full load for extended periods.A similar pimp for List also resulted in about 10% better performance.I just wanted to comment for people who might lose faith in Scala over issues like this that these kinds of issues come up in the performance of just about all functional languages. If you are optimizing a fold in Haskell, you will often have to re-write it as a recursive tail-call-optimized loop, or else you'll have performance and memory issues to contend with.I know it's unfortunate that FPs aren't yet optimized to the point where we don't have to think about things like this, but this is not at all a problem particular to Scala.Problems specific to Scala have already been discussed, but the main problem is that using a brute-force algorithm is not very cool. Consider this (much faster than the original Java code):Try the one-liner given in the solution The time given is at least faster than yours, though far from the while loop.. :)"},
Scala

I want to merge them, and sum the values of same keys. So the result will be:Now I have 2 solutions:andBut I want to know if there are any better solutions. has the concept of a  which captures what you want to do here, and leads to arguably the shortest/cleanest solution:Specifically, the binary operator for  combines the keys of the maps, folding 's semigroup operator over any duplicate values.  The standard semigroup for  uses the addition operator, so you get the sum of values for each duplicate key.: A little more detail, as per user482745's request.Mathematically a  is just a set of values, together with an operator that takes two values from that set, and produces another value from that set.  So integers under addition are a semigroup, for example - the  operator combines two ints to make another int.You can also define a semigroup over the set of \"all maps with a given key type and value type\", so long as you can come up with some operation that combines two maps to produce a new one which is somehow the combination of the two inputs.If there are no keys that appear in both maps, this is trivial.  If the same key exists in both maps, then we need to combine the two values that the key maps to.  Hmm, haven't we just described an operator which combines two entities of the same type?  This is why in Scalaz a semigroup for  exists if and only if a Semigroup for  exists - 's semigroup is used to combine the values from two maps which are assigned to the same key.So because  is the value type here, the \"collision\" on the  key is resolved by integer addition of the two mapped values (as that's what Int's semigroup operator does), hence .  If the values had been Strings, a collision would have resulted in string concatenation of the two mapped values (again, because that's what the semigroup operator for String does).(And interestingly, because string concatenation is not commutative - that is,  - the resulting semigroup operation isn't either.  So  is different from  in the String case, but not in the Int case.)The shortest answer I know of that uses only the standard library isWell, now in scala library (at least in 2.10) there is something you wanted -  function. BUT it's presented only in HashMap not in Map. It's somewhat confusing. Also the signature is cumbersome - can't imagine why I'd need a key twice and when I'd need to produce a pair with another key. But nevertheless, it works and much cleaner than previous \"native\" solutions.Also in scaladoc mentioned thatQuick solution:This can be implemented as a  with just plain Scala. Here is a sample implementation. With this approach, we can merge not just 2, but a list of maps.The Map based implementation of the Monoid trait that merges two maps.Now, if you have a list of maps that needs to be merged (in this case, only 2), it can be done like below.I wrote a blog post about this , check it out :basically using scalaz semi group you can achieve this pretty easilywould look something like :This is what I came up with...You can also do that with .Andrzej Doyle's answer contains a great explanation of semigroups which allows you to use the  operator to join two maps and sum the values for matching keys.There are many ways something can be defined to be an instance of a typeclass, and unlike the OP you might not want to sum your keys specifically. Or, you might want to do operate on a union rather than an intersection. Scalaz also adds extra functions to  for this purpose:You can doI've got a small function to do the job, it's in my small library for some frequently used  functionality which isn't in standard lib.\nIt should work for all types of maps, mutable and immutable, not only HashMapsHere is the usageAnd here's the body"},
Scala

Following on from , can someone explain the following in Scala:I understand the distinction between  and  in the type declaration (it compiles if I use ). But then how does one actually write a class which is covariant in its type parameter without resorting to creating the thing ? How can I ensure that the following can only be created with an instance of ? - now got this down to the following:this is all good, but I now have two type parameters, where I only want one. I'll re-ask the question thus:: Duh! I used  and not . The following is what I wanted:Generically, a  type parameter is one which is allowed to vary down as the class is subtyped (alternatively, vary with subtyping, hence the \"co-\" prefix).  More concretely: is a subtype of  because  is a subtype of .  This means that you may provide an instance of  when a value of type  is expected.  This is really a very intuitive way for generics to work, but it turns out that it is unsound (breaks the type system) when used in the presence of mutable data.  This is why generics are invariant in Java.  Brief example of unsoundness using Java arrays (which are erroneously covariant):We just assigned a value of type  to an array of type .  For reasons which should be obvious, this is bad news.  Java's type system actually allows this at compile time.  The JVM will \"helpfully\" throw an  at runtime.  Scala's type system prevents this problem because the type parameter on the  class is invariant (declaration is  rather than ).Note that there is another type of variance known as .  This is very important as it explains why covariance can cause some issues.  Contravariance is literally the opposite of covariance: parameters vary  with subtyping.  It is a lot less common partially because it is so counter-intuitive, though it does have one very important application: functions.Notice the \"\" variance annotation on the  type parameter.  This declaration as a whole means that  is contravariant in  and covariant in .  Thus, we can derive the following axioms:Notice that  must be a subtype (or the same type) of , whereas it is the opposite for  and .  In English, this can be read as the following:The reason for this rule is left as an exercise to the reader (hint: think about different cases as functions are subtyped, like my array example from above).With your new-found knowledge of co- and contravariance, you should be able to see why the following example will not compile:The problem is that  is covariant, while the  function expects its type parameter to be .  Thus,  is varying the wrong direction.  Interestingly enough, we could solve this problem by making  contravariant in , but then the return type  would be invalid as the  function expects its return type to be .Our only two options here are to a) make  invariant, losing the nice, intuitive sub-typing properties of covariance, or b) add a local type parameter to the  method which defines  as a lower bound:This is now valid.  You can imagine that  is varying downward, but  is able to vary upward with respect to  since  is its lower-bound.  With this method declaration, we can have  be covariant and everything works out.Notice that this trick only works if we return an instance of  which is specialized on the less-specific type .  If you try to make  mutable, things break down since you end up trying to assign values of type  to a variable of type , which is disallowed by the compiler.  Whenever you have mutability, you need to have a mutator of some sort, which requires a method parameter of a certain type, which (together with the accessor) implies invariance.  Covariance works with immutable data since the only possible operation is an accessor, which may be given a covariant return type.@Daniel has explained it very well. But to explain it in short, if it was allowed: will then throw an error at runtime as it was unsuccessful in converting an  to  (duh!).In general mutability doesn't go well with co-variance and contra-variance. That is the reason why all Java collections are invariant. See , page 57+ for a full discussion of this.If I'm understanding your comment correctly, you need to reread the passage starting at the bottom of page 56 (basically, what I think you are asking for isn't type-safe without run time checks, which scala doesn't do, so you're out of luck).  Translating their example to use your construct:If you feel I'm not understanding your question (a distinct possibility), try adding more explanation / context to the problem description and I'll try again.In response to your edit: Immutable slots are a whole different situation...* smile * I hope the example above helped.You need to apply a lower bound on the parameter. I'm having a hard time remembering the syntax, but I think it would look something like this:The Scala-by-example is a bit hard to understand, a few concrete examples would have helped."},
Scala

I have learned the basic difference between  and Is there any other difference ?Any specific reason to have two methods with similar functionality?Few things to mention here, before giving the actual answer:Here is the signature of  (could also have been  for the point I'm going to make):And here is the signature of  (again the direction doesn't matter here)These two look very similar and thus caused the confusion.  is a special case of  (which by the way means that you  can express the same thing by using either of them).When you call  say on a  it will literally reduce the whole list of integers into a single value, which is going to be of type  (or a supertype of , hence ).When you call  say on a  it will fold the whole list (imagine rolling a piece of paper) into a single value, but this value doesn't have to be even related to  (hence ).Here is an example:This method takes a  and returns a  or . It calculates the sum and returns a tuple with a list of integers and it's sum. By the way the list is returned backwards, because we used  instead of . is just a convenience method. It is equivalent to is more generic, you can use it to produce something completely different than what you originally put in. Whereas  can only produce an end result of the same type or super type of the collection type. For example:The  will apply the closure with the last folded result (first time using initial value) and the next value.  on the other hand will first combine two values from the list and apply those to the closure. Next it will combine the rest of the values with the cumulative result. See:If the list is empty  can present the initial value as a legal result.  on the other hand does not have a legal value if it can't find at least one value in the list.The basic reason they are both in Scala standard library is probably because they are both in Haskell standard library (called  and ). If  wasn't, it would quite often be defined as a convenience method in different projects.For reference,  will error if applied to an empty container with the following error.Reworking the code to use is one potential option.  Another is to use the  variant which returns an Option wrapped result.From  (Martin Odersky):[as opposed to , which throws an exception when called on an empty list.]The course (see lecture 5.5) provides abstract definitions of these functions, which illustrates their differences, although they are very similar in their use of pattern matching and recursion.Note that  returns a value of type , which is not necessarily the same type as , but reduceLeft returns a value of the same type as the list).To really understand what are you doing with fold/reduce,\ncheck this: \nvery good explanation. once you get the concept of fold,\nreduce will come together with the answer above:\nlist.tail.foldLeft(list.head)(_)"},
Scala

I am keen to look into Scala, and have one basic question I cant seem to find an answer to:\nin general, is there a difference in performance and usage of memory between Scala and Java?Scala makes it very easy to use enormous amounts of memory without realizing it.  This is usually very powerful, but occasionally can be annoying.  For example, suppose you have an array of strings (called ), and a map from those strings to files (called ).  Suppose you want to get all files that are in the map and come from strings of length greater than two.  In Java, you mightWhew!  Hard work.  In Scala, the most compact way to do the same thing is:Easy!  But, unless you're fairly familiar with how the collections work, what you might not realize is that this way of doing this created an extra intermediate array (with ), and an extra object for  (with , which returns an option).  It also creates two function objects (one for the filter and one for the flatMap), though that is rarely a major issue since function objects are small.So basically, the memory usage is, at a primitive level, the same.  But Scala's libraries have many powerful methods that let you create enormous numbers of (usually short-lived) objects very easily.  The garbage collector is usually pretty good with that kind of garbage, but if you go in completely oblivious to what memory is being used, you'll probably run into trouble sooner in Scala than Java.Note that the Computer Languages Benchmark Game Scala code is written in a rather Java-like style in order to get Java-like performance, and thus has Java-like memory usage.  You can do this in Scala: if you write your code to look like high-performance Java code, it will be high-performance Scala code.  (You  be able to write it in a more idiomatic Scala style and still get good performance, but it depends on the specifics.)I should add that per amount of time spent programming, my Scala code is usually  than my Java code since in Scala I can get the tedious not-performance-critical parts done with less effort, and spend more of my attention optimizing the algorithms and code for the performance-critical parts.I'm a new user, so I'm not able to add a comment to Rex Kerr's answer above (allowing new users to \"answer\" but not \"comment\" is a very odd rule btw).I signed up simply to respond to the \"phew, Java is so verbose and such hard work\" insinuation of Rex's popular answer above.  While you can of course write more concise Scala code, the Java example given is clearly bloated.  Most Java developers would code something like this:And of course, if we are going to pretend that Eclipse doesn't do most of the actual typing for you and that every character saved really makes you a better programmer, then you could code this:Now not only did I save the time it took me to type full variable names and curly braces (freeing me to spend 5 more seconds to think deep algorithmic thoughts), but I can also enter my code in obfuscation contests and potentially earn extra cash for the holidays.Write your Scala like Java, and you can expect almost identical bytecode to be emitted - with almost identical metrics.Write it more \"idiomatically\", with immutable objects and higher order functions, and it'll be a bit slower and a bit larger.  The one exception to this rule-of-thumb is when using generic objects in which the type params use the  annotation, this'll create even larger bytecode that can outpace Java's performance by avoiding boxing/unboxing.Also worth mentioning is the fact that more memory / less speed is an inevitable trade-off when writing code that can be run in parallel.  Idiomatic Scala code is far more declarative in nature than typical Java code, and is often a mere 4 characters () away from being fully parallel.So ifWould you then say that the Scala code is now comparatively 25% slower, or 3x faster?The correct answer depends on exactly how you define \"performance\" :)Computer Language Benchmarks Game: java/scala 1.71/2.25 java/scala 66.55/80.81So, this benchmarks say that java is 24% faster and scala uses 21% more memory.All-in-all it's no big deal and should not matter in real world apps, where most of the time is consumed by database and network. If Scala makes you and your team (and people taking project over when you leave) more productive, then you should go for it.Others have answered this question with respect to tight loops although there seems to be an obvious performance difference between Rex Kerr's examples that I have commented on.This answer is really targeted at people who might investigate a need for tight-loop optimisation as design flaw.I am relatively new to Scala (about a year or so) but the feel of it, thus far, is that it allows you to  many aspects of design, implementation and execution relatively easily (with enough background reading and experimentation :) (sorry, no links)These features, to me, are the ones that help us to tread the path to fast, tight applications.Rex Kerr's examples differ in what aspects of execution are deferred.  In the Java example, allocation of memory is deferred until it's size is calculated where the Scala example defers the mapping lookup. To me, they seem like completely different algorithms.Here's what I think is more of an apples to apples equivalent for his Java example:No intermediary collections, no  instances etc.\nThis also preserves the collection type so 's type is  - 's  implementation will probably be doing something along the lines of what Mr Kerr's Java code does.The deferred design features I listed above would also allow Scala's collection API developers to implement that fast Array-specific collect implementation in future releases without breaking the API. This is what I'm referring to with treading the path to speed.Also:The  method that I've used here instead of  fixes the intermediate collection problem but there is still the Option instance issue.One example of simple execution speed in Scala is with logging.In Java we might write something like:In Scala, this is just:because the message parameter to debug in Scala has the type \"\" which I think of as a parameter-less function that executes when it is evaluated, but which the documentation calls pass-by-name.EDIT {\nFunctions in Scala are objects so there is an extra object here. For my work, the weight of a trivial object is worth removing the possibility of a log message getting needlessly evaluated.\n}This doesn't make the code faster but it does make it more likely to be faster and we're less likely to have the experience of going through and cleaning up other people's code en masse.To me, this is a consistent theme within Scala.Hard code fails to capture why Scala is faster though it does hint a bit.I feel that it's a combination of code re-use and the ceiling of code quality in Scala.In Java, awesome code is often forced to become an incomprehensible mess and so isn't really viable within production quality APIs as most programmers wouldn't be able to use it.I have high hopes that Scala could allow the einsteins among us to implement far more competent APIs, potentially expressed through DSLs. The core APIs in Scala are already far along this path.\u00b4s presentation on the subject -  which does some Java/Scala comparisions. Tools: Great blogpost: Java and Scala both compile down to JVM bytecode, so the difference isn't that big. The best comparison you can get is probably on the , which essentially says that Java and Scala both have the same memory usage. Scala is only  slower than Java on some of the benchmarks listed, but that could simply be because the implementation of the programs are different.Really though, they're both so close it's not worth worrying about. The productivity increase you get by using a more expressive language like Scala is worth so much more than minimal (if any) performance hit.The Java example is really not an idiom for typical application programs.\nSuch optimized code might be found in a system library method. But then it would use an array of the right type, i.e. File[] and would not throw an IndexOutOfBoundsException. (Different filter conditions for counting and adding). \nMy version would be (always (!) with curly braces because I don't like to spend an hour searching a bug which was introduced by saving the 2 seconds to hit a single key in Eclipse):But I could bring you a lot of other ugly Java code examples from my current project. I tried to avoid the common copy&modify style of coding by factoring out common structures and behaviour. In my abstract DAO base class I have an abstract inner class for the common caching mechanism. For every concrete model object type there is a subclass of the abstract DAO base class, in which the inner class is subclassed to provide an implementation for the method which creates the business object when it is loaded from the database. (We can not use an ORM tool because we access another system via a proprietary API.)This subclassing and instantiation code is not at all clear in Java and would be very readable in Scala."},
Scala

The Akka Streams library already comes with quite a . However, the main problem for me is that it provides too much material - I feel quite overwhelmed by the number of concepts that I have to learn. Lots of examples shown there feel very heavyweight and can't easily be translated to real world use cases and are therefore quite esoteric. I think it gives way too much details without explaining how to build all the building blocks together and how exactly it helps to solve specific problems.There are sources, sinks, flows, graph stages, partial graphs, materialization, a graph DSL and a lot more and I just don't know where to start. The  is meant to be a starting place but I don't understand it. It just throws in the concepts mentioned above without explaining them. Furthermore the code examples can't be executed - there are missing parts which makes it more or less impossible for me to follow the text.Can anyone explain the concepts sources, sinks, flows, graph stages, partial graphs, materialization and maybe some other things that I missed in simple words and with easy examples that don't explain every single detail (and which are probably not needed anyway at the beginning)?This answer is based on  version . The API can be slightly different in other versions. The dependency can be consumed by :Alright, lets get started. The API of Akka Streams consists of three main types. In contrast to , these types are a lot more powerful and therefore more complex. It is assumed that for all the code examples the following definitions already exist:The  statements are needed for the type declarations.  represents the actor system of Akka and  represents the evaluation context of the stream. In our case we use a , which means that the streams are evaluated on top of actors. Both values are marked as , which gives the Scala compiler the possibility to inject these two dependencies automatically whenever they are needed. We also import , which is a execution context for .Akka Streams have these key properties:In the following a deeper introduction in how to use the three main types shall be given.A  is a data creator, it serves as an input source to the stream. Each  has a single output channel and no input channel. All the data flows through the output channel to whatever is connected to the .A  can be created in multiple ways:In the above cases we fed the  with finite data, which means they will terminate eventually. One should not forget, that Reactive Streams are lazy and asynchronous by default. This means one explicitly has to request the evaluation of the stream. In Akka Streams this can be done through the  methods. The  would be no different to the well known  function - through the  addition it makes explicit that we ask for an evaluation of the stream. Since finite data is boring, we continue with infinite one:With the  method we can create an artificial stop point that prevents us from evaluating indefinitely. Since actor support is built-in, we can also easily feed the stream with messages that are sent to an actor:We can see that the  are executed asynchronously on different threads, which explains the result. In the above example a buffer for the incoming elements is not necessary and therefore with  we can configure that the stream should fail on a buffer overflow. Especially through this actor interface, we can feed the stream through any data source. It doesn't matter if the data is created by the same thread, by a different one, by another process or if they come from a remote system over the Internet.A  is basically the opposite of a . It is the endpoint of a stream and therefore consumes data. A  has a single input channel and no output channel.  are especially needed when we want to specify the behavior of the data collector in a reusable way and without evaluating the stream. The already known  methods do not allow us these properties, therefore it is preferred to use  instead.A short example of a  in action:Connecting a  to a  can be done with the  method. It returns a so called , which is as we will later see a special form of a  - a stream that can be executed by just calling its  method.It is of course possible to forward all values that arrive at a sink to an actor:Data sources and sinks are great if you need a connection between Akka streams and an existing system but one can not really do anything with them. Flows are the last missing piece in the Akka Streams base abstraction. They act as a connector between different streams and can be used to transform its elements.If a  is connected to a  a new  is the result. Likewise, a  connected to a  creates a new . And a  connected with both a  and a  results in a . Therefore, they sit between the input and the output channel but by themselves do not correspond to one of the flavors as long as they are not connected to either a  or a .In order to get a better understanding of , we will have a look at some examples:Via the  method we can connect a  with a . We need to specify the input type because the compiler can't infer it for us. As we can already see in this simple example, the flows  and  are completely independent from any data producers and consumers. They only transform the data and forward it to the output channel. This means that we can reuse a flow among multiple streams: and  represent completely new streams - they do not share any data through their building blocks.Before we move on we should first revisit some of the key aspects of Reactive Streams. An unbounded number of elements can arrive at any point and can put a stream in different states. Beside from a runnable stream, which is the usual state, a stream may get stopped either through an error or through a signal that denotes that no further data will arrive. A stream can be modeled in a graphical way by marking events on a timeline as it is the case here:We have already seen runnable flows in the examples of the previous section. We get a  whenever a stream can actually be materialized, which means that a  is connected to a . So far we always materialized to the value , which can be seen in the types:For  and  the second type parameter and for  the third type parameter denote the materialized value. Throughout this answer, the full meaning of materialization shall not be explained. However, further details about materialization can be found at the . For now the only thing we need to know is that the materialized value is what we get when we run a stream. Since we were only interested in side effects so far, we got  as the materialized value. The exception to this was a materialization of a sink, which resulted in a . It gave us back a , since this value can denote when the stream that is connected to the sink has been ended.  So far, the previous code examples were nice to explain the concept but they were also boring because we only dealt with finite streams or with very simple infinite ones. To make it more interesting, in the following a full asynchronous and unbounded stream shall be explained.As an example, we want to have a stream that captures click events. To make it more challenging, let's say we also want to group click events that happen in a short time after each other. This way we could easily discover double, triple or tenfold clicks. Furthermore, we want to filter out all single clicks. Take a deep breath and imagine how you would solve that problem in an imperative manner. I bet no one would be able to implement a solution that works correctly on the first try. In a reactive fashion this problem is trivial to solve. In fact, the solution is so simple and straightforward to implement that we can even express it in a diagram that directly describes the behavior of the code:The gray boxes are functions that describe how one stream is transformed into another. With the  function we accumulate clicks within 250 milliseconds, the  and  functions should be self-explanatory. The color orbs represent an event and the arrows depict how they flow through our functions. Later in the processing steps, we get less and less elements that flow through our stream, since we group them together and filter them out. The code for this image would look something like this:The whole logic can be represented in only four lines of code! In Scala, we could write it even shorter:The definition of  is a little bit more complex but this is only the case because the example program runs on the JVM, where capturing of click events is not easily possible. Another complication is that Akka by default doesn't provide the  function. Instead we had to write it by ourselves. Since this function is (as it is the case for the  or  functions) reusable across different use cases I don't count these lines to the number of lines we needed to implement the logic. In imperative languages however, it is normal that logic can't be reused that easily and that the different logical steps happen all at one place instead of being applied sequentially, which means that we probably would have misshaped our code with the throttling logic. The full code example is available as a  and shall not be discussed here any further.What should be discussed instead is another example. While the click stream is a nice example to let Akka Streams handle a real world example, it lacks the power to show parallel execution in action. The next example shall represent a small web server that can handle multiple requests in parallel. The web sever shall be able to accept incoming connections and receive byte sequences from them that represent printable ASCII signs. These byte sequences or strings should be split at all newline-characters into smaller parts. After that, the server shall respond to the client with each of the split lines. Alternatively, it could do something else with the lines and give a special answer token, but we want to keep it simple in this example and therefore don't introduce any fancy features. Remember, the server needs to be able to handle multiple requests at the same time, which basically means that no request is allowed to block any other request from further execution. Solving all of these requirements can be hard in an imperative way - with Akka Streams however, we shouldn't need more than a few lines to solve any of these. First, let's have an overview over the server itself:Basically, there are only three main building blocks. The first one needs to accept incoming connections. The second one needs to handle incoming requests and the third one needs to send a response. Implementing all of these three building blocks is only a little bit more complicated than implementing the click stream:The function  takes (besides from the address and the port of the server) also an actor system and a materializer as implicit parameters. The control flow of the server is represented by , which takes a source of incoming connections and forwards them to a sink of incoming connections. Inside of , which is our sink, we handle every connection by the flow , which will be described later.  returns a , which completes when the server has been started or the start failed, which could be the case when the port is already taken by another process. The code however, doesn't completely reflect the graphic as we can't see a building block that handles responses. The reason for this is that the connection already provides this logic by itself. It is a bidirectional flow and not just a unidirectional one as the flows we have seen in the previous examples. As it was the case for materialization, such complex flows shall not be explained here. The  has plenty of material to cover more complex flow graphs. For now it is enough to know that   represents a connection that knows how to receive requests and how to send responses. The part that is still missing is the  building block. It can look like this:Once again, we are able to split the logic in several simple building blocks that all together form the flow of our program. First we want to split our sequence of bytes in lines, which we have to do whenever we find a newline character. After that, the bytes of each line need to be converted to a string because working with raw bytes is cumbersome. Overall we could receive a binary stream of a complicated protocol, which would make working with the incoming raw data extremely challenging. Once we have a readable string, we can create an answer. For simplicity reasons the answer can be anything in our case. In the end, we have to convert back our answer to a sequence of bytes that can be sent over the wire. The code for the entire logic may look like this:We already know that  is a flow that takes a  and has to produce a . With  we can split a  in smaller parts - in our case it needs to happen whenever a newline character occurs.  is the flow that takes all of the split byte sequences and converts them to a string. This is of course a dangerous conversion, since only printable ASCII characters should be converted to a string but for our needs it is good enough.  is the last component and is responsible for creating an answer and converting the answer back to a sequence of bytes. As opposed to the graphic we didn't split this last component in two, since the logic is trivial. At the end, we connect all of the flows through the  function. At this point one may ask whether we took care of the multi-user property that was mentioned at the beginning. And indeed we did even though it may not be obvious immediately. By looking at this graphic it should get more clear:The  component is nothing but a flow that contains smaller flows. This component takes an input, which is a request, and produces an output, which is the response. Since flows can be constructed multiple times and they all work independently to each other, we achieve through this nesting our multi-user property. Every request is handled within its own request and therefore a short running request can overrun a previously started long running request. In case you wondered, the definition of  that was shown previously can of course be written a lot shorter by inlining most of its inner definitions:A test of the web server may look like this:In order for the above code example to function correctly, we first need to start the server, which is depicted by the  script:The full code example of this simple TCP server can be found . We are not only able to write a server with Akka Streams but also the client. It may look like this:The full code TCP client can be found . The code looks quite similar but in contrast to the server we don't have to manage the incoming connections anymore. In the previous sections we have seen how we can construct simple programs out of flows. However, in reality it is often not enough to just rely on already built-in functions to construct more complex streams. If we want to be able to use Akka Streams for arbitrary programs we need to know how to build our own custom control structures and combinable flows that allow us to tackle the complexity of our applications. The good news is that Akka Streams was designed to scale with the needs of the users and in order to give you a short introduction into the more complex parts of Akka Streams, we add some more features to our client/server example.One thing we can't do yet is closing a connection. At this point it starts to get a little bit more complicated because the stream API we have seen so far doesn't allow us to stop a stream at an arbitrary point. However, there is the  abstraction, which can be used to create arbitrary graph processing stages with any number of input or output ports. Let's first have a look at the server side, where we introduce a new component, called :This API looks a lot more cumbersome than the flow API. No wonder, we have to do a lot of imperative steps here. In exchange, we have more control over the behavior of our streams. In the above example, we only specify one input and one output port and make them available to the system by overriding the  value. Furthermore we defined a so called  and a , which are in this order responsible for receiving and emitting elements. If you looked closely to the full click stream example you should recognize these components already. In the  we grab an element and if it is a string with a single character , we want to close the stream. In order to give the client a chance to find out that the stream will get closed soon, we emit the string  and then we immediately close the stage afterwards. The  component can be combined with a stream via the  method, which was introduced in the section about flows.Beside from being able to close connections, it would also be nice if we could show a welcome message to a newly created connection. In order to do this we once again have to go a little bit further:The function   now takes the incoming connection as a parameter. Inside of its body we use a DSL that allows us to describe complex stream behavior. With  we create a stream that can only emit one element - the welcome message.  is what was described as  in the previous section. The only notable difference is that we added  to it. Now actually comes the interesting part of the DSL.  The  function makes a builder  available, which is used to express the stream as a graph. With the  function it is possible to connect input and output ports with each other. The  component that is used in the example can concatenate elements and is here used to prepend the welcome message in front of the other elements that come out of . In the last line, we only make the input port of the server logic and the output port of the concatenated stream available because all the other ports shall remain an implementation detail of the  component. For an in-depth introduction to the graph DSL of Akka Streams, visit the corresponding section in the . The full code example of the complex TCP server and of a client that can communicate with it can be found . Whenever you open a new connection from the client you should see a welcoming message and by typing  on the client you should see a message that tells you that the connection has been canceled.There are still some topics which weren't covered by this answer. Especially materialization may scare one reader or another but I'm sure with the material that is covered here everyone should be able to go the next steps by themselves. As already said, the  is a good place to continue learning about Akka Streams."},
Scala

When should I use , , , ,  or ?I want an intuition/overview of their differences - possibly with some simple examples.In general, all 6 fold functions apply a binary operator to each element of a collection. The result of each step is passed on to the next step (as input to one of the binary operator's two arguments). This way we can  a result. and  cumulate a single result. and  cumulate a single result using a start value. and  cumulate a collection of intermediate cumulative results using a start value.With a collection of elements  and a binary operator  we can explore what the different fold functions do when going forwards from the LEFT element of the collection (from A to C):\nIf we start with the RIGHT element and go backwards (from C to A) we'll notice that now the  argument to our binary operator accumulates the result (the operator is the same, we just switched the argument names to make their roles clear): .If instead we were to  some result by subtraction starting from the LEFT element of a collection, we would cumulate the result through the first argument  of our binary operator :\nBut look out for the xRight variations now! Remember that the (de-)cumulated value in the xRight variations is passed to the  parameter  of our binary operator :The last List(-2, 3, -1, 4, 0) is maybe not what you would intuitively expect! As you see, you can check what your foldX is doing by simply running a scanX instead and debug the cumulated result at each step.Normally REDUCE,FOLD,SCAN method works by accumulating data on LEFT and keep on changing the RIGHT variable. Main difference between them is REDUCE,FOLD is:-Fold will always start with a  value i.e. user defined starting value. \nReduce will throw a exception if collection is empty where as fold gives back the seed value. Scan is used for some processing order of items from left or right hand side, then we can make use of previous result in subsequent calculation. That means we can scan items. A part of output for below mentioned code would be :- using  operation over a list of numbers (using  value ) using , operations over a list of Strings Code :"},
Scala

One handy feature of Scala is , where the evaluation of a  is delayed until it's necessary (at first access).Of course, a  must have some overhead - somewhere Scala must keep track of whether the value has already been evaluated and the evaluation must be synchronized, because multiple threads might try to access the value for the first time at the same time.What exactly is the cost of a  - is there a hidden boolean flag associated with a  to keep track if it has been evaluated or not, what exactly is synchronized and are there any more costs?In addition, suppose I do this:Is this the same as having two separate s  and  or do I get the overhead only once, for the pair ?This is taken from the  and gives implementation details of  in terms of Java code (rather than bytecode):is compiled to something equivalent to the following Java code:It looks like the compiler arranges for a class-level bitmap int field to flag multiple lazy fields as initialized (or not) and initializes the target field in a synchronized block if the relevant xor of the bitmap indicates it is necessary.Using:produces sample bytecode:Values initialed in tuples like  have nested caching via the same mechanism.  The tuple result is lazily evaluated and cached, and an access of either x or y will trigger the tuple evaluation.  Extraction of the individual value from the tuple is done independently and lazily (and cached).  So the above double-instantiation code generates an , , and an  field of type .With Scala 2.10, a lazy value like:is compiled to byte code that resembles the following Java code:Note that the bitmap is represented by a . If you add another field, the compiler will increase the size of the field to being able to represent at least 2 values, i.e. as a . This just goes on for huge classes.But you might wonder why this works? The thread-local caches must be cleared when entering a synchronized block such that the non-volatile  value is flushed into memory. This blog article gives . proposes a new implementation of lazy val, which is more correct but ~25% slower than the \"current\" version.The  looks like:As of June 2013 this SIP hasn't been approved. I expect that it's likely to be approved and included in a future version of Scala based on the mailing list discussion.  Consequently, I think you'd be wise to heed :I've written a post with regard to this issue In nutshell, the penalty is so small that in practice you can ignore it.given the bycode generated by scala for lazy, it can suffer thread safety problem as mentioned in double check locking  "},
Scala

I just got started with Scala/LiftWeb/Sbt developing, and I'd like to import a Sbt project in IntelliJ Idea.\nActually, I managed to import my project in two different ways:1) with Maven. I created a Maven project, and of top of that I created a Sbt project, which I then imported in IntelliJ. I could then easily start, stop the jetty server, and do other stuff.\nBut that's not what I want. I want to do the same stuff, just Maven-free.\nThat lead me to 2) with Eclipse. So, I created a new Sbt project (with a little script I wrote, configuring the Sbt project to be a WebProject). I used then the sbt-eclipsify plugin to 'convert' the project for Eclipse, which I then imported in IntelliJ (existing source -> eclipse).\nBut the problems started here: I cannot get the IntelliJ Sbt plugin to work. Can anyone help me with this?There are three basic ways how to create a project - modern versions of IntelliJ can import sbt project out of the box, otherwise you can either use sbt plugin to generate IntelliJ project, or use IntelliJ Scala plugin to create sbt project. Basic features work out of the box using both solutions, some complex builds can have problems, so try other tools to see if it works there.IntelliJ IDEA has become so much better these days. The current version (14.0.2) supports sbt projects out of the box with the Scala plugin. Just install the plugin and you should be able to open up Scala/sbt projects without any troubles.With the plugin, just point at a sbt project and IDEA is going to offer you a wizard to open that kind of project.IntelliJ plugin can be found here \n or can be installed directoly from within the IDE using Settings -> Plugins dialog. Afterwards one can just do File -> New Project -> Scala -> SBT based. IntelliJ will generate basic build.sbt, download necessary dependencies and open project. Sbt plugin that generate an idea project based on the sbt files can be found here: Simply add  to your ; no additional resolvers are needed.Create and add the following lines to  OR Use  in sbt to create IDEA project files.By default, classifiers (i.e. sources and javadocs) of sbt and library dependencies are loaded if found and references added to IDEA project files. If you don't want to download/reference them, use command .\n(according to the plugin author, 0.10.0  work!)Create and add the following lines to ~/.sbt/plugins/build.sbt:Use  sbt task to create IDEA project files.By default, classifiers (i.e. sources and javadocs) of sbt and library dependencies are loaded if found and references added to IDEA project files. If you don't want to download/reference them, use command .To use it, simply run this from your sbt shell, it will use the plugin as an external program:You can also add trait in your project definition, as you want:For now I do this by hand. It is quite simple.That's it from memory. It would be better if it were automated, but it's no big deal as it is now.One note of caution: The above approach doesn't work well with new-school sbt, i.e. versions 0.10 and newer, because it doesn't copy dependencies into lib_managed by default.  You can add to your build.sbt to make it copy the dependencies into lib_managed. and IntelliJ IDEA has become so much better these days. It's 2015 after all, isn't it?Having said that,  supports sbt projects out of the box with . Just install the plugin and you should be able to open up Scala/sbt projects without much troubles.I'm using the Early Access version of the plugin which is 1.2.67.6.EAP as of the time of the writing.With the plugin just point at a sbt project and IDEA is going to offer you a wizard to open that kind of project.For sbt  the system-wide plugin configuration file -  or  - should have the following lines:Run  to generate IDEA project files.Read  for more up-to-date information. You may also find my blog entry  useful.See .Clone and build Ismael's sbt-idea:Create an sbt plugin lib directory if you don't have one alreadyCopy the jar built in step one into hereRestart or reload sbt, then you can run  (or  if you want sources and javadoc in intelliJ too)Source: .You can open an SBT-based project in IDEA nowadays. It will create the necessary project and modules, and keep your dependencies up-to-date whenever you make changes to the build scripts.I just went through all this pain.  I spend days trying to get an acceptable environment up and have come to the conclusion that ENSIME, SBT and JRebel are going to be my development environment for some time.  Yes, it is going back to Emacs, but ENSIME turns it into a bit or an idea with refactoring, debugging support, navigation, etc.  It's not nowhere near as good as Eclipse (Java), but unless the scala plugins work better it's the best we have.Until the Scala development environments get up to snuff (Eclipse or IntelliJ) I'm not going to bother.  They're just way too buggy.See the discussion on the lift site.Within that thread, there is a link to a HOWTO for IntelliJ, but although it kinda works, there are many issues that render it a little less that useful.The answers are old for 2014.\nIn , the plugin Scala is ver 0.41.2 ( SBT is included).My  (terminal :   )Go to the project's root folder and enter in the terminalYou will see two new hidden folders   and .Then in IntelliJ, File > Open > select the project. \nIt should open the project without any problem.Before you start creating your SBT project, make sure that the Scala plugin is downloaded and enabled in IntelliJ IDEA.below link explains everything you need to know. "},
Scala

What is the difference between:and Both can be called like .Method  evaluates on call and creates new function every time (new instance of ).With  you can get new function on every call: evaluates when defined,  - when called:Note that there is a third option: .It evaluates when called the first time:But returns the same result (in this case same instance of ) every time: evaluates when defined. evaluates on every call, so performance could be worse then with  for multiple calls. You'll get the same performance with a single call. And with no calls you'll get no overhead from , so you can define it even if you will not use it in some branches.With a  you'll get a lazy evaluation: you can define it even if you will not use it in some branches, and it evaluates once or never, but you'll get a little overhead from double check locking on every access to your .As @SargeBorsch noted you could define method, and this is the fastest option:But if you need a function (not method) for function composition or for higher order functions (like ) compiler will generate a function from your method every time you are using it as function, so performance could be slightly worse than with .Consider this: Do you see the difference? In short:: For every call to , it calls the body of the  method again. But with  i.e. , the function is initialized only once while declaration (and hence it prints  at line 4 and never again) and the same output is used each time it accessed. For example try doing this:When  is initialized, the value returned by  is set as the final value of . Next time  is used again, it will always return the same value.You can also lazily initialize . i.e. first time it is used it is initialized and not while declaration. For example:See this:Surprisingly, this will print 4 and not 9! val (even var) is evaluated immediately and assigned.\nNow change val to def.. it will print 9! Def is a function call.. it will evaluate each time it is called."},
Scala

What is a good way to do logging in a Scala application? Something that is consistent with the language philosophy, does not clutter the code, and is low-maintenance and unobtrusive. Here's a basic requirement list:I know I can use the existing Java logging solutions, but they fail on at least two of the above, namely clutter and configuration.Thanks for your replies.Most of Scala's logging libraries have been some wrappers around a Java logging framework (slf4j, log4j etc), but as of March 2015, the surviving log libraries are all slf4j. These log libraries provide some sort of  object to which you can call , , etc. I'm not a big fan of slf4j, but it now seems to be the predominant logging framework. Here's the description of :The ability to change underlying log library at deployment time brings in unique characteristic to the entire slf4j family of loggers, which you need to be aware of:In a large project, it could actually be convenient to be able to control the logging behavior of transitive dependencies if everyone used slf4j. is written by Heiko Seeberger as a successor to his . It uses macro to expand calls into if expression to avoid potentially expensive log call.With Scala 2.10+ Consider ScalaLogging by Typesafe.  Uses macros to deliver a very clean APIQuoting from their wiki:After the macro has been applied, the code will have been transformed into the above described idiom.In addition ScalaLogging offers the trait  which conveniently provides a  instance initialized with the name of the class mixed into:Using slf4j and a wrapper is nice but the use of it's built in interpolation breaks down when you have more than two values to interpolate, since then you need to create an Array of values to interpolate.A more Scala like solution is to use a thunk or cluster to delay the concatenation of the error message.  A good example of this is Lift's logger\nWhich looks like this:Note that msg is a call-by-name and won't be evaluated unless isTraceEnabled is true so there's no cost in generating a nice message string.  This works around the slf4j's interpolation mechanism which requires parsing the error message.  With this model, you can interpolate any number of values into the error message.If you have a separate trait that mixes this Log4JLogger into your class, then you can doinstead ofI've actually followed the recommendation of Eugene and tried it and found out that it has a clumsy configuration and is subjected to bugs, which don't get fixed (such as ). It doesn't look to be well maintained and it . Here's what you need to be running it with Maven:This is how I got  working for me:Put this in your :Then, after doing an , this prints out a friendly log message:If you are using Play, you can of course simply  for writing log messages such as: .See the  for more info.I pulled a bit of work form the  trait of , and created a trait that also integrated a  library.Then stuff kind of looks like this:We like the approach so far.Implementation:I use SLF4J + Logback classic and apply it like this:Then you can use it whichever fits your style better:but this approach of course uses a logger instance per class instance. You should have a look at the scalax library :\n\nIn this library, there is a Logging trait, using sl4j as backend.\nBy using this trait, you can log quite easily (just use the logger field \nin the class inheriting the trait).,  and a  implementation.Haven't tried it yet, but Configgy looks promising for both configuration and logging: After using slf4s and logula for a while, I wrote , a simple logging trait wrapping slf4j. It offers an API similar to that of Python's logging library, which makes the common cases (basic string, simple formatting) trivial and avoids formatting boilerplate.I find very convenient using some kind of java logger, sl4j for example, with simple scala wrapper, which brings me such syntaxIn my opinion very usefull mixin of java proven logging frameworks and scala's fancy syntax.Quick and easy forms.Scala 2.10 and older:And build.sbt:Scala 2.11+ and newer:And build.sbt:"},
Scala

For reading, there is the useful abstraction . How can I write lines to a text file?Edit (September 2011): since  asks about Scala2.9, and since  comments that  is pretty much non-existent since mid-2009... has changed place: see its , from  (also ):Original answer (January 2011), with the old place for scala-io:If you don't want to wait for Scala2.9, you can use the  library.\n(as mentioned in \"\")See This is one of the features missing from standard Scala that I have found so useful that I add it to my personal library.  (You probably should have a personal library, too.)  The code goes like so:and it's used like this:Similar to the answer by Rex Kerr, but more generic. First I use a helper function:Then I use this as:and  etc.A simple answer:Giving another answer, because my edits of other answers where rejected.  This is the  (similar to Garret Hall's)This is similar to Jus12, but without the verbosity and with correct Note you do NOT need the curly braces for , nor lambdas, and note usage of placeholder syntax. Also note better naming.One liners for saving/reading to/from , using .This isn't suitable for large files, but will do the job.Some links:\n\n\nHere is a concise one-liner using the Scala compiler library:Alternatively, if you want to use the Java libraries you can do this hack:From A micro library I wrote: orAfter reviewing all of these answers on how to easily write a file in Scala, and some of them are quite nice, I had three issues:Before starting, my goal isn't conciseness. It's to facilitate easier understanding for Scala/FP beginners, typically those coming from Java. At the very end, I will pull all the bits together, and then increase the conciseness.First, the  method needs to be updated to use  (again, conciseness is not the goal here). It will be renamed to :The beginning of the above  method might be confusing because it appears to have two parameter lists instead of the customary single parameter list. This is called currying. And I won't go into detail how currying works or where it is  useful. It turns out that for this particular problem space, it's the right tool for the job.Next, we need to create method, , which will create a (or overwrite an existing)  and write a . It uses a  which is encapsulated by a  which is in turn encapsulated by a . And to elevate performance, a default buffer size much larger than the default for  is defined, , and assigned the value 65536.Here's the code (and again, conciseness is not the goal here):The above  method is useful in that it takes a  as input and sends it to a . Let's now create a  method which takes a  and writes it to a .Here's the code (and I'll let you guess conciseness's priority here):Finally, it is useful to be able to fetch the contents of a  as a . While  provides a convenient method for easily obtaining the contents of a , the  method must be used on the  to release the underlying JVM and file system handles. If this isn't done, then the resource isn't released until the JVM GC (Garbage Collector) gets around to releasing the  instance itself. And even then, there is only a weak JVM guarantee the  method will be called by the GC to  the resource. This means that it is the client's responsibility to explicitly call the  method, just the same as it is the responsibility of a client to tall  on an instance of . For this, we need a second definition of the using method which handles .Here's the code for this (still not being concise):And here is an example usage of it in a super simple line streaming file reader (currently using to read tab delimited files from database output):An  has been provided as an answer to a .Now, bringing that all together with the imports extracted (making it much easier to paste into Scala Worksheet present in both Eclipse ScalaIDE and IntelliJ Scala plugin to make it easy to dump output to the desktop to be more easily examined with a text editor), this is what the code looks like (with increased conciseness):As a Scala/FP newbie, I've burned many hours (in mostly head scratching frustration) earning the above knowledge and solutions. I hope this helps other Scala/FP newbies get over this particular learning hump faster.Here's an example of writing some lines to a file using .To surpass samthebest and the contributors before him, I have improved the naming and conciseness:This line helps to write a file from an Array or String."},
Scala

In shapeless, the Nat type represents a way to encode natural numbers at a type level. This is used for example for fixed size lists. You can even do calculations on type level, e.g. append a list of  elements to a list of  elements and get back a list that is known at compile time to have  elements.Is this representation capable of representing large numbers, e.g.  or 2, or will this cause the Scala compiler to give up?I will attempt one myself. I will gladly accept a better answer from Travis Brown or Miles Sabin.Nat can currently  be used to represent large numbersIn the current implementation of Nat, the value corresponds to the number of nested shapeless.Succ[] types:So to represent the number 1000000, you would have a type that is nested 1000000 levels deep, which would definitely blow up the scala compiler. The current limit seems to be about 400 from experimentation, but for reasonable compile times it would probably be best to stay below 50.However, there is a way to encode large integers or other values at type level, . The only thing you can do with those as far as I know is to check if they are equal or not. See below.This could be used to e.g. enforce same array size when doing bit operations on Array[Byte].Shapeless's  encodes natural numbers at the type level using Church encoding. An alternate method is to represent the naturals as a type level HList of bits. Check out  which implements this solution in a shapeless style. :)"},
Scala

When I compile Scala code, by running ,  says:How do I do that? (From within SBT?)If you don't want to change your :Edit: Added  and  per comments.Add this setting to your build.sbt, and, if you have a multi-module project, add it to every project's settings.As times flows new solutions are emerged. So, now you could re-run the scala compiler without issuing entire project rebuild.You need to install : After that you could use the  task to compile single file. SBT allows per tasks settings configuration, so you could change for that tasks only:"},
Scala

It sounds like a stupid question, but all I found on the internet was trash.\nI simply can't add an element of type T into a list List[T].\nI tried with  but it seems it creates a strange object and accessing to  always returns the first element that was put inside the list.Note that this operation has a complexity of O(n). If you need this operation frequently, or for long lists, consider using another data type (e.g. a ListBuffer).That's because you shouldn't do it (at least with an immutable list).\nIf you really really need to append an element to the end of a data structure and this data structure really really needs to be a list and this list really really has to be immutable then do eiher this:or that:Lists in Scala are not designed to be modified. In fact, you can't add elements to a Scala ; it's an , like a Java String. \nWhat you actually do when you \"add an element to a list\" in Scala is to create a . Instead of using lists for such use cases, I suggest to either use an  or a . Those datastructures are designed to have new elements added.Finally, after all your operations are done, the buffer then can be converted into a list. See the following REPL example:We can append or prepend two lists or list&array\n        "},
Scala

Operator overloading in C++ is considered by many to be A Bad Thing(tm), and a mistake not to be repeated in newer languages. Certainly, it was one feature specifically dropped when designing Java.Now that I've started reading up on Scala, I find that it has what looks very much like operator overloading (although technically it doesn't have operator overloading because it doesn't have operators, only functions). However, it wouldn't seem to be qualitatively different to the operator overloading in C++, where as I recall operators are defined as special functions.So my question is what makes the idea of defining \"+\" in Scala a better idea than it was in C++?C++ inherits true blue operators from C.  By that I mean that the \"+\" in 6 + 4 is very special.  You can't, for instance, get a pointer to that + function.Scala on the other hand doesn't have operators in that way.  It just has great flexibility in defining method names plus a bit of built in precedence for non-word symbols.  So technically Scala doesn't have operator overloading.Whatever you want to call it, operator overloading isn't inherently bad, even in C++.   The problem is when bad programmers abuse it.  But frankly, I'm of the opinion that taking away programmers ability to abuse operator overloading doesn't put a drop in the bucket of fixing all the things that programmers can abuse.  The real answer is mentoring.  None-the-less, there are differences between C++'s operator overloading and Scala's flexible method naming which, IMHO, make Scala both less abusable and more abusable.In C++ the only way to get in-fix notation is using operators.  Otherwise you must use object.message(argument) or pointer->messsage(argument) or function(argument1, argument2).  So if you want a certain DSLish style to your code then there's pressure to use operators.In Scala you can get infix notation with any message send.  \"object message argument\" is perfectly ok, which means you don't need to use non-word symbols just to get infix notation.C++ operator overloading is limited to essentially the C operators.  Combined with the limitation that only operators may be used infix that puts pressure on people to try to map a wide range of unrelated concepts onto a relatively few symbols like \"+\" and \">>\"Scala allows a huge range of valid non-word symbols as method names.  For instance, I've got an embedded Prolog-ish DSL where you can write The :-, !, ?, and & symbols are defined as ordinary methods.   In C++ only & would be valid so an attempt to map this DSL into C++ would require some symbols that already evoke very different concepts.  Of course, this also opens up Scala to another kind of abuse.  In Scala you can name a method $!&^% if you want to. For other languages that, like Scala, are flexible in the use of non-word function and method names see Smalltalk where, like Scala, every \"operator\" is just another method and Haskell which allows the programmer to define precedence and fixity of flexibly named functions.Only by the ignorant. It is absolutely required in a language like C++, and it is noticeable that other languages that started off taking a \"purist\" view, have added it once their designers found out how necessary it is.Operator overloading was never universally thought to be a bad idea in C++ - just the abuse of operator overloading was thought to be a bad idea. One doesn't really need operator overloading in a language since they can be simulated with more verbose function calls anyway.  Avoiding operator overloading in Java made the implementation and specification of Java a little simpler and it forced programmers to not abuse operators.  There has been some debate in the Java community about introducing operator overloading.The advantages and disadvantages of operator overloading in Scala are the same as in C++  - you can write more natural code if you use operator overloading appropriately - and more cryptic, obfuscated code if you don't.FYI: Operators are not defined as special functions in C++, they behave just like any other function - although there are some differences in name lookup, whether they need to be member functions, and the fact that they can be called in two ways: 1) operator syntax, and 2) operator-function-id syntax.This article - \"\" - answers your question directly.Java mistakenly (according to the author) omitted operator overloading because it was complicated in C++, but forgot why (or didn't realize that it didn't apply to Java).Thankfully, higher level languages like Scala give developers options, while still running on the same JVM.There is nothing wrong with operator overloading.  In fact, there's something wrong with  having operator overloading for numeric types.  (Take a look at some Java code that uses BigInteger and BigDecimal.)C++ has a tradition of abusing the feature, though.  An often-cited example is that the bitshift operators are overloaded to do I/O.In general it is not a bad thing.\nNew languages such as C# also have operator overloading.It is the abuse of operator overloading that is a bad thing.But there are also problems with operator overloading as defined in C++. Because overloaded operators are just syntactic sugar for method calls they behave just like method. On the other hand normal built-in operators do not behave like methods. These inconsistency can be cause problems.Off the top of my head operators  and .\nThe built in versions of these are short-cut operators. This is not true for overloaded versions and has caused some problems.The fact that + - * / all return the same type that they operate on (after operator promotion)\nThe overloaded versions can return anything (This is where the abuse sets in, If your operators start to return some arbitrator type the user was not expecting things go down hill).Operator overloading is not something that you really \"need\" very often, but when using Java, if you hit a point where you genuinely need it, it'll make you want to rip your fingernails out just so you have an excuse to stop typing.That code which you've just found overflows a long? Yup, you're going to have to retype the whole lot to make it work with BigInteger. There is nothing more frustrating that having to reinvent the wheel just to change the type of a variable.Guy Steele argued that operator overloading should be in Java as well, in his keynote speech \"Growing a language\" - there's a video and a transcription of it, and it's really an amazing speech. You will wonder what he is talking about for the first couple of pages, but if you keep on reading, you will see the point and achieve enlightenment. And the very fact that he could do such a speech at all is also amazing.At the same time, this talk inspired a lot of fundamental research, probably including Scala - it's one of those papers that everybody should read to work in the field.Back to the point, his examples are mostly about numeric classes (like BigInteger, and some weirder stuff), but that's not essential.It is true, though, that misuse of operator overloading can lead to terrible results, and that even proper uses can complicate matters, if you try to read code without studying a bit the libraries it uses. But is that a good idea? OTOH, shouldn't such libraries try to include an operator cheat sheet for their operators?Operator overloading was not a C++ invention - it came from Algol IIRC and even Gosling does not claim it is a bad idea in general.I believe EVERY answer missed this. In C++ you can overload operators all you want, but you can't effect the precedence with which they're evaluated. Scala doesn't have this issue, IIRC.As for it being a bad idea, besides precedence issues, people come up with really daft meanings for operators, and it rarely aids readability. Scala libraries are especially bad for this, goofy symbols that you must memorize each time, with library maintainers sticking their heads in the sand saying, 'you only need to learn it once'. Great, now I need to learn some 'clever' author's cryptic syntax * the number of libraries I care to use. It wouldn't be so bad if there existed a convention of ALWAYS supplying a literate version of the operators.The only thing known wrong in C++ is the lack of the ability to overload []= as a separate operator. This could be hard to implement in a C++ compiler for what is probably not an obvious reason but plenty worth it.As the other answers have pointed out; operator overloading itself isn't necessarily bad. What is bad it when it is used in ways that make the resulting code un-obvious. Generally when using them you need to make them do the least surprising thing (having operator+ do division would cause trouble for a rational class's usage) or as Scott Meyers says:Now some people have taken operator overloading to the extreme with things like . At this level you have no idea how it is implemented but it makes an interesting syntax to get what you want done. I'm not sure if this is good or bad. It seems nice, but I haven't used it. I have never seen an article claiming that C++'s operator overloading is bad.User-definable operators permit an easier higher level of expressivity and usability for users of the language. AFAIK, There is nothing special in operator functions compared to \"normal\" member functions. Of course you only have a certain set of operators that you can overload, but that doesn't make them very special."},
Scala

It seems that  was late to the Scala collections party, and all the influential blog posts had already left.In Java  is the default collection - I might use  but only when I've thought through an algorithm and care enough to optimise. In Scala should I be using  as my default , or trying to work out when  is actually more appropriate?As a general rule, default to using .  It\u2019s faster than  for  everything and more memory-efficient for larger-than-trivial sized sequences. See this  of the relative performance of Vector compared to the other collections. There are some downsides to going with .  Specifically:Another downside before Scala 2.10 was that pattern matching support was better for , but this was rectified in 2.10 with generalized  and  extractors.There is also a more abstract, algebraic way of approaching this question: what sort of sequence do you  have?  Also, what are you  doing with it?  If I see a function that returns an , I know that function has some holes in its domain (and is thus partial).  We can apply this same logic to collections.If I have a sequence of type , I am effectively asserting two things.  First, my algorithm (and data) is entirely stack-structured.  Second, I am asserting that the only things I\u2019m going to do with this collection are full, O(n) traversals.  These two really go hand-in-hand.  Conversely, if I have something of type , the  thing I am asserting is that my data has a well defined order and a finite length.  Thus, the assertions are weaker with , and this leads to its greater flexibility.Well, a  can be incredibly fast if the algorithm can be implemented solely with ,  and . I had an object lesson of that very recently, when I beat Java's  by generating a  instead of an , and couldn't beat that with anything else.However,  has a fundamental problem: it doesn't work with parallel algorithms. I cannot split a  into multiple segments, or concatenate it back, in an efficient manner.There are other kinds of collections that can handle parallelism much better -- and  is one of them.  also has great locality -- which  doesn't -- which can be a real plus for some algorithms.So, all things considered,  is the best choice  you have specific considerations that make one of the other collections preferable -- for example, you might choose  if you want lazy evaluation and caching ( is faster but doesn't cache), or  if the algorithm is naturally implemented with the operations I mentioned.By the way, it is preferable to use  or  unless you want a specific piece of API (such as 's ), or even  or  if your algorithm can be run in parallel.For immutable collections, if you want a sequence, your main decision is whether to use an  or a , which give different guarantees for performance. An IndexedSeq provides fast random-access of elements and a fast length operation. A LinearSeq provides fast access only to the first element via , but also has a fast  operation. (Taken from the Seq documentation.)For an  you would normally choose a . s and s are also IndexedSeqs.For a  you would normally choose a  or its lazy equivalent . Other examples are s and s.So in Java terms,  used similarly to Scala's , and  similarly to Scala's . But in Scala I would tend to use List more often than Vector, because Scala has much better support for functions that include traversal of the sequence, like mapping, folding, iterating etc. You will tend to use these functions to manipulate the list as a whole, rather than randomly accessing individual elements.Some of the statements here are confusing or even wrong, especially the idea that immutable.Vector in Scala is anything like an ArrayList.\nList and Vector are both immutable, persistent (i.e. \"cheap to get a modified copy\") data structures.\nThere is no reasonable default choice as their might be for mutable data structures, but it rather depends on what your algorithm is doing.\nList is a singly linked list, while Vector is a base-32 integer trie, i.e. it is a kind of search tree with nodes of degree 32.\nUsing this structure, Vector can provide most common operations reasonably fast, i.e. in O(log_32(n)). That works for prepend, append, update, random access, decomposition in head/tail. Iteration in sequential order is linear.\nList on the other hand just provides linear iteration and constant time prepend, decomposition in head/tail. Everything else takes in general linear time.This might look like as if Vector was a good replacement for List in almost all cases, but prepend, decomposition and iteration are often the crucial operations on sequences in a functional program, and the constants of these operations are (much) higher for vector due to its more complicated structure.\nI made a few measurements, so iteration is about twice as fast for list, prepend is about 100 times faster on lists, decomposition in head/tail is about 10 times faster on lists and generation from a traversable is about 2 times faster for vectors. (This is probably, because Vector can allocate arrays of 32 elements at once when you build it up using a builder instead of prepending or appending elements one by one).\nOf course all operations that take linear time on lists but effectively constant time on vectors (as random access or append) will be prohibitively slow on large lists.So which data structure should we use?\nBasically, there are four common cases:In situations which involve a lot random access and random mutation, a  (or \u2013 as the  say \u2013 a ) seems to be a good compromise. This is also what the  suggest.Also, the  class seems to play nicely in distributed environments without much data duplication because there is no need to do a copy-on-write for the complete object. (See: )If you're programming immutably and need random access, Seq is the way to go (unless you want a Set, which you often actually do). Otherwise List works well, except it's operations can't be parallelized. If you don't need immutable data structures, stick with ArrayBuffer since it's the Scala equivalent to ArrayList."},
Scala

I know this question is a bit open but I have been looking at Scala/Lift as an alternative to Java/Spring and I wonder what are the real advantages that Scala/Lift has over it. From my perspective and experience, Java Annotations and Spring really minimizes the amount of coding that you have to do for an application. Does Scala/Lift improve upon that?Spring and Lift are almost diametrically opposed in terms of maturity and goals.In a sentence, Spring is heavyweight and Lift is lightweight.  With sufficient determination and resources you can turn that on its head, but you would need a  of both.Here are concrete differences that stuck in my mind after working with both frameworks.  This isn't an exhaustive list, which I can't compile anyhow.  Just what seemed most interesting to me...Both frameworks are compelling.  There's a broad range of apps where you can choose either and do well.I've gotta say that I strongly disagree with Dan LaRocque's answer.Lift is not monolithic.  It is composed on discrete elements.  It does not ignore J/EE elements, it support the likes of JNDI, JTA, JPA, etc.  The fact that you're not forced to uses these elements of J/EE is a strong indication of Lift's modular design.With the above being said, let me talk some about Lift's design philosophy.I wrote  before I started writing Lift.  To a great degree, and to a greater degree than is true for any other web framework that I know of, Lift meets these goals.Lift at its core seeks to abstract away the HTTP request/response cycle rather than placing object wrappers around the HTTP Request.  At the practical level, this means that most any action that a user can take (submitting form elements, doing Ajax, etc.) is represented by a GUID in the browser and a function on the server.  When the GUID is presented as part of the an HTTP request, the function is applied (called) with the supplied parameters.  Because the GUIDs are hard to predict and session-specific, replay attacks and many parameter tampering attacks are far more difficult with Lift than most other web frameworks, including Spring.  It also means that developers are more productive because they are focusing on user actions and the business logic associated with user actions rather than the plumbing of packing and unpacking an HTTP request.  For example, code for accepting or rejecting a FourSquare friend request:It's that simple.  Because the friendRequest is in the scope when the function is created, the function closes over the scope... there's no need to expose the primary key of the friend request or do anything else... just define the text of the button (it can be localized or it can be pulled from an XHTML template or it can be pulled from a localized template) and the function to execute when the button is pushed.  Lift takes care of assigning the GUID, setting up the Ajax call (via jQuery or YUI, and yes, you can add your own favorite JavaScript library), doing automatic retries with back-offs, avoiding connection starvation by queuing Ajax requests, etc.So, one big difference between Lift and Spring is that Lift's philosophy of GUID associated with function has the dual benefit of much better security and much better developer productivity.  The GUID -> Function association has proven very durable... the same construct works for normal forms, ajax, comet, multi-page wizards, etc.The next core piece of Lift is keeping the high level abstractions around for as long as possible.  On the page generation side, that means building the page as XHTML elements and keeping the page as XHTML until just before streaming the response.  The benefits are resistance to cross site scripting errors, the ability to move CSS tags to the head and scripts to the bottom of the page after the page has been composed, and the ability to rewrite the page based on the target browser.  On the input side, URLs can be re-written to extract parameters (both query and path parameters) in a type-safe manner, high level, security checked data is available for processing very early in the request cycle.  For example, here's how to define servicing of a REST request:Using Scala's built-in pattern matching, we match an incoming request, extract the third part of the path and get the User that corresponds to that value, and even apply access control checks (does the current session or request have permissions to access the given User record).  So, by the time the User instance hits the application logic, it's vetted.With these two core pieces, Lift has a tremendous advantage in terms of security.  To give you an idea of the magnitude of Lift's security that doesn't get in the way of features,  who did security for Yahoo! had this to say about FourSquare (one of the Lift poster-child sites):At the time, FourSquare had one engineer working on the code (not that @harryh isn't a super-genius) and his main focus was re-writing the PHP version of FourSquare while coping with weekly traffic doubling.The last part of Lift's security focus is SiteMap.  It's a unified access control, site navigation, and menu system.  The developer defines the access control rules for each page using Scala code (e.g.  or ) and those access control rules are applied before any page rendering starts.  This is much like Spring Security, except that it's baked in from the beginning of the project and the access control rules are unified with the rest of the application so you don't have to have process for updating the security rules in XML when the URLs change or the methods that calculate the access control change.To summarize so far, Lift's design philosophy gives you the benefits of baked in access control, resistance to the OWASP top 10 security vulnerabilities, much better Ajax support and much higher developer productivity than does Spring.But Lift also gives you the best Comet support of any web framework around.  That's why Novell chose Lift to power their  and here's what Novell has to say about Lift:So, Lift is not just another me-too MVC framework.  It's a framework that's got some core design principles behind it that have matured very well.  It's a framework that gives the dual advantages of security and developer productivity.  Lift is a framework that's built in layers and gives the developer the right choices based on their needs... choices for view generation, choices for persistence, etc.Scala and Lift give developers a much better experience than the melange of XML, annotations, and other idioms that make up Spring.I would recommend you to check play framework, it has some very interesting ideas and supports development in Java and ScalaJust for fun. And for the sake of learning new programming approaches. I strongly looked into using Lift for a recent web project, not being a big fan of Spring MVC. I have not used the latest versions, but the earlier versions of Spring MVC made you jump through a lot of hoops to get a web application running. I was almost sold on Lift until I saw that Lift can be very session dependent and would require 'sticky sessions' to work correctly. Excerpt from So once a Session is required, the user would have to be pin to that node. This creates the need for intelligent load balancing and affects scaling, which prevented Lift from being a solution in my case. I ended up selecting  and have been very pleased. Play has been stable and reliable so far and very easy to work with.I  come to Lift and Scala from a Java background, so this isn't from personal experience, but I know that many Lift developers find Scala to be a much more concise and efficient language than Java.Expanding your knowledge is always a worthwhile endeavor :) I just started learning Scala, it's affecting how I write normal Java and I can say it's been very beneficial so far. I hate to completely throw your world for a loop.  But you can you use Scala, Java, Lift, Spring in one application and have it not be a problem.In my humble opinion, imagination is what matters.Let's consider you want to write an app. If you're a decent developer, the app should already be build in your mind. The next step is to discover how it works through code. In order to do that, you need to pass the imagined app through a function that translates it to a real world app. That function is a programming language. So So the language choice is important. So is the framework. There are a ton of smart people here that will advise you on what to chose, but ultimately, the language / framework that best translates your imagination should be your choice. So prototype with both and make your choice.As for me, I'm slowly learning Scala and Lift and loving it.But the main problem is we can't compare spring with lift. Lift is basically use as UI framework and Spring is use as DI framework. \n\nIf you are developing web app that does have that much of backend sure you can use lift.\n\nbut if your developing web app that have some series backend and you definelty need to goto spring."},
Scala

The question is best explained by an example:In Java for a JPA EntityManager, I can do the following(Account is my Entity class):In Scala, my naive attempt is:But when I try to use  in Scala, it seems to not like this.  How can I specify the java.lang.Class object for the Account class in Scala?According to \"\", However,  and  return slightly different values, reflecting the effect of type erasure on the JVM, in the case of getClass.That is why the :There is a .( reports that the ticket is \"now\", ie Nov. 2011, two years later, fixed.\nIn 2.9.1,  now does: )Back in 2009:Note: regarding , a possible workaround would be: in Scala is equivalent to  in Java."},
Scala

I have seen many examples of ARM (automatic resource management) on the web for Scala. It seems to be a rite-of-passage to write one, though most look pretty much like one another. I  see a pretty cool example using continuations, though.At any rate, a lot of that code has flaws of one type or another, so I figured it would be a good idea to have a reference here on Stack Overflow, where we can vote up the most correct and appropriate versions.Daniel,I've just recently deployed the scala-arm library for automatic resource management.  You can find the documentation here: This library supports three styles of usage (currently):1) Imperative/for-expression:2) Monadic-style3)  Delimited Continuations-styleHere's an \"echo\" tcp server:The code makes uses of a Resource type-trait, so it's able to adapt to most resource types.   It has a fallback to use structural typing against classes with either a close or dispose method.   Please check out the documentation and let me know if you think of any handy features to add.Chris Hansen's  talks about about slide 21 of Martin Odersky's . This next block is taken straight from slide 21 (with permission): --end quote--Then we can call like this:What are the drawbacks of this approach? That pattern would seem to address 95% of where I would need automatic resource management... added code snippet extending the design pattern - taking inspiration from python  statement and addressing:This is with Scala 2.8.Here's  solution using continuations:Here are the solutions with and without continuations for comparison:And here's Tiark Rompf's suggestion of improvement:Daniel, good you asked this. I am myself intrigued after seeing James Iry's code. I see a gradual 4 step evolution for doing ARM in Scala:What I would really love to see is a presentation describing these. It will be very educational and should convince the begots that there is a world beyond Monads :)There is light-weight (10 lines of code) ARM included with better-files. See: Here is how it is implemented if you don't want the whole library:"},
Scala

How to split a List of elements into lists with at most N items?ex: Given a list with 7 elements, create groups of 4, leaving the last group possibly with less elements.I think you're looking for . It returns an iterator, but you can convert the result to a list,Or if you want to make your own: Use:: upon reviewing this 2 years later, I wouldn't recommend this implementation since  is O(n), and hence this method is O(n^2), which would explain why the built-in method becomes faster for large lists, as noted in comments below. You could implement efficiently as follows:or even (slightly) more efficiently using :I am adding a tail recursive version of the split method since there was some discussion of tail-recursion versus recursion. I have used the  tailrec annotation to force the compiler to complain in case the implementation is not indeed tail-recusive. Tail-recursion I believe turns into a loop under the hood and thus will not cause problems even for a large list as the stack will not grow indefinitely. I think this is the implementation using splitAt instead of take/drop"},
Scala

In the last version of scala (2.10.3) REPL, I can type  to quit from REPL.  However, in Scala 2.11.0 this doesn't work.  I ran into the same issue on upgrade, just use colon q.Additionally,  was deprecated in 2.10.x with  suggested instead, so this works as well:As a side note, I think they did this so you can distinguish between exiting the scala console in sbt and exiting sbt itself, though I could be wrong.You options to leave the REPL as stated in the answers before are:Use the end of file characters.  on linux,  on Windows.Using the  command on my 2.10.3 REPL gets me this hint: I don't know whether  is still there in 2.11.0 or not though.  When I use  in 2.10.4, I got a warning: You can use:all of them work in 2.11.x."},
Scala

Learning Scala currently and needed to invert a Map to do some inverted value->key lookups.  I was looking for a simple way to do this, but came up with only:Anybody have a more elegant approach?Assuming values are unique, this works:On Scala 2.8, however, it's easier:Being able to do that is part of the reason why Scala 2.8 has a new collection library.Mathematically, the mapping might not be ivertible, e.g., from , you can't get , but rather you get , because there might be different keys associated with same values. So, if you are interested in knowing all the keys, here's the code: You can avoid the ._1 stuff while iterating in few ways.  Here's one way.  This uses a partial function that covers the one and only case that matters for the map: Here's another way:The map iteration calls a function with a two element tuple, and the anonymous function wants two parameters.  Function.tupled makes the translation.I came here looking for a way to invert a Map of type Map[A, Seq[B]] to Map[B, Seq[A]], where each B in the new map is associated with every A in the old map for which the B was contained in A's associated sequence. E.g.,\n\nwould invert to \nHere's my solution :where oldMap is of type  and newMap is of type The nested foldLefts make me cringe a little bit, but this is the most straightforward way I could find to accomplish this type of inversion. Anyone have a cleaner solution?In scala REPL:Note that duplicate values will be overwritten by the last addition to the map:You could invert a map using:The problem with this approach is that if your values, which have now become the hash keys in your map, are not unique you will drop the duplicate values. To illustrate:To avoid this you can convert your map to a list of tuples first, then invert, so that you don't drop any duplicate values:If it's a one-to-one map, you end up with singleton lists which can be trivially tested and transformed to a Map[B,A] rather than Map[B,List[A]]."},
Scala

I've been curious about the impact of not having an explicit primary constructor in Scala, just the contents of the class body.In particular, I suspect that the private or protected constructor pattern, that is, controlling construction through the companion object or another class or object's methods might not have an obvious implementation. Am I wrong? If so, how is it done?You can declare the default constructor as private/protected by inserting the appropriate keyword between the class name and the parameter list, like this:'s answer is correct, but  offers an additional alternative:"},
Scala

The question is in two parts. The first is conceptual. The next looks at the same question more concretely in Scala.I come from an imperative programming background (C++, Java). I have been exploring functional programming, specifically Scala.Some of the primary principles of pure functional programming:Even though modern  are extremely efficient with object creation and  is very inexpensive for short lived objects, it's probably still better to minimize object creation right? At least in a single-threaded application where concurrency and locking is not an issue. Since Scala is a hybrid paradigm, one can choose to write imperative code with mutable objects if necessary. But, as someone who has spent a lot of years trying to reuse objects and minimize allocation. I would like a good understanding of the school of thought that would not even allow that.As a specific case, I was a little surprised by this code snippet in   . It has a Java version of Quicksort followed by a neat looking Scala implementation of the same.Here is my attempt to benchmark the implementations. I haven't done detailed profiling. But, my guess is that the Scala version is slower because the number of objects allocated is linear (one per recursion call). Is there any way chance that tail call optimizations can come into play? If I am right, Scala supports tail call optimizations for self-recursive calls. So, it should only be helping it. I am using Scala 2.8.Time in milliseconds for five consecutive runsSince there are a few  flying around here, I\u2019d like to clarify some points.There are  of a functional quicksort implementation. In the following, let\u2019s consider this reference implementation in Haskell (I don\u2019t know Scala \u2026) from the :A third disadvantage is somewhat hidden: unlike the \u201cin-place\u201d variant, this implementation  for the cons cells of the list and potentially scatters memory all over the place. As a result, this algorithm has a very . I don\u2019t know whether smart allocators in modern functional programming languages can mitigate this \u2013 but on modern machines, cache misses have become a major performance killer. Unlike others, I wouldn\u2019t say that quicksort is inherently imperative and that\u2019s why it performs badly in an FP environment. Quite on the contrary, I would argue that quicksort is a perfect example of a functional algorithm: it translates seamlessly into an immutable environment, its asymptotic running time and space complexity are on par with the procedural implementation, and even its procedural implementation employs recursion.But this algorithm  performs worse when constrained to an immutable domain. The reason for this is that the algorithm has the peculiar property of benefitting from a lot of (sometimes low-level) fine-tuning that can only be efficiently performed on arrays. A naive description of the quicksort misses all these intricacies (both in the functional and in the procedural variant).After reading \u201cEngineering a sort function\u201d I can no longer consider quicksort an elegant algorithm. Implemented efficiently, it is a clunky mess, an engineer\u2019s piece of work, not an artist\u2019s (not to devalue engineering! this has its own aesthetic).But I would also like to point out that this point is particular to quicksort. Not every algorithm is amenable to the same sort of low-level tweaking. A lot of algorithms and data structures really  be expressed without performance loss in an immutable environment.And immutability can even  performance costs by removing the need of costly copies or cross-thread synchronizations.So, to answer the original question, \u201c\u201d \u2013 In the particular case of quicksort, there is a cost that is indeed a result of immutability. But in general, .There are a bunch of things wrong with this as a benchmark of functional programming.  Highlights include:So, this comparison is a great illustration that you must understand your language (and algorithm) in detail in order to write high-performance code.  But it's not a very good comparison of FP vs. non-FP.  If you want that, check out .  The take-home message there is that the penalty is typically not more than a factor of 2 or 3 or so, but it really depends.  (No promises that the Haskell folks have written the fastest algorithms possible either, but at least some of them probably tried!  Then again, some of the Haskell calls C libraries....)Now, suppose you do want a more reasonable benchmark of Quicksort, recognizing that this is probably one of the worst cases for FP vs. mutable algorithms, and ignoring the data-structure issue (i.e. pretending that we can have an immutable Array):Note the modification to the functional Quicksort so it only goes through the data once if at all possible, and the comparison to the built-in sort.  When we run it we get something like:So, aside from learning that trying to write your own sort is a bad idea, we find that there is a ~3x penalty for an immutable quicksort if the latter is implemented somewhat carefully.  (You could also write a trisect method that returns three arrays: those less than, those equal, and those greater than the pivot.  This might speed things up slightly more.)I don't think the Scala version is actually tail recursive, since you are using .Also, just because this is idiomatic Scala code, this doesn't mean it is the best way to do it.The best way to do this would be to use one of Scala's built-in sorting functions. That way you get the immutability guarantee and know you have a speedy algorithm.See Stack Overflow question  for an example.Sorting an array is, like, the most imperative task in the universe.  It is not surprising that many elegant 'immutable' strategies/implementations fail poorly on a 'sort an array' microbenchmark.  This does not imply that immutability is expensive \"in general\", though.  There are many tasks where immutable implementations will perform comparably to mutable ones, but array sorting often is not one of them.If you're simply rewriting your imperative algorithms and data structures into functional language it indeed will be expensive and useless. To make the things shine, you should use the features available only in functional programming: data stuctures persistence, lazy evaluations etc. The cost of immutability in Here is a version that is nearly as fast than the Java one. ;)This version makes a copy of the array, sorts it in place using the Java version and returns the copy. Scala does not force you to use immutable structure internally. So the benefit of Scala is that you can leverage mutability and immutability as you see fit. The disadvantage is that if you do that wrong you don't really get the benefits of immutability.Immutability is not expensive. It sure can be expensive if you measure a small subset of the tasks a program have to do, and pick a solution based on mutability to boot -- such as measuring quicksort.To put it simply, you don't quicksort when using purely functional languages.Let's consider this from another angle. Let's consider these two functions:Benchmark THAT, and you'll find that the code using mutable data structures has much worse performance, because it needs to copy the array, while the immutable code need not concern itself with that.When you program with immutable data structures, you structure your code to take advantage of its strengths. It is not simply the data type, or even individual algorithms. The program will be  in a different manner.Which is why benchmarking is usually meaningless. Either you choose algorithms that are natural to one style or another, and that style wins, or you benchmark the whole application, which is often impractical.QuickSort is known to be faster when done in-place, so this is hardly a fair comparison!Having said that... Array.concat?\nIf nothing else, you're showing how a collection type optimised for imperative programming is particularly slow when you try and use it in a functional algorithm; almost any other choice would be faster!Another  important point to consider, perhaps  most important issue when comparing the two approaches is: \"how well does this scale out to multiple nodes/cores?\"Chances are, if you're looking for an immutable quicksort then you're doing so because you actually want a parallel quicksort.  Wikipedia has some citations on this subject: The scala version can simply fork before the function recurses, allowing it to very quickly sort a list containing billions of entries if you have enough cores available.Right now, the GPU in my system has 128 cores available to me if I could just run the Scala code on it, and this is on a simple desktop system two years behind the current generation.  How would that stack up against the single-threaded imperative approach I wonder...Perhaps the more important question is therefore:It's been said that OO programming uses abstraction to hide complexity, and functional programming uses immutability to remove complexity. In the hybrid world of Scala we can use OO to hide the imperative code leaving application code none the wiser. Indeed the collections libraries use plenty of imperative code but that doesn't mean we shouldn't use them. As others have said, used with care, you really get the best of both worlds here."},
Scala

What is so powerful about flatmap that it deserves such a place in the Scala folklore?The reasoning behind this phrase is that you can replace a lot of tedious if/then/else code you would write with calls to flatMap (and other higher order functions).This is especially true for Options (see ) But it applies to other monads as well (although I have to admit, I don't exactly understand the details yet myself)Imagine the situation where you have a collection for which you want to apply a function (or a series of functions) where each function might return null. When you actually use null you code will be riddled with null checks. But if you use Options instead of values, you can just flatmap the values with the desired functions, chaining the functions in the case of multiple functions and get a collection with just the results that aren't null, which in many cases is exactly what you want. Since that description is rather convoluted the shorter advice \"just flatmap that shit\" established itself.The story I heard was that two preeminent Scala programmers were pairing when one of them started writing some code like this:At which point the other said \"What is this? Amateur hour? Flat map that shit!\"As to what's so powerful about , well... First, it's the fundamental monadic operator. That means it is a common operation shared by, for example, containers (such as , collections, etc), continuations, state, etc. Second, while you can de-construct an , that, as opposed to , is not a monadic operation, so it cannot be as widely applied. Also, it requires too much knowledge about the data you are manipulating.The crucial thing about  is that it's Scala's representation of the monadic bind operation. There are numerous tutorials on the web explaining the purpose of monads and why exactly they're so useful; James Iry has one at  which goes into some detail.Runar Bjarnason is the person you're looking for for the origin.Realising why it's so powerful is something that can only come with time to be honest. The Option class is the best place to start for seeing how you would repeatedly flatMap a series of lookups (for example) into a final result."},
Scala

When a case class has many fields and their names are long, it is often a good idea to write each field in each line like:This resembles C/C++  definition and totally readable even when the case class becomes bigger. But IntelliJ IDEA's default Scala plugin automatically changes its indentation:which looks weird to me, but the  doesn't mention anything about case class indentation.I couldn't find anything in the IDE settings that can change this behaviour. Is there an option to make the auto-indentation work like the way I described above or disable auto-indentation for case classes?Try File -> Settings... -> Code Style -> ScalaThere are lots of settings to customize your code formatting in there. In the \"Wrapping and Braces\" tab, under \"Method declaration parameters\":This will change it to the example you provided.If you want it to use the indenting in \"Continuation indent\" under \"Tabs and Indent\" you have to have both of the option above unchecked."},
Scala

I've heard (and I know I've seen examples too, if only I can remember where) that  can obtain dependencies from a git repo.I am looking to obtain the dependency  from github. The repository does not provide any artifact JAR files, only a source tree which is set up to be built using . The process that I am imagining is that  will download the source repo, build it, and then use that as the dependency artifact.I may be imagining that  can in fact do something like this. Can it? And if so, how?Yes indeed. You can give your  a dependency with the  operator, and you can reference a Github project by its URI, for example . Alternatively, you can  the project, and then reference your local copy with . See  on the SBT wiki for details and examples.You can import unpackaged dependencies into your project from GitHub by treating them as project dependencies, using the  operator. (This is distinct from the way that precompiled library dependencies are included).Note that you can specify which branch to pull using  notation. Here's some Scala SBT code that is working well for me:Note that if you have multiple SBT projects dependending on the same external project, it's worth setting up a central  to avoid unnecessary recompilations (see ).Since I had problems getting the dependencies of my library resolved (using the suggested ) I'd like to point out to the object called . Thus, if one need to depend on a library residing in git, I suggest to do so as follows:"},
Scala

I need to get the first date (as ) of a month and the last one. Getting the first is trivial, but getting the last seems to need some logic as months have different length and February length even varies over years. Is there a mechanism for this already built in to JodaTime or should I implement it myself?How about: returns a  which represents the \"day of month\" field in a way which knows the originating .As it happens, the  method is even  to recommend it for this particular task:Another simple method is this:An old question, but a top google result when I was looking for this.If someone needs the actual last day as an  instead using JodaTime you can do this:Using JodaTime,we can do this : As describe here in my small gist on github :  "},
Scala

I'm new to Scala ,just started learning it today.I would like to know how to initialize an array in scala.What is the equivalent of the above code in Scala ? To initialize an array filled with zeros, you can use:This is equivalent to Java's .Can also do more dynamic inits with fill, e.g.==>Additional to Vasil's answer: If you have the values given as a Scala collection, you can writeBut usually the toArray method is more handy:If you know Array's length but you don't know its content, you can use If you want to have two dimensions array but you don't know its content, you can useOf course, you can change String to other type. If you already know its content, you can useAnother way of declaring multi-dimentional arrays:"},
Scala

I am reading  and the concept of  makes perfect sense and easy to understand. But have two questions about :is easy to read but do we really need to write like that? I tried to implement it only with Future and without Promise like this:What is the difference between this and the given example and what makes a Promise necessary?The Promise and Future are complementary concepts. The Future is a value which will be retrieved, well, sometime in the future and you can do stuff with it when that event happens. It is, therefore, the read or out endpoint of a computation - it is something that you retrieve a value from.A Promise is, by analogy, the writing side of the computation. You create a promise which is the place where you'll put the result of the computation and from that promise you get a future that will be used to read the result that was put into the promise. When you'll complete a Promise, either by failure or success, you will trigger all the behavior which was attached to the associated Future.Regarding your first question, how can it be that for a promise p we have . You can imagine this like a single-item buffer - a container which is initially empty and you can afterwords store one value which will become its content forever. Now, depending on your point of view this is both a Promise and a Future. It is promise for someone who intends to write the value in the buffer. It is a future for someone who waits for that value to be put in the buffer.Specifically, for the Scala concurrent API, if you take a look at the Promise trait in  you can see how the methods from the Promise companion object are implemented :Now, those implementation of promises, DefaultPromise and KeptPromise can be found . They both extend a base little trait which happens to have the same name, but it is located in a different package:So you can see what they mean by . is the buffer I was referring above, while  is a buffer with the value put in from its very creation.Regarding your example, the future block you use there actually creates a promise behind the scenes. Let's look at the definition of  in  :By following the chain of methods you end up in the :So, as you can see, the result you get from your producer block gets poured into a promise.:Regarding the real-world use: Most of the time you won't deal with promises directly. If you'll use a library which performs asynchronous computation then you'll just work with the futures returned by the library's methods. Promises are, in this case, created by the library - you're just working with the reading end of what those methods do.But if you need to implement your own asynchronous API you'll have to start working with them.\nSuppose you need to implement an async HTTP client on top of, lets say, Netty. Then your code will look somewhat like this"},
Scala

I'm doing matching against some case classes and would like to handle two of the cases in the same way. Something like this:But when I do this I get the error:I can get it working of I remove the parameters from the definition of B and C but how can I match with the params?Looks like you don't care about the values of the String parameters, and want to treat B and C the same, so:If you must, must, must extract the parameter and treat them in the same code block, you could:Though I feel it would be much cleaner to factor that out into a method:There are a couple of ways that I can see to achieve what you are after, if you have some commonality between case classes. The first is to have the case classes extend a trait which declares the commonality, the second is to use a structural type which removes the need to extend your case classes.The structural type method generates a warning about erasure which, at present I'm not sure how to eliminate. Well, it doesn't really make sense, does it? B and C are mutually exclusive, so either sb or sc get bound, but you don't know which, so you'd need further selection logic to decide which to use (given that they were bound to a Option[String], not a String). So there's nothing gained over this:Or this:"},
Scala

I'm adding the Joda Time repository to SBT withThen I merrily use it like this:But, when I compile the project in SBT, I get a nasty:I tried the 2.0 version of joda-time, but get the same error.Add this dependency: It's an optional dependency of joda-time.\nI had to add it in my own project for the scala compiler to accept working with the joda-time jar.Your issue seems to be the same.Version is as at time of editing, latest versions can be found  I was running into a similar issue: Explicitly adding a dependency  resolved the issue."},
Scala

Take the following function:This pattern matches nicely:What I would like to be able to do is the following:This gives off the following error: I guess this is because it thinks that target is actually a name you'd like to assign to whatever the input is. Two questions:What you're looking for is a . In Scala, these must either start with an uppercase letter, or be surrounded by backticks.Both of these would be solutions to your problem:To avoid accidentally referring to variables that already existed in the enclosing scope, I think it makes sense that the default behaviour is for lowercase patterns to be variables and not stable identifiers. Only when you see something beginning with upper case, or in back ticks, do you need to be aware that it comes from the surrounding scope."},
Scala

I try to understand some Slick works and what it requires.Here it an example:Could somebody explain me what's the purpose of  method here, what is , why ? and what is Projection - method ' returns the instance of ? - Since no one else has answered, this might help to get you started. I don't know Slick very well.From the :In other words, slick needs to know how to deal with a row returned from the database. The method you defined uses their parser combinator functions to combine your column definitions into something that can be used on a row. "},
Scala

I've been programming in Scala for a while and I like it but one thing I'm annoyed by is the time it takes to compile programs.  It's seems like a small thing but with Java I could make small changes to my program, click the run button in netbeans, and BOOM, it's running, and over time compiling in scala seems to consume a lot of time.  I hear that with many large projects a scripting language becomes very important because of the time compiling takes, a need that I didn't see arising when I was using Java.But I'm coming from Java which as I understand it, is faster than any other compiled language, and is fast because of the reasons I switched to Scala(It's a very simple language).  So I wanted to ask, can I make Scala compile faster and will scalac ever be as fast as javac.The Scala compiler is more sophisticated than Java's, providing type inference, implicit conversion, and a much more powerful type system.  These features don't come for free, so I wouldn't expect scalac to ever be as fast as javac.  This reflects a trade-off between the programmer doing the work and the compiler doing the work.That said, compile times have already improved noticeably going from Scala 2.7 to Scala 2.8, and I expect the improvements to continue now that the dust has settled on 2.8.  documents some of the ongoing efforts and ideas to improve the performance of the Scala compiler.There are two aspects to the (lack of) speed for the Scala compiler.You should be aware that Scala compilation takes at least an order of magnitude longer than Java to compile. The reasons for this are as follows:The best way to do Scala is with IDEA and SBT. Set up an elementary SBT project (which it'll do for you, if you like) and run it in automatic compile mode (command ) and when you save your project, SBT will recompile it.You can also use the SBT plug-in for IDEA and attach an SBT action to each of your Run Configurations. The SBT plug-in also gives you an interactive SBT console within IDEA.Either way (SBT running externally or SBT plug-in), SBT stays running and thus all the classes used in building your project get \"warmed up\" and JIT-ed and the start-up overhead is eliminated. Additionally, SBT compiles only source files that need it. It is by far the most efficient way to build Scala programs.The latest revisions of  (Eclipse) are much better atmanaging incremental compilation.See \"\" for more.The other solution is to integrate  - (as illustrated in this ) as a builder in your IDE.But not in  Eclipse though, as  mentions in the comments:Finally, as  reminds me in the comments: also include some kind of \"incremental\" compilation (through ), even though it , and enhanced incremental compilation is in the work for the upcoming 0.9 sbt version.Use  - it is a fast scala compiler that sits as a background task and does not need loading all the time. It can reuse previous compiler instance.I'm not sure if Netbeans scala plugin supports fsc (documentation says so), but I couldn't make it work. Try nightly builds of the plugin.You can use the JRebel plugin which is free for Scala. So you can kind of \"develop in the debugger\" and JRebel would always reload the changed class on the spot. I read some statement somewhere by Martin Odersky himself where he is saying that the searches for implicits (the compiler must make sure there is not more than one single implicit for the same conversion to rule out ambiguities) can keep the compiler busy. So it might be a good idea to handle implicits with care.If it doesn't have to be 100% Scala, but also something similar, you might give  a try.-- OliverI'm sure this will be down-voted, but extremely rapid turn-around is not always conducive to quality or productivity.Take time to think more carefully and execute fewer development micro-cycles. Good Scala code is denser and more essential (i.e., free from incidental details and complexity). It demands more thought and that takes time (at least at first). You can progress well with fewer code / test / debug cycles that are individually a little longer and still improve your productivity and the quality of your work.In short: Seek an optimum working pattern better suited to Scala."},
Scala

What does Scala's @ operator do?For example, in the blog post  there is a something like thisIt enables one to bind a matched pattern to a variable. Consider the following, for instance:You can easily extract the content:But what if you wanted not the  of , but the option itself? That would be accomplished with this:Note that  can be used at  level, not just at the top level of the matching. can be used to bind a name to a successfully matched pattern, or subpattern. Patterns can be used in pattern matching, the left hand side of the  in for comprehensions, and in destructuring assigments.When pattern matching  binds  to the value matched by  if the pattern matches. In this case that means that the value of  will be  in that case-clause.Allows you to match the top-level of a pattern.  Example:It sets the value of  to the pattern which matches. In your example,  would therefore be  (as you could determine from a call to )"},
Scala

In what cases I should use Array(Buffer) and List(Buffer). Only one difference that I know is that arrays are nonvariant and lists are covariant. But what about performance and some other characteristics? The Scala  is an immutable recursive data structure which is such a fundamental structure in Scala, that you should (probably) be using it much more than an  (which is actually  - the  of  is ).If you are coming from a Java background, then the obvious parallel is when to use  over . The former is generally used for lists which are only ever  (and whose size is not known upfront) whereas the latter should be used for lists which either have a known size (or maximum size) or for which  is important.  provides a constant-time conversion to a  which is reason alone to use  if such later conversion is required.A scala  should be implemented on the JVM by a Java array, and hence an  may be much more performant (as an ) than a  (which will box its contents, unless you are using the very latest versions of Scala which have the new  feature).However, I think that the use of s in Scala should be kept to a minimum because it feels like you really need to know what is going on under the hood to decide whether your array really will be backed by the required primitive type, or may be boxed as a wrapper type. In addition to the answers posted already, here are some specifics.While an  is literally a Java array, a  is an immutable data structure that is either  (the empty list) or consists of a pair .So unless you need rapid random access or need to count batches of elements, a  is better than an .An Array is mutable, meaning you can change the values of each index, while a List (by default) is immutable, meaning that a new list is created every time you do a modification.  In most cases it is a more \"functional\" style to work with immutable datatypes and you should probably try and use a List with constructs like , ,  and so forth.For performance characteristics, an Array is faster with random access to elements, whereas a List is faster when prepending (adding) new elements.  Iterating over them is comparable.  "},
Scala

I am new to Scala and I could not really find a lot about the  keyword. I am trying to understand what the following expression may mean: is some kind of an alias, but what does it signify?Yes, the   is just a shorthand for Type aliases are often used to keep the rest of the code simple: you can now writewhich will be interpreted by the compiler asThis helps to avoid defining many custom types that are just tuples or functions defined on other types, for example.There are also several other interesting use cases for , as described for example in  of .Actually the  keyword in Scala can do much more than just aliasing a complicated type to a shorter name. It introduces .As you know, a class can have field members and method members. Well, Scala also allows a class to have type members.In your particular case  is, indeed, introducing an alias that allows you to write more concise code. The type system just replaces the alias with the actual type when type-checking is performed.But you can also have something like thisLike any other member of a class, type members can also be abstract (you just don't specify what their value actually is) and can be overridden in implementations.Type members can be viewed as dual of generics since much of the things you can implement with generics can be translated into abstract type members.So yes, they can be used for aliasing, but don't limit them to just this, since they are a powerful feature of Scala's type system.Please see this excellent answer for more details:Just an example to see how to use \"type\" as alias : The definition above defines Action to be an alias of the type of procedures(methodes) that take an empty parameter list and that return Unit."},
Scala

What is a standard way of profiling Scala method calls?What I need are hooks around a method, using which I can use to start and stop Timers.In Java I use aspect programming, aspectJ, to define the methods to be profiled and inject bytecode to achieve the same.Is there a more natural way in Scala, where I can define a bunch of functions to be called before and after a function without losing any static typing in the process?Do you want to do this without changing the code that you want to measure timings for? If you don't mind changing the code, then you could do something like this:In addition to Jesper's answer, you can automatically wrap method invocations in the REPL:Now - let's wrap anything in thisOK - we need to be in power modeWrap awayI have no idea why that printed stuff out 5 timesUpdate as of 2.12.2:There are  that you can avail of. Since the URLs on the linked site are likely to change, I am pasting the relevant content below.This what I use: might be useful.I use a technique that's easy to move around in code blocks. The crux is that the same exact line starts and ends the timer - so it is really a simple copy and paste. The other nice thing is that you get to define what the timing means to you as a string, all in that same line.Example usage:The code:Pros: Cons: I like the simplicity of @wrick's answer, but also wanted:This is achieved here:For even more accuracy, a simple modification allows a JVM Hotspot warmup loop (not timed) for timing small snippets: is a nice library to perform benchmarking in ScalaBelow is a simple exampleIf you execute above code snippet in Scala Worksheet you get the running time in millisecondsWhile standing on the shoulders of giants...A solid 3rd-party library would be more ideal, but if you need something quick and std-library based, following variant provides:.Also worth noting you can use the  method to convert to the biggest time unit possible, although I am not sure how friendly this is with minor time difference between runs e.g.You can use : Usage:nanoTime will show you , so it will hard to see. So I suggest that you can use currentTimeMillis instead of it."},
Scala

One of the new features of Scala 2.8 are context bounds. What is a context bound and where is it useful?Of course I searched first (and found for example ) but I couldn't find any really clear and detailed information.Did you find ?  It covers the new context bound feature, within the context of array improvements.  Generally, a type parameter with a  is of the form ; it is expanded to plain type parameter  together with an implicit parameter of type .  Consider the method  which forms an array from the results of applying\na given function f on a range of numbers from 0 until a given length. Up to Scala 2.7, tabulate could be\nwritten as follows:In Scala 2.8 this is no longer possible, because runtime information is necessary to create the right representation of . One needs to provide this information by passing a  into the method as an implicit parameter:As a shorthand form, a  can be used on the type parameter  instead, giving:Robert's answer covers the techinal details of Context Bounds. I'll give you my interpretation of their meaning.In Scala a View Bound () captures the concept of 'can be seen as' (whereas an upper bound  captures the concept of 'is a'). A context bound () says 'has a' about a type. You can read the examples about manifests as \" has a \". The example you linked to about  vs  illustrates the difference. A methodsays that the parameter can be seen as an . Compare withwhich says that the parameter has an associated .In terms of use, I don't think conventions are properly established (because context bounds are new).  One suggestion is that their use is preferred when you need to transfer an implicit definition from one scope to another without needing to refer to it directly (this is certainly the case for the   used to create an array).Another way of thinking about view bounds and context bounds is that the first transfers implicit conversions from the caller's scope. The second transfers implicit objects from the caller's scope.Context Bounds actually generalize View Bounds.So, given this code expressed with a View Bound:This could also be expressed with a Context Bound, with the help of a type alias representing functions from type  to type .A context bound must be used with a type constructor of kind . However the type constructor  is of kind . The use of the type alias partially applies second type parameter with the type , yielding a type constructor of the correct kind for use as a context bound.There is a proposal to allow you to directly express partially applied types in Scala, without the use of the type alias inside a trait. You could then write:As , a context bound represents a \"has-a\" constraint between a type parameter and a type class.  Put another way, it represents a constraint that an implicit value of a particular type class exists.When utilizing a context bound, one often needs to surface that implicit value. For example, given the constraint , one will often need the instance of  that satisfies the constraint.  , it's possible to access the implicit value by using the  method or a slightly more helpful  method:or "},
Scala

One of the most powerful patterns available in Scala is the enrich-my-library* pattern, which uses implicit conversions to  to add methods to existing classes without requiring dynamic method resolution.  For example, if we wished that all strings had the method  that counted how many whitespace characters they had, we could:Unfortunately, this pattern runs into trouble when dealing with generic collections.  For example, a number of questions have been asked about .  There is nothing built in that works in one shot, so this seems an ideal candidate for the enrich-my-library pattern using a generic collection  and a generic element type :except, of course, it .  The REPL tells us:There are two problems: how do we get a  from an empty  list (or from thin air)?  And how do we get a  back from the  line instead of a ?*The key to understanding this problem is to realize that there are  in the collections library.  One is the public collections interface with all its nice methods.  The other, which is used extensively in  the collections library, but which are almost never used outside of it, is the builders.Our problem in enriching is exactly the same one that the collections library itself faces when trying to return collections of the same type.  That is, we want to build collections, but when working generically, we don't have a way to refer to \"the same type that the collection already is\".  So we need .Now the question is: where do we get our builders from?  The obvious place is from the collection itself.  .  We already decided, in moving to a generic collection, that we were going to forget the type of the collection.  So even though the collection could return a builder that would generate more collections of the type we want, it wouldn't know what the type was.Instead, we get our builders from  implicits that are floating around.  These exist specifically for the purpose of matching input and output types and giving you an appropriately typed builder.So, we have two conceptual leaps to make:Let's look at an example.Let's take this apart.  First, in order to build the collection-of-collections, we know we'll need to build two types of collections:  for each group, and  that gathers all the groups together.  Thus, we need two builders, one that takes s and builds s, and one that takes s and builds s.  Looking at the type signature of , we seewhich means that CanBuildFrom wants to know the type of collection we're starting with--in our case, it's , and then the elements of the generated collection and the type of that collection.  So we fill those in as implicit parameters  and .Having realized this, that's most of the work.  We can use our s to give us builders (all you need to do is apply them).  And one builder can build up a collection with , convert it to the collection it is supposed to ultimately be with , and empty itself and be ready to start again with .  The builders start off empty, which solves our first compile error, and since we're using builders instead of recursion, the second error also goes away.One last little detail--other than the algorithm  that actually does the work--is in the implicit conversion.  Note that we use  not .  This is because the class declaration was for  with one parameter, which it fills it itself with the  passed to it.  So we just hand it the type , and let it create  out of it.  Minor detail, but you'll get compile-time errors if you try another way.Here, I've made the method a little bit more generic than the \"equal elements\" collection--rather, the method cuts the original collection apart whenever its test of sequential elements fails.Let's see our method in action:It works!The only problem is that we don't in general have these methods available for arrays, since that would require two implicit conversions in a row.  There are several ways to get around this, including writing a separate implicit conversion for arrays, casting to , and so on.Edit: My favored approach for dealing with arrays and strings and such is to make the code even  generic and then use appropriate implicit conversions to make them more specific again in such a way that arrays work also.  In this particular case: Here we've added an implicit that gives us an  from --for most collections this will just be the identity (e.g.  already is an ), but for arrays it will be a real implicit conversion.  And, consequently, we've dropped the requirement that --we've basically just made the requirement for  explicit, so we can use it explicitly at will instead of having the compiler fill it in for us.  Also, we have relaxed the restriction that our collection-of-collections is --instead, it's any , which we will fill in later to be what we want.  Because we're going to fill this in later, we've pushed it up to the class level instead of the method level.  Otherwise, it's basically the same.Now the question is how to use this.  For regular collections, we can:where now we plug in  for  and  for .  Note that we do need the explicit generic types on the call to  so it can keep straight which types correspond to what.  Thanks to the , this automatically handles arrays.But wait, what if we want to use strings?  Now we're in trouble, because you can't have a \"string of strings\".  This is where the extra abstraction helps: we can call  something that's suitable to hold strings.  Let's pick , and do the following:We need a new  to handle the building of a vector of strings (but this is really easy, since we just need to call ), and then we need to fill in all the types so that the  is typed sensibly.  Note that we already have floating around a  CanBuildFrom, so strings can be made from collections of chars.Let's try it out:As of  it's a lot easier to \"enrich\" Scala collections than it was when Rex gave his excellent answer. For simple cases it might look like this,which adds a \"same result type\" respecting  operation to all s,And for the example from the question, the solution now looks like,Sample REPL session,Again, note that the same result type principle has been observed in exactly the same way that it would have been had  been directly defined on .As of  the magic incantation is slightly changed from what it was when Miles gave his excellent answer.The following works, but is it canonical?  I hope one of the canons will correct it.  (Or rather, cannons, one of the big guns.)  If the view bound is an upper bound, you lose application to Array and String.  It doesn't seem to matter if the bound is GenTraversableLike or TraversableLike; but IsTraversableLike gives you a GenTraversableLike.There's more than one way to skin a cat with nine lives.  This version says that once my source is converted to a GenTraversableLike, as long as I can build the result from GenTraversable, just do that. I'm not interested in my old Repr.This first attempt includes an ugly conversion of Repr to GenTraversableLike."},
Scala

How does the following compile:What is actually going on here?There are a few things going on. First, Scala allows dots and parens to be omitted from many method calls, so  is equivalent to *.Second, an \"implicit conversion\" is applied. Since  is an  and  has no  method, the compiler searches for an implicit conversion that takes an  and returns something that  a  method, with the search constrained by the scope of your method call.You have imported  into your scope. Since  is an implicit class with an  parameter, its constructor defines an implicit  conversion.  has a  method, so it satisfies all the search criteria. Therefore, the compiler rewrites your call as **. *I mean this loosely.  is actually invalid because the  method has no parameter list and therefore the parens  be omitted on the method call.**Actually, this isn't quite true because  is a value class, so the compiler will avoid wrapping the integer if possible. The \"magic\" that's going on there is called \"implicit conversion\". You are importing the implicit conversions, and some of them handle the conversion between Int (and Double) to Duration. That's what's you are dealing with."},
Scala

I know that artificial benchmarks are evil. They can show results only for very specific narrow situation. I don't assume that one language is better than the other because of the some stupid bench. However I wonder why results is so different. Please see my questions at the bottom.Benchmark is simple math calculations to find pairs of prime numbers which differs by 6 (so called )\nE.g. sexy primes below 100 would be: \nRunning: all except Factor was running in VirtualBox (Debian unstable amd64 guest, Windows 7 x64 host)\nCPU: AMD A4-3305M[*1] - I'm afraid to imagine how much time will it takeC:Ruby:Scala:Scala opimized  (the same idea like in Clojure optimization):Clojure:Clojure optimized :PythonFactorBash(zsh):Rough answers:Most important optimisation in the Clojure code would be to use typed primitive maths within , something like:With this improvement, I get Clojure completing 10k in 0.635 secs (i.e. the second fastest on your list, beating Scala) note that you have printing code inside your benchmark in some cases - not a good idea as it will distort the results, especially if using a function like  for the first time causes initialisation of IO subsystems or something like that!I'll answer just #2, since it's the only one I've got anything remotely intelligent to say, but for your Python code, you're creating an intermediate list in , whereas you're using  in your  in Ruby which is just iterating.If you change your  to:they're on par.I could optimize the Python further, but my Ruby isn't good enough to know when I've given more of an advantage (e.g., using  makes Python win on my machine, but I don't remember if the Ruby range you used creates an entire range in memory or not). Without being too silly, making the Python code look like:which doesn't change much more, puts it at 1.5s for me, and, with being extra silly, running it with PyPy puts it at .3s for 10K, and 21s for 100K.Here's a fast Clojure version, using the same basic algorithms:It runs about 20x faster than your original on my machine. And here's a version that leverages the new reducers library in 1.5 (requires Java 7 or JSR 166):This runs about 40x faster than your original. On my machine, that's 100k in 1.5 seconds.You can make the Scala a lot faster by modifying your  method toNot quite as concise but the program runs in 40% of the time! We cut out the superfluous  and anonymous  objects, the Scala compiler recognizes the tail-recursion and turns it into a while-loop, which the JVM can turn into more or less optimal machine code, so it shouldn't be too far off the C version.See also: Here is my scala version in both parallel and no-parallel, just for fun:\n(In my dual core compute, the parallel version takes 335ms while the no-parallel version takes 655ms)EDIT: According to 's suggestion, I have changed my code to avoid the effects of IO and jvm warmup:The result shows in my compute:Never mind the benchmarks; the problem got me interested and I made some fast tweaks.  This uses the  decorator, which memoizes a function; so when we call  we basically get that prime check for free.  This change cuts the work roughly in half.  Also, we can make the  calls step through just the odd numbers, cutting the work roughly in half again.This requires Python 3.2 or newer to get , but could work with an older Python if you install a Python recipe that provides .  If you are using Python 2.x you should really use  instead of .The above took only a very short time to edit.  I decided to take it one step further, and make the primes test only try prime divisors, and only up to the square root of the number being tested.  The way I did it only works if you check numbers in order, so it can accumulate all the primes as it goes; but this problem was already checking the numbers in order so that was fine.On my laptop (nothing special; processor is a 1.5 GHz AMD Turion II \"K625\") this version produced an answer for 100K in under 8 seconds.The above code is pretty easy to write in Python, Ruby, etc. but would be more of a pain in C.You can't compare the numbers on this version against the numbers from the other versions without rewriting the others to use similar tricks.  I'm not trying to prove anything here; I just thought the problem was fun and I wanted to see what sort of easy performance improvements I could glean.Don't forget Fortran!  (Mostly joking, but I would expect similar performance to C).  The statements with exclamation points are optional, but good style. ( is a comment character in fortran 90)I couldn't resist to do a few of the most obvious optimizations for the C version which made the 100k test now take 0.3s on my machine (5 times faster than the C version in the question, both compiled with MSVC 2010 /Ox).Here is the identical implemention in Java:With Java 1.7.0_04 this runs almost exactly as fast as the C version. Client or server VM doesn't show much difference, except that JIT training seems to help the server VM a bit (~3%) while it has almost no effect with the client VM. The output in Java seems to be slower than in C. If the output is replaced with a static counter in both versions, the Java version runs a little faster than the C version.These are my times for the 100k run:and the 1M run (16386 results):While this does not really answer your questions, it shows that small tweaks can have a noteworthy impact on performance. So to be able to really compare languages you should try to avoid all algorithmic differences as much as possible.It also gives a hint why Scala seems rather fast. It runs on the Java VM and thus benefits from its impressive performance.In Scala try using Tuple2 instead of List, it should go faster. Just remove the word 'List' since (x, y) is a Tuple2.Tuple2 is specialized for Int, Long and Double meaning it won't have to box/unbox those raw datatypes. . List isn't specialized. .Here's the code for the Go (golang.org) version:It ran just as fast as the C version.\nIntel Core 2 Duo T6500 2.1GHz, 2MB L2 cache, 800MHz FSB.\n4GB RAM The 100k version:  With 1000000 (1M instead of 100K):   But I think that it would be fair to use Go's built in multithreading capabilities and compare that version with the regular C version (without multithreading), just because it's almost too easy to do multithreading with Go.Update: I did a parallel version using Goroutines in Go:The parallelized version completed in 1.706 seconds. It used less than 1.5 Mb RAM. Fixed with a call to Update: I ran the paralellized version up to 1M numbers.  With 1000000 (1M instead of 100K):    The 100k version:   Based on , I wrote a scala version using recursion, and I improved on it by only going to the sqrt instead of x/2 for the prime check function. I get ~250ms for 100k, and ~600ms for 1M. I went ahead and went to 10M in ~6s.I also went back and wrote a CoffeeScript (V8 JavaScript) version, which gets ~15ms for 100k, 250ms for 1M, and 6s for 10M, by using a counter (ignoring I/O). If I turn on the output it takes ~150ms for 100k, 1s for 1M, and 12s for 10M. Couldn't use tail recursion here, unfortunately, so I had to convert it back into loops.Just for the fun of it, here is a parallel Ruby version. On my 1.8GHz Core i5 MacBook Air, the performance results are:It looks like the JVM's JIT is giving Ruby a nice performance boost in the default case, while true multithreading helps JRuby perform 50% faster in the threaded case. What's more interesting is that JRuby 1.7 improves the JRuby 1.6 score by a healthy 17%!The answer to your question #1 is that Yes, the JVM is incredably fast and yes static typing helps.The JVM should be faster than C in the long run, possibly even faster than \"Normal\" assembly language--Of course you can always hand optimize assembly to beat anything by doing manual runtime profiling and creating a separate version for each CPU, you just have to be amazingly good and knowledgable.The reasons for Java's speed are: The JVM can analyze your code while it runs and hand-optimize it--for instance, if you had a method that could be statically analyzed at compile time to be a true function and the JVM noticed that you were often calling it with the same parameters, it COULD actually eliminate the call completely and just inject the results from the last call (I'm not sure if Java actually does this exactly, but it doest a lot of stuff like this). Due to static typing, the JVM can know a lot about your code at compile time, this lets it pre-optimize quite a bit of stuff.  It also lets the compiler optimize each class individually without knowledge of how another class is planning to use it.  Also Java doesn't have arbitrary pointers to memory location, it KNOWS what values in memory may and may not be changed and can optimize accordingly.Heap allocation is MUCH more efficient than C, Java's heap allocation is more like C's stack allocation in speed--yet more versatile.  A lot of time has gone into the different algroithims used here, it's an art--for instance, all the objects with a short lifespan (like C's stack variables) are allocated to a \"known\" free location (no searching for a free spot with enough space) and are all freed together in a single step (like a stack pop). The JVM can know quirks about your CPU architecture and generate machine code specifically for a given CPU.The JVM can speed your code long after you shipped it.  Much like moving a program to a new CPU can speed it up, moving it to a new version of the JVM can also give you huge speed performances taylored to CPUs that didn't even exist when you initially compiled your code, something c physically cannot do without a recomiple.By the way, most of the bad rep for java speed comes from the long startup time to load the JVM (Someday someone will build the JVM into the OS and this will go away!) and the fact that many developers are really bad at writing GUI code (especially threaded) which caused Java GUIs to often become unresponsive and glitchy.  Simple to use languages like Java and VB have their faults amplified by the fact that the capibilities of the average programmer tends to be lower than more complicated languages."},
Scala

I need some code samples (and I also really curious about them) of Scala and Java code which show that Scala code is more simple and concise then code written in Java (of course both samples should solve the same problem).If there is only Scala sample with comment like \"this is abstract factory in Scala, in Java it will look much more cumbersome\" then this is also acceptable.Thanks!I like most of all accepted and  answersLet's improve  and use Scala's :The above Scala class contains all features of the below Java class,  - for example it supports  (which Java doesn't have). Scala 2.8 adds named and default arguments, which are used to generate a  for case classes, which gives the same ability as the with* methods of the following Java class.Then, in usage we have (of course):AgainstI found this one impressiveJavaScalaAs well as these ones (sorry for not pasting, I didn't want to steal the code) Write a program to index a list of keywords (like books).You have a list  of objects of class  that has fields  and . Your task is to sort this list first by , and then by .Since I wrote this answer, there has been quite some progress. The lambdas (and method references)have finally landed in Java, and they are taking the Java world by storm.This is what the above code will look like with  (contributed by @fredoverflow):While this code is almost as short, it does not work quite as elegantly as the Scala one. In Scala solution, the  method accepts a function  where  is required to  an .  is a type-class. Think best of both worlds: Like , it's implicit for the type in question, but like , it's extensible and can be added retrospectively to types that did not have it. Since Java lacks type-classes, it has to duplicate every such method, once for , then for . For example, see  and  .The type-classes allow one to write rules such as \"If A has ordering and B has ordering, then their tuple (A, B) also has ordering\". In code, that is:That is how the  in our code can compare by name and then by age. Those semantics will be encoded with the above \"rule\". A Scala programmer would intuitively expect this to work this way. No special purpose methods like  had to be added to .Lambdas and method references are just a tip of an iceberg that is functional programming. :) You have got an XML file \"company.xml\" that looks like this:You have to read this file and print the  and  fields of all the employees.\n\n [ taken from  ]\n [ taken from , slide #19 ] Hmm, how to do it without replying in an unformatted reply section... Hmph.  I guess I'll edit your answer and let you delete it if it bugs you.This is how I would do it in Java with better libraries:This is just a quick hack involving no magic and all reusable components.  If I wanted to add some magic I could do something better than returning an array of string arrays, but even as is this GoodXMLLib would be completely reusable.  The first parameter of scanFor is the section, all future parameters would be the items to find which is limited, but the interface could be buffed slightly to add multiple levels of matching with no real problem.I will admit that Java has some pretty poor library support in general, but come on--to compare a horrible usage of Java's decade(?) old XML library to an implementation done based on being terse is just not fair--and is far from a comparison of the languages!A map of actions to perform depending on a string.Java 7:Scala:And it's all done in the best possible taste!Java 8:I liked this simple example of sorting and transformation, taken from David Pollak's 'Beginning Scala' book:In Scala:In Java:I'm writing a Blackjack game in Scala now. Here is how my dealerWins method would look in Java:Here's how it looks in Scala:Hooray for higher-order functions!Java 8 solution:I liked   so much I'm going to try to improve upon it. The code below is  a direct translation of the Java example, but it accomplishes the same task with the same API.I like much the method getOrElseUpdate, found in mutableMap and shown here, first Java, without: yes - a WordCount, and here in scala: And here it is in Java 8:And if you want to go 100% functional: and  have already been shown, but look how easy they are integrated with the map:This is a very simple example: Square integers and then add themIn scala:Compact map applies the function to all elements of the array, so:Fold left is will start with 0 as the accumulator (s) and apply  to all the elements (i) of the array, so that:Now this can be further compacted to:This one I will not try in Java (to much work), turn XML to a Map: Another one liner to get the map from the XML:How about Quicksort?The following is a java example found via a google search, the URL is A quick attempt at a Scala version. Open season for code improvers ;@) you need to design a method that will execute any given code asynchronously. \nSolution in :The same thing in  (using actors):The Circuit Breaker pattern from  in  \n() implementation looks like this in Scala: Which I think is super nice. It looks just as a pice of the language but it is a simple mixin in the  doing all work. Reference in other languages Google for \"Circuit breaker\" + your language. Why nobody posted this before:Java:116 characters.Scala:56 characters.I am preparing a document that gives several examples of Java and Scala code, utilising only the simple to understand features of Scala:If you would like me to add something to it, please reply in the comments.Lazily evaluated infinite streams are a good example:Here is a question addressing infinite streams in Java: Another good example are first class functions and closures:Java doesn't support first class functions, and mimicking closures with anonymous inner classes isn't very elegant.  Another thing this example shows that java can't do is running code from an interpreter/REPL. I find this immensely useful for quickly testing code snippets.This Scala code......would be completely unreadable in Java, if possible at all."},
Scala

What is the best way to do an inverse sort in scala?  I imagine the following is somewhat slow.Is there a conveinient way of using sortBy but getting a reverse sort?  I would rather not need to use .There may be the obvious way of changing the sign, if you sort by some numeric valueMore generally, sorting may be done by method sorted with an implicit Ordering, which you may make explicit, and Ordering has a reverse (not the list reverse below)\nYou can do If the ordering you want to reverse is the implicit ordering, you can get it by implicitly[Ordering[A]] (A the type you're ordering on) or better Ordering[A]. That would besortBy is like using Ordering.by, so you can doMaybe not the shortest to write (compared to minus) but intent is clearThe last line does not work. To accept the  in , the compiler needs to know on which type we are ordering, so that it may type the . It may seems that would be the type of the element of the list, but this is not so, as the signature of sorted is\n. The ordering may be on , but also on any ancestor of  (you might use ). And indeed, the fact that list is covariant forces this signature. \nOne can dobut this is much less pleasant.maybe to shorten it a little more:Easy peasy (at least in case of ): has implicit parameter  which provides orderingso, we can define own  objectBoth  and  have a compact syntax:I find the one with  easier to understand.Another possibility in cases where you pass a function that you may not be able to modify directly to an Arraybuffer via sortWith for example:this is my code ;)val wordCounts = logData.flatMap(line => line.split(\" \")).map(word => (word, 1)).reduceByKey((a, b) => a + b)wordCounts.sortBy(- _._2).collect()"},
Scala

There are path dependent types and I think it is possible to express almost all the features of such languages as Epigram or Agda in Scala, but I'm wondering why Scala does not support  more explicitly like it does very nicely in other areas (say, DSLs) ?\nAnything I'm missing like \"it is not necessary\" ?Syntactic convenience aside, the combination of singleton types, path-dependent types and implicit values means that Scala has surprisingly good support for dependent typing, as I've tried to demonstrate in .Scala's intrinsic support for dependent types is via . These allow a type to depend on a selector path through an object- (ie. value-) graph like so,In my view, the above should be enough to answer the question \"Is Scala a dependently typed language?\" in the positive: it's clear that here we have types which are distinguished by the values which are their prefixes.However, it's often objected that Scala isn't a \"fully\" dependently type language because it doesn't have  as found in Agda or Coq or Idris as intrinsics. I think this reflects a fixation on form over fundamentals to some extent, nevertheless, I'll try and show that Scala is a lot closer to these other languages than is typically acknowledged.Despite the terminology, dependent sum types (also known as Sigma types) are simply a pair of values where the type of the second value is dependent on the first value. This is directly representable in Scala,and in fact, this is a crucial part of the  in Scala prior to 2.10 (or earlier via the experimental -Ydependent-method types Scala compiler option).Dependent product types (aka Pi types) are essentially functions from values to types. They are key to the representation of  and the other poster children for dependently typed programming languages. We can encode Pi types in Scala using a combination of path dependent types, singleton types and implicit parameters. First we define a trait which is going to represent a function from a value of type T to a type U,We can than define a polymorphic method which uses this type,(note the use of the path-dependent type  in the result type ). Given a value of type T, this function will return a(n empty) list of values of the type corresponding to that particular T value.Now let's define some suitable values and implicit witnesses for the functional relationships we want to hold,And now here is our Pi-type-using function in action,(note that here we use Scala's  subtype-witnessing operator rather than  because  and  are singleton types and hence more precise than the types we are verifying on the RHS).In practice, however, in Scala we wouldn't start by encoding Sigma and Pi types and then proceeding from there as we would in Agda or Idris. Instead we would use path-dependent types, singleton types and implicits directly. You can find numerous examples of how this plays out in shapeless: , , , ,  etc. etc.The only remaining objection I can see is that in the above encoding of Pi types we require the singleton types of the depended-on values to be expressible. Unfortunately in Scala this is only possible for values of reference types and not for values of non-reference types (esp. eg. Int). This is a shame, but not an intrinsic difficulty: Scala's type checker represents the singleton types of non-reference values internally, and there have been a  of  in making them directly expressible. In practice we can work around the problem with a .In any case, I don't think this slight domain restriction can be used as an objection to Scala's status as a dependently typed language. If it is, then the same could be said for Dependent ML (which only allows dependencies on natural number values) which would be a bizarre conclusion.I would assume it is because (as I know from experience, having used dependent types in the Coq proof assistant, which fully supports them but still not in a very convenient way) dependent types are a very advanced programming language feature which is really hard to get right - and can cause an exponential blowup in complexity in practice. They're still a topic of computer science research.I believe that Scala's path-dependent types can only represent \u03a3-types, but not \u03a0-types. This:is not exactly a \u03a0-type. By definition, \u03a0-type, or dependent product, is a function which result type depends on argument value, representing universal quantifier, i.e. \u2200x: A, B(x). In the case above, however, it depends only on type T, but not on some value of this type. Pi trait itself is a \u03a3-type, an existential quantifier, i.e. \u2203x: A, B(x). Object's self-reference in this case is acting as quantified variable. When passed in as implicit parameter, however, it reduces to an ordinary type function, since it is resolved type-wise. Encoding for dependent product in Scala may look like the following:The missing piece here is an ability to statically constraint field x to expected value t, effectively forming an equation representing the property of all values inhabiting type T. Together with our \u03a3-types, used to express the existence of object with given property, the logic is formed, in which our equation is a theorem to be proven.On a side note, in real case theorem may be highly nontrivial, up to the point where it cannot be automatically derived from code or solved without significant amount of effort. One can even formulate Riemann Hypothesis this way, only to find the signature impossible to implement without actually proving it, looping forever or throwing an exception."},
Scala

I have been trying:vs:and they seem to behave the same although I couldn't find anywhere saying that  expands to  so my question is, are these\nidentical/similar?On a side note, I have been trying to use  on these code pieces and they\nproduce the same code except for an extra line in the second one. How do I\nread that extra line?This is barely a constructor parameter. If this variable is not used anywhere except the constructor, it remains there. No field is generated. Otherwise  field is created and value of  parameter is assigned to it. No getter is created.Such declaration of parameter will create  field with private getter. This behavior is the same as above no matter if the parameter was used beside the constructor (e.g. in  or not).Same as above but Scala-like getter is public in case classesWhen case classes are involved, by default each parameter has  modifier.In the first case,  is only a constructor parameter. Since the main constructor is the content of the class itself, it is accessible in it, but only from this very instance. So it is almost equivalent to:On the other hand, in the second case  is a  private field, so it is accessible to this instance  other instances of .\nFor example, this compiles fine:And runs:But this doesn't:"},
Scala

I would like to be able to find a match between the first letter of a word, and one of the letters in a group such as \"ABC\". In pseudocode, this might look something like:But how do I grab the first letter in Scala instead of Java? How do I express the regular expression properly? Is it possible to do this within a ?You can do this because regular expressions define extractors but you need to define the regex pattern first.  I don't have access to a Scala REPL to test this but something like this should work.Since version 2.10, one can use Scala's string interpolation feature:Even better one can bind regular expression groups:It is also possible to set more detailed binding mechanisms:An impressive example on what's possible with  is shown in the blog post :As delnan pointed out, the  keyword in Scala has nothing to do with regexes. To find out whether a string matches a regex, you can use the  method. To find out whether a string starts with an a, b or c in lower or upper case, the regex would look like this:You can read this regex as \"one of the characters a, b, c, A, B or C followed by anything\" ( means \"any character\" and  means \"zero or more times\", so \".*\" is any string).To expand a little on : The fact that regular expressions define extractors can be used to decompose the substrings matched by the regex very nicely using Scala's pattern matching, e.g.:Note that the approach from @AndrewMyers's answer matches the  string to the regular expression, with the effect of anchoring the regular expression at both ends of the string using  and . Example:And with no  at the end:String.matches is the way to do pattern matching in the regex sense.But as a handy aside, word.firstLetter in real Scala code looks like:Scala treats Strings as a sequence of Char's, so if for some reason you wanted to explicitly get the first character of the String and match it, you could use something like this:I'm not proposing this as the general way to do regex pattern matching, but it's in line with your proposed approach to first find the first character of a String and then match it against a regex.EDIT:\nTo be clear, the way I would do this is, as others have said:Just wanted to show an example as close as possible to your initial pseudocode. Cheers!First we should know that regular expression can separately be used. Here is an example:Second we should notice that combining regular expression with pattern matching would be very powerful. Here is a simple example.In fact, regular expression itself is already very powerful; the only thing we need to do is to make it more powerful by Scala. Here are more examples in Scala Document:  "},
Scala

I am diving into Scala and noticed sbt. I have been quite happy with Gradle in java/groovy projects, and I know there's a scala plugin for Gradle.What could be good reasons to favour sbt over Gradle in a Scala project?Note that one key difference between SBT and Gradle is its : mentions that the all situation could evolve in the future:(both tools can )For me the key features of SBT are:The downsides are:sbt is a Scala DSL and for it Scala is a first class citizen, so in principal it seems to be a good fit.But sbt suffers from major incompatible changes between versions, which makes it hard to find the correct working plugin for a task and get it to work.I personally gave up on sbt, since it was causing more problems than it solved. I actually switched to gradle.Go figure.I'm fairly new to gradle, and very new to sbt - what I really like about sbt so far is the interactive console. It allows me to use commands like 'inspect' to get a better idea of what's going on. AFAIK gradle does not provide something like this atm.Sbt and gradle, both are based on statically typed languages....but sbt has few advantages:"},
Scala

If I have an  and a corresponding  I can run them together:If the enumerator monad is \"bigger\" than the iteratee monad, I can use  or, more generally,  to \"lift\" the iteratee to match:But what do I do when the iteratee monad is \"bigger\" than the enumerator monad?There doesn't seem to be a  instance for , nor any obvious \"lift\" method."},
Scala

All roads lead to Rome, and that is the same for SBT: To get started with  there is , , , etc, and then there are different ways to include and decide on repositories. I'm asking because sometimes I get a little lost. The SBT documentation is very thorough and complete, but I find myself not knowing when to use  or  or  or .Then it becomes fun, there is the  and  -  What comes first, the chicken or the egg? Do I just pull out a machette and start hacking my way forward? I quite often find projects that include everything and the kitchen sink, and then I realize - I'm not the only one who gets a little lost.As a simple example, right now, I'm starting a brand new project. I want to use the latest features of  and  and this will probably require the latest version of SBT.  In what file should I define it and how should it look? I know I can get this working, but I would really like an expert opinion on where everything should go (why it should go there will be a bonus).I've been using  for small projects for well over a year now. I used  and then  (as it made some headaches magically disappear), but I'm not sure why I should be using the one or the other. I'm just getting a little frustrated for not understanding how things fit together ( and repositories), and think it will save the next guy coming this way a lot of hardship if this could be explained in human terms.For Scala-based dependencies, I would go with what the authors recommend. For instance:  indicates to use:Or  has instructions on where to add:For Java-based dependencies, I use  to see what's out there, then click on the SBT tab. For instance  indicates to use:Then pull out the machette and start hacking your way forward. If you are lucky you don't end up using jars that depends on some of the same jars but with incompatible versions. Given the Java ecosystem, you often end up including everything and the kitchen sink and it takes some effort to eliminate dependencies or ensure you are not missing required dependencies. I think the sane point is to . Make sure you understand:Keep those 4 pages open at all times so that you can jump and look up various definitions and examples:Make maximum use of  and   to get familiar with actual values of settings, their dependencies, definitions and related settings. I don't believe the relationships you'll discover using  are documented anywhere. If there is a better way I want to know about it.The way I use sbt is:I don't bother checking in the IDE project files since they are generated by sbt, but there may be reasons you want to do that.You can see an example set up like this .Use Typesafe Activator, a fancy way of calling sbt, which comes with project templates and seeds : "},
Scala

I started to learn Scala and almost in every tutorial I see a  file which describes project settings. But now I have installed  and created a project from template. And generated project from template missed  file, but it have  (which seems used for same purposes, but it is more flexible).   So what is the difference between  and ?\nWhich is more preferred and why?To give a brief example, this :is a shorthand notation roughly equivalent to this :The  file can also include s, s, and s (but not s and es).See , particularly the section \"Relating build.sbt to Build.scala\".Consider a  build definition if you're doing something complicated where you want the full expressiveness of Scala.Update July 2016 (3 years later) is officially deprecated in   implements that deprecation.\n\"\" has been updated.When s are being compiled, they are before that sort of merged with the  files inside  directory. They can't be used in recursive tasks, that is, you can't customize  from , for example. For more detailed information, consider reading related section is sbt documentation: "},
Scala

While there might be valid cases where such method overloadings could become ambiguous, why does the compiler disallow code which is neither ambiguous at compile time nor at run time?Example:Are there any reasons why these restrictions can't be loosened a bit?Especially when converting heavily overloaded Java code to Scala default arguments are a very important and it isn't nice to find out after replacing plenty of Java methods by one Scala methods that the spec/compiler imposes arbitrary restrictions.I'd like to cite Lukas Rytz (from ):A solution for future Scala version could be to incorporate  of the non-default arguments (those at the beginning of a method, which disambiguate overloaded versions) into the naming schema, e.g. in this case:it would be something like:Someone willing to ?It would be very hard to get a readable and precise spec for the interactions of overloading resolution with default arguments. Of course, for many individual cases, like the one presented here, it's easy to say what should happen. But that is not enough. We'd need a spec that decides all possible corner cases. Overloading resolution is already very hard to specify. Adding default arguments in the mix would make it harder still. That's why we have opted to separate the two. I can't answer your question, but here is a workaround:If you have two very long arg lists which differ in only one arg, it might be worth the trouble...One of the possible scenario is The compiler will be confused about which one to call. In prevention of other possible dangers, the compiler would allow at most one overloaded method has default arguments.Just my guess:-)My understanding is that there can be name collisions in the compiled classes with default argument values. I've seen something along these lines mentioned in several threads.The named argument spec is here:\nIt states:So, for the time being at any rate, it's not going to work.You could do something like what you might do in Java, eg:If you called  which one should it invoke?"},
Scala

I saw this quote on the question: Is this true?  If so, what is it about the JVM that creates this fundamental limitation?This post:  might help.In short, tail call optimization is hard to do in the JVM because of the security model and the need to always have a stack trace available. These requirements could in theory be supported, but it would probably require a new bytecode (see ).There is also more discussion in , where the evaluation (from 2002) ends:Currently, there is some work going on in the  project. The tail call subproject's status is listed as \"proto 80%\"; it is unlikely to make it into Java 7, but I think it has a very good chance at Java 8.The fundamental limitation is simply that the JVM does not provide tail calls in its byte code and, consequently, there is no direct way for a language built upon the JVM to provide tail calls itself. There are workarounds that can achieve a similar effect (e.g. trampolining) but they come at the grave cost of awful performance and obfuscating the generated intermediate code which makes a debugger useless.So the JVM cannot support any production-quality functional programming languages until Sun implement tail calls in the JVM itself. They have been discussing it for years but I doubt they will ever implement tail calls: it will be very difficult because they have prematurely optimized their VM before implementing such basic functionality, and Sun's effort is strongly focused on dynamic languages rather than functional languages.Hence there is a very strong argument that Scala is not a real functional programming language: these languages have regarded tail calls as an essential feature since Scheme was first introduced over 30 years ago.Scala 2.7.x supports tail-call optimization for self-recursion (a function calling itself) of final methods and local functions.Scala 2.8 might come with library support for trampoline too, which is a technique to optimize mutually recursive functions.A good deal of information about the state of Scala recursion can be found in .In addition to the paper linked in Lambda The Ultimate (from the link mmyers posted above), John Rose from Sun has some more to say about tail call optimization.I have heard that it might be implemented on the JVM someday. Tail call support amongst other things are being looked at on the Da Vinci Machine.All sources point to the JVM being unable to optimize in the case of tail recursion, but upon reading  (2003, O'reilly) I found the author claiming he can achieve greater recursion performance by implementing tail recursion.You can find his claim on page 212 (search for 'tail recursion' it should be the second result). What gives?"},
Scala

If you're writing code that's using lots of beautiful, immutable data structures, case classes appear to be a godsend, giving you all of the following for free with just one keyword:But what are the disadvantages of defining an immutable data structure as a case class?What restrictions does it place on the class or its clients?Are there situations where you should prefer a non-case class?One big disadvantage: a case classes can't extend a case class. That's the restriction.Other advantages you missed, listed for completeness: compliant serialization/deserialization, no need to use \"new\" keyword to create.I prefer non-case classes for objects with mutable state, private state, or no state (e.g. most singleton components).  Case classes for pretty much everything else.First the good bits: This list should also include the uber-powerful copy method, one of the best things to come to Scala 2.8Then the bad, there are only a handful of real restrictions with case classes:In practice though, this is rarely a problem.  Changing behaviour of the generated apply method is guaranteed to surprise users and should be strongly discouraged, the only justification for doing so is to validate input parameters - a task best done in the main constructor body (which also makes the validation available when using )True, though it's still possible for a case class to itself be a descendant.  One common pattern is to build up a class hierarchy of traits, using case classes as the leaf nodes of the tree.It's also worth noting the  modifier.  Any subclass of a trait with this modifier  be declared in the same file.  When pattern-matching against instances of the trait, the compiler can then warn you if you haven't checked for all possible concrete subclasses.  When combined with case classes this can offer you a very high level level of confidence in your code if it compiles without warning.No real workaround, except to stop abusing classes with this many params :)One other restriction sometimes noted is that Scala doesn't (currently) support lazy params (like s, but as parameters).  The workaround to this is to use a by-name param and assign it to a lazy val in the constructor.  Unfortunately, by-name params don't mix with pattern matching, which prevents the technique being used with case classes as it breaks the compiler-generated extractor.This is relevant if you want to implement highly-functional lazy data structures, and will hopefully be resolved with the addition of lazy params to a future release of Scala.I think the TDD principle apply here: do not over-design. When you declare something to be a , you are declaring a lot of functionality. That will decrease the flexibility you have in changing the class in the future.For example, a  has an  method over the constructor parameters. You may not care about that when you first write your class, but, latter, may decide you want equality to ignore some of these parameters, or do something a bit different. However, client code may be written in the mean time that depends on  equality.Martin Odersky gives us a good starting point in his course  (Lecture 4.6 - Pattern Matching) that we could use when we must choose between class and case class.\nThe chapter 7 of  contains the same example.Furthermore, adding a new Prod class does not entail any changes to existing code:In contrast, add a new method requires modification of all existing classes.The same problem solved with case classes.Adding a new method is a local change.Adding a new Prod class requires potentially change all pattern matching.Transcript from the videolecture Remember: we must use this like a starting point and not like the only criteria."},
Scala

Given three ways of expressing the same function :How do these definitions differ?  The REPL does not indicate any obvious differences: is a function that takes an integer and returns an integer. is a method with zero arity that returns a function that takes an integer and returns an integer. (When you type  at REPL later, it becomes a call to the method .) is same as . You're just not employing type inference there.Inside a class,  is evaluated on initialization while  is evaluated only when, , the function is called. In the code below you will see that x is evaluated the first time the object is used, but not again when the x member is accessed. In contrast, y is not evaluated when the object is instantiated, but is evaluated every time the member is accessed. Executing a definition such as  x = e will not evaluate the expression . Instead  is evaluated whenever  is used. Alternatively, Scala offers a value definition\n x = e, which does evaluate the right-hand-side  as part of the evaluation\nof the definition. If  is then used subsequently, it is immediately replaced by the\npre-computed value of , so that the expression need not be evaluated again."},
Scala

In Java, reading environment variables is done with .Is there a way to do this in Scala?Since Scala 2.9 you can use  for the same effect:I think is nice to use the Scala API instead of Java. There are currently several project to compile Scala to other platforms than JVM (.NET, javascript, native, etc.) Reducing the dependencies on Java API, will make your code more portable.There is an object:this has a collection of methods that can be used to get environment info, includingSame way:If Lightbend's configuration library is used (by default in Play2 and Akka) then you can use syntax to override foo if an environment variable VAR_NAME exist. \nMore details in    To print  environment variables, you can use"},
Scala

I have some big (more than 3 fields) Objects which can and should be immutable. Every time I run into that case i tend to create constructor abominations with long parameter lists. It doesn't feel right, is hard to use and readability suffers.It is even worse if the fields are some sort of collection type like lists. A simple  would ease the object creation so much but renders the object mutable.What do you guys use in such cases? I'm on Scala and Java, but i think the problem is language agnostic as long as the language is object oriented.Solutions I can think of:Thanks for your input!Well, you want both an easier to read and immutable object once created?I think a fluent interface  would help you.It would look like this (purely made up example):I wrote  in bold because most Java programmers get fluent interfaces wrong and pollute their object with the method necessary to build the object, which is of course completely wrong.The trick is that  (hence you Foo can be immutable).,  and  all create \"something else\".That something else may be a FooFactory, here's one way to do it....You FooFactory would look like this:In Scala 2.8, you could use named and default parameters as well as the  method on a case class. Here's some example code:Well, consider this on Scala 2.8:This does have its share of problems, of course. For instance, try making  and , and then getting two persons married to each other. I can't think of a way to solve that without resorting to either a  and/or a  constructor plus a factory.Here are a couple of more options:Make the implementation itself mutable, but separate the interfaces that it exposes to mutable and immutable. This is taken from the Swing library design.If your application contains a large but pre-defined set of immutable objects (e.g., configuration objects), you might consider using the  framework.You could also make the immutable objects expose methods that look like mutators (like addSibling) but let them return a new instance. That's what the immutable Scala collections do.The downside is that you might create more instances than necessary. It's also only applicable when there exist intermediate valid configurations (like some node without siblings which is ok in most cases) unless you don't want to deal with partially built objects.For example a graph edge which has no destination yet isn't a valid graph edge.Consider four possibilities:To me, each of 2, 3, and 4 is adapted to a difference situation. The first one is hard to love, for the reasons cited by the OP, and is generally a symptom of a design that has suffered some creep and needs some refactoring.What I'm listing as (2) is good when there is no state behind the 'factory', whereas (3) is the design of choice when there is state. I find myself using (2) rather than (3) when I don't want to worry about threads and synchronization, and I don't need to worry about amortizing some expensive setup over the production of many objects. (3), on the other hand, is called forth when real work goes into the construction of the factory (setting up from an SPI, reading configuration files, etc).Finally, someone else's answer mentioned option (4), where you have lots of little immutable objects and the preferable pattern is to get news ones from old ones.Note that I'm not a member of the 'pattern fan club' -- sure, some things are worth emulating, but it seems to me that they take on an unhelpful life of their own once people give them names and funny hats.Another potential option is to refactor to have fewer configurable fields.  If groups of fields only work (mostly) with each other, gather them up into their own small immutable object.  That \"small\" object's constructors/builders should be more manageable, as will the constructor/builder for this \"big\" object.It helps to remember there are . For your case, I think \"popsicle\" immutability will work really well:So you initialize your object, then set a \"freeze\" flag of some sort indicating that its no longer writable. Preferably, you'd hide the mutation behind a function so the function is still pure to clients consuming your API.I use C#, and these are my approaches. Consider: Constructor with optional parametersUsed as e.g. . Not for Java or C# versions before 4.0. but still worth showing, as it's an example how not all solutions are language agnostic. Constructor taking a single parameter objectUsage example: C# from 3.0 on makes this more elegant with object initializer syntax (semantically equivalent to the previous example):\nRedesign your class not to need such a huge number of parameters. You could split its repsonsibilities into multiple classes. Or pass parameters not to the constructor but only to specific methods, on demand. Not always viable, but when it is, it's worth doing."},
Scala

I'm writing some Scala code which uses the  API. I would like to iterate over the rows contained in the  that I get from the Sheet class. I would like to use the iterator in a  style loop, so I have been trying to convert it to a native Scala collection but will no luck.I have looked at the Scala wrapper classes/traits, but I can not see how to use them correctly. How do I iterate over a Java collection in Scala without using the verbose  style of loop?Here's the code I wrote based on the correct answer:There is a wrapper class (). So if you define then it will act as a sub class of the Scala iterator so you can do .As of Scala 2.8, all you have to do is to import the JavaConversions object, which already declares the appropriate conversions.This won't work in previous versions though.The correct answer here is to define an implicit conversion from Java's  to some custom type. This type should implement a  method which delegates to the underlying . This will allow you to use a Scala -loop with any Java .For Scala 2.10:With Scala 2.10.4+ (and possibly earlier) it is possible to implicitly convert java.util.Iterator[A] to scala.collection.Iterator[A] by importing scala.collection.JavaConversions.asScalaIterator. Here is an example:You could convert the Java collection to an array and use that:Or go on and convert the array to a Scala list:If you would like to avoid the implicits in  you can use  to convert explicitly.Note the use of the  method to convert the Java  to a Scala .The JavaConverters have been available since Scala 2.8.1.Scala 2.12.0 deprecates , so since 2.12.0 one way of doing this would be something like:(notice the import, new is JavaConverters, deprecated is JavaConversions)If you are iterating through a large dataset, then you probably don't want to load whole collection into memory with  implicit conversion. In this case, a handy way approach is to implement  traitIt has similar concept but less verbose IMO :)"},
Scala

What is the difference between  and  in Scala, and when to use which?Is the implementation same as in Java?EDIT: The related question talks about specific cases of . The more general case is .You normally use , it routes to , except that it treats s properly. Reference equality (rarely used) is .  is a final method, and calls , which is not final.This is radically different than Java, where  is an operator rather than a method and strictly compares reference equality for objects.NOTE: On the case of , just as in Java, it may not return the same result if you switch the arguments eg  will return  where the inverse will return . This is because of each implementation checking only specific types. Primitive numbers dont check if the second argument is of  nor  types but only of other primitive typesThe  method is the one overridden by subclasses. A method from the Java Specification that has come over to Scala too. If used on an unboxed instance, it is boxed to call this (though hidden in Scala; more obvious in Java with ->). The default implementation merely compares references (as in Java)The  method compares two objects and allows either argument to be null (as if calling a static method with two instances). It compares if both are , then it calls the  method on boxed instance.The  method compares  references, that is where the instance is located in memory. There is no implicit boxing for this method.There is an interesting difference between  and  for  and  types: They treat  differently: As was pointed out in a comment - \"this also happens in Java\" - depends on what exactly  is:This will printSo, the  yields  when compared for equality because this is how IEEE floating point numbers define it and this should really happen in every programming language (although it somehow messes with the notion of identity).The boxed NaN yields true for the comparison using  in Java as we are comparing object references.I do not have an explanation for the  case, IMHO it really should behave the same as  on unboxed double values, but it does not.Translated to Scala the matter is a little more complicated as Scala has unified primitive and object types into  and translates into the primitive double and the boxed Double as needed. Thus the scala  apparently boils down to a comparison of primitive  values but  uses the one defined on boxed Double values (there is a lot of implicit conversion magic going on and there is stuff pimped onto doubles by ).If you really need to find out if something is actually  use :In Scala  first check for  values and then calls  method on first object"},
Scala

We are thinking on moving our Rest API Server (it is inside the web service, on Symfony PHP) to Scala for several reasons: speed, no overhead, less CPU, less code, scalability, etc. I didn't know Scala until several days ago but I've been enjoying what I've been learning these days with the Scala book and all the blog posts and questions (it's not so ugly!)I have the following options:Some things that I will have to use: HTTP requests, JSON output, MySQL (data), OAuth, Memcache (cache), Logs, File uploads, Stats (maybe Redis).What would you recommend?In no particular order: I'm going to recommend . It's an idiomatic Web framework that does things \"the Scala way\" and is very beautiful.Take a look at  (I'm its author), it provides everything you listed.  is quite extensive. From README:Xitrum is an async and clustered Scala web framework and web server on top of Netty and Hazelcast:I would add two more options: akka with built-in JAX-RS support, and simply using JAX-RS directly (probably the Jersey implementation).  While arguably less \"Scala-y\" than others (relying upon annotations to bind parameters and paths), JAX-RS is a joy to use, cleanly solving all of the problems of web service coding with minimal footprint.  I've not used it via akka, I would anticipate it being excellent there, getting impressive scalability via it's continuation-based implementation.  Take a look at , a Scala combinator library for building  HTTP services. Finch allows you to construct complex HTTP endpoints out of the number of predefined basic blocks. Similarly to parser combinators, Finch endpoints are easy to reuse, compose, test, and reason about.All good answers so far. One point in Lift's favor is its , which can make it quite easy to write short, elegant API methods. In addition, all the other things you want to do should be quite straight-forward to implement in Lift. That being said, Memcache might be not be necessary.A little late on the scene but I would definitely recommend using  framework for creation of REST API's. It small, to the point and automatic case class conversion support! "},
Scala

In Scala, is there any difference at all between  and ?If not, which one is more idiomatic Scala style? Both for creating new empty lists and pattern matching on empty lists.Nil is more idiomatic and can be preferred in most cases.\nQuestions? has shown that the run time value of both  and  are the same. However, their static type is not:This is of particular importance when it is used to infer a type, such as in a fold's accumulator:As user unknown's answer shows, they are the same object.  Idiomatically Nil should be preferred because it is nice and short. There's an exception though: if an explicit type is needed for whatever reason I think is nicer than "},
Scala

So, there is Is there an equivalent to write a string to file. a concise one ?Most languages support something like that. My fav is groovyThe use case being a one line to a small page of code. Having to carry your own library dosent make sense here. I expect a modern language to let me write a something to a file conveniently. There are posts similar to this. but, they dont answer my exact question or focused on older scala versions.\nthis  and this\nA concise one line:It is strange that no one had suggested NIO.2 operations (available since Java 7):I think this is by far the simplest and easiest and most idiomatic way, and it does not need any dependencies sans Java itself.Here is a concise one-liner using the Scala compiler library:Alternatively, if you want to use the Java libraries you can do this hack:If you like Groovy syntax, you can use the  design pattern to bring it to Scala:It will work as expected:You can easily use . Look at function . We use this library in our projects.One also has this format, which is both concise and the underlying library is beautifully written (see the source code):A micro library I wrote: orThis is concise enough, I guess:You can do this with a mix of Java and Scala libraries. You will have full control over the character encoding. But unfortunately, the file handles will not be closed properly. UPDATE: I have since created a more effective solution upon which I have elaborated here: I find myself working more and more in the Scala Worksheet within the Scala IDE for Eclipse (and I believe there is something equivalent in IntelliJ IDEA). Anyway, I need to be able to do a one-liner to output some of the contents as I get the \"Output exceeds cutoff limit.\" message if I am doing anything significant, especially with the Scala collections.I came up with a one-liner I insert into the top of each new Scala Worksheet to simplify this (and so I don't have to do the whole external library import exercise for a very simple need). If you are a stickler and notice that it is technically two lines, it's only to make it more readable in this forum. It is a single line in my Scala Worksheet.And the usage is simply:  This allows me to optionally provide the file name should I want to have additional files beyond the default (which completely overwrites the file each time the method is called).So, the second usage is simply:  Enjoy!I know it's not one line, but it solves the safety issues as far as I can tell;If you didn't care about the exception handling then you can writeThrough the magic of the semicolon, you can make anything you like a one-liner."},
Scala

According to , Scala's type system is . What resources are available that enable a newcomer to take advantage of the power of type-level programming?Here are the resources I've found so far:These resources are great, but I feel like I'm missing the basics, and so do not have a solid foundation on which to build. For instance, where is there an introduction to type definitions? What operations can I perform on types?Are there any good introductory resources?Type-level programming has many similarities with traditional, value-level programming. However, unlike value-level programming, where the computation occurs at runtime, in type-level programming, the computation occurs at compile time. I will try to draw parallels between programming at the value-level and programming at the type-level.There are two main paradigms in type-level programming: \"object-oriented\" and \"functional\". Most examples linked to from here follow the object-oriented paradigm.A good, fairly simple example of type-level programming in the object-oriented paradigm can be found in apocalisp's , replicated here:As can be seen in the example, the object-oriented paradigm for type-level programming proceeds as follows:The Functional paradigm consists of defining lots of parameterized type constructors that are not grouped together in traits.The trick is to use implicit functions and values. The base case is usually an implicit value and the recursive case is usually an implicit function. Indeed, type-level programming makes heavy use of implicits.Consider this example ( and ):Here you have a peano encoding of the natural numbers. That is, you have a type for each non-negative integer: a special type for 0, namely ; and each integer greater than zero has a type of the form , where  is the type representing a smaller integer. For instance, the type representing 2 would be:  (successor applied twice to the type representing zero).We can alias various natural numbers for more convenient reference. Example:(This is a lot like defining a  to be the result of a function.)Now, suppose we want to define a value-level function  which takes in an argument value, , that conforms to  and returns an integer representing the natural number encoded in 's type. For example, if we have the value  ( of type ), we would want  to return .To implement , we're going to make use of the following class:As we will see below, there will be an object constructed from class  for each  from  up to (e.g.) , and each will store the value representation of the corresponding type (i.e.  will store the value ,  will store the value , etc.). Note,  is parameterized by two types:  and .  corresponds to the type we're trying to assign values to (in our example, ) and  corresponds to the type of value we're assigning to it (in our example, ).Now we make the following two implicit definitions:And we implement  as follows:To understand how  works, let's consider what it does on a couple of inputs:When we call , the compiler looks for an implicit argument  of type  (since  is of type ). It finds the object , it calls the  method of this object and gets back . The important point to note is that we did not specify to the program which object to use, the compiler found it implicitly.Now let's consider . This time, the compiler looks for an implicit argument  of type  (since  is of type ). It finds the function , which can return an object of the appropriate type () and evaluates it. This function itself takes an implicit argument () of type  (that is, a  where the first type parameter is has one fewer ). The compiler supplies  (as was done in the evaluation of  above), and  constructs a new  object with value . Again, it is important to note that the compiler is providing all of these values implicitly, since we do not have access to them explicitly. There are several ways to verify that your type-level computations are doing what you expect. Here are a few approaches. Make two types  and , that you want to verify are equal. Then check that the following compile:Alternatively, you can convert the type to a value (as shown above) and do a runtime check of the values. E.g. , where  is of type  and  is of type .The complete set of available constructs can be found in the types section of . has several academic papers about type constructors and related topics with examples from scala: is a blog with many examples of type-level programming in scala. is a very active project that is providing functionality that extends the Scala API using various type-level programming features. It is a very interesting project that has a big following. is a type-level library for Scala, including meta types for natural numbers, booleans, units, HList, etc. It is a project by .The  has some awesome examples of type-level programming in Scala (from other answer): has some relevant posts as well:(I've been doing some research on this subject and here's what I've learned. I'm still new to it, so please point out any inaccuracies in this answer.)In addition to the other links here, there are also my blog posts on type level meta programming in Scala:As suggested on Twitter:  by Miles Sabin. has source code, a wiki and examples."},
Scala

How is pattern matching in Scala implemented at the bytecode level?Is it like a series of  constructs, or something else? What are its performance implications?For example, given the following code (from  pages 46-48), how would the equivalent Java code for the  method look like?P.S. I can read Java bytecode, so a bytecode representation would be good enough for me, but probably it would be better for the other readers to know how it would look like as Java code.P.P.S. Does the book  give an answer to this and similar questions about how Scala is implemented? I have ordered the book, but it has not yet arrived.The low level can be explored with a disassembler but the short answer is that it's a bunch of if/elses where the predicate depends on the patternThere's much more that you can do with patterns like or patterns and combinations like \"case Foo(45, x)\", but generally those are just logical extensions of what I just described.   Patterns can also have guards, which are additional constraints on the predicates.  There are also cases where the compiler can optimize pattern matching, e.g when there's some overlap between cases it might coalesce things a bit.  Advanced patterns and optimization are an active area of work in the compiler, so don't be surprised if the byte code improves substantially over these basic rules in current and future versions of Scala.  In addition to all that, you can write your own custom extractors in addition to or instead of the default ones Scala uses for case classes.  If you do, then the cost of the pattern match is the cost of whatever the extractor does.  A good overview is found in James (above) said it best. However, if you're curious it's always a good exercise to look at the disassembled bytecode. You can also invoke  with the  option, which will print your program with all Scala-specific features removed. It's basically Java in Scala's clothing. Here's the relevant  output for the code snippet you gave:Since version 2.8, Scala has had the  annotation. The goal is to ensure, that pattern matching will be compiled into  instead of series of conditional  statements."},
Scala

I have a Java API that returns a List like:I am using the below scala code:Now if I try scala syntax sugar like:it does not work. I get the error:It seems I need to convert Java List to Scala List. How to do that in above context?Since  this conversion is now built into the language using:works.  did not workThere's a handy Scala object just for this - You can do the import and  afterwards as follows:This should give you Scala's  representation allowing you to accomplish .I was looking for an answer written in Java and surprisingly couldn't find any clean solutions here. After a while I was able to figure it out so I decided to add it here in case someone else is looking for the Java implementation (I guess it also works in Scala?):If you have to convert a Java  to a Scala , then you must do the following:1) Add2) Use methods ,  and then 3) Add the following to the  constructor that receives  as a parameter:"},
Scala

There are a lot of functional idioms: monads, applicatives, arrows, etc. They are documented in different articles but unfortunately I don't know any book or article where they're summarized in one place (there is  but it has a lot of areas that aren't covered well). Can anyone recommend an article/book which covers them well in one place and which can be accessible to a programmer with intermediate skills in FP?My suggestion is, if you want to learn Scala, to read the book from Paul Chiusano and Tony Morris: Part II: Functional design and combinator libraries Part III: Functional design patterns Part IV: Breaking the rules: effects and I/O I'm sorry I don't know of articles or books which cover in detail the different usages for all of those constructs, but I can give you a few links to individual resources.A quite common pattern is to build  instead of simple monads (see also the link in the next paragraph). It basically means you build something that must be combined with other monads, resulting in a more complex one able to handle features of both of them.In  there are a few chapters about monads. In  the authors explain the basics and some common usages (maybe, list, state).  provides more explanations about how to effectively use them (it covers the reader monad as well). The following chapter explains how to use , but it may be more interesting to search for articles covering how it actually works: it should be a really good example of a well-organized use of monads for parsing. Fianlly,  introduces how monad transformers work and then shows how to build one, step by step. The considerations towards the final sections of the chapter are also interesting.I read once a really interesting question on SO about . The proposed links were awesome reads about the topic. With that spirit, I tried to ask the same for : I definitely got less answers than the one on monads, but interesting ones nevertheless.With respect to OOP patterns by the gang of four, there is a nice set of 3 articles by IBM about the topic in their series . The target functional language is Scala. They proceed by explaining usual design patterns in OOP and showing how they map into Scala.The most relevant article w.r.t. your question is for sure the first one, but the other two may be interesting related readings nevertheless.Jeremy Gibbons has a  which is destined eventually to become pretty much the book you're asking for. Of course, that's not yet in a condition to be as useful as you might want just now, but he deserves some encouragement!Meanwhile, I'll say +1 for Brent Yorgey's Typeclassopedia. It's really useful, and if there are later parts which confuse, this site is a good place to get to the bottom of them. I know Brent keeps it under review. If he's not reaching his readers, give him some help.Lot of FP stuff are published on Oleg's site:\n Presentation about FP patterns from Josh Suereth:\nHave you read the later chapters of ?It doesn't cover Arrows or Comonads, which are a more advanced topic in Haskell. To understand how and why to use Arrows or Comonads you should definitely have a firm grasp of Monads already, so I don't think this is a problem - LYAH is firmly aimed at the beginner end of the Haskell market."},
Scala

: Re-written this question based on original answerThe  class is not covariant in its type parameter. Why is this?  is invariant in its type parameter because of the concept behind sets as functions.  The following signatures should clarify things slightly:If  were covariant in , the  method would be unable to take a parameter of type  due to the contravariance of functions.   could potentially be  in , but this too causes issues when you want to do things like this:In short, the best solution is to keep things invariant, even for the immutable data structure.  You'll notice that  is also invariant in one of its type parameters.at  Martin Odersky writes:So, it seems that all of our efforts to construct a principled reason for this were misguided :-): for anyone wondering why this answer seems slightly off-topic, this is because I (the questioner) have modified the question. Scala's type inference is good enough to figure out that you want CharSequences and not Strings in some situations. In particular, the following works for me in 2.7.3:As to how to create immutable.HashSets directly: don't. As an implementation optimization, immutable.HashSets of less than 5 elements are not actually instances of immutable.HashSet. They are either EmptySet, Set1, Set2, Set3, or Set4. These classes subclass immutable.Set, but not immutable.HashSet."},
Scala

Are there any guidelines in Scala on when to use val with a mutable collection versus using var with an immutable collection? Or should you really aim for val with an immutable collection?The fact that there are both types of collection gives me a lot of choice, and often I don't\nknow how to make that choice.Pretty common question, this one. The hard thing is finding the duplicates.You should strive for . What that means is that, if I have an expression \"e\", I could make a , and replace  with . This is the property that mutability break. Whenever you need to make a design decision, maximize for referential transparency.As a practical matter, a method-local  is the safest  that exists, since it doesn't escape the method. If the method is short, even better. If it isn't, try to reduce it by extracting other methods.On the other hand, a mutable collection has the  to escape, even if it doesn't. When changing code, you might then want to pass it to other methods, or return it. That's the kind of thing that breaks referential transparency.On an object (a field), pretty much the same thing happens, but with more dire consequences. Either way the object will have state and, therefore, break referential transparency. But having a mutable collection means even the object itself might lose control of who's changing it.If you work with immutable collections and you need to \"modify\" them, for example, add elements to them in a loop, then you have to use s because you need to store the resulting collection somewhere. If you only read from immutable collections, then use s.In general, make sure that you don't confuse references and objects. s are immutable references (constant pointers in C). That is, when you use , you'll be able  that  points to, but you won't be able   points. The opposite holds if you use . Picking up my initial advice: if you don't need to change to which object a reference points, use s.The best way to answer this is with an example.  Suppose we have some process simply collecting numbers for some reason.  We wish to log these numbers, and will send the collection to  process to do this.Of course, we are still collecting numbers after we send the collection to the logger.  And let's say there is some overhead in the logging process that delays the actual logging.  Hopefully you can see where this is going. If we store this collection in a mutable , (mutable because we are continuously adding to it), this means that the process doing the logging will be looking at the  that's still being updated by our collection process.  That collection may be updated at any time, and so when it's time to log we may not actually be logging the collection we sent.If we use an immutable , we send an immutable data structure to the logger.  When we add more numbers to our collection, we will be  our  with a .  This doesn't mean collection sent to the logger is replaced!  It's still referencing the collection it was sent.  So our logger will indeed log the collection it received.I think the examples in this blog post will shed more light, as the question of which combo to use becomes even more important in concurrency scenarios: . And while we're at it, note the preferred use of synchronised vs @volatile vs something like AtomicReference: "},
Scala

The pimp-my-library pattern allows me to seemingly add a method to a class by making available an implicit conversion from that class to one that implements the method.Scala does not allow two such implicit conversions taking place, however, so I cannot got from  to  using an implicit  to  and another implicit  to . Is there a way around this restriction?Scala has a restriction on automatic conversions to add a method, which is that it won't apply more than one conversion in trying to find methods. For example: (You can use type classes instead)However, if an implicit definition requires an implicit parameter itself(View bound), Scala  look for additional implicit values for as long as needed. Continue from the last example:\"Magic!\", you might say. Not so. Here is how the compiler would translate each one:So, while  is being used as an implicit conversion,  and  are being passed as , instead of being chained as implicit conversions.Related question of interest:Note that you can build circles with implicit parameters, too. Those are, however, detected by the compiler, as exhibited by this:The error(s) given to the user are not as clear as they could be, though; it just complains  for all three construction site. That might obscure the underlying problem in less obvious cases. a code that also accumulates the path."},
Scala

What is the naming convention for Scala constants? A brief search on StackOverflow suggestions uppercase CamelCase (the first line below), but I wanted to double-check.Which is recommended Scala style?The officially recommended style (and I do mean officially) is the first style, camel case with first letter are upper case. It's laid down clearly by Odersky on Programming in Scala.The style is also followed by the standard library, and has some support in language semantics: identifiers starting with upper case are treated as constants in pattern matching.(Section 6.10, p. 107 in the second edition)(This is an addendum comment to Daniel's answer, but I'm posting it as an answer for the benefit of syntax highlighting and formatting.)Daniel's point about the style of using an initial capital letter being important in the language semantics is more subtle and important than I originally gave it credit for when I learned Scala.Consider the following code:Naively I would have expected that to reach all of the cases in the match.  Instead it prints:What's going on is that the  shadows the val  and creates a local variable of the same name which will be populated any time a  containing a string is evaluated.There are admittedly ways to work around it, but the simplest is to follow the style guide for constant naming.If you can't follow the naming convention, then as @reggoodwin points out in the comments below, you can put the variable name in ticks, like so "},
Scala

Is there any List/Sequence built-in that behaves like  and provides the element's index as well?I believe you're looking for zipWithIndex?From: You also have variations like: or:Use . in .Result:The proposed solutions suffer from the fact that they create intermediate collections or introduce variables which are not strictly necessary. For ultimately all you need to do is to keep track of the number of steps of an iteration. This can be done using memoizing. The resulting code might look likeThe -Function wraps the interior function which receives both an index an the elements of . This might be familiar to you from JavaScript.Here is a way to achieve this purpose. Consider the following utility:This is already all you need. You can apply this for instance as follows:which results in the listThis way, you can use the usual Traversable-functions at the expense of wrapping your effective function. The overhead is the creation of the memoizing object and the counter therein. Otherwise this solution is as good (or bad) in terms of memory or performance as using unindexed . Enjoy!There is  in 2.7.x (which you can get from a normal iterator with .counted).  I believe it's been deprecated (or simply removed) in 2.8, but it's easy enough to roll your own.  You do need to be able to name the iterator:Or, assuming your collection has constant access time, you could map the list of indexes instead of the actual collection:"},
Scala

I have looked at  but still don't understand the difference between Iterable and Traversable traits. Can someone explain ?To put it simply, iterators keep state, traversables don't.A  has one abstract method: . When you call ,  will feed the passed function all the elements it keeps, one after the other.On the other hand, an  has as abstract method , which returns an . You can call  on an  to get the next element at the time of your choosing. Until you do, it has to keep track of where it was in the collection, and what's next.Think of it as the difference between blowing and sucking.When you have call a s , or its derived methods, it will blow its values into your function one at a time - so it has control over the iteration.With the  returned by an  though, you suck the values out of it, controlling when to move to the next one yourself.  are  that can produce stateful First, know that  is subtrait of .Second, For example, the implemetation of  for  uses  (via a for comprehension) and throws a  exception to halt iteration once a satisfactory element has been found.In contrast, the  subtract overrides this implementation and calls  on the , which simply stops iterating once the element is found:It'd be nice not to throw exceptions for  iteration, but that's the only way to partially iterate when using just .From one perspective,  is the more demanding/powerful trait, as you can easily implement  using , but you can't really implement  using .In summary,  provides a way to pause, resume, or stop iteration via a stateful . With , it's all or nothing (sans exceptions for flow control).Most of the time it doesn't matter, and you'll want the more general interface. But if you ever need more customized control over iteration, you'll need an , which you can retrieve from an ."},
Scala

I'll start with an example. Here's an equivalent of  for tuples as a macro in Scala 2.10:We can use this method as follows:This guy is a weird bird in a couple of respects. First, the  argument must be a literal integer, since we need to use it at compile time. In previous versions of Scala there was no way (as far as I know) for a method even to tell whether one of its arguments was a compile-time literal or not.Second, the  return type \u2014the static return type will include the specific arity and element type determined by the arguments, as shown above.So how would I document this thing? I'm not expecting Scaladoc support at this point, but I'd like to have a sense of conventions or best practices (beyond just making sure the compile-time error messages are clear) that would make running into a macro method\u2014with its potentially bizarre demands\u2014less surprising for users of a Scala 2.10 library.The most mature demonstrations of the new macro system (e.g., , , the others listed ) are still relatively undocumented at the method level. Any examples or pointers would be appreciated, including ones from other languages with similar macro systems.I think the best way to document these is with example code, as Miles has been doing in his experimental  of shapeless."},
Scala

I'm developing several modules with dependencies among them, and would like to work with them all together in one IDEA project.  I'm using  to generate IDEA projects from the sbt build definitions, which works great for individual projects.  In the multiple-module case, however, the things I've tried so far don't quite work:; then create a master IDEA project from scratch an add those modules to it.  This makes the module sources all editable in the same window, but the dependencies among them are not tracked (so trying to navigate from some source within the  project to something in  takes me to the imported library version of , not the local sources)., where the parent project's Build.scala contains things like:This almost works, in that sbt-idea generates a master IDEA project with the dependencies among the subprojects tracked.  There are however two caveats: To summarize: I'd like to collect modules  into one big IDEA project with tracked dependencies for convenient editing.  How can I do it?  Thanks!With sbt 13.5 and intellij 13.x, you can specify inter-project dependency with relative path, using a .\nLet's say you have two projects, a core project  and another project , both living in a common directory The approach with multi-project build is the correct one. You can have a nested tree of subprojects of arbitrary length, but you cannot have a module belonging to multiple parent projects. This makes absolutely sense, and in Maven happens the same.The reason is that it would be hard to have the same module into multiple projects and keep the sources synchronized. A normal workflow is the following:If you want to load a module which does not belong to the current project inside Idea, this is however feasible as you can add this as an external module to the workspace:"},
Scala

I am currently trying to get started with Akka and I am facing a weird problem. I've got the following code for my Actor:And this is how I start my workers:And this is how I shut everything down:Now what happens is if I send the workers messages with n > 0 (no exception is thrown), everything works fine and the application shuts down properly. However, as soon as I send it a single message which results in an exception, the application does not terminate because there is still an actor running, but I can't figure out where it comes from.In case it helps, this is the stack of the thread in question:PS: The thread which is not terminating isn't any of the worker threads, because I've added a postStop callback, every one of them stops properly.PPS:  workarounds the problem, but I think shutdownAll should only be used as a last resort, shouldn't it?The proper way to handle problems inside akka actors is not to throw an exception but rather to set supervisor hierarchies see  the above is true for old versions of Akka (1.2)\nIn newer versions (e.g. 2.2) you'd still set a supervisor hierarchy but it will trap Exceptions thrown by child processes. e.g.and in the supervisor:see Turning off the logging to make sure things terminate, as proposed by Viktor, is a bit strange. What you can do instead is:that cleanly shuts down all the (logger) listeners that keep the world running after the exception:Turn of the logger in the "},
Scala

What are the differences using Scala Actors instead of JMS? For example from a performance and scalability perspective, what does the Scala Actor model add compared to JMS? In which cases does it make more sense to use Actors rather than JMS, i.e. what problems does Actors address that JMS cannot cover?JMS and Scala actors share a theoretical similarity but don't think of them as necessarily solving the same problems architecturally. Actors are meant to be a lightweight alternative to shared-memory concurrency where races and deadlocks are generally harder to accidentally create.  JMS is a sophisticated API that's meant to span direct messaging, publish/subscribe, transactions, EJB integration, etc.The closest JMS equivalent to an actor would be a message driven bean that is backed by a non-persistent, non-transactional, non-pub/sub queue.  I'll call that a \"simple JMS bean\".Now, to your questions.Performance is a hard thing to talk about since JMS is a specification rather than an implementation.  None-the-less when using simple JMS bean I'd expect performance to be roughly similar with perhaps a bit of an edge to the actor in time and memory.  As you add capabilities to JMS such as pub/sub, transactions, etc performance will naturally degrade even further but then you're trying to compare apples to oranges.As for scalability, simple JMS beans should scale pretty much exactly the same way as actors.  Adding transactions into the JMS mix will naturally hurt scalability by an amount depending on the scope of the transactions.The broader question of what do actors do that JMS can't.  Well, without built-in pub sub or transactions it would seem that actors subtract from JMS - and broadly that's true.  But here's the thing: actors require so little code that I can happily use them for very fine grained concurrency.  In ordinary Java code I might say \"I don't feel like screwing with JMS and its dependencies or the code it requires etc so I'll just spawn a thread, use a lock, and share a data structure.\"  With Scala actors I'm much more likely to say \"I'll just whip up an actor and move on.\"There's also a philosophical difference in design.  Actors have a simple, built in concept of supervisor hierarchies.  Actors are usually used in a \"let it crash\" design.  If an actor dies for some reason then another actor is responsible for deciding what to do about it such as restarting that actor, killing a bunch of actors and restarting all of them, or killing a bunch of actors and itself so that some otther actor can deal with the problem.  That kind of thing can appended onto JMS, but it's not core to the API and must be managed externally somehow.By the way, for a Scala actor library that moves more into the realms that JMS covers see .  Akka also brings a declarative approach to many common actor hierarchy strategies."},
Scala

I am having a discussion around  in the Scala Style Guide I maintain. I've come to realize that there are two ways of , and I'm wondering what the use cases are:The style guide incorrectly implies these are the same, when they are clearly not. The guide is trying to make a point about created curried functions, and, while the second form is not \"by-the-book\" currying, it's still very similar to the first form (though arguably easier to use because you don't need the )From those that use these forms, what's the consensus on when to use one form over the other?Methods with multiple parameter sections can be used to assist local type inference, by using parameters in the first section to infer type arguments that will provide an expected type for an argument in the subsequent section.  in the standard library is the canonical example of this.If this were this written as:One would have to provide more explicit types:Another use for multiple parameter section methods is to create an API that looks like a language construct. The caller can use braces instead of parentheses.Application of N argument lists to method with M parameter sections, where N < M, can be converted to a function explicitly with a , or implicitly, with an expected type of . This is a safety feature, see the change notes for Scala 2.0, in the Scala References, for an background.Curried functions (or simply, functions that return functions) more easily be applied to N argument lists.This minor convenience is sometimes worthwhile. Note that functions can't be type parametric though, so in some cases a method is required.Your second example is a hybrid: a one parameter section method that returns a function.Where else are curried functions useful? Here's a pattern that comes up all the time:How can we share the result ? A common solution is to provide a vectorized version of :Ugly! We've entangled unrelated concerns -- calculating  and mapping over a sequence of .We could also use a method that returns a function. In this case its a bit more readable:But if we try to do the same with a method with multiple parameter sections, we get stuck:You can curry only functions, not methods.  is a method, so you need the  to force its conversion to a function.  returns a function, so the  is not only unnecessary but makes no sense here. Considering how different methods and functions are (e.g. from the perspective of the JVM), Scala does a pretty good job blurring the line between them and doing \"The Right Thing\" in most cases, but there  a difference, and sometimes you just need to know about it.I think it helps to grasp the differences if I add that with  you pretty much just define a method with  parameters, only those two parameters are grouped into two parameter lists (see the consequences of that in other comments). In fact, that method is just  as far as Java (not Scala!) is concerned. When you write , that's just a function literal, a shorter form of . On the other hand, with  you define a method that has only one parameter, and for Java it will be . When you write  in Scala it's just a plain method call (as opposed to a function literal).Also note that  has (potentially) less overhead than  has if you immediately provide all parameters. Like  just translates to  on the JVM level, no  object is created. On the other hand,  will first create a  object that encloses , and then call  on that."},
Scala

I heard that with  it is somehow possible to do dynamic typing in Scala. But I can't imagine how that might look like or how it works.I found out that one can inherit from trait The  says that one can use it like this:But when I try it out it doesn't work:This is completely logical, because after looking to the , it turned out that this trait is completely empty. There is no method  defined and I can't imagine how to implement it by myself.Can someone show me what I need to do to make it to work?Scalas type  allows you to call methods on objects that don't exist or in other words it is a replica of \"method missing\" in dynamic languages.It is correct,  doesn't have any members, it is just a marker interface - the concrete implementation is filled-in by the compiler. As for Scalas  feature there are well defined rules describing the generated implementation. In fact, one can implement four different methods:To use one of these methods it is enough to write a class that extends  and to implement the methods there:Furthermore one need to add aor set the compiler option  because the feature is hidden by default. is the easiest one to implement. The compiler translates a call of  to , thus it is required that this method has an argument list expecting a :As one can see, it is also possible to call the dynamic methods explicitly.Because  is used to update a value this method needs to return . Furthermore, the name of the field to update and its value are passed to different argument lists by the compiler:The code works as expected - it is possible to add methods at runtime to the code. On the other side, the code isn't typesafe anymore and if a method is called that doesn't exist this must be handled at runtime as well. In addition this code is not as useful as in dynamic languages because it is not possible to create the methods that should be called at runtime. This means that we can't do something likewhere  would be transformed to  at runtime. But this is not that bad because even in dynamic languages this is a dangerous feature.Another thing to note here, is that  needs to be implemented together with . If we don't do this we will get a compile error - this rule is similar to the implementation of a Setter, which only works if there is a Getter with the same name.The ability to call methods with arguments is provided by :The name of the method and its arguments again are separated to different parameter lists. We can call arbitrary methods with an arbitrary number of arguments if we want but if we want to call a method without any parentheses we need to implement .Hint: It is also possible to use apply-syntax with :The last available method allows us to name our arguments if we want:The difference in the method signature is that  expects tuples of the form  where  is an arbitrary type.All of the above methods have in common that their parameters can be parameterized:Luckily, it is also possible to add implicit arguments - if we add a  context bound we can easily check the types of the arguments. And the best thing is that even the return type is correct - even though we had to add some casts.But Scala would not be Scala when there is no way to find a way around such flaws. In our case we can use type classes to avoid the casts:While the implementation doesn't look that nice, its power can't be questioned:At the top of all, it is also possible to combine  with macros:Macros give us back all compile time guarantees and while it is not that useful in the above case, maybe it can be very useful for some Scala DSLs.If you want to get even more information about  there are some more resources:"},
Scala

In Scala I see such feature as object-private variable. From my not very rich Java background I learnt to close everything (make it private) and open (provide accessors) if necessary. Scala introduces even more strict access modifier. Should I always use it by default? Or should I use it only in some specific cases where I need to explicitly restrict changing field value even for objects of the same class? In other words how should I choose betweenThe second is more strict and I like it but should I always use it or only if I have a strong reason?EDITED: As I see  private[this] is just some subcase and instead of  I can use other modifiers: \"package, class or singleton object\". So I'll leave it for some special case.I don't think it matters too much, since any changes will only touch one class either way. So the most important reason to prefer  over  over  doesn't apply.Use  where performance really matters (since you'll get direct field access instead of methods this way). Otherwise, just settle on one style so people don't need to figure out why  property is  and  one is .There is a case where  is required to make code compile. This has to do with an interaction of variance notation and mutable variables. Consider the following (useless) class:So this class is designed to hold an optional value, return it as an option and enable the user to call  to clear the value (hence the var). As stated, this is useless except to demonstrate the point.If you try compiling this code with  instead of  it will fail with the following error message:This error occurs because value is a mutable variable on the covariant type T (+T) which is normally a problem unless marked as private to the instance with . The compiler has special handling in its variance checking to handle this special case.So it's esoteric but there is a case where  is required over .so you can do private[this] every time you want but you can have some problem if you need refer it  is accessible from any method of the  (and its companion ). is accessible from methods of  object only, not from other objects of .This was tested using scala 2.11.5. Consider the code belowit will compile and work as this java (1.8) codehowever if you use '[this]' modifier the code below won't compileThis is because in the first case 'x' is accessible on class level, whereas in the second case is it more strict instance level. It means that 'x' can be accessed only from the instance to which it belongs. So 'this.x' is fine but 'other.x' is not.You can refer to section 13.5 of \"Programming in Scala: A Comprehensive Step-By-Step Guide\" book for more details about access modifiers.When adding the scope to the  modifier (), it effectively behaves as a \u201cup to\u201d X, where X designates some enclosing package, class or singleton object.For example, , where  is a package means that every instance of every class belonging to package  can access whichever member the modifier is restricting.In the case of , it means that the member is only accessible for each instance.\nThis becomes more clear in the following example:As you can see, the second Foo doesn\u2019t have any problem since any instance can access the private val i. However for the first Foo there\u2019s an error since each instance cannot see other instance\u2019s i.It\u2019s a good practice to write private[this] since it imposes a bigger restriction.To elaborate on the performance issue Alexey Romanov has mentioned, here are some of my guesses.\nQuotes from book \"Programming in Scala: A Comprehensive Step-by-Step Guide, 2nd Edition\" Section 18.2:To test it out, this code will cause compilation error:Scala complains about . Adding override keyword to  won't help should prove that the method is generated by the compiler. Adding  keyword to variable  will still cause this compilation error. However, the following code compiles fine:So, I guess  will prevent scala from generating getter and setter methods. Thus, accessing such variable will save the overhead of calling the getter and setter method.It's better to use  if you plan to synchronize the variable. Here a good example from the :In most OOP programming language like java, private fields/methods mean that these private fields/methods are not accessible outside from the class. However, instances/objects of same class can have access to the private fields of objects using assignment operator or by means of copy constructor. In Scala,private[this] is object private,which makes sure that any other object of same class is unable to access private[this] members.1.Without private[this] 2.Using private[this] Hence private[this] makes sure that _password field is only accessible with this."},
Scala

Why do Scala and frameworks like Spark and Scalding have both  and ? So then what's the difference between  and ?A big big difference, not mentioned in any other stackoverflow answer relating to this topic clearly, is that  should be given a , i.e. an operation that is both commutative and associative.  This means the operation can be parallelized.This distinction is very important for Big Data / MPP / distributed computing, and the entire reason why  even exists.  The collection can be chopped up and the  can operate on each chunk, then the  can operate on the results of each chunk - in fact the level of chunking need not stop one level deep.  We could chop up each chunk too.  This is why summing integers in a list is O(log N) if given an infinite number of CPUs.If you just look at the signatures there is no reason for  to exist because you can achieve everything you can with  with a .  The functionality of  is a greater than the functionality of . you cannot parallelize a , so its runtime is always O(N) (even if you feed in a commutative monoid). This is because it's assumed the operation is  a commutative monoid and so the cumulated value will be computed by a series of sequential aggregations.   does not assume commutativity nor associativity.  It's associativity that gives the ability to chop up the collection, and it's commutativity that makes cumulating easy because order is not important (so it doesn't matter which order to aggregate each of the results from each of the chunks). Strictly speaking commutativity is not necessary for parallelization, for example distributed sorting algorithms, it just makes the logic easier because you don't need to give your chunks an ordering.If you have a look at the Spark documentation for  it specifically says \"... commutative and associative binary operator\"Here is proof that  is NOT just a special case of Now this is where it gets a little closer to the FP / mathematical roots, and a little trickier to explain.  Reduce is defined formally as part of the MapReduce paradigm, which deals with orderless collections (multisets), Fold is formally defined in terms of recursion (see catomorphism) and thus assumes a structure / sequence to the collections.There is no  method in Scalding because under the (strict) Map Reduce programming model we cannot define  because chunks do not have an ordering and  only requires associativity, not commutativity.Put simply,  works without an order of cumulation,  requires an order of cumulation and it is that order of cumulation that necessitates a zero value NOT the existence of the zero value that distinguishes them.  Strictly speaking   work on an empty collection, because its zero value can by deduced by taking an arbitrary value  and then solving , but that doesn't work with a non-commutative operation as there can exist a left and right zero value that are distinct (i.e. ).  Of course Scala doesn't bother to work out what this zero value is as that would require doing some mathematics (which are probably uncomputable), so just throws an exception.It seems (as is often the case in etymology) that this original mathematical meaning has been lost, since the only obvious difference in programming is the signature. The result is that  has become a synonym for , rather than preserving it's original meaning from MapReduce. Now these terms are often used interchangeably and behave the same in most implementations (ignoring empty collections). Weirdness is exacerbated by peculiarities, like in Spark, that we shall now address.So Spark  have a , but the order in which sub results (one for each partition) are combined (at the time of writing) is the same order in which tasks are completed - and thus non-deterministic. Thanks to @CafeFeed for pointing out that  uses , which after reading through the code I realised that it's non-deterministic. Further confusion is created by Spark having a  but no .There is a difference between  and  even when applied to non-empty sequences. The former is defined as part of the MapReduce programming paradigm on collections with arbitrary order () and one ought to assume operators are commutative in addition to being associative to give deterministic results. The latter is defined in terms of catomorphisms and requires that the collections have a notion of sequence (or are defined recursively, like linked lists), thus do not require commutative operators.In practice due to the unmathematical nature of programming,  and  tend to behave in the same way, either correctly (like in Scala) or incorrectly (like in Spark).My opinion is that confusion would be avoided if use of the term  was completely dropped in Spark.  At least spark does have a note in their documentation:If I am not mistaken, even though the Spark API does not require it, fold also requires for the f to be commutative. Because the order in which the partitions will be aggregated is not assured.\nFor example in the following code only the first print out is sorted:  Print out:abcdefghijklmnopqrstuvwxyzabcghituvjklmwxyzqrsdefnopdefghinopjklmqrstuvabcwxyzOne other difference for Scalding is the use of combiners in Hadoop. Imagine your operation is commutative monoid, with  it will be applied on the map side also instead of shuffling/sorting all data to reducers. With  this is not the case. It is always good practice to define your operations as monoid in Scalding. in Apache Spark is not the same as  on not-distributed collections. In fact  to produce deterministic results:This  by  and suggested by  in . that observed behavior is related to  when in fact  doesn't shuffle and doesn't use .Explained: for RDDis the same  for RDD:where  is performed with disregard of partition order and results in need of commutative function. and  are equivalent in terms of order of processing and effectively (by inheritance and delegation) implemented by  and  on . Conclusion:  on RDD cannot depend on order of chunks and needs ."},
Scala

I have scala map:When I try to iterate over map like;the above does not work. In each iteration I must know what is the key and what is the value. What is the proper way to iterate over scala map using scala syntactic sugar? method receives  as argument, not 2 arguments. So you can either use it like tuple:or you can make pattern match:Three options:The trick is that iteration gives you key-value pairs, which you can't split up into a key and value identifier name without either using  or ."},
Scala

I've already read the question and answers to .Usually, we use messaging solutions which have existed for years already: either a JMS implementation such as WebSphere MQ or Apache ActiveMQ is used for Point-To-Point communication, or Tibco Rendevous for Multicast messaging.They are very stable, proven and offer high availability and performance. Nevertheless, configuration and setup seem much more complex than in Akka.When and why should I use Akka for some use cases where the aforementioned products - WebSphere MQ or ActiveMQ - have been used successfully so far? Why should I consider using Akka instead of WebSphere MQ or Tibco RV in my future project? And when should I avoid Akka? Does it offer the same high availability and performance as the other solutions? Or is it a bad idea to even compare Akka to the other messaging middlewares?Maybe there also is another messaging solution in the JVM environment which I should consider besides JMS (Point-to-Point), TibcoRV (Multicast) and Akka?First off the \"older\" message systems (MQ) are older in implementation but they are a newer in engineering idea of: . Scala Actors and Akka maybe a newer implementation but are built on an older concurrency model of Actors.The two models however end up being very similar in practice because they both are event message based: See my answer to .If you're going to code only for the JVM then Akka is probably a good choice. Otherwise I would use RabbitMQ.Also if you're a Scala developer, then Akka should be a no-brainer. However Akka's Java bindings are not very Java-ish and require casting due to Scala's type system. Also in Java people don't typically make immutable objects which I recommend you do for messaging. Consequently its very easy in Java to accidentally do something using Akka that will not scale (using mutable objects for messages, relying on weird closure callback state). With MQ this is not a problem because the messages are always serialized at the cost of speed. With Akka they are generally not.Akka also scales better with large amount of consumers than most MQ. This is because for most MQ (JMS, AMQP) clients  every queue connection requires a thread... thus lots of queues == lots of permanently running threads. This is mainly a client issue though. I think ActiveMQ Apollo has a non-blocking dispatcher that purportedly fixes that issue for AMQP. The RabbitMQ client has channels that allow you to combine multiple consumers but there are still issues with large number of consumers potentially causing deadlocks or connections to die so generally more threads are added to avoid this issue. That being said  is rather new and probably still doesn't offer all the reliable message guarantees and QoS that traditional message queues provide (but that is changing everyday). Its also generally peer-to-peer but does I think support server-to-peer which is generally what most MQ systems do (ie single point of failure) but there are MQ systems that are peer-to-peer (RabbitMQ is server-to-peer). You can use Akka as a wrapper to RabbitMQ particularly since RabbitMQ does not help you with handling the consumption of messages and routing the messages locally (in a single JVM).I made an assumption that the OP was concerned with distributed processing which both  and Message Queues can handle. That is I assumed he was talking about . . I say most because you can apply the message queue model locally as a concurrency model (ie topic, queues, exchanges) which both the  library and  do.Picking the right concurrency model/library is very important for low latency applications. A distributed processing solution such as a message queue is generally not ideal because the routing is almost always done over the wire which is obviously slower than within application and thus Akka would be a superior choice. However I believe some proprietary MQ technologies allow for local routing. Also as I mentioned earlier most MQ clients are pretty stupid about threading and do not rely on non-blocking IO and have a thread per connection/queue/channel... ironically non-blocking io is not always low latency but is generally more resource efficient.As you can see the topic of distributed programming and concurrent programming is rather large and changing everyday so my original intention was not confuse but rather focus on one particular area of distributed message processing which is what I though the OP was concerned with. In terms of concurrency one might want to focus their searches on \"reactive\" programming (RFP / streams) which is a \"newer\" but similar model to the actor model and message queue model of which all of these models can be generally combined because they are event based.I'm not an expert in messaging systems, but you can combine them with Akka in your apps, getting the best of both worlds. Here's an example that you might find useful for experimenting with Akka and messaging systems, in this case ZeroMQ:Akka-Camel would be a better example than ZeroMQ - ZeroMQ is a direct tcp to tcp communication (hence zero - there is no message queue).With AkkaCamel you can abstract away the queue and produce/consume messages direct from an actor without any code to deal with the message queue message pushing/pulling.You can forego akka-zeromq and use Akka directly with remoting.\nI think akka-zeromq is being removed from the core library but we built a good zeromq library for akka called scala-zeromq ()Akka has a couple key core use cases:1) Mutable stateIt's easier to handle shared state by hiding it in an actor. As actors handle messages synchronously, you can hold state in an actor and expose that field with high consistency via the actor API2) DistributionConcurrency is free in akka so you say it's really about solving distribution problems. Distribution across machines and cores. Akka has build in \"location transparency\" for sending messages over the wire. It has clustering and patters associated for scaling up a single service as well. This makes it a very good solution for distribution (eg micro-service architecture)Here is an example of using Akka with ActiveMQ with Akka-Camel (using Java8)"},
Scala

With the release of Scala 2.9.0, the Typesafe Stack  was also announced, which combines the Scala language with the Akka framework. Now, though Scala has actors in its standard library, Akka uses its own implementation. And, if we look for other implementations, we'll also find that Lift and Scalaz have implementations too!So, what is the difference between these implementations?This answer isn't really mine.  by Viktor Klang (of Akka fame) with the help of David Pollak (of Lift fame), Jason Zaugg (of Scalaz fame), Philipp Haller (of Scala Actors fame).All I'm doing here is formatting it (which would be easier if Stack Overflow supported tables).There are a few places I'll fill later when I have more time.If user defines public methods on\ntheir Actors, are they callable from\nthe outside?(1) Any function f becomes such an actor: (2) Any function f becomes such an actor:(3) Contravariant functor: . Also Kleisli composition in .TBDSupports nested receives?TBDTBD &  for average latency and throughput on JVM 1.8.0_x."},
Scala

Following on from , what are some good resources which explain how the new   collections library has been structured. I'm interested to find some information on how the following fit together:There's a  by Martin Odersky which should probably be your first reference. It has been supplemented as well with , which will be of particular interest to those who want to design their own collections. The rest of this answer was written way before any such thing existed (in fact, before 2.8.0 itself was released).You can find a paper about it as . Other papers in that area should be interesting as well to people interested in the differences between Scala 2.7 and 2.8.I'll quote from the paper, selectively, and complement with some thoughts of mine. There are also some images, generated by Matthias at decodified.com, and the original SVG files can be found .There are actually three hierarchies of traits for the collections: one for mutable collections, one for immutable collections, and one which doesn't make any assumptions about the collections.There's also a distinction between parallel, serial and maybe-parallel collections, which was introduced with Scala 2.9. I'll talk about them in the next section. The hierarchy described in this section refers .The following image shows the non-specific hierarchy introduced with Scala 2.8:\nAll elements shown are traits. In the other two hierarchies there are also classes directly inheriting the traits as well as classes which can be  belonging in that hierarchy through implicit conversion to wrapper classes. The legend for these graphs can be found after them.Graph for immutable hierarchy:\nGraph for mutable hierarchy:\nLegend:Here's an abbreviated ASCII depiction of the collection hierarchy, for those who can't see the images.When Scala 2.9 introduced parallel collections, one of the design goals was to make their use as seamless as possible. In the simplest terms, one can replace a non-parallel (serial) collection with a parallel one, and instantly reap the benefits.However, since all collections until then were serial, many algorithms using them assumed and depended on the fact that they  serial. Parallel collections fed to the methods with such assumptions would fail. For this reason, all the hierarchy described in the previous section .Two new hierarchies were created to support the parallel collections.The parallel collections hierarchy has the same names for traits, but preceded with : , ,  and . Note that there is no , since any collection supporting parallel access is capable of supporting the stronger  trait. It doesn't have some of the more specialized traits present in the serial hierarchy either. This whole hierarchy is found under the directory .The classes implementing parallel collections also differ, with  and  for both mutable and immutable parallel collections, plus  and  implementing  and  implementing .Another hierarchy also exists that mirrors the traits of serial and parallel collections, but with a prefix : , , ,  and . These traits are  to both parallel and serial collections. This means that a method taking a  cannot receive a parallel collection, but a method taking a  is expected to work with both serial and parallel collections.Given the way these hierarchies were structured, code written for Scala 2.8 was fully compatible with Scala 2.9, and demanded serial behavior. Without being rewritten, it cannot take advantage of parallel collections, but the changes required are very small.Any collection can be converted into a parallel one by calling the method  on it. Likewise, any collection can be converted into a serial one by calling the method  on it.If the collection was already of the type requested (parallel or serial), no conversion will take place. If one calls  on a parallel collection or  on a serial collection, however, a new collection with the requested characteristic will be generated.Do not confuse , which turns a collection into a non-parallel collection, with , which returns a  created from the elements of the collection. Calling  on a parallel collection will return a , not a serial collection.While there are many implementing classes and subtraits, there are some basic traits in the hierarchy, each of which providing more methods or more specific guarantees, but reducing the number of classes that could implement them.In the following subsections, I'll give a brief description of the main traits and the idea behind them.This trait is pretty much like trait  described below, but with the limitation that you can only use it . That is, any methods called on a   render it unusable.This limitation makes it possible for the same methods to be shared between the collections and . This makes it possible for a method that works with an  but not using -specific methods to actually be able to work with any collection at all, plus iterators, if rewritten to accept .Because  unifies collections and iterators, it does not appear in the previous graphs, which concern themselves only with collections.At the top of the  hierarchy is trait . Its only abstract operation isThe operation is meant to traverse all elements of the collection, and apply the given operation f to each\nelement. The application is done for its side effect only; in fact any function result of f is discarded by\nforeach.Traversible objects can be finite or infinite. An example of an infinite traversable object is the stream\nof natural numbers . The method  indicates whether a collection is possibly\ninfinite. If  returns true, the collection is certainly finite. If it returns false, the\ncollection has not been not fully elaborated yet, so it might be infinite or finite.This class defines methods which can be efficiently implemented in terms of  (over 40 of them).This trait declares an abstract method  that returns an iterator that yields all the collection\u2019s elements one by one. The  method in  is implemented in terms of . Subclasses of  often override foreach with a direct implementation for efficiency.Class  also adds some less-often used methods to , which can be implemented efficiently only if an  is available. They are summarized below.After  there come three base traits which inherit from it: , , and . All three have an  method and all three implement the  trait, but the meaning of  is different in each case.I trust the meaning of ,  and  is intuitive. After them, the classes break up in specific implementations that offer particular guarantees with regards to performance, and the methods it makes available as a result of it. Also available are some traits with further refinements, such as ,  and .This was done to achieve maximum code reuse. The concrete  implementation for classes with a certain structure (a traversable, a map, etc) is done in the Like classes. The classes intended for general consumption, then, override selected methods that can be optmized.The builder for the classes, ie, the object which knows how to create instances of that class in a way that can be used by methods like , is created by a method in the companion object. So, in order to build an object of type X, I need to get that builder from the companion object of X. Unfortunately, there is no way, in Scala, to get from class X to object X. Because of that, there is a method defined in each instance of X, , which returns the companion object of class X.While there might be some use for such method in normal programs, its target is enabling code reuse in the collection library.You aren't supposed to care about that. They are implicit precisely so that you don't need to figure out how to make it work.These implicits exists to enable the methods on the collections to be defined on parent classes but still return a collection of the same type. For example, the  method is defined on , but if you used on a  you'll get a  back."},
Scala

In Scala, if I define a method called  in a class or a top-level object, that method will be called whenever I append a pair a parentheses to an instance of that class, and put the appropriate arguments for  in between them. For example:So basically,  is just syntactic sugar for .How does Scala do this conversion?Is there a globally defined implicit conversion going on here, similar to the implicit type conversions in the Predef object (but different in kind)? Or is it some deeper magic? I ask because it seems like Scala strongly favors consistent application of a smaller set of rules, rather than many rules with many exceptions. This initially seems like an exception to me.I don't think there's anything deeper going on than what you have originally said: it's just syntactic sugar whereby the compiler converts  into  as a special syntax case.This might seem like a specific rule, but only a few of these (for example, with ) allows for -like constructs and libraries.It is actually the other way around, an object or class with an apply method is the normal case and a function is way to construct implicitly an object of the same name with an apply method. Actually every function you define is an subobject of the Function trait (n is the number of arguments).Refer to section  on page 77 of the  for more information of the topic.Yes. And this rule belongs to this smaller set."},
Scala

I'm using IntelliJ IDEA 13 (Community Edition) with the Scala plugin.My initial import of an existing Scala project with a  worked fine.  The library dependencies were picked up by IDEA. Additional dependencies added after the initial import were not picked up, although I had checked the  option.How can I force IDEA to reload the dependencies from ?You can force SBT to reload changes:\nOpen SBT toolwindow (on the right side of IDE) and press refresh button.If you use auto-import feature you need to save your file to force auto-refresh.As of 7 Dec, 2013, the issue is solved.  (this applies to both community and ultimate editions).This is the link to the issue opened on JetBrains developer community web site:\nIF plugin gets 'stuck' it helps to invalidate cache (under file menu) and restart intellij.This may be due to a broken publication of  that occurred tonight, about 4 or 5 hours ago.  Given that your post is 4 hours old ...You can see the ivy activity in  ( or  on OSX). I have opened a ticket at JetBrains.Ticket for broken plublication of sbt.jetbrains is resolved. Updating scala plugin will fix this issue\nTicket : "},
Scala

How do I get an instance of  in Scala? In Java, I can do this:What would be the equivalent in Scala?There is a method  in  that retrieves the runtime representation of a class type.You can use the  method to get the class object of an instance at runtime in the same manner as Java"},
Scala

I come from a Python background, where at any point in my code I can addand at runtime I'll be dropped into an interactive interpreter at that spot. Is there an equivalent for scala, or is this not possible at runtime?Yes, you can, on Scala 2.8. Note that, for this to work, you have to include the scala-compiler.jar in your classpath. If you invoke your scala program with , it will be done automatically (or so it seems in the tests I made).You can then use it like this:You may pass multiple  arguments. When the REPL comes up, the value on the right will be bound to a val whose name you provided on the left. For instance, if I change that line like this:Then the execution will happen like this:You continue the execution by typing .You may also unconditionally drop into REPL by invoking , which receives a  of  instead of a vararg. Here's a full example, code and execution:And then:To add to Daniel's answer, as of Scala 2.9, the  and  methods are contained in . Also,  is now .As of Scala 2.10 both  and  have been removed from .To break into interpreter you will have to work with  directly.First add  library. For Eclipse Scala, right click on project =>  =>  => .And then you can use the following where you want to start the interpreter:In Eclipse Scala the interpreter can be used from the  view:"},
Scala

Is there a good \"scala-esque\" (I guess I mean functional) way of recursively listing files in a directory? What about matching a particular pattern?For example recursively all files matching  in .Scala code typically uses Java classes for dealing with I/O, including reading directories.  So you have to do something like:You could collect all the files and then filter using a regex:Or you could incorporate the regex into the recursive search:I would prefer solution with Streams becouse you can iterate over infinite file system(Streams are lazy evaluated collections)Example for searchingScala is a multi-paradigm language. A good \"scala-esque\" way of iterating a directory would be to reuse an existing code!I'd consider  a perfectly scala-esque way of iterating a directory. You can use some implicit conversions to make it easier. LikeI like yura's stream solution, but it (and the others) recurses into hidden directories. We can also simplify by making use of the fact that  returns null for a non-directory.Now we can list filesor realise the whole stream for later processingApache Commons Io's  fits on one line, and is quite readable:As of Java 1.7 you all should be using java.nio. It offers close-to-native performance (java.io is very slow) and has some useful helpersBut Java 1.8 introduces exactly what you are looking for:You also asked for file matching. Try  and also See documentation here: Take a look at scala.tools.nsc.ioThere are some very useful utilities there including deep listing functionality on the Directory class.If I remember correctly this was highlighted (possibly contributed) by retronym and were seen as a stopgap before io gets a fresh and more complete implementation in the standard library.And here's a mixture of the stream solution from @DuncanMcGregor with the filter from @Rick-777:This gives you a Stream[File] instead of a (potentially huge and very slow) List[File] while letting you decide which sorts of directories to recurse into with the descendCheck() function.I personally like the elegancy and simplicity of @Rex Kerr's proposed solution. But here is what a tail recursive version might look like:How aboutScala has library 'scala.reflect.io' which considered experimental but does the workNo-one has mentioned yet Here's a similar solution to Rex Kerr's, but incorporating a file filter:The method returns a List[File], which is slightly more convenient than Array[File].  It also ignores all directories that are hidden (ie. beginning with '.').It's partially applied using a file filter of your choosing, for example:The simplest Scala-only solution (if you don't mind requiring the Scala compiler library):Otherwise, @Renaud's solution is short and sweet (if you don't mind pulling in Apache Commons FileUtils):Where  is a java.io.File:It seems nobody mentions the  library from scala-incubrator...Or with Or if you want  explicitly...Documentation is available here: This incantation works for me:You can use tail recursion for it:Why are you using Java's File instead of Scala's AbstractFile?With Scala's AbstractFile, the iterator support allows writing a more concise version of James Moore's solution:"},
Scala

I have noticed a strange behavior of my scala compiler. It occasionally throws an OutOfMemoryError when compiling a class. Here's the error message:It only happens once in a while and the error is usually not thrown on the subsequent compile run. I use Scala 2.9.0 and compile via SBT.Does anybody have a clue as to what might be the cause for this error? Thanks in advance for your insights.The cause for  is that it doesn't have enough  :) If you are using Oracle JVM, you need to add the  (or some other amount of space) argument to your  script. For other JVMs, look at their documentation.I use HomeBrew to install sbt on OS X. It supports a  argument which can be put in  file with .I assumed you're using  0.13.6 or higher. Create  file in your  project's root with the following content: is for Java 8 whereas  is for Java 7. They are critical to prevent out of memory errors related either to  or  exhaustion. Of course, consider adapting flag values or adding any other flags required.More details and alternative approaches can be found in this .I had this issue, played around with it for 10 minutes looking at sites trying to change the memory size.Turns out i resolved it by,Then,This cleared it up for me.It looks like a memory leak in SBT for me as in my case the program compiles and runs successfully for about 3-5 times before hitting the exception which is fixed by SBT restart.The most adequate solution indeed seems to be  JVM parameter as Alexey Romanov suggests or to restart SBT periodically if it helps.But there is another interesting way: try switching to . AFAIK it doesn't use PermGen any more and is probably immune to this exception this way.I still hope SBT authors will address this issue in future versions.I am building with the Jenkins sbt plugin and had the same problems. They were resolved after copying the SBT_OPTS from the sbt file to the Jenkins job config's JVM flags. Originally using a command like:I got first OutOfMemoryError:  which I solved using , and then OutOfMemoryError: , to which  was the remedy. So in my case, a command like this worked:"},
Scala

Can someone please explain traits in Scala? What are the advantages of traits over extending an abstract class?The short answer is that you can use multiple traits -- they are \"stackable\". Also, traits cannot have constructor parameters.Here's how traits are stacked. Notice that the ordering of the traits are important. They will call each other from right to left.This  gives a good example of trait usage.  One big advantage of traits is that you can extend multiple traits but only one abstract class. Traits solve many of the problems with multiple inheritance but allow code reuse. If you know ruby, traits are similar to mix-insThis is the best example I've seenScala in practice: Composing Traits \u2013 Lego style:\nTraits are useful for mixing functionality into a class.  Take a look at .  Note how you can mix in various domain-specific languages (DSL) into a test class.  look at the quick start guide to look at some of the DSL's supported by Scalatest (  )Similar to interfaces in Java, traits are used to define object types by specifying the signature of the supported methods. Unlike Java, Scala allows traits to be partially implemented; i.e. it is possible to define default implementations for some methods. In contrast to classes, traits may not have constructor parameters.\nTraits are like classes, but which define an interface of functions and fields that classes can supply concrete values and implementations.Traits can inherit from other traits or from classes.   I am quoting from the website of the book  and more specifically the section called \"\" from Chapter 12.There is a bit more information in the above link regarding traits and I suggest you read the full section. I hope this helps."},
Scala

What are the precise rules for when you can omit (omit) parentheses, dots, braces, = (functions), etc.?For example, (service.findAllPresentations.get.first.votes.size) must be equalTo(2).Why can't I go:?The compiler error is:Why does it think I'm trying to pass in a parameter? Why must I use dots for every method call?Why must  be equalTo(2) result in:Yet, the \"must be equalTo 2\" of\n must be equalTo 2, that is, method chaining works fine? - object chain chain chain param.I've looked through the Scala book and website and can't really find a comprehensive explanation.Is it in fact, as Rob H explains in Stack Overflow question , that the only valid use-case for omitting the '.' is for \"operand operator operand\" style operations, and not for method chaining?You seem to have stumbled upon the answer. Anyway, I'll try to make it clear.You can omit dot when using the prefix, infix and postfix notations -- the so called . While using the operator notation, and only then, you can omit the parenthesis if there is less than two parameters passed to the method.Now, the operator notation is a notation for , which means it can't be used in the absence of the object which is being called.I'll briefly detail the notations.Only , ,  and  can be used in prefix notation. This is the notation you are using when you write  or .That's the notation where the method appears between an object and it's parameters. The arithmetic operators all fit here.That notation is used when the method follows an object . For example, you can write , and that's postfix notation.You can chain infix notation calls without problem, as long as no method is curried. For example, I like to use the following style:That's the same thing as:Now, why am I using parenthesis here, if filter and map take a single parameter? It's because I'm passing anonymous functions to them. I can't mix anonymous functions definitions with infix style because I need a boundary for the end of my anonymous function. Also, the parameter definition of the anonymous function might be interpreted as the last parameter to the infix method.You can use infix with multiple parameters:Curried functions are hard to use with infix notation. The folding functions are a clear example of that:You need to use parenthesis outside the infix call. I'm not sure the exact rules at play here.Now, let's talk about postfix. Postfix can be hard to use, because it . For example, you can't do the following:Because tail does not appear at the end of the expression. You can't do this either:You could use infix notation by using parenthesis to mark end of expressions:Note that postfix notation is discouraged because .I hope this has cleared all the doubts. If not, just drop a comment and I'll see what I can do to improve it. or  can be omitted from class parameters which will make the parameter private.Adding var or val will cause it to be public (that is, method accessors and mutators are generated). can be omitted if the class has no body, that is,Generic parameters can be omitted if they can be inferred by the compiler. However note, if your types don't match, then the type parameter is always infered so that it matches. So without specifying the type, you may not get what you expect - that is, givenThis will give you a type error Whereas this works fine:Because the type parameter, T, is inferred as the least common supertype of the two - Any. can be dropped if the function returns Unit (nothing). for the function body can be dropped if the function is a single statement, but only if the statement returns a value (you need the  sign), that is,but this doesn't work:The return type of the function can be omitted if it can be inferred (a recursive method must have its return type specified). can be dropped if the function doesn't take any arguments, that is,which by convention is reserved for methods which have no side effects - more on that later. isn't actually dropped per se when defining a  paramenter, but it is actually a quite semantically different notation, that is,Says myOp takes a pass-by-name parameter, which results in a String (that is, it can be a code block which returns a string) as opposed to function parameters,which says  takes a function which has zero parameters and returns a String.(Mind you, pass-by-name parameters get compiled into functions; it just makes the syntax nicer.) can be dropped in the function parameter definition if the function only takes one argument, for example:But if it takes more than one argument, you must include the (): can be dropped to use operator notation, which can  be used for infix operators (operators of methods that take arguments). See  for more information.Because this notation is reserved by convention for methods that have no side effects, like List#tail (that is, the invocation of a function with no side effects means that the  function has no observable effect, except for its return value).When calling a function which takes a function, you cannot omit the () from the inner function definition, for example:When calling a function that takes a by-name parameter, you cannot specify the argument as a parameter-less anonymous function. For example, given:You must call it as:orbut not:IMO, overuse of dropping return types can be harmful for code to be re-used. Just look at specification for a good example of reduced readability due to lack of explicit information in the code. The number of levels of indirection to actually figure out what the type of a variable is can be nuts. Hopefully better tools can avert this problem and keep our code concise.A collection of quotes giving insight into the various conditions...Personally, I thought there'd be more in the specification. I'm sure there must be, I'm just not searching for the right words...There are a couple of sources however, and I've collected them together, but nothing really complete / comprehensive / understandable / that explains the above problems to me...:From :From :From blog post :From the language specification:From :But what also confuses me is this quote:Because as far as I can see, there  an object to receive the call...Actually, on second reading, maybe this is the key:As mentioned on the blog post:  .So perhaps this is actually a very strict \"syntax sugar\" which  works where you are effectively . e.g.And nothing else.This would explain my examples in the question.But as I said, if someone could point out to be exactly where in the language spec this is specified, would be great appreciated.Ok, some nice fellow (paulp_ from #scala) has pointed out where in the language spec this information is:Hmm - to me it doesn't mesh with what I'm seeing or I just don't understand it ;)There aren't any. You will likely receive advice around whether or not the function has side-effects. This is bogus. The correction is to not use side-effects to the reasonable extent permitted by Scala. To the extent that it cannot, then all bets are off.  bets. Using parentheses is an element of the set \"all\" and is superfluous. It does not provide any value once all bets are off.This advice is essentially an attempt at an  that fails (not to be confused with: is less useful than other effect systems).Try not to side-effect. After that, accept that all bets are off. Hiding behind a de facto syntactic notation for an effect system can and does, only cause harm.I find it easier to follow this rule of thumb: in expressions spaces alternate between methods and parameters. In your example,  parses as . Note that the parentheses around the 2 have a higher associativity than the spaces. Dots also have higher associativity, so would parse as . parses as . "},
Scala

In Scala 2.8 is there a way to overload constructors of a case class?If yes, please put a snippet to explain, if not, please explain why?Overloading constructors isn't special for case classes:However, you may like to also overload the  method in the companion object, which is called when you omit .In Scala 2.8, named and default parameters can often be used instead of overloading.You can define an overloaded constructor the usual way, but to invoke it you have to use the \"new\" keyword."},
Scala

The Eclipse scala plugin has a nice feature which shows you the type of a variable when you hover the mouse over it.  How do I see the same information with the IntelliJ plugin?Select expression and type  + .If you want to change the shortcut go to  and enter \"Type Info\" in the search field. In older versions, it's  +  +  + .CTRL / Command key and hover over the variable or method.You can hit  +  on a variable or method signature to view its type.There is also a neat trick to view type of any expression: select the expression and type  +  + . This will show  dialog with expression type to be extracted shown for convenience.On OS X, it's  +  +  for me. This shows the exact type with resolved generics.Under MacOS with  keybindings, it is supposed to be +, however that does not seem to work at all (for me).In the settings ( and enter \"Type Info\" in the search field), \nI added the shortcut ++ to the action. This shortcut works fine.You can set IntelliJ up sort of like eclipse. Go to:and then tick \"Show type info on mouse hover after, ms\" and set your preferred timeout.This works well except that other messages seem to take preference. The most common being \"Declaration is never used\" which is quite a lot of the time if you have just written a  and want to see it's type. Then you have to resort to ( + ) for PC or ( +  + ) forMac.Hold down the Command key as you mouseover.  Note: I tested this on Mac OS X with standard keybindings.  Different OSes or non-standard keybindings may of course be different, but the functionality is certainly there.There's good tips gathered around here, but since the mappings vary by the keyboard bindings, here's a summary for the  bindings.Note: The  bindings are  not the default in IntelliJ 13.1, but they really should be. They have a more native OS X feel than the old  bindings. You can activate them via  (in the search field) > The real usability problem with these (as of IntelliJ 13.1) is that one needs to hold the key,  move the cursor. It should ideally also work when you have the cursor already on the expression, then start keeping ctrl/alt/cmd pressed in. I'll request them for this.ps. I know it's OS X, officially, not Mac OS X. IntelliJ IDEA still uses the old naming at least for the keycaps."},
Scala

I have a handy function that I've used in Java for converting an InputStream to a String.  Here is a direct translation to Scala:Is there an idiomatic way to do this in scala?does pretty much the same thing.  Not sure why you want to get lines and then glue them all back together, though.  If you can assume the stream's nonblocking, you could just use , read the whole thing into a byte array, and create a string from that directly.Edit: in 2.11, a performance bug with  on  has been fixed, so now it's just\nwill also do the deed.....Faster way to do this:"},
Scala

In Scala, we can use at least two methods to retrofit existing or new types. Suppose we want to express that something can be quantified using an . We can define the following trait.And then we can use implicit conversions to quantify e.g. Strings and Lists.After importing these, we can call the method  on strings and lists. Note that the quantifiable list stores its length, so it avoids the expensive traversal of the list on subsequent calls to .An alternative is to define a \"witness\"  that states, that some type  can be quantified.We then provide instances of this type class for  and  somewhere.And if we then write a method that needs to quantify its arguments, we write:Or using the context bound syntax:Now comes the question. How can I decide between those two concepts?What I have noticed so far.Present one (or more) use case(s) where the difference between both concepts matters and explain why I would prefer one over the other. Also explaining the essence of the two concepts and their relation to each other would be nice, even without example.While I don't want to duplicate my material from ,  I think it's worth noting that type classes / type traits are infinitely more flexible.has the ability to search its local environment for a default type class.   However, I can override default behavior at any time by one of two ways:Here's an example:This makes type classes infinitely more flexible.   Another thing is that type classes / traits support implicit  better.In your first example, if you use an implicit view, the compiler will do an implicit lookup for:Which will look at 's companion object and the  companion object.Notice that  is  in the implicit lookup.   This means you have to place the implicit view in a package object  import it into scope.   It's more work to remember what's going on.On the other hand, a type class is .  You see what it's looking for in the method signature.   You also have an implicit lookup ofwhich will look in 's companion object  's companion object.   Meaning that you can provide defaults  new types (like a  class) can provide a default in their companion object and it will be implicitly searched.In general, I use type classes.   They are infinitely more flexible for the initial example.   The only place I use implicit conversions is when using an API layer between a Scala wrapper and a Java library, and even this can be 'dangerous' if you're not careful.One criterion that can come into play is how you want the new feature to \"feel\" like; using implicit conversions, you can make it look like it is just another method:...while using type classes it will always look like it you are calling an external function:One thing that you can achieve with type classes and not with implicit conversions is adding properties to a , rather than to an instance of a type. You can then access these properties even when you do not have an instance of the type available. A canonical example would be:This example also shows how the concepts are tightly related: type classes would not be nearly as useful if there were no mechanism to produce infinitely many of their instances; without the  method (not a conversion, admittedly), I could only have finitely many types have the  property.You can think of the difference between the two techniques by analogy to function application, just with a named wrapper.  For example:An instance of the former encapsulates a function of type , whereas an instance of the latter has already been applied to an .  You could continue the pattern...thus you could think of  sort of like the partial application of  to some  instance.  A great example of this was written up by Miles Sabin as .So really my point is that, in principle:"},
Scala

I just finished , and I've been looking into the changes between Scala 2.7 and 2.8. The one that seems to be the most important is the continuations plugin, but I don't understand what it's useful for or how it works. I've seen that it's good for asynchronous I/O, but I haven't been able to find out why. Some of the more popular resources on the subject are these:And this question on Stack\u00a0Overflow:Unfortunately, none of these references try to define what continuations are for or what the shift/reset functions are supposed to do, and I haven't found any references that do.  I haven't been able to guess how any of the examples in the linked articles work (or what they do), so one way to help me out could be to go line-by-line through one of those samples. Even this simple one from the third article:Why is the result 8? That would probably help me to get started.My  does explain what  and  do, so you may want to read that again.Another good source, which I also point in my blog, is the Wikipedia entry on . That one is, by far, the most clear on the subject, though it does not use Scala syntax, and the continuation is explicitly passed.The paper on delimited continuations, which I link to in my blog but seems to have become broken, gives many examples of usage.But I think the best example of the  of delimited continuations is Scala Swarm. In it, the library  the execution of your code at one point, and the remaining computation becomes the continuation. The library then does something -- in this case, transferring the computation to another host, and returns the result (the value of the variable which was accessed) to the computation that was stopped.Now, you don't understand even the simple example on the Scala page, so  read my blog. In it I'm  concerned with explaining these basics, of why the result is .I found the existing explanations to be less effective at explaining the concept than I would hope.  I hope this one is clear (and correct.)  I have not used continuations yet.When a continuation function  is called:So in this example, follow the letters from A to ZThis prints:Continuation capture the state of a computation, to be invoked later.Think of the computation between leaving the shift expression and leaving the reset expression as a function. Inside the shift expression this function is called k, it is the continuation. You can pass it around, invoke it later, even more than once.I think the value returned by the reset expression is the value of the expression inside the shift expression after the =>, but about this I'm not quite sure.So with continuations you can wrap up a rather arbitrary and non-local piece of code in a function. This can be used to implement non-standard control flow, such as coroutining or backtracking.So continuations should be used on a system level. Sprinkling them through your application code would be a sure recipe for nightmares, much worse than the worst spaghetti code using goto could ever be. I have no in depth understanding of continuations in Scala, I just inferred it from looking at the examples and knowing continuations from Scheme.Given the canonical example from the  for Scala's delimited continuations, modified slightly so the function input to  is given the name  and thus is no longer anonymous.The Scala plugin transforms this example such that the computation (within the input argument of ) starting from each  to the invocation of   is  with the function (e.g. ) input to .The replaced computation is  (i.e. moved) into a function . The function  inputs the function , where   the replaced computation,  inputs , and the computation in  replaces  with .Which has the same effect as:Note the type  of the input parameter  (i.e. the type signature of ) was given by the type signature of the input parameter of .Another  example with the conceptually equivalent abstraction, i.e.  is the function input to :I believe this would be translated to the logical equivalent of:I hope this elucidates the coherent common abstraction which was somewhat obfuscated by prior presentation of these two examples. For example, the canonical first example was presented in the  as an anonymous function, instead of my named , thus it was not immediately clear to some readers that it was abstractly analogous to the  in the  second example.Thus delimited continuations create the illusion of an inversion-of-control from \"you call me from outside of \" to \"I call you inside \".Note the return type of  is, but  is not, required to be the same as the return type of , i.e.  has the freedom to declare any return type for  as long as  returns the same type as . Ditto for  and  (see also  below).Delimited continuations do not implicitly invert the control of state, e.g.  and  are not pure functions. Thus the caller can not create referentially transparent expressions and thus does not have .We can explicitly achieve pure functions with delimited continuations.I believe this would be translated to the logical equivalent of:This is getting noisy, because of the explicit environment.Tangentially note, Scala does not have Haskell's global type inference and thus as far as I know couldn't support implicit lifting to a state monad's  (as one possible strategy for hiding the explicit environment), because Haskell's global (Hindley-Milner) type inference depends on .From my point of view, the best explanation was given here: One of examples:Another (more recent -- May 2016) article on Scala continuations is:\n\"\" by \n.\nIt also refers to 's  mentioned in 's .But before that, it describes Continuations like so:That being said, as announced in "},
Scala

I'm looking for a good open source library for scala for math and statistics. Hopefully something like Apache Math or Colt, but implemented in Scala. Can anyone point me in the right direction? Yes, there are some:by twitter for graph processing:Abstract algebra library from twitter:! has experimental status !Figaro is a Scala library for Probabilistic Programming. You could find more information about Figaro here Figaro is available for download from The author of this library is currently writing a book on Probabilistic Programming using Figaro. Here is the link to the book page: "},
Scala

With equals sign:Without equals sign:Both of the above programs execute the same way. In the blog post  I read that when the equals sign are missing, the method will return  (same as Java's ), so methods that return a value must use the equals sign. But methods that don't return a value can be written either way.What is the best practice for using the equals sign in Scala methods that don't return a value?I actually disagree pretty strongly with Daniel. I think the non-equal syntax should  be used. If your method is being exposed as an API and you're worried about accidentally returning the wrong type, add an explicit type annotation:The non-equal syntax is shorter and might look \"cleaner\", but I think it just adds the possibility of confusion. I have sometimes forgotten to add an equal sign and believed my method was returning a value when actually it was returning Unit. Because the non-equal and equal-with-inferred-type syntaxes are so visually similar, it's easy to miss this problem.Even though it costs me a little more work, I prefer the explicit type annotations when they matter (namely, exposed interfaces).UPDATE: as of Scala-2.10, using equals sign is preferred. Old answer:Methods which return  should  use the non-equals syntax.  This avoids potential mistakes in implementation carrying over into the API.  For example, you could have accidentally done something like this:Trivial example of course, but you can see how this might be a problem.  Because the last expression does  return , the method itself will have a return type other than .  This is exposed in the public API, and might cause other problems down the road.  With the non-equals syntax, it doesn't matter what the last expression is, Scala fixes the return type as .It's also two characters cleaner.  :-)  I also tend to think that the non-equals syntax makes the code just a little easier to read.  It is more obvious that the method in question returns  rather than some useful value.On a related note, there is an analogous syntax for abstract methods:The method  has signature .  Scala does this when you omit the type annotation on an abstract member.  Once again, this is cleaner, and (I think) easier to read.You  use equals sign in call declarations except the definitions returning Unit.In this latter case, you  forgo the equals sign. This syntax may be deprecated, though, so it's best avoided. Using equals sign and declaring the return type will always work.For methods,  recommends the equals syntax as opposed to procedure syntaxOne thing : imagine the last statement of a method that should return Unit does not return Unit. Using the non-equal syntax is then very convenient, I hope this will not be deprecated as I see several use case for itAs time as progressed the default style has changed, and this has been mentioned in many of the comments to answers, it is recommended in the  to use the  syntax for function declarations.for method that dont have a return value,  a way to express such methods is leaving out the result type and the\nequals sign, following the method with a block enclosed in curly braces. In\nthis form, the method looks like a procedure, a method that is executed only\nfor its side effects. "},
Scala

Is there a case where a companion object (singleton) for a class is needed? Why would I want to create a class, say  and also create a companion object for it?The companion object basically provides a place where one can put \"static-like\" methods. Furthermore, a companion object, or companion module, has full access to the class members, including private ones.Companion objects are great for encapsulating things like factory methods. Instead of having to have, for example,  and  everywhere, you can have a class with a companion object take on the factory responsibilities.Companion objects are useful for storing state and methods that are common to all instances of a class  methods or fields. They use regular virtual methods which can be overridden through inheritance. Scala truly has nothing static. There are lots of ways you can use this but here's a simple example.Which produces this output:...and it's a good place to store static factory methods (not that DP) for accompanied classes. If you name those overloaded factory methods apply(//) you will be able to create/initialize you class Example code:I wouldn't call the object/base class AbstractXxxxx because it doesn't looks bad: like creating something abstract. Give those names a real meaning.\nConsider using immutable, method less, case classes and seal the abstract base class. In addition to the things Saem said in , the Scala compiler also looks for  of types in the corresponding companion objects (of either the source or the target), so the conversions don't need to be imported.About the reason for singleton objects in general  says:I always see companion objects as a  to write both functional and object oriented code in Scala. Many times we just need pure functions which take some input and provide a processing result. Putting those relevant functions in the companion object makes it easy to look up and use, for myself as well as some one building on top of my code. Moreover, it is a language provided feature to write the singleton pattern without doing anything. This is especially useful when you need a singleton to encapsulate a delegator for the life of JVM. For example, writing a simple HTTP client library in Scala where you can encapsulate an underlying Java implementation based delegator and let consumers of your API live in pure world."},
Scala

How do I split a sequence into two lists by a predicate?Alternative: I can use  and , or write my own method, but isn't there a better more general (built-in) method ?By using  method: Good that  was the thing you wanted -- there's another method that also uses a predicate to split a list in two: .The first one,  will put all \"true\" elements in one list, and the others in the second list. will put all elements in one list until an element is \"false\" (in terms of the predicate). From that point forward, it will put the elements in the second list.You might want to take a look at  - it allows you to search the scala standard library for functions by their signature. For example, type the following:You would see .You can also use foldLeft if you need something a little extra.  I just wrote some code like this when partition didn't cut it:If you want to split a list into more than 2 pieces, and ignore the bounds, you could use something like this (modify if you need to search for ints)"},
Scala

I'm looking for a way to convert an arbitrary length list of Futures to a Future of List. I'm using Playframework, so ultimately, what I really want is a , but to make things simpler, let's just say  The normal way to do this would be to use  but there's a twist... The list I'm given usually has around 10-20 futures in it, and it's not uncommon for one of those futures to fail (they are making external web service requests). Instead of having to retry all of them in the event that one of them fails, I'd like to be able to get at the ones that succeeded and return those.   For example, doing the following doesn't workInstead of getting the only the exception, I'd like to be able to pull the 1 and 3 out of there. I tried using , but that apparently just calls  behind the scenes. Thanks in advance for the help!The trick is to first make sure that none of the futures has failed.   is your friend here, you can combine it with  to convert all the  results to  instances, all of which are certain to be successful futures.Then use  as before, to give you a Then filter:You can even pull out the specific failures, if you need them:I tried Kevin's answer, and I ran into a glitch on my version of Scala (2.11.5)...  I corrected that, and wrote a few additional tests if anyone is interested... here is my version >  I just came across this question and have another solution to offer:The idea here is that within the fold you are waiting for the next element in the list to complete (using the for-comprehension syntax) and if the next one fails you just fallback to what you already have."},
Scala

I am not able to understand the point of  class in Scala. I mean, I am not able to see any advanages of  over .For example, consider the code:Now suppose, the method  returns , then the call made to  on first line of  is bound to fail with . Similarly if  returns , the  call will again fail with some similar error.If so, then why does Scala complicate things by introducing a new value wrapper () instead of following a simple approach used in Java?I have edited my code as per 's suggestion. I am still not able to see any particular advantage of . I have to test for the exceptional  or  in both cases. :(If I have understood correctly from , is the only advantage of  is that it explicitly tells the programmer that ? Is this the only reason behind this design choice?You'll get the point of  better if you force yourself to never, ever, use . That's because  is the equivalent of \"ok, send me back to null-land\".So, take that example of yours. How would you call  without using ? Here are some alternatives:None of this alternatives will let you call  on something that does not exist.As for why  exists, Scala doesn't tell you how your code should be written. It may gently prod you, but if you want to fall back to no safety net, it's your choice.You nailed it here:Except for the \"only\". But let me restate that in another way: the  advantage of  over  is type safety. It ensures you won't be sending a  method to an object that may not exist, as the compiler won't let you.You said you have to test for nullability in both cases, but if you forget -- or don't know -- you have to check for null, will the compiler tell you? Or will your users?Of course, because of its interoperability with Java, Scala allows nulls just as Java does. So if you use Java libraries, if you use badly written Scala libraries, or if you use badly written  Scala libraries, you'll still have to deal with null pointers.Other two important advantages of  I can think of are:The latter one takes much longer to fully appreciate, and it's not well suited to simple examples, as it only shows its strength on complex code. So, I'll give an example below, but I'm well aware it will hardly mean anything except for the people who get it already.Compare:with:The monadic property , which appears in Scala as the  function, allows us to chain operations on objects without worrying about whether they are 'null' or not.Take this simple example a little further. Say we wanted to find all the favourite colours of a list of people.Or perhaps we would like to find the name of a person's father's mother's sister:I hope this sheds some light on how options can make life a little easier.The difference is subtle. Keep in mind to be truly a function it  return a value - null is not really considered to be a \"normal return value\" in that sense, more a /nothing. But, in a practical sense, when you call a function that optionally returns something, you would do: Granted, you can do something similar with null - but this makes the semantics of calling  obvious by virtue of the fact it returns  (a nice practical thing, other than relying on someone reading the doc and getting an NPE because they don't read the doc). I will try and dig up a functional programmer who can give a stricter answer than I can.For me options are really interesting when handled with for comprehension syntax. Taking  preceding example:If any of the assignation are , the  will be  but no  will be raised. You can then safely pass to a function taking Option parameters without worrying. so you don't check for null and you don't care of exceptions. Compare this to the java version presented in  example.You have pretty powerful composition capabilities with Option:Maybe someone else pointed this out, but I didn't see it:One advantage of pattern-matching with Option[T] vs. null checking is that Option is a sealed class, so the Scala compiler will issue a warning if you neglect to code either the Some or the None case. There is a compiler flag to the compiler that will turn warnings into errors. So it's possible to prevent the failure to handle the \"doesn't exist\" case at compile time rather than at runtime. This is an enormous advantage over the use of the null value.It's not there to help avoid a null check, it's there to force a null check.  The point becomes clear when your class has 10 fields, two of which could be null.  And your system has 50 other similar classes.  In the Java world, you try to prevent NPEs on those fields using some combination of mental horesepower, naming convention, or maybe even annotations.  And every Java dev fails at this to a significant degree.  The Option class not only makes \"nullable\" values visually clear to any developers trying to understand the code, but allows the compiler to enforce this previously unspoken contract. [ copied from  by  ]One point that nobody else here seems to have raised is that while you can have a null reference, there is a distinction introduced by Option.That is you can have , which would be inhabited by ,  and  where  is one of the usual inhabitants of . This means that if you have some kind of container, and want to be able to store null pointers in it, and get them out, you need to pass back some extra boolean value to know if you actually got a value out. Warts like this  in the java containers APIs and some lock-free variants can't even provide them. is a one-off construction, it doesn't compose with itself, it is only available for reference types, and it forces you to reason in a non-total fashion.For instance, when you checkyou have to carry around in your head throughout the  branch that  and that this has already been checked. However, when using something like optionyou  y is not by construction -- and you'd know it wasn't  either, if it weren't for Hoare's .Option[T] is a monad, which is really useful when you using high-order functions to manipulate values.I'll suggest you read articles listed below, they are really good articles that show you why Option[T] is useful and how can it be used in functional way.Adding on to Randall's , understanding why the potential absence of a value is represented by  requires understanding what  shares with many other types in Scala\u2014specifically, types modeling monads. If one represents the absence of a value with null, that absence-presence distinction can't participate in the contracts shared by the other monadic types.If you don't know what monads are, or if you don't notice how they're represented in Scala's library, you won't see what  plays along with, and you can't see what you're missing out on. There are many benefits to using  instead of null that would be noteworthy even in the absence of any monad concept (I discuss some of them in the \"Cost of Option / Some vs null\"  mailing list thread ), but talking about it isolation is kind of like talking about a particular linked list implementation's iterator type, wondering why it's necessary, all the while missing out on the more general container/iterator/algorithm interface. There's a broader interface at work here too, and  provides a presence-and-absence model of that interface.I think the key is found in Synesso's answer: Option is  primarily useful as a cumbersome alias for null, but as a full-fledged object that can then help you out with your logic.The problem with null is that it is the  of an object.  It has no methods that might help you deal with it (though as a language designer you can add increasingly long lists of features to your language that emulate an object if you really feel like it).One thing Option can do, as you've demonstrated, is to emulate null; you then have to test for the extraordinary value \"None\" instead of the extraordinary value \"null\".  If you forget, in either case, bad things will happen.  Option does make it less likely to happen by accident, since you have to type \"get\" (which should remind you that it  null, er, I mean None), but this is a small benefit in exchange for an extra wrapper object.Where Option really starts to show its power is helping you deal with the concept of I-wanted-something-but-I-don't-actually-have-one.Let's consider some things you might want to do with things that might be null.Maybe you want to set a default value if you have a null.  Let's compare Java and Scala:In place of a somewhat cumbersome ?: construct we have a method that deals with the idea of \"use a default value if I'm null\".  This cleans up your code a little bit.Maybe you want to create a new object only if you have a real value.  Compare:Scala is slightly shorter and again avoids sources of error.  Then consider the cumulative benefit when you need to chain things together as shown in the examples by Synesso, Daniel, and paradigmatic.It isn't a  improvement, but if you add everything up, it's well worth it everywhere save very high-performance code (where you want to avoid even the tiny overhead of creating the Some(x) wrapper object).The match usage isn't really that helpful on its own except as a device to alert you about the null/None case.  When it is really helpful is when you start chaining it, e.g., if you have a list of options:Now you get to fold the None cases and the List-is-empty cases all together in one handy statement that pulls out exactly the value you want.It is really a programming style question. Using Functional Java, or by writing your own helper methods, you could have your Option functionality but not abandon the Java language:Just because Scala includes it by default doesn't make it special. Most aspects of functional languages are available in that library and it can coexist nicely with other Java code.  Just as you can choose to program Scala with nulls you can choose to program Java without them.Null return values are only present for compatibility with Java. You should not use them otherwise.Admitting in advance that it is a glib answer, Option is a monad.Actually I share the doubt with you. About Option it really bothers me that 1) there is a performance overhead, as there is a lor of \"Some\" wrappers created everywehre. 2) I have to use a lot of Some and Option in my code. So to see advantages and disadvantages of this language design decision we should take into consideration alternatives. As Java just ignores the problem of nullability, it's not an alternative. The actual alternative provides Fantom programming language. There are nullable and non-nullable types there and ?. ?: operators instead of Scala's map/flatMap/getOrElse. I see the following bullets in the comparison:Option's advantage:Nullable's advantage:So there is no obvious winner here. And one more note. There is no principal syntactic advantage for using Option. You can define something like:Or use some implicit conversions to get pritty syntax with dots.The real advantage of having explicit option types is that you are able to  use them in 98% of all places, and thus statically preclude null exceptions. (And in the other 2% the type system reminds you to check properly when you actually access them.)Another situation where Option works, is in situations where types are not able to have a null value. It is not possible to store null in an Int, Float, Double, etc. value, but with an Option you can use the None.In Java, you would need to use the boxed versions (Integer, ...) of those types."},
Scala

What's the easiest way to debug Scala code managed by sbt using IntelliJ's built-in debugger? The documentation from  lists commands for running the main class for a project or the tests, but there seem to be no commands for debugging.Follow-up question: what's the easiest way to attach IntelliJ's debugger to Jetty when using sbt's jetty-run command?For ordinary debugging in IntelliJ, you can use an Application run/debug configuration in the usual way, regardless of whether you're using sbt to compile your code.To connect to your application running in Jetty, you'll need to create a Remote debug configuration.  When you do so, IntelliJ will give you a set of command line arguments for running the remote JVM -- something likeLaunch sbt with these arguments and then execute . Finally, launch your remote debug configuration in IntelliJ.  might be useful.There's a very convenient  flag in the official  for Mac, Linux & . You can use the flag to specify the debug port:, this starts the JVM for SBT with the typical verbose debugging incantation:You now can run your code as normal, for example with the sbt  command.Now you connect IntelliJ to your running process using a . Note that the upper 3 fields in this form, while scary, are just for you to copy text  of, rather than into (they're giving the verbose debugging incantation specified above, which  already takes care of for you) - the only configuration you can change is in the section halfway down:I had some trouble with this too, so at the risk of being overly detailed, here's what I did:I am adding another answer here, because I found this question when looking up a related problem: Debugging test classes using breakpoints.I am using ScalaTest, and I typically run a suite using sbt's 'test-only' command. Now when I want to use the interactive debugger, I can do the following:Create a new Run/Debug Configuration of type 'ScalaTest', put the main \"Test Class:\" name, and choose \"Before launch: Run SBT Action 'test-compile'\". That's it, you can place breakpoints now in the test sources, and run this configuration.None of these answers or provided links worked for me, so once I figured this out, I figured I'd share...including the background understanding I didn't have when I started...This is based mostly on the instructions  just with additional explanation that carried me through it.My Environment:\nScala 2.10.2, SBT 0.13, and IntelliJ 13.1Background:What is Debugging?What is Remote Debugging?Referencing the link above, the following explanations/modifications are useful:This one works for me every time, and the only thing you need to set up is remote debugging in IntelliJ; I start up SBT with JVM parameters from the terminal in IntelliJ:After that I can start remote debugging on localhost:5005Using Scala 2.10 and  SBT 0.12, I got it working like this: I've been struggling with debugging too on Windows with a Spray-can / Akka / Scala app built via SBT, using Intellij.  Piecing together various suggestions, the simplest approach for me was:In particular use the suspend=y option.  This will hold the app until you connect a remote debugger from IntellijFor what it's worth Windows folk, edit  and locate the following lines of code:then replace them with this code:Best I can do to get same behaviour for  when seen in the Bash script launcherNB. I don't think  actually exists outside this script, unless you created explicitly in you environment, but anyway you get the point :DFile->Settings->Other Settings->SBT \n VM parameters\n    -Xmx512M -XX:MaxPermSize=256M -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005Run->Edit Configurations\n      Press + and then select remote\n      Press ApplyNow in the SBT console (Started inside by intelliJ) when you execute the command 'run'  You will see \"Listening for transport dt_socket at address: 5005\"Now press Run->Debug. You will see the debug menus below activated. It has two tabs Debugger and Console.Use F7 to from next line to nextI chose suspend to be n. With it being y when I ran the run command it was stuckI also got the same problem, I like to share how I resolved. By the way I am using Ubuntu 14.04 and IntelliJ 15. you should see this line in terminal: \"Listening for transport dt_socket at address: 5005\"\n3. Edit Configurations -> Click + -> Select 'Remote' You should see Debug View opened and in Debug Console You should able to see \"Connected to the target VM, address: , transport: 'socket'\"ex: com.myproject.module.AddServiceTest[Spec]I hope It will help for you "},
Scala

In Scala, you often use an iterator to do a  loop in an increasing order like:How would you do it so it goes from 10 to 1? I guess  gives an empty iterator (like usual range mathematics)?I made a Scala script which solves it by calling reverse on the iterator, but it's not nice in my opinion, is the following the way to go?The answer from @Randall is good as gold, but for sake of completion I wanted to add a couple of variations: Having programmed in Pascal, I find this definition nice to use:Used this way:Scala provides many ways to work on downwards in loop. 1st Solution: with \"to\" and \"by\" 2nd Solution:  With \"to\" and \"reverse\" 3rd Solution: with \"to\" only"},
Scala

I prefer Python over Scala. But, as Spark is natively written in Scala, I was expecting my code to run faster in the Scala than the Python version for obvious reasons.With that assumption, I thought to learn & write the Scala version of some very common preprocessing code for some 1\u00a0GB of data. Data is picked from the SpringLeaf competition on . Just to give an overview of the data (it contains 1936 dimensions and 145232 rows). Data is composed of various types e.g. int, float, string, boolean. I am using 6 cores out of 8 for Spark processing; that's why I used minPartitions=6 so that every core has something to process.\nStage 0 (38 mins), Stage 1 (18 sec)\n\nStage 0 (11 mins), Stage 1 (7 sec)\nBoth produces different DAG visualisation graphs (due to which both pics show different stage 0 functions for Scala (map) and Python (reduceByKey))But, essentially both code tries to transform data into (dimension_id, string of list of values) RDD and save to disk. The output will be used to compute various statistics for each dimension.Performance wise, Scala code for this real data like this seems to run  than the Python version.\nGood news for me is that it gave me good motivation to stay with Python. Bad news is I didn't quite understand why?The original answer discussing the code can be found below.First of all, you have to distinguish between different types of API, each with its own performance considerations.This is the component which will be most affected by the performance of the Python code and the details of PySpark implementation. While Python performance is rather unlikely to be a problem, there at least few factors you have to consider: Basic considerations are pretty much the same as before with a few additional issues. While basic structures used with MLlib are plain Python RDD objects, all algorithms are executed directly using Scala.It means an additional cost of converting Python objects to Scala objects and the other way around, increased memory usage and some additional limitations we'll cover later.As of now (Spark 2.x), the RDD-based API is in a maintenance mode and is .These are probably the best choice for standard data processing tasks. Since Python code is mostly limited to high-level logical operations on the driver, there should be no performance difference between Python and Scala.A single exception is Python UDFs which significantly less efficient than their Scala equivalents. While there is some chance for improvements (there has been substantial development in Spark 2.0.0), the biggest limitation is full roundtrip between internal representation (JVM) and Python interpreter. If possible, you should favor a composition of built-in expressions (. Python UDF behavior has been improved in Spark 2.0.0, but it is still suboptimal compared to native execution.Also be sure to avoid unnecessary passing data between  and . This requires expensive serialization and deserialization, not to mention data transfer to and from Python interpreter.It is worth noting that Py4J calls have pretty high latency. This includes simple calls like:Usually, it shouldn't matter (overhead is constant and doesn't depend on the amount of data) but in the case of soft real-time applications, you may consider caching/reusing Java wrappers. As for now (Spark  2.1) neither one provides PySpark API so you can say that PySpark is infinitely worse than Scala.In practice, GraphX development stopped almost completely and the project is currently in the maintenance mode with .  library provides an alternative graph processing library with Python bindings.Subjectively speaking there is not much place for statically typed  in Python and even if there was the current Scala implementation is too simplistic and doesn't provide the same performance benefits as .From what I've seen so far, I would strongly recommend using Scala over Python. It may change in the future if PySpark gets support for structured streams but right now Scala API seems to be much more robust, comprehensive and efficient. My experience is quite limited.Structured streaming in Spark 2.x seem to reduce the gap between languages but for now it is still in its early days. Nevertheless, RDD based API is already referenced as \"legacy streaming\" in the  (date of access 2017-03-03)) so it reasonable to expect further unification efforts.Not all Spark features are exposed through PySpark API. Be sure to check if the parts you need are already implemented and try to understand possible limitations. It is particularly important when you use MLlib and similar mixed contexts (see ). To be fair some parts of the PySpark API, like , provides a more comprehensive set of methods than Scala.The PySpark API closely reflects its Scala counterpart and as such is not exactly Pythonic. It means that it is pretty easy to map between languages but at the same time, Python code can be significantly harder to understand.PySpark data flow is relatively complex compared to pure JVM execution. It is much harder to reason about PySpark programs or debug. Moreover at least basic understanding of Scala and JVM in general is pretty much a must have.The Spark DataFrame (SQL, Dataset) API provides an elegant way to integrate Scala/Java code in PySpark application. You can use  to expose data to a native JVM code and read back the results. I've explained some options  and you can find a working example of Python-Scala roundtrip in .It can be further augmented by introducing User Defined Types (see ).First of all, there is one part in your code which doesn't make sense at all. If you already have  pairs created using  or  what is the point in creating string just to split it right afterwards?  doesn't work recursively so you can simply yield tuples and skip following  whatsoever.Another part I find problematic is . Generally speaking,  is useful if applying aggregate function can reduce the amount of data that has to be shuffled. Since you simply concatenate strings there is nothing to gain here. Ignoring low-level stuff, like the number of references, the amount of data you have to transfer is exactly the same as for .Normally I wouldn't dwell on that, but as far as I can tell it is a bottleneck in your Scala code. Joining strings on JVM is a rather expensive operation (see for example: ). It means that something like this   which is equivalent to  in your code is not a good idea.If you want to avoid  you can try to use  with . Something similar to this should do the trick:but I doubt it is worth all the fuss.Keeping the above in mind, I've rewritten your code as follows:::In  mode (Intel(R) Xeon(R) CPU E3-1245 V2 @ 3.40GHz) with 4GB memory per executor it takes (n = 3):I am pretty sure that most of that time is spent on shuffling, serializing, deserializing and other secondary tasks. Just for fun, here's naive single-threaded code in Python that performs the same task on this machine in less than a minute:"},
Scala

I have already read various accounts of Clojure vs. Scala and while I realize that both have their place.  There are a few considerations that I haven't acquired a complete explanation on when it comes to comparing both Clojure with Scala:1.) Which of the two languages is generally ?  I realize that this will vary from one language feature to another but an general assessment of performance would be helpful.  For example: I know that Python dictionaries are really fast.  But as a whole, it is a  slower language than Java.  I don't want to go with Clojure and run into this problem down the road.2.) How is interoperability with Java?  All I have read so far is that Scala has native collections types that make it a bit clumsy to integrate with a large Java code-base, whereas Clojure follows a simple Iterable/Iterator-centric way to inter-operate with Java classes.  Any more thoughts/details on this?Ultimately, if it is a close enough draw between clojure and scala, I might try them both.  One thing about Clojure is the language seems  simple.  But then again, Scala has a very flexible type system.  But, I know that Scala is fast (based on multiple personal accounts).  So, if Clojure is significantly slower: I'd like to know sooner rather than later.I think either language will be fast enough for you. When comparing Python and Java, it seems a bit unreasonable to blame the language for the speed difference. Java is compiled JIT (except on mobile devices*) whereas Python is interpreted. Just because both use a bytecode does not mean the implementations will have even remotely comparable performance. But both Scala and Clojure are JVM languages so they should have similar performance.Scala has a few implementation advantages over Clojure and I would expect somewhat higher performance. Although Scala's static typing would normally translate into a speed advantage over Clojure's duck typing, Clojure  support type hinting which can speed up code considerably. Possibly, ordinary Scala is faster than ordinary Clojure, but you only need to optimize the bottlenecks. Most of a program's run time is generated by a small amount of the actual code.Regarding interop w/ Java, Scala is closer to Java but I'm sure both languages interoperate well. In  Stuart Halloway writes: \"[you can access] \".And since Scala author Martin Odersky  Sun's Java compiler, I kinda think no balls have been dropped on the Scala side, either. :-)You would be hard-pressed to pick two better languages, though I like Ruby also. Why are you worried about which one to try?  Why not try them both? Scala is more likely to be \"the next Java\", while it's hard to imagine that Lisp will finally take off after not doing so for over 50 years. But it's clear that Lisp is on its own unique level of abstraction, and Clojure is fairly simple, so Scala + Clojure won't be that much harder than just (the rather complex) Scala and I'm sure you will be glad you did it. And for that matter they interoperate...* dalvik (android's JVM) got a JIT compiler in 2.2 version in 2010 With the present JVM Scala has an advantage on the account of being statically typed, as JVM support for dynamic typing -- reflection -- is slow. In fact, one Scala feature which must be implemented through the same techniques, structural types, is often warned against for this very reason.Also, Scala accepts mutable objects just fine, and some algorithms are just faster to implement with mutability.As both Scala and Java are essentially class-based languages, they interoperate more easily. Or, perhaps, more seamlessly. A Java class is a class to Scala, and a Scala class is a class to Java. Problems might arise when it comes to Scala's singletons or Java's static members, particularly when there's a framework involved expecting things to work in a certain way.So I'd go with Scala on both  accounts. Clojure is, in many ways, a better , and it certainly has very interesting features not present (so far) on Scala, but you reap such benefits by going fully functional. If you intend to do that, then Clojure is very likely better. If you don't, then you should probably stay with Scala.Note that Clojure and Scala are two totally different types of programming languages - Clojure is a functional Lisp-like language, it is  object oriented. Scala is an object oriented language which has functional programming features.In my opinion, the features and concepts of a language (functional, OO, ...) are much more important criteria for choosing a language than the performance (of a particular implementation of that language) - altough I understand that you don't want to get trapped into a language for which there is no well-performing implementation available.I'd go for Scala, because it is object oriented but also allows you to learn functional programming (if you're interested in that). On the other hand, if you don't care about OO and you want to learn \"pure\" functional programming, try Clojure.The stats produced by the \"\" are about the best you're probably going to find.They are in-depth and you can compare many languages.  The problem is that they don't cover Clojure :(That said, it's pretty easy to submit anything--it's all open source.The stats do say that Scala is pretty damn quick.If your code is time-critical or space-critical throughout, stick to Java. But it isn't, even if you think it is. The  sheds little light on Clojure's true resource costs. No Clojure data structures are employed. Functional and sequence abstractions do not appear. Clojure may appear to be simple. It isn't, but it is expressive. It may run five times slower than Java, but  is five times smaller (YMMV). For most of most applications, this is a big win. But for some, and for some parts of many others, it's a devastating loss. With experience of the Clojure language, I believe it is possible to tell in advance whether your problem will cleave cleanly into a part that can be succinctly and adequately (in performance terms) expressed in Clojure and a part that needs doing in Java. Scala has been said to be . Clojure is nothing like Java. You might say that it is  - a bold, some would say preposterous, claim - which may turn out to be true. On interoperability, I can't speak for Clojure, but I would expect it to be in a similar situation as Scala.It is trivially easy to call Java from Scala.It is easy to call Scala from Java as long as you conform your external API to the common points between Scala and Java. For example, a Scala object is used in some ways like static methods in Java, but it's not the same thing. Scala classes may compile to a number of classes with names that look funny in Java.You will not want to mix and match much. Building component in Scala or Clojure that uses lots of Java libraries is very feasible. You can of course call into this component from Java, but what you are not going to want to do is try to consume a Scala API intended for use by Scala programs from Java.SVN claims to be \"CVS done right\". In my view, Scala is Java done right.The  discusses Clojure-Java interoperability. Calling Java methods is straightforward, but extending Java classes/interfaces is quite different.Scala on the other hand is much closer to Java. Scala-Java interoperability is elaborated at Calling Java code and extending Java classes/interfaces works the same way as calling Scala code. Some pain points might be some edge cases of dealing with Java's generics, because Scala's type system is  than Java's. Creating getters and setters following the Java Bean convention .Calling Scala from Java is most of the time straightforward, but for example Scala's companion objects requires knowing how they are compiled to bytecode. Also using traits with non-abstract methods from Java should be complicated, and calling methods with special characters would require knowing how they are encoded in the bytecode.It's now (as of May 2010) worth loking at the latest 1.2 branch of Clojure - this includes a lot of additional support for primitive types and static typing (through various type hints and protocols).My understanding is that you can use these features when you need it to get speed equivalent to writing exactly the same code in pure Java."},
Scala

I see this code in this blog: :There is an operator  in the code  which I've never seen. Since it's difficult to search it(ignored by search engines), who can tell me what does it mean?To explain it, we first have to explain nested classes in Scala. Consider this simple example:Now let's try something with it:When you declare a class inside another class in Scala, you are saying that  of that class has such a subclass. In other words, there's no  class, but there are  and  classes, and they are  classes, as the error message is telling us above.If you did not understand that, look up path dependent types.Now,  makes it possible for you to refer to such nested classes without restricting it to a particular instance. In other words, there's no , but there's , which means a  nested class of  instance of .We can see this in work by changing the code above:And trying it out:It's known as type projection, and is used to access type members.Basically, it's a way of referring to classes within other classes.  (search for \"pound\")Here's a couple resources for searching on \"symbolic operators\" (which are really methods), but I haven't figured out how to escape \"#\" to search on in scalex)"},
Scala

What's the Scala recipe for reading line by line from the standard input ? Something like the equivalent java code : The most straight-forward looking approach will just use  which is part of . however that is rather ugly as you need to check for eventual null value:this is so verbose, you'd rather use  instead.I think a more pretty approach will use :For the console you can use . You can write (if you want to stop on an empty line):If you cat a file to generate the input you may need to stop on either null or empty using: Can you not useAs available here : A recursive version (the compiler detects a tail recursion for improved heap usage),Note the use of  from Scala 2.11 . Also note with this approach we can accumulate user input in a collection that is eventually returned -- in addition to be printed out. Namely,"},
Scala

When a resilient distributed dataset (RDD) is created from a text file or collection (or from another RDD), do we need to call \"cache\" or \"persist\" explicitly to store the RDD data into memory? Or is the RDD data stored in a distributed way in the memory by default?As per my understanding, after the above step, textFile is a RDD and is available in all/some of the node's memory.If so, why do we need to call \"cache\" or \"persist\" on textFile RDD then?Most RDD operations are lazy. Think of an RDD as a description of a series of operations. An RDD is not data. So this line:It does nothing. It creates an RDD that says \"we will need to load this file\". The file is not loaded at this point.RDD operations that require observing the contents of the data cannot be lazy. (These are called .) An example is  \u2014 to tell you the number of lines in the file, the file needs to be read. So if you write , at this point the file will be read, the lines will be counted, and the count will be returned.What if you call  again? The same thing: the file will be read and counted again. Nothing is stored. An RDD is not data.So what does  do? If you add  to the above code:It does nothing.  is also a lazy operation. The file is still not read. But now the RDD says \"read this file and then cache the contents\". If you then run  the first time, the file will be loaded, cached, and counted. If you call  a second time, the operation will use the cache. It will just take the data from the cache and count the lines.The cache behavior depends on the available memory. If the file does not fit in the memory, for example, then  will fall back to the usual behavior and re-read the file.I think the question would be better formulated as:Spark processes are lazy, that is, nothing will happen until it's required.\nTo quick answer the question, after  is issued, nothing happens to the data, only a  is constructed, using the file as source.Let's say we transform that data a bit:Again, nothing happens to the data. Now there's a new RDD  that contains a reference to  and a function to be applied when needed.Only when an action is called upon an RDD, like , the RDD chain, called  will be executed. That is, the data, broken down in partitions, will be loaded by the Spark cluster's executors, the  function will be applied and the result will be calculated.On a linear lineage, like the one in this example,  is not needed. The data will be loaded to the executors, all the transformations will be applied and finally the  will be computed, all in memory - if the data fits in memory. is useful when the lineage of the RDD branches out. Let's say you want to filter the words of the previous example into a count for positive and negative words. You could do this like that:Here, each branch issues a reload of the data. Adding an explicit  statement will ensure that processing done previously is preserved and reused. The job will look like this:For that reason,  is said to 'break the lineage' as it creates a checkpoint that can be reused for further processing.Rule of thumb: Use  when the lineage of your RDD  or when an RDD is used multiple times like in a loop.Yes, only if needed.No! And these are the reasons why :For more details please check the .Adding another reason to add (or temporarily add)  method call. with  method, spark will give debugging informations regarding the size of the RDD. so in the spark integrated UI, you will get RDD memory consumption info. and this proved very helpful diagnosing memory issues. "},
Scala

I am using the build in JSON class in Scala 2.8 to parse JSON code. I don't want to use the Liftweb one or any other due to minimizing dependencies.The way I am doing it seems too imperative, is there a better way to do it?This is a solution based on extractors which will do the class cast:At the start of the for loop I artificially wrap the result in a list so that it yields a list at the end. Then in the rest of the for loop I use the fact that generators (using ) and value definitions (using ) will make use of the unapply methods.(Older answer edited away - check edit history if you're curious)This is the way I do the pattern match:I like @huynhjl's answer, it led me down the right path. However, it isn't great at handling error conditions. If the desired node does not exist, you get a cast exception. I've adapted this slightly to make use of  to better handle this.Of course, this doesn't handle errors so much as avoid them. This will yield an empty list if any of the json nodes are missing. You can use a  to check for the presence of a node before acting...I tried a few things, favouring pattern matching as a way of avoiding casting but ran into trouble with type erasure on the collection types. The main problem seems to be that the complete type of the parse result mirrors the structure of the JSON data and is either cumbersome or impossible to fully state. I guess that is why  is used to truncate the type definitions. Using  leads to the need for casting.I've hacked something below which is concise but is extremely specific to the JSON data implied by the code in the question. Something more general would be more satisfactory but I'm not sure if it would be very elegant."},
Scala

Just going through the sample Scala code on Scala website, but encountered an annoying error when trying to run it.Here's the code: . On running it on Eclipse, I got this message 'Editor does not contain a main type' that prevents it from running.Is there anything I need to do...i.e break that file into multiple files, or what?I have this problem a lot with Eclipse and Scala. It helps if you clean your workspace and rebuild your Project.Sometimes Eclipse doesn't recognize correctly which files it has to recompile :(Edit:\nThe Code runs fine in EclipseIn Eclipse, make sure you add your source folder in the project properties -> java build path -> source.  Otherwise, the main() function may not be included in your project.You have to make sure that your .java files  .src folder in eclipse. I had the same exact problem until I got it figured out.A simplier way is to close your project and reopen it !Just make sure that the folder you work in is added to the built path: your folder, -->  --> and it should now find  thereinhope this helpsI had the same problem. I tried all sorts of things. And I came to know thatThings I did:Project properties >> Java Build Path >> Source This solved the error.What you should do is, create a Java Project, but make sure you put this file in the package file of that project, otherwise you'll encounter same error.That code is valid. Have you tried to compile it by hand using scalac? Also, have you called your file \"addressbook\", all lowercase, like the name of the object?Also, I found that Eclipse, for some reason, set the main class to be \".addressbook\" instead of \"addressbook\".A quick solution: First, exclude the package:\nRight click on the source package >> Build Path >> ExcludeThen include it back:\nRight click on the source package >> Build Path >> Includeyou should create your file by selecting on right side you will find your file name,under that will find src folder their you right click select -->class optiontheir your file should be createdYou can try to run the main function from the outline side bar of eclipse.*** your project in eclipse. Sometime there are linkage problems. This solved my problemI just had this problem too. The solution is to make sure eclipse created the project as Java project. Just create a new Java project and copy your class into the src folder (and import the eventual dependencies). This should fix the problem.The correct answer is: the Scala library needs to before the JRE library in the buildpath.  Go to  and move Scala library to the topI had this problem with a Java project that I imported from the file system (under Eclipse Helios).  Here's a hint: the src code didn't seem to be compiled at all, as no \"bin\" directory showed up.I had to create a Java project from scratch (using the wizard), then compare the  files of the non-working and working projects.The project giving \"Editor does not contain a main type\" had this as the \"buildSpec\" in the .project file:But the working project had this as the \"buildSpec\":I copied this in, and the imported project worked.I know my answer is for Java, but the same might be the issue for your Scala project.May be the file you have created is outside the src(source) folder. Trying to call the class object(from the file located in the src folder) from the .java file outside the source folder results in the same error. Copy .java file to the source folder, then build it. The error will be gone.Make sure that your .java file is present either in the str package, or in some other package. If the java file with the main function is outside all packages, this error is thrown.I had the same problem. I had the main class out of the src package, in other folder. I move it in and correct folder and solvedrun \"eclipse -clean -refresh\" from command line.  This fixed the issue for me when all other solutions failed.  This could be the issue with the Java Build path.\nTry below steps :This should resolve the issue.For me, in Eclipse 3.6,  this problem occurs when my main method is not public.  I caused the problem by having a main method like this:The dubugger was unable to detect this by itself.  I am pretty suprised Eclipse overlooked this.In the worst case - create the project once again with all the imports from the beginning. In my case none of the other options worked. This type of error hints that there is an error in the project settings. I once managed to solve it, but once further developments were done, the error came back. Recreating everything from the beginning helped me understand and optimize some links, and now I am confident it works correctly.Follow the below steps:File >> Import >> Existing Projects into Workspace >> Select Archive Filed >> Browse and locate file >> Finish. If its already imported some other way delete it and try it that way. I was having the same problem until i tried that. One more thing to check: make sure that your source file contains the correct package declaration corresponding to the subdirectory it's in.  The error mentioned by the OP can be seen when trying to run a \"main type\" declared in a file in a subdirectory but missing the package statement.I have this problem too after I changed the source folder. The solution that worked for is just editing the file and save it. Try 'Update Project'. Once I did this, The Run as Java Application option appeared.In my particular 'Hello World' case the cause for this problem was the fact, that my  method was inside the Scala .That is because Scala  in Java terms is the entity with only static members and methods inside.That is why Java's  in Scala must be placed under .(Scala  may not contain static's inside)On reason for an Error of: \"Editor does not contain a main type\"Error encountered in: Eclipse NeonOperating System: Windows 10 ProWhen you copy your source folders over from a thumb-drive and leave out the Eclipse_Projects.metadata folder.  Other than a fresh install, you will have to make sure you merge the files from (Thrumb-drive)F:Eclipse_Projects.metadata.plugins  . These plug-ins are the bits and pieces of library code taken from the SDK when a class is created.  I really all depends on what you-----import javax.swing.*;-----  into your file.  Because your transferring it over make sure to merge the ------Eclipse_Projects.metadata.plugins------ manually with a simple copy and paste, while accepting the skip feature for already present plugins in your Folder.For windows 10: you can find your working folders following a similar pattern of file hierarchy. C:Users>Mikes Laptop> workspace > .metadata > .plugins <---merge plugins hereIf it is maven project please check the java file is created under src/main/javaIf you are not getting please change the JRE path and create the java files in above folder structure"},
Scala

Related to Stack Overflow question , how do I convert a Java collection ( say) into a Scala collection ?I am actually trying to convert a Java API call to  , which returns a , into a Scala immutable . So for example:This seems to work. Criticism is welcome!Your last suggestion works, but you can also avoid using :Note that  is made available by default thanks to .For future reference: With Scala 2.8, it could be done like this: is a  after this.Also see  for a more explicit way (using JavaConverters), which seems to be recommended now.If you want to be more explicit than the JavaConversions demonstrated in , you can use JavaConverters: () and  () have been deprecated with .Instead of  use:as suggested by .Instead of  use:For both there is also the possibility to only import the conversions/converters to Java or Scala respectively, e.g.:\nThe statement above that  and  were deprecated seems to be wrong. There were some deprecated properties in Scala 2.10, which resulted in deprecation warnings when importing them. So the alternate imports here seem to be only aliases. Though I still prefer them, as IMHO the names are more appropriate.You may also want to explore this excellent library:  that has two-way conversion between Java and Scala collections. In your case, to convert a java.util.List to Scala List you can do this:You can add the type information in the toArray call to make the Set be parameterized:This might be preferable as the collections package is going through a major rework for Scala 2.8 and the scala.collection.jcl package is Another simple way to solve this problem:You could convert the Java collection to an array and then create a Scala list from that:"},
Scala

I used to think that  and  are same, until I saw section 4.1 in Scala Reference:And I have written a test: output:The byte code is just as Scala Reference said:  is not .Why doesn't  just treat  as ? Is there any underlying reason?So, this is just a guess, but it was a perennial annoyance in Java that final static variables with a literal on the right-hand side get inlined into bytecode as constants. That engenders a performance benefit sure, but it causes binary compatibility of the definition to break if the \"constant\" ever changed. When defining a final static variable whose value might need to change, Java programmers have to resort to hacks like initializing the value with a method or constructor.A val in Scala is already final in the Java sense. It looks like Scala's designers are using the redundant modifier final to mean \"permission to inline the constant value\". So Scala programmers have complete control over this behavior without resorting to hacks: if they want an inlined constant, a value that should never change but is fast, they write \"final val\". if they want flexibility to change the value without breaking binary compatibility, just \"val\".I think the confusion here arises from conflating immutability with the semantics of final.  s can be overridden in child classes and therefore can't be treated as final unless marked as such explicitly.@Brian The REPL provides class scope at the line level.  See:"},
Scala

How do you terminate a run in SBT without exiting?I'm trying CTRL+C but it exits SBT. Is there a way to only exit the running application while keeping SBT open?In the default configuration, your runs happen in the same JVM that sbt is running, so you can't easily kill them separately.If you do your run in a separate, forked JVM, as described at , then you can kill that JVM (by any means your operating system offers) without affecting sbt's JVM:From sbt version 0.13.5 you can add to your build.sbtIt is defined as \"Enables (true) or disables (false) the ability to interrupt task execution with CTRL+C.\" in the There are some bugs reported:I've found the following useful when I have control over the main loop of the application being run from sbt.I tell sbt to fork when running the application (in build.sbt):I also tell sbt to forward stdin from the sbt shell to the application (in build.sbt):Finally, in the main thread of the application, I wait for end-of-file on stdin and then shutdown the JVM:Of course, you can use any thread to read stdin and shutdown, not just the main thread.Finally, start sbt, optionally switch to the subproject you want to run, run.Now, when you want to stop the process, close its stdin by typing CTRL-D in the sbt shell."},
Scala

Mostly, Android applications are written in Java. But i heard that its also possible to use Scala or some other languages. And I also read that it's possible to include native C/C++ code.Is there a refernce/list available that shows which languages can be used?Scala is . See .Support for other languages is :As stated above, many languages are available for developing in Android. Java, C, Scala, C++, several scripting languages etc. Thanks to Mono you are also able to develop using C# and the .Net framework. Here you have some speedcomparisions: See:  can be used, but it's slow.See also: , and a .I made good experiences with Scala. I use the simple build tool (sbt: ) with the Android-Plugin ()Java and C:You may find more information in Android developers site."},
Scala

Let's say I'm getting a (potentially big) list of images to download from some URLs. I'm using Scala, so what I would do is :I'm a bit new to Scala, so this still looks a little like magic to me :Thanks for your advice!Use Futures in Scala 2.10. They were joint work between the Scala team, the Akka team, and Twitter to reach a more standardized future API and implementation for use across frameworks. We just published a guide at: Beyond being completely non-blocking (by default, though we provide the ability to do managed blocking operations) and composable, Scala's 2.10 futures come with an implicit thread pool to execute your tasks on, as well as some utilities to manage time outs.Above, we first import a number of things: remains largely the same as what you originally did- the only difference here is that we use managed blocking- . It notifies the thread pool that the block of code you pass to it contains long-running or blocking operations. This allows the pool to temporarily spawn new workers to make sure that it never happens that all of the workers are blocked. This is done to prevent starvation (locking up the thread pool) in blocking applications. Note that the thread pool also knows when the code in a managed blocking block is complete- so it will remove the spare worker thread at that point, which means that the pool will shrink back down to its expected size.(If you want to absolutely prevent additional threads from ever being created, then you ought to use an AsyncIO library, such as Java's NIO library.)Then we use the collection methods of the Future companion object to convert  from   to a .The  object is how we can ensure that  is executed on the calling thread--  simply forces the current thread to wait until the future that it is passed is completed. (This uses managed blocking internally.)"},
Scala

Suppose I haveIs there a list operation that returns \"a\", \"b\", \"c\"Have a look at the ScalaDoc for ,. Others have suggested using  rather than . That's fine, but be aware that by default, the  interface doesn't preserve element order. You may want to use a Set implementation that explicitly  preserve order, such as .Before using Kitpon's solution, think about using a  rather than a , it ensures each element is unique.As most list operations (, , , ...) are the same for sets and lists, changing collection could be very easy in the code. now has a  method.So calling  is now possible without converting to a  or .Using Set in the first place is the right way to do it, of course, but:Works. Or just  as it supports the   interface. inArr.distinct foreach println _ The algorithmic way..."},
Scala

 allows you to search many standard Haskell libraries by either function name, or by approximate type signature. I find it very useful. Is there anything like Hoogle for Scala? Search in  only finds types and packages by name.There are plans to make the Hoogle interface work with multiple languages: In the past few months I've worked on a new search engine for Scala APIs: The functionality is quite similar to Hoogle and also searches like  provide meaningful results.It's a pity that it does not even have an index like javadoc. Hoogle is nicer, though. I use a personal search engine from Google to search the Scaladocs. A search provider (searching with site: ) in Firefox is another way to search the docs. Both do not work well for the Scala 2.8. release \u2013 it's not indexed well enough to be useful \u2013 and works not with all operators. For example a search for Cons  returns only nonsense."},
Scala

I am aware of following projects (mostly from ):implemented in Java:implemented in Scala: What are the respective performance characteristics, pitfalls, quirks? Which ones support the Github extensions? Which one would you recommend for a Play! / Scala application?The  created by MarkdownPapers' author compares the performance for the following implementations:TxtMark far exceeds the performance of the other tools, as shown in the following graph:PegDown, which supports many GitHub extensions and others, is far more fully featured. Custom plugins or extensions are also possible.My use case involved processing markdown from an administrative screen where performance was less impactful than a rich feature set, which meant PegDown won over TxtMark."},
Scala

I've just read: As far as I understand,  is a trait and its only instance is .When a method takes a Null argument, then we can only pass it a  reference or  directly, but not any other reference, even if it is null ( for example).I just wonder in which cases using this  trait could be useful.\nThere is also the Nothing trait for which I don't really see any more examples.I don't really understand either what is the difference between using Nothing and Unit as a return type, since both doesn't return any result, how to know which one to use when I have a method that performs logging for example?Do you have usages of Unit / Null / Nothing as something else than a return type?You only use Nothing if the method never returns (meaning it cannot complete normally by returning, it could throw an exception). Nothing is never instantiated and is there for the benefit of the type system (to quote James Iry: ). From the article you linked to:Your logging method would return Unit. There is a value Unit so it can actually be returned. From the :The article you quote can be misleading. The  type is there for compatibility with the , and Java in particular.We must consider that :thus it becomes necessary to define a type for the  value, which is the  trait, and has  as its only instance.There is nothing especially useful in the  type unless you're the type-system or you're developing on the compiler. In particular I can't see any sensible reason to define a  type parameter for a method, since you can't pass anything but  can be used like this:This allows you to pass in an arbitrary block of code to be executed. might be used as a bottom type for any value that is nullable. An example is this: is used in the definition of This allows you to assign a  to any type of  because  'extends' everything.I've never actually used the  type, but you use , where you would on java use .  is a special type, because as Nathan already mentioned, there can be no instance of .  is a so called bottom-type, which means, that it is a sub-type of any other type. This (and the contravariant type parameter) is why you can prepend any value to  - which is a  - and the list will then be of this elements type.  also if of type . Every attempt to access the values inside such a container will throw an exception, because that it the only valid way to return from a method of type .if you use , there is no things to do (include print console)\nif you do something, use output type ... then how to use ?"},
Scala

What is the motivation for Scala assignment evaluating to Unit rather than the value assigned?A common pattern in I/O programming is to do things like this:But this is not possible in Scala because..... returns Unit, not the new value of bytesRead.Seems like an interesting thing to leave out of a functional language.\nI am wondering why it was done so?I advocated for having assignments return the value assigned rather than unit.  Martin and I went back and forth on it, but his argument was that putting a value on the stack just to pop it off 95% of the time was a waste of byte-codes and have a negative impact on performance.I'm not privy to inside information on the actual reasons, but my suspicion is very simple. Scala makes side-effectful loops awkward to use so that programmers will naturally prefer for-comprehensions.It does this in many ways. For instance, you don't have a  loop where you declare and mutate a variable. You can't (easily) mutate state on a  loop at the same time you test the condition, which means you often have to repeat the mutation just before it, and at the end of it. Variables declared inside a  block are not visible from the  test condition, which makes  much less useful. And so on.Workaround:For whatever it is worth.As an alternate explanation, perhaps Martin Odersky had to face a few very ugly bugs deriving from such usage, and decided to outlaw it from his language. has  with some actual facts, which are clearly endorsed by the fact that  himself commented his answer, giving credence to the performance-related issues argument put forth by Pollack.This happened as part of Scala having a more \"formally correct\" type system.  Formally-speaking, assignment is a purely side-effecting statement and therefore should return .  This does have some nice consequences; for example:The  method returns  (as would be expected for a setter) precisely because assignment returns .I agree that for C-style patterns like copying a stream or similar, this particular design decision can be a bit troublesome.  However, it's actually relatively unproblematic in general and really contributes to the overall consistency of the type system.I'd guess this is in order to keep the program / the language free of side effects.What you describe is the intentional use of a side effect which in the general case is considered a bad thing.Perhaps this is due to the  principle?CQS tends to be popular at the intersection of OO and functional programming styles, as it creates an obvious distinction between object methods that do or do not have side-effects (i.e., that alter the object). Applying CQS to variable assignments is taking it further than usual, but the same idea applies.A short illustration of why CQS is useful: Consider a hypothetical hybrid F/OO language with a  class that has methods , , , and . In imperative OO style, one might want to write a function like this:Whereas in more functional style, one would more likely write something like this:These seem to be  to do the same thing, but obviously one of the two is incorrect, and without knowing more about the behavior of the methods, we can't tell which one. Using CQS, however, we would insist that if  and  alter the list, they must return the unit type, thus preventing us from creating bugs by using the second form when we shouldn't. The presence of side effects therefore also becomes implicit in the method signature.It is not the best style to use an assignment as a boolean expression. You perform two things at the same time which leads often to errors. And the accidential use of \"=\" instead of \"==\" is avoided with Scalas restriction.By the way: I find the initial while-trick stupid, even in Java. Why not somethign like this?Granted, the assignment appears twice, but at least bytesRead is in the scope it belongs to, and I'm not playing with funny assignment tricks...You can have a workaround for this as long as you have a reference type for indirection. In a na\u00efve implementation, you can use the following for arbitrary types.Then, under the constraint that you\u2019ll have to use  to access the reference afterwards, you can write your  predicate asand you can do the checking against  in a more implicit manner without having to type it."},
Scala

Split on an empty string returns an array of size 1 :Consider that this returns empty array:Please explain :)For the same reason thatandwill return an array of size 2. Everything before the first match is returned as the first element.If you split an orange zero times, you have exactly one piece - the orange.Splitting an empty string returns the empty string as the first element. If no delimiter is found in the target string, you will get an array of size 1 that is holding the original string, even if it is empty. -> \ntherefore\n -> The Java and Scala split methods operate in two steps like this:According to this, the result of  should be an empty array because of the second step, right? And that is bad, but at least it  in , if you remember to take a look at the documentation:So, I advise you to always pass  as the second parameter (this will skip step two above), unless you specifically know what you want to achieve / you are sure that the empty string is not something that your program would get as an input. Splitting the empty string is an artificially introduced corner case and the documentation warns you about that. Always pass -1 as the second parameter to avoid bugs, unless you have a good reason.In all programming languages I know a blank string is still a valid String. So doing a split using any delimiter will always return a single element array where that element is the blank String. If it was a null (not blank) String then that would be a different issue."},
Scala

Why does Overloading makes it a little harder to lift a method to a function:You cannot selectively import one of a set of overloaded methods.There is a greater chance that ambiguity will arise when trying to apply implicit views to adapt the arguments to the parameter types:It can quietly render default parameters unusable:Individually, these reasons don't compel you to completely shun overloading. I feel like I'm missing some bigger problems.The evidence is stacking up.The reasons that Gilad and Jason (retronym) give are all very good reasons to avoid overloading if possible. Gilad's reasons focus on why overloading is problematic in general, whereas Jason's reasons focus on why it's problematic in the context of other Scala features.To Jason's list, I would add that overloading interacts poorly with type inference. Consider:A change in the inferred type of  could alter which  method gets called. The  of  need not change, just the inferred type of , which could happen for all sorts of reasons.For all of the reasons given (and a few more I'm sure I'm forgetting), I think method overloading should be used as sparingly as possible.I think the advice is not meant for scala especially, but for OO in general (so far I know scala is supposed to be a best-of-breed between OO and functional). is fine, it's the heart of polymorphism and is central to OO design.  on the other hand is more problematic. With method overloading it's hard to discern which method will be really invoked and it's indeed a frequently a source of confusion. There is also rarely a justification why overloading is really necessary. The problem can most of the time be solved another way and I agree that overloading is a smell.Here is  that explain nicely what I mean with \"overloading is a source of confusion\", which I think is the prime reason why it's discouraged. It's for java but I think it applies to scala as well."},
Scala

What is the conceptual difference between abstract classes and traits?A class can only , and thus, only one abstract class. If you want to compose several classes the Scala way is to use : you combine an (optional) superclass, your own member definitions and one or more . A trait is restricted in comparison to classes in that it cannot have constructor parameters (compare the ). The restrictions of traits in comparison to classes are introduced to avoid typical problems with multiple inheritance. There are more or less complicated rules with respect to the inheritance hierarchy; it might be best to avoid a hierarchy where this actually matters. ;-)  As far as I understand, it can only matter if you inherit two methods with the same signature / two variables with the same name from two different traits.One aspect of traits is that they are a . Allowing a constrainted form of AOP (around advice).The resolution of  reflects the linearization of the inheritance hierarchy.Conceptually, a trait is a component of a class, not a class by itself. As such, it typically does not have constructors, and it is not meant to \"stand by itself\".I suggest using an abstract class when it has an independent meaning, and traits when you just want to add functionality in an object-oriented manner. , you might find that if all your methods revolve around doing a single thing, you probably want a trait.For a (non-language-specific) example, if your Employee should extend both \"Person\" and \"Cloneable\", make Person a base class and Cloneable a trait.Traits(in Scala at least) system has an explicit way of declaring parent priority in subclass to avoid typical problems associated with multiple inheritance ie. conflicts with inherited methods having same signature. Traits are akin to Java interfaces, but are allowed to have method implementations. "},
Scala

Suppose I have several futures and need to wait until  any of them fails  all of them succeed. For example: Let there are 3 futures: , , . How would you implement it?You could use a for-comprehension as follows instead:In this example, futures 1, 2 and 3 are kicked off in parallel.  Then, in the for comprehension, we wait until the results 1 and then 2 and then 3 are available.  If either 1 or 2 fails, we will not wait for 3 anymore.  If all 3 succeed, then the  val will hold a tuple with 3 slots, corresponding to the results of the 3 futures.  Now if you need the behavior where you want to stop waiting if say fut2 fails first, things get a little trickier.  In the above example, you would have to wait for fut1 to complete before realizing fut2 failed.  To solve that, you could try something like this:Now this works correctly, but the issue comes from knowing which  to remove from the  when one has been successfully completed.  As long as you have some way to properly correlate a result with the Future that spawned that result, then something like this works.  It just recursively keeps removing completed Futures from the Map and then calling  on the remaining  until there are none left, collecting the results along the way.  It's not pretty, but if you really need the behavior you are talking about, then this, or something similar could work.You can use a promise, and send to it either the first failure, or the final completed aggregated success:Then you can  on that resulting  if you want to block, or just  it into something else.The difference with for comprehension is that here you get the error of the first to fail, whereas with for comprehension you get the first error in traversal order of the input collection (even if another one failed first). For example:And:Here is a solution without using actors.You can do this with futures alone.  Here's one implementation.  Note that it won't terminate execution early!  In that case you need to do something more sophisticated (and probably implement the interruption yourself).  But if you just don't want to keep waiting for something that isn't going to work, the key is to keep waiting for the first thing to finish, and stop when either nothing is left or you hit an exception:Here's an example of it in action when everything works okay:But when something goes wrong:This question has been answered but I am posting my value class solution (value classes were added in 2.10) since there isn't one here. Please feel free to criticize.ConcurrentFuture is a no overhead Future wrapper that changes the default Future map/flatMap from do-this-then-that to combine-all-and-fail-if-any-fail. Usage:In the example above, f1,f2 and f3 will run concurrently and if any fail in any order the future of the tuple will fail immediately.You can use this:For this purpose I would use an Akka actor. Unlike the for-comprehension, it fails as soon as any of the futures fail, so it's a bit more efficient in that sense.Then, create the actor, send a message to it (so that it will know where to send its reply to) and wait for a reply.You might want to checkout Twitter's Future API. Notably the Future.collect method. It does exactly what you want: The source code Future.scala is available here:\n"},
Scala

how to sort a list in Scala by two fields, in this example I will sort by lastName and firstName?I try things like this but it doesn't work. So I be curious for a good and easy solution.Thanks in advance!PongoIf you want to sort by the merged names, as in your question, or if you first want to sort by lastName, then firstName; relevant for longer names (Wild, Wilder, Wilderman).If you writewith 2 underlines, the method expects two parameters:In general, if you use a stable sorting algorithm, you can just sort by one key, then the next.The final result will be sorted by lastname, then where that is equal, by firstname.Perhaps this works only for a List of Tuples, butappears to work and be a simple way to express it."},
Scala

I can see there's a sorting object, , with a  method, , on it.What would be a code example of using it, sorting an array of object of arbitrary type? It looks like I need to pass in an implementation of the  trait, but I am unsure of the syntax.Also, I would prefer answers doing this the 'Scala way'. I know I can just use a Java library.Sorting.quickSort declares functions for taking an Array of numbers or Strings, but I'm assuming you mean you want to sort a list of objects of your own classes?The function I think you're looking at isWhich, if I'm reading this right, means that the objects in the Array must have the  trait. So your class must extend  (or must mix it in), and therefore must implement the  method of that trait.So to rip off an example from the book:So given an Array[MyClass], then Sorting.quickSort should work.With Scala 2.8 or later it is possible to do:that uses , an implementation of quicksort.Nowadays this one works too: If you just want to sort things, but aren't married to the Sorting object in particular, you can use the sort method of List.  It takes a comparison function as an argument, so you can use it on whatever types you'd like:Lists probably qualify as \"more scalaish\" than arrays.From the scala api :Scala's \"default\" array is a mutable data structure, very close to Java's Array. Generally speaking, that means an \"array\" is not very Scala-ish, even as mutable data structures go. It serves a purpose, though. If array is the right data type for your need, then that is how you sort it. There are other sorting methods on object Sorting, by the way.I think I just realized what your question is... you don't need to pass any implicit parameter (it's implicit, after all). That parameter exists to say that there must be some way to convert the type K into an Ordered[K]. These definitions already exist for Scala's classes, so you don't need them.For an arbitrary class you can define it this way:Now, if Person was Ordered to begin with, this wouldn't be a problem:While the accepted answer isn't wrong, the quicksort method provides more flexibility than that. I wrote this example for you.This shows how implicit and explicit conversions from Foo to some class extending Ordered[Foo] can be used to get different sort orders."},
Scala

In Scala, algebraic data types are encoded as  one-level type hierarchies. Example:With es and s, Scala generates a bunch of things like , ,  (used by pattern matching) etc that brings us many of the key properties and features of traditional ADTs.There is one key difference though \u2013 . Compare the following two for example (Copied from the respective REPLs).I have always considered the Scala variation to be on the advantageous side.After all, .  for instance is a subtype of .In fact, . (Could we call this a limited version of dependent typing?) This can be put to good use \u2013 Once you know what data constructor was used to create a value, the corresponding type can be propagated through rest of the flow to add more type safety. For example, Play JSON, which uses this Scala encoding, will only allow you to extract  from , not from any arbitrary .In Haskell,  would probably have type . Which means it will fail at runtime for a  etc. This problem also manifests in the form of well known partial record accessors.  \u2013 on Twitter, mailing lists, IRC, SO etc. Unfortunately I don't have links to any of those, except for a couple -  by Travis Brown, and , a purely functional JSON library for Scala.Argonaut  takes the Haskell approach (by ing case classes, and providing data constructors manually). You can see that the problem I mentioned with Haskell encoding exists with Argonaut as well. (Except it uses  to indicate partiality.)I have been pondering this for quite some time, but still do not understand what makes Scala's encoding wrong. Sure it hampers type inference at times, but that does not seem like a strong enough reason to decree it wrong. What am I missing?To the best of my knowledge, there are two reasons why Scala's idiomatic encoding of case classes can be bad: type inference, and type specificity.  The former is a matter of syntactic convenience, while the latter is a matter of increased scope of reasoning.The subtyping issue is relatively easy to illustrate:The type of  turns out to be , which is probably not what you wanted.  You can generate similar issues in other, more problematic areas:The type of  is .  This is basically  to be not what you want.  In order to get around this issue, containers like  need to be covariant in their type parameter.  Unfortunately, covariance introduces a whole bucket of issues, and in fact degrades the soundness of certain constructs (e.g. Scalaz compromises on its  type and several monad transformers by allowing covariant containers, despite the fact that it is unsound to do so).So, encoding ADTs in this fashion has a somewhat viral effect on your code.  Not only do you need to deal with subtyping in the ADT itself, but  container you ever write needs to take into account the fact that you're landing on subtypes of your ADT at inopportune moments.The second reason not to encode your ADTs using public case classes is to avoid cluttering up your type space with \"non-types\".  From a certain perspective, ADT cases are not really types: they are data.  If you reason about ADTs in this fashion (which is not wrong!), then having first-class types for each of your ADT cases increases the set of things you need to carry in your mind to reason about your code.For example, consider the  algebra from above.  If you want to reason about code which uses this ADT, you need to be constantly thinking about \"well, what if this type is ?\"  That just not a question anyone really  to ask, since  is data.  It's a tag for a particular coproduct case.  That's all.Personally, I don't care much about any of the above.  I mean, the unsoundness issues with covariance are real, but I generally just prefer to make my containers invariant and instruct my users to \"suck it up and annotate your types\".  It's inconvenient and it's dumb, but I find it preferable to the alternative, which is a lot of boilerplate folds and \"lower-case\" data constructors.As a wildcard, a third potential disadvantage to this sort of type specificity is it encourages (or rather, allows) a more \"object-oriented\" style where you put case-specific functions on the individual ADT types.  I think there is very little question that mixing your metaphors (case classes vs subtype polymorphism) in this way is a recipe for bad.  However, whether or not this outcome is the fault of typed cases is sort of an open question."},
Scala

In java world (more precisely if you have no multiple inheritance/mixins) the rule of thumb is quite simple: \"Favor object composition over class inheritance\".  I'd like to know if/how it is changed if you also consider mixins, especially in scala?\nAre mixins considered a way of multiple inheritance, or more class composition?\nIs there also a \"Favor object composition over class composition\" (or the other way around) guideline?I've seen quite some examples when people use (or abuse) mixins when object composition could also do the job and I'm not always sure which one is better. It seems to me that you can achieve quite similar things with them, but there are some differences also, some examples: I know the short answer is \"It depends\", but probably there are some typical situation when this or that is better.Some examples of guidelines I could come up with so far (assuming I have two traits A and B and A wants to use some methods from B):In many cases mixins seem to be easier (and/or less verbose), but I'm quite sure they also have some pitfalls, like the \"God class\" and others described in two artima articles: ,  (BTW it seems to me that most of the other problems are not relevant/not so serious for scala).Do you have more hints like these?A lot of the problems that people have with mix-ins can be averted in Scala if you only mix-in abstract traits into your class definitions, and then mix in the corresponding concrete traits at object instantiation time.  For instanceThis construct has several things to recommend it.  First, it prevents there from being an explosion of classes as different combinations of trait functionalities are needed.  Second, it allows for easy testing, as one can create and mix-in \"do-nothing\" concrete traits, similar to mock objects.  Finally, we've completely hidden the locking trait used, and even that locking is going on, from consumers of our service.    Since we've gotten past most of the claimed drawbacks of mix-ins, we're still left with a tradeoff\nbetween mix-in and composition.  For myself, I normally make the decision based on whether a hypothetical delegate object would be entirely encapsulated by the containing object, or whether it could potentially be shared and have a lifecycle of it's own.  Locking provides a good example of entirely encapsulated delegates.  If your class uses a lock object to manage concurrent access to its internal state, that lock is entirely controlled by the containing object, and neither it nor its operations are advertised as part of the classes public interface. For entirely encapsulated functionality like this, I go with mix-ins.  For something shared, like a datasource, use composition.Other differences you haven't mentioned: ()Hence the :That last part, regarding the  of an object, has often helped decide between class (and class composition) and trait (and mixins) for a given concept."},
Scala

I am trying to get a subarray in scala, and I am a little confused on what the proper way of doing it is.  What I would like the most would be something like how you can do it in python:but I am fairly certain you cannot do this.The most obvious way to do it would be to use the Java Arrays util library.But it always makes me feel a little dirty to use Java libraries in Scala.  The most \"scalaic\" way I found to do it would bebut is there a better way?You can call the slice method:It works like in python."},
Scala

I just had a look at the new  and  packages to see if there is something helpful here. However, I am at a complete loss.Has anybody got an example on how to actually start a process?And, which is most interesting for me: Can you detach processes?A detached process will continue to run when the parent process ends and is one of the weak spots of Ant.There seem to be some confusion what detach is. Have a real live example from my current project. Once with z-Shell and once with TakeCommand:In both cases it is fire and forget, the emulator is started and will continue to run even after the script has ended. Of course having to write the scripts twice is a waste. So I look into Scala now for unified process handling without cygwin or xml syntax.First import:then create a ProcessBuilderThen you have two options:If you want to handle the input and output of the process you can use :I'm pretty sure detached processes work just fine, considering that you have to explicitly wait for it to exit, and you need to use threads to babysit the stdout and stderr.  This is pretty basic, but it's what I've been using:Process was imported from SBT. Here's a thorough guide on how to use the process library .Most of what you'll do is related to , the trait. Get to know that.There are implicits that make usage less verbose, and they are available through the package object . Import its contents, like shown in the examples. Also, take a look at its scaladoc as well.The following function will allow easy use if here documents:Sadly I was not able to (did not have the time to) to make it an infix operation. Suggested calling convention is therefore:It would be call if anybody could give me a hint on how to make it a more shell like call:Documenting process a little better was second on my list for probably two months.  You can infer my list from the fact that I never got to it.  Unlike most things I don't do, this is something I said I'd do, so I greatly regret that it remains as undocumented as it was when it arrived.  Sword, ready yourself! I fall upon thee!If I understand the dialog so far, one aspect of the original question is not yet answered:The primary difficulty is that all of the classes involved in spawning a process must run on the JVM, and they are unavoidably terminated when the JVM exits.   However, a workaround is to indirectly achieve the goal by leveraging the shell to do the \"detach\" on your behalf.  The following scala script, which launches the gvim editor, appears to work as desired:It assumes that scala is in the PATH, and it does (unavoidably) leave a JVM parent process running as well."},
Scala

I can find tons of examples but they seem to either rely mostly on Java libraries or just read characters/lines/etc.I just want to read in some file and get a byte array with scala libraries - can someone help me with that?Java 7:I believe this is the simplest way possible. Just leveraging existing tools here. NIO.2 is wonderful.This should work (Scala 2.8): The library  is problematic, DON'T USE IT in reading binary files.The error can be reproduced as instructed here: In the file , it contains the hexidecimal , which is  in binary and should be converted to  in decimal.The  file contain two ways to read the file:When I run , the program outputs follows:The Java library generates correct output, while the Scala library not.You might also consider using :"},
Scala

So, for example, in Python the 2nd item of a tuple would be accessed via .In Scala, access is only possible via strange names .So the question is, why can't I access data in tuples as Sequence or List if it is by definition? Is there some sort of idea or just yet not inspected?Scala knows the arity of the tuples and is thus able to provide accessors like , , etc., and produce a compile-time error if you select  on a pair, for instance. Moreover, the type of those fields is exactly what the type used as parameter for  (e.g.  on a  will return a ).If you want to access the nth element, you can write , but the return type of this can only be , so you lose the type information.I believe the following excerpt from \"Programming in Scala: A Comprehensive Step-by-Step Guide\" (Martin Odersky, Lex Spoon and Bill Venners) directly addresses both of your questions:Scala tuples get very little preferential treatment as far as the language syntax is concerned, apart from expressions  being treated by the compiler as an alias for scala.Tuplen() class instantiation. Otherwise tuples do behave as any other Scala objects, in fact they are written in Scala as . Tuple2 and Tuple3 are also known under the aliases of Pair and Triple respectively:One big difference between ,  or any collection and tuple is that in tuple each element has it's own type where in List all elements have the same type.And as consequence, in Scala you will find classes like  or , so for each element you also have type parameter. Collections accept only 1 type parameter: . Syntax like  is just syntactic sugar for . And , , etc. are just fields on tuple that return correspondent element.  You can easily achive that with :A lot of methods available for standard collection are also available for tuples this way (, , , ,  and  for concatenation,  and  for adding elements, , , , , , , , , , ...)With normal index access, any expression can be used, and it would take some serious effort to check at compiletime if the result of the index expression it is guaranteed to be in range. Make it an attribute, and a compile-time error for  follows \"for free\". Things like allowing only integer constants inside item access on tuples would be a very special case (ugly and unneeded, some would say ridiculous) and again some work to implement in the compiler.Python, for instance, can get away with that because it wouldn't (couldn't) check (at compiletime, that is) if the index is in range anyway.I think it's for type checking. As delnan says, if you have a tuple  and an index  (an arbitrary expression),  would give the compiler no information about which element is being accessed (or even if it's a valid element for a tuple of that size). When you access elements by field name ( is a valid identifier, it's not special syntax), the compiler knows which field you're accessing and what type it has. Languages like Python don't really have types, so this is not necessary for them.Apart from the benefits Jean-Philippe Pellet already mentioned this notation is also very common in mathematics (see ).  A lot of lecturers append indexes to tuple variables if they want to referring to the elements of a tuple.  And the common (LaTeX) notation for writing \"with index \" (referring to the -th element of the tuple) is .  So I find it actually very intuitive."},
Scala

I know there have been quite a few questions on this, but I've created a simple example that I thought should work,but still does not and I'm not sure I understand whyCan someone explain why the second statement does not compile?It expands to:You want:The placeholder syntax for anonymous functions replaces the smallest possible containing expression with a function."},
Scala

It seems that there has been a recent rising interest in STM (software transactional memory) frameworks and language extensions.   in particular has an excellent implementation which uses  rather than a rolling commit log.  GHC Haskell also has  which also allows transaction composition.  Finally, so as to toot my own horn just a bit, I've recently implemented an  which statically enforces reference restrictions.All of these are interesting experiments, but they seem to be confined to that sphere alone (experimentation).  So my question is: have any of you seen or used STM in the real world?  If so, why?  What sort of benefits did it bring?  What about performance?  (there seems to be a great deal of conflicting information on this point)  Would you use STM again or would you prefer to use some other concurrency abstraction like actors?I participated in the hobbyist development of the BitTorrent client in Haskell (named conjure). It uses STM quite heavily to coordinate different threads (1 per peer + 1 for storage management + 1 for overall management).Benefits: less locks, readable code.Speed was not an issue, at least not due to STM usage.Hope this helpsThe article \"Software Transactional Memory: why is it only a research toy?\" fails to look at the Haskell implementation, which is a really big omission.  The problem for STM, as the article points out, is that implementations must chose between either making all variable accesses transactional unless the compiler can prove them safe (which kills performance) or letting the programmer indicate which ones are to be transactional (which kills simplicity and reliability).  However the Haskell implementation uses the purity of Haskell to avoid the need to make most variable uses transactional, while the type system provides a simple model together with effective enforcement for the transactional mutation operations.  Thus a Haskell program can use STM for those variables that are truly shared between threads whilst guaranteeing that non-transactional memory use is kept safe.We use it pretty routinely for high concurrency apps at Galois (in Haskell). It works, its used widely in the Haskell world, and it doesn't deadlock (though of course you can have too much contention). Sometimes we rewrite things to use MVars, if we've got the design right -- as they're faster.Just use it. It's no big deal. As far as I'm concerned, STM in Haskell is \"solved\". There's no further work to do. So we use it.We, , are using Haskell STM with GHC in production.  Our server receives a stream of messages about new and modified \"objects\" from a clincal \"data server\", it transforms this event stream on the fly (by generating new objects, modifying objects, aggregating things, etc) and calculates which of these new objects should be synchronized to connected iPads.  It also receives form inputs from iPads which are processed, merged with the \"main stream\" and also synchronized to the other iPads.  We're using STM for all channels and mutable data structures that need to be shared between threads.  Threads are very lightweight in Haskell so we can have lots of them without impacting performance (at the moment 5 per iPad connection). Building a large application is always a challenge and there were many lessons to be learned but we never had any problems with STM.  It always worked as you'd naively expect.  We had to do some serious performance tuning but STM was never a problem. (80% of the time we were trying to reduce short-lived allocations and overall memory usage.)STM is one area where Haskell and the GHC runtime really shines.  It's not just an experiment and not for toy programs only.We're building a different component of our clincal system in Scala and have been using Actors so far, but we're really missing STM.  If anybody has experience of what it's like to use one of the Scala STM implementations in production I'd love to hear from you. :-)You may want to read this article:\nWe have implemented our entire  (in-memory database and runtime) on top of our own STM implementation in C. Prior to this, we had some log and lock based mechanism to deal with concurrency, but this was a pain to maintain. We are very happy with STM since we can treat every operation the same way. Almost all locks could be removed. We use STM now for almost anything at any size, we even have a memory manager implement on top. The performance is fine but to speed things up we now developed a custom  in collaboration with ETH Zurich. The system natively supports transactional memory.But there are some challenges caused by STM as well. Especially with larger transactions and hotspots that cause unnecessary transaction conflicts. If for example two transactions put an item into a linked list, an unnecessary conflict will occur that could have been avoided using a lock free data structure.I'm currently using Akka in some PGAS systems research.  is a Scala library for developing scalable concurrent systems using Actors, STM, and built-in fault tolerance capabilities modeled after Erlang's \"Let It Fail/Crash/Crater/ROFL\" philosophy. Akka's STM implementation is supposedly built around a Scala port of Clojure's STM implementation. An overview of Akka's STM module can be found ."},
Scala

Let's say I want to handle multiple return values from a remote service using the same code. I don't know how to express this in Scala:I know I can use Extract Method and call that, but there's still repetition in the call. If I were using Ruby, I'd write it like this:Note that I simplified the example, thus I don't want to pattern match on regular expressions or some such. The match values are actually complex values.You can do:Note that you cannot bind parts of the pattern to names - you can't do this currently:"},
Scala

If I have a  in Scala, what is the idiomatic way to filter out the  values?One way is to use the following:Is there a more \"idiomatic\" way? This does seem pretty simple.If you want to get rid of the options at the same time, you can use :someList.filter(_.isDefined) if you want to keep the result type as List[Option[A]]"},
Scala

I've written a rather large program in Scala 2.7.5, and now I'm looking forward to version 2.8. But I'm curious about how this big leap in the evolution of Scala will affect me.What will be the biggest differences between these two versions of Scala? And perhaps most importantly:You can find here a  (April 2009), completed with recent  (June 2009)\"Rewriting code\" is not an obligation (except for using some of the improved Collections), but some features like  (: an abstract representation of the control state, or the \"rest of computation\" or \"rest of code to be executed\") can give you some new ideas. A good introduction is , written by  (who has also posted a much  in this thread).Note:  seems to work with some 2.8 nightly-build (vs. the )When you migrate, the compiler can provide you with some safety nets.There are many other new features that can be safely ignored as you start migrating, for example  and Continuations.VonC's answer is hard to improve on, so I won't even try to. I'll cover some other stuff not mentioned by him.First, some deprecated stuff will go. If you have deprecation warnings in your code, it's likely it won't compile anymore.Next, Scala's library is being expanded. Mostly, common little patterns such as catching exceptions into  or , or converting an AnyRef into an Option with  mapped into . These things can mostly pass unnoticed, but I'm getting tired of posting something on the blog and later having someone tell me it's already on Scala 2.8. Well, actually, I'm not getting  of it, but, rather, and happily, used to it. And I'm not talking here about the Collections, which  getting a major revision.Now, it  be nice if people posted actual examples of such library improvements as answers. I'd happily upvote all such answers.REPL is not getting just command-completion. It's getting a lot of stuff, including the ability to examine the AST for an object, or the ability to insert break points into code that fall into REPL.Also, Scala's compiler is being modified to be able to provide fast partial compilation to IDEs, which means we can expect them to become much more \"knowledgable\" about Scala -- by querying the Scala compiler itself about the code.One big change is likely to pass unnoticed by many, though it will decrease problems for library writers and users alike. Right now, if you write the following:You are importing not Java's  library, but 's  library, as , ,  and  all got within scope, and  can be found inside . With Scala 2.8, only  gets scoped. Since, sometimes, you want some of the rest to be in Scope, an alternative  syntax is now allowed:which is equivalent to:And happens to get both  and  into scope.needs to becomeI had to visit the IRC channel for that one, but then realized I should have started here.Here's a checklist from Eric Willigers, who has been using Scala since 2.2. Some of this stuff will seem dated to more recent users.>\n>\n>"},
Scala

I am trying to issue a simple POST request to a webservice which returns some XML in Scala.It seems that  is the standard library used for this task, but I cannot find documentation for it. The main site, which I link above, explains at length what is a promise and how to do asynchronous programming, but does not actually document the API. There is a  - which looks a bit scary - but it only seems useful to people who already know what to do and only need a reminder for the cryptic syntax.It also seems that , but I cannot find any documentation for it either.I use the following: .Here's a simple GET request:and an example of a POST:Scalaj HTTP is available through SBT:You could use .  The documentation is lacking (it took me some digging to find out ) but it's a great option if you are already using spray.  And the documentation is better than dispatch.We're using it at  over  because the operators are less symbolic and we're already using spray/actors.I'm using dispatch: They've just released a new version (0.9.0) with a complete new api that I really like. And it is async.Example from project page:edit: This might help you Another option is Typesafe's play-ws, which is the Play Framework WS library broken out as a standalone lib:I wouldn't necessarily offer this as the best option, but worth mentioning.Why not use  ? Here's the , which covers a wide range of scenarios.If I can make a shameless plug, I have an API called  which is simply a wrapper in Scala for Java's HttpUrlConnection.I had to do the same to test one end point (in Integration test). So following is the code to fetch response from GET request in Scala.\nI am making use of scala.io.Source to read from endpoint and ObjectMapper for json to object conversion.And here is my test method for the same"},
Scala

How to create a list with the same element n-times ?Manually implementnation:Is there also a built-in way to do the same ?See  that collection data structures, like , ,  and so on, extend: It's not available in Scala 2.7.Using  like this,I have another answer which emulates flatMap I think (found out that this solution returns Unit when applying duplicateN)}but this is rather for a predetermined List and you want to duplicate n times each elementWorks like a charm."},
Scala

Does anyone know if there is a nice way I can convert a Scala case class instance, e.g.Into a mapping of some kind, e.g.Which works for any case class, not just predefined ones. I've found you can pull the case class name out by writing a method that interrogates the underlying Product class, e.g.So I'm looking for a similar solution but for the case class fields. I'd imagine a solution might have to use Java reflection, but I'd hate to write something that might break in a future release of Scala if the underlying implementation of case classes changes.Currently I'm working on a Scala server and defining the protocol and all its messages and exceptions using case classes, as they are such a beautiful, concise construct for this. But I then need to translate them into a Java map to send over the messaging layer for any client implementation to use. My current implementation just defines a translation for each case class separately, but it would be nice to find a generalised solution.This should work:Because case classes extend  one can simply use  to get field values:Or alternatively:One advantage of Product is that you don't need to call  on the field to read its value. Another is that productIterator doesn't use reflection.Note that this example works with simple case classes that don't extend other classes and don't declare fields outside the constructor.If anybody looks for a recursive version, here is the modification of @Andrejs's solution:It also expands the nested case-classes into maps at any level of nesting.Solution with  from interpreter package:Here's a simple variation if you don't care about making it a generic function:I don't know about nice... but this seems to work, at least for this very very basic example. It probably needs some work but might be enough to get you started? Basically it filters out all \"known\" methods from a case class (or any other class :/ )Details: If you happen to be using Json4s, you could do the following:You could use shapeless.LetDefine a LabelledGeneric representationDefine two typeclasses to provide the toMap methodsThen you can use it like this.which prints For nested case classes, (thus nested maps)\ncheck  "},
Scala

since concurrent programming becomes constantly more important, I was wondering\nwhat you think about Erlang vs. Scala in that respect. It seems to me that Scala\nhas a larger user base and potentially a brighter future than Erlang. Furthermore,\nScala is kind of java.I know these questions are alway a bit subjective, but what would be the better\nfuture investment: Erlang or Scala. Or even another language?Erlang has been designed for concurrent, fault-tolerant communication systems. You can easily write servers that handle large number of network connections and (thanks to one garbage collector per Erlang process) the servers can retain soft real-time characteristics (i.e., the whole server is not paused until GC finishes). You can also hot-swap Erlang code, distribute it across several nodes, etc. That's why (arguably) the most-scalable XMPP server (ejabberd) is written in Erlang. Yaws (a web server) is another example where Erlang excels, see: . Riak/Couch are examples of NoSQL DB build with Erlang. These are the problems where Erlang is a great choice.But Erlang VM is not as fast as JVM in terms of raw computations, so as soon as you need to do something computationally intensive (e.g. financial modeling) JVM will be your preferred platform. Moreover, Erlang's concurrency model (actors) is baked in the language. If that doesn't fit the problem you're trying to solve, then you won't be happy with Erlang.Scala is more 'general' language in a sense that concurrency, horizontal scalability, or fault-tolerance is not part of the language. It is solved at the level of libraries (that's why there are at least 3 implementations of actors in Scala). The good thing is that you can pick concurrency model that fits your domain. For example if you need software transactional memory (STM), just pick Akka and you're good to go ().Plus there is the whole argument that with Scala you can leverage your \"JVM investments\" and multitude of JVM libs.You didn't give any info on what kind of software you want to write with either of those languages so it's hard to give you a definitive answer. Having said that, given all the above, Scala may be \"safer\" investment than Erlang (not bashing Erlang/OTP at all, it's a fine language/platform).BTW. If a single-machine concurrency is important to you Clojure () should not be overlooked (also JVM language).UPDATE1: If you like what Erlang offers but not its syntax, take a look at  Just pick one and stick with it for a while.  Learn some stuff, make some cool things and either keep going with that language or move on to another one.With respect to learning concurrent programming, either will be fine.  The key here is that you will be learning something new and unless there's a job opening that you are trying to get hired for that uses Erlang specifically, it really doesn't matter.  Plus, even if that opening did require Erlang, you would still likely have a good chance if you knew Scala really well.Just think, all of the time you have spent trying to pick a new language could have been better spent if you just picked one and already started learning it by now.Both languages, at the core, are not that hard to learn, and also to learn the concurrency features they provide. In fact, Scala actors are influenced by Erlang actors. I would go to both of them, take your time looking at their construct, do some tests in concurrency problems, etc.If you know Java, Scala will be more natural, as Erlang is more like prolog. If, on the contrary, you're more oriented towards mathematical or logical type of languages, start with Erlang."},
Scala

What is the syntax for adding an element to a scala.collection.mutable.Map ?Here are some failed attempts:The point is that the first line of your codes is not what you expected. You should use orinstead.As always, you should question whether you truly need a mutable map.Immutable maps are trivial to build:Mutable maps are no different when first being built:In both of these cases, inference will be used to determine the correct type parameters for the Map instance.You can also hold an immutable map in a , the variable will then be updated with a new immutable map instance every time you perform an \"update\"If you don't have any initial values, you can use Map.empty:When you sayyou are not creating a map instance, but instead aliasing the Map type.Try instead the following:Create a new immutable map:Add a new key/value pair to the above map (and create a new map, since they're both immutable):Create a mutable map without initial value:Create a mutable map with initial values:Update existing key-value:Add new key-value:Check the updated map:"},
Scala

I am a Scala programmer, learning Haskell now. It's easy to find practical use cases and real world examples for OO concepts, such as decorators, strategy pattern etc. Books and interwebs are filled with it. I came to the realization that this somehow is not the case for functional concepts. Case in point: .  I am struggling to find practical use cases for applicatives. Almost all of the tutorials and books I have come across so far provide the examples of  and . I expected applicatives to be more applicable than that, seeing all the attention they get in the FP community.  I think I understand the conceptual basis for  (maybe I am wrong), and I have waited long for my moment of enlightenment. But it doesn't seem to be happening. Never while programming, have I had a moment when I would shout with a joy, \"Eureka! I can use applicative here!\" (except again, for  and ).  Can someone please guide me how applicatives can be used in a day-to-day programming? How do I start spotting the pattern? Thanks!Well, how often in your day-to-day Haskell programming do you create new data types? Sounds like you want to know when to make your own Applicative instance, and in all honesty unless you are rolling your own parser, you probably won't need to do it very much.  applicative instances, on the other hand, you should learn to do frequently.Applicative is not a \"design pattern\" like decorators or strategies. It is an abstraction, which makes it much more pervasive and generally useful, but much less tangible. The reason you have a hard time finding \"practical uses\" is because the example uses for it are almost too simple. You use decorators to put scrollbars on windows. You use strategies to unify the interface for both aggressive and defensive moves for your chess bot. But what are applicatives for? Well, they're a lot more generalized, so it's hard to say what they are for, and that's OK. Applicatives are handy as parsing combinators; the Yesod web framework uses Applicative to help set up and extract information from forms. If you look, you'll find a million and one uses for Applicative; it's all over the place. But since it's so abstract, you just need to get the feel for it in order to recognize the many places where it can help make your life easier.Applicatives are great when you've got a plain old function of several variables, and you have the arguments but they're wrapped up in some kind of context. For instance, you have the plain old concatenate function  but you want to apply it to 2 strings which were acquired through I/O. Then the fact that  is an applicative functor comes to the rescue:Even though you explicitly asked for non- examples, it seems like a great use case to me, so I'll give an example. You have a regular function of several variables, but you don't know if you have all the values you need (some of them may have failed to compute, yielding ). So essentially because you have \"partial values\", you want to turn your function into a partial function, which is undefined if any of its inputs is undefined. Thenbutwhich is exactly what you want.The basic idea is that you're \"lifting\" a regular function into a context where it can be applied to as many arguments as you like. The extra power of  over just a basic  is that it can lift functions of arbitrary arity, whereas  can only lift a unary function.Since many applicatives are also monads, I feel there's really two sides to this question.  This is mostly a matter of style. Although monads have the syntactic sugar of -notation, using applicative style frequently leads to more compact code.In this example, we have a type  and we want to construct random values of this type. Using the monad instance for , we might writeThe applicative variant is quite a bit shorter.Of course, we could use  to get similar brevity, however the applicative style is neater than having to rely on arity-specific lifting functions.In practice, I mostly find myself using applicatives much in the same way like I use point-free style: To avoid naming intermediate values when an operation is more clearly expressed as a composition of other operations.Since applicatives are more restricted than monads, this means that you can extract more useful static information about them.An example of this is applicative parsers. Whereas monadic parsers support sequential composition using , applicative parsers only use . The types make the difference obvious: In monadic parsers the grammar can change depending on the input, whereas in an applicative parser the grammar is fixed.By limiting the interface in this way, we can for example determine whether a parser will accept the empty string . We can also determine the first and follow sets, which can be used for optimization, or, as I've been playing with recently, constructing parsers that support better error recovery. I think of Functor, Applicative and Monad as design patterns. Imagine you want to write a Future[T] class. That is, a class that holds values that are to be calculated.In a Java mindset, you might create it likeWhere 'get' blocks until the value is available. You might realize this, and rewrite it to take a callback:But then what happens if there are two uses for the future? It means you need to keep a list of callbacks. Also, what happens if a method receives a Future[Int] and needs to return a calculation based on the Int inside? Or what do you do if you have two futures and you need to calculate something based on the values they will provide?But if you know of FP concepts, you know that instead of working directly on T, you can manipulate the Future instance.Now your application changes so that each time you need to work on the contained value, you just return a new Future.Once you start in this path, you can't stop there. You realize that in order to manipulate two futures, you just need to model as an applicative, in order to create futures, you need a monad definition for future, etc.UPDATE: As suggested by @Eric, I've written a blog post: I finally understood how applicatives can help in day-to-day programming with that presentation:The autor shows how applicatives can help for combining validations and handling failures. The presentation is in Scala, but the author also provides the full code example for Haskell, Java and C#.I think Applicatives ease the general usage of monadic code. How many times have you had the situation that you wanted to apply a function but the function was not monadic and the value you want to apply it to is monadic? For me: quite a lot of times!\nHere is an example that I just wrote yesterday:in comparison to this using Applicative:This form looks \"more natural\" (at least to my eyes :)Coming at Applicative from \"Functor\" it generalizes \"fmap\" to easily express acting on several arguments (liftA2) or a sequence of arguments (using <*>).Coming at Applicative from \"Monad\" it does not let the computation depend on the value that is computed.  Specifically you cannot pattern match and branch on a returned value, typically all you can do is pass it to another constructor or function.Thus I see Applicative as sandwiched in between Functor and Monad.  Recognizing when you are not branching on the values from a monadic computation is one way to see when to switch to Applicative.Here is an example taken from the aeson package:There are some ADTs like ZipList that can have applicative instances, but not monadic instances.  This was a very helpful example for me when understanding the difference between applicatives and monads.  Since so many applicatives are also monads, it's easy to not see the difference between the two without a concrete example like ZipList.I think it might be worthwhile to browse the sources of packages on Hackage, and see first-handedly how applicative functors and the like are used in existing Haskell code.I described an example of practical use of the applicative functor in a discussion, which I quote below.Note the code examples are pseudo-code for my hypothetical language which would hide the type classes in a conceptual form of subtyping, so if you see a method call for  just translate into your type class model, e.g.  in Scalaz or Haskell.It is useful to read , because I can't copy it all here. I expect that url to not break, given who the owner of that blog is. For example, I quote from further down the discussion.I think what I presented  serves as a good example of an use case for  spotted in the wild."},
Scala

I am struggling to find any decent links to design patterns, best practice or good, basic architectural principles that should be used in building Actor-based apps. Those few that I know of are:This is related to a , if not  the same! It's not such a simple question because the  of concurrency allows for many different types of applications to be built, from a stateful single-VM application (with a few separate actor classes) to a stateless cluster of thousands of instances of an actor class. The core principles are the same however:I posted a blog on  in Scala a few weeks ago.  It's a post of a best practices and things to avoid based on a few years of experience with the paradigm.The book 'Reactive Design Patterns' is in the making at Manning.See: "},
Scala

A friend of mine posed a seemingly innocuous Scala language question last week that I didn't have a good answer to: whether there's an easy way to declare a collection of things belonging to some common typeclass.  Of course there's no first-class notion of \"typeclass\" in Scala, so we have to think of this in terms of traits and context bounds (i.e. implicits).Concretely, given some trait  representing a typeclass, and types ,  and , with corresponding implicits in scope ,  and , we want to declare something like a , into which we can throw instances of ,  and  with impunity.  This of course doesn't exist in Scala; a  discusses this in more depth.The natural follow-up question is \"how does Haskell do it?\"  Well, GHC in particular has a type system extension called , described in the  paper.  In brief, given a typeclass  one can legally construct a list .  Given a declaration of this form, the compiler does some dictionary-passing magic that lets us retain the typeclass instances corresponding to the types of each value in the list at runtime.Thing is, \"dictionary-passing magic\" sounds a lot like \"vtables.\"  In an object-oriented language like Scala, subtyping is a much more simple, natural mechanism than the \"Boxy Types\" approach.  If our ,  and  all extend trait , then we can simply declare  and be happy.  Likewise, as Miles notes in a comment below, if they all extend traits ,  and  then I can use  as an equivalent to the impredicative Haskell .However, the main, well-known disadvantage with subtyping compared to typeclasses is tight coupling: my ,  and  types have to have their  behavior baked in.  Let's assume this is a major dealbreaker, and I  use subtyping.  So the middle ground in Scala is pimps^H^H^H^H^Himplicit conversions: given some ,  and  in implicit scope, I can again quite happily populate a  with my ,  and  values...... Until we want .  At that point, even if we have implicit conversions ,  and , we can't put an  into the list.  We could restructure our implicit conversions to literally provide , but I've never seen anybody do that before, and it seems like yet another form of tight coupling.Okay, so my question finally is, I suppose, a combination of a couple questions that were previously asked here:  and  ... is there some unifying theory that says impredicative polymorphism and subtype polymorphism are one and the same?  Are implicit conversions somehow the secret love-child of the two?  And can somebody articulate a good, clean pattern for expressing multiple bounds (as in the last example above) in Scala?You're confusing impredicative types with existential types. Impredicative types allow you to put  values in a data structure, not arbitrary concrete ones. In other words  means that you have a list where each element works as any numeric type, so you can't put e.g.  and  in a list of type , but you can put something like  in it. Impredicative types is not what you want here.What you want is existential types, i.e.  (not real Haskell syntax), which says that each element is some unknown numeric type. To write this in Haskell, however, we need to introduce a wrapper data type:Note the change from  to . That's because we're describing the . We can put any numeric type , but then the type system \"forgets\" which type it was. Once we take it back out (by pattern matching), all we know is that it's some numeric type. What's happening under the hood, is that the  type contains a hidden field which stores the type class dictionary (aka. vtable/implicit), which is why we need the wrapper type.Now we can use the type  for a list of arbitrary numbers, but we need to wrap each number on the way in, e.g. . The correct dictionary for each type is looked up and stored in the hidden field automatically at the point where we wrap each number. The combination of existential types and type classes is in some ways similar to subtyping, since the main difference between type classes and interfaces is that with type classes the vtable travels separately from the objects, and existential types packages objects and vtables back together again.However, unlike with traditional subtyping, you're not forced to pair them one to one, so we can write things like this which packages one vtable with two values of the same type.or even fancier things. Once we pattern match on the wrapper, we're back in the land of type classes. Although we don't know which type  and  are, we know that they're the same, and we have the correct dictionary available to perform numeric operations on them. Everything above works similarly with multiple type classes. The compiler will simply generate hidden fields in the wrapper type for each vtable and bring them all into scope when we pattern match.As I'm very much a beginner when it comes to Scala, I'm not sure I can help with the final part of your question, but I hope this has at least cleared up some of the confusion and given you some ideas on how to proceed.@hammar's answer is perfectly right. Here is the scala way of doint it. For the example i'll take  as the type class and the values  and  to pack in a list :What we want is to be able run the following codeBuilding the list is easy but the list won't \"remember\" the exact type of each of its elements. Instead it will upcast each element to a common super type . The more precise super super type between  and  being , the type of the list is .The problem is: what to forget and what to remember? We want to forget the exact type of the elements BUT we want to remember that they are all instances of . The following class does exactly thatThis is an encoding of the existential :It pack a value with the corresponding type class instance.Finally we can add an instance for The  is required to bring the instance into scope. Thanks to the magic of implicits:which is very close to the expected code."},
Scala

Scala has a language feature to support disjunctions in pattern matching ('Pattern Alternatives'):However, I often need to trigger an action if the scrutiny satisfies PatternA  PatternB (conjunction.)I created a pattern combinator '&&' that adds this capability. Three little lines that remind me why I love Scala!\nI've just been asked how the compiler interprets . These are infix operator patterns (Section 8.1.9 of the Scala Reference). You could also express this with standard extract patterns (8.1.7) as Boolean#&&val b = true && false && true`.I really like this trick. I do not know of any existing way to do this, and I don't foresee any problem with it -- which doesn't mean much, though. I can't think of any way to create a .As for adding it to the standard library... perhaps. But I think it's a bit hard. On the other hand, how about talking Scalaz people into including it? It looks much more like their own bailiwick.A possible problem with this is the bloated translation that the pattern matcher generates. \nHere is the  of the sample program, generated with . Even  fails to simplify the  expressions.Large pattern matches already generate more bytecode than is legal for a single method, and use of this combinator may amplify that problem.If  was built into the language, perhaps the translation could be smarter. Alternatively, small improvements to  could help."},
Scala

In Scala, a class's primary constructor has no explicit body, but is defined implicitly from the class body. How, then, does one distinguish between fields and local values (i.e. values local to the constructor method)?For example, take the following code snippet, a modified form of some sample code from \"Programming in Scala\":My understanding is that this will generate a class with three fields: a private \"g\", and public \"x\" and \"y\". However, the g value is used only for calculation of the x and y fields, and has no meaning beyond the constructor scope.So in this (admittedly artificial) example, how do you go about defining local values for this constructor?E.g.There are a few ways to do that. You can declare such temporary variables inside private definitions, to be used during construction time. You can use temporary variables inside blocks which return expressions (such as in Alaz's answer). Or, finally, you can use such variables inside alternate constructors.In a manner similar to the alternate constructors, you could also define them inside the object-companion's \"apply\" method.What you  do is declare a field to be \"temporary\".Note also that any parameter received by the primary constructor is a field also.  If you don't want such parameters to become fields, and don't want to expose the actual fields in a constructor, the usual solution is to make the primary constructor private, with the actual fields, and use either an alternate constructor or an object-companion's apply() as the effective \"primary\" constructor.Another option we have is to make the primary object constructor private and use a companion object's apply method as a builder. If we apply (pun is not intended) this approach to your example it will look like this:To create an R instance instead of:write: This is a little bit verbose, but it could be worse, I think :). Let's hope that private[this] vals will be treated as temporary variables in future releases of Scala. Martin himself hinted that.Some discussion on this topic, including Martin Odersky's comments, is "},
Scala

Coming back to Scala after a spell writing Haskell, I've started using the type keyword to make my class definitions a bit more readable, eg:The trouble I've run into is that these type definitions need to live inside a class or object - they're not \"first class citizens\" like they are in Haskell. If I try to define a type outside of a class or object, I get a compiler .My problem then is how to use these types across multiple classes and objects in a package? What I've done now seems quite ugly:And then in another class file:Is there a nicer way of doing this - and incidentally do the Scala gurus think it's a good thing or a bad thing that types can only be defined inside classes/objects?Will  work for you?From the article:The  has many types and values already, so I think you can use the same technique for your own types.I'm not sure what constitutes niceness in this case, but here are two options:Using a trait: ()Or just import the object's members, effectively using it like a package:Youn can use a package object and put the type declaration in there. When you import that package the type definition will be available. An example : Notice that the package object has the same name as the package in order to be usable without a object prefix i.e myType.mine\nIf you name it with a different name for example :it can be accessed with mainType.mine when you import \"package\"for more info :\n"},
Scala

Can someone explain to me in simple terms what the Shapeless library is for?Scala has generics and inheritance functionality so I'm a bit confused what Shapeless is for.Maybe a use case to clarify things would be helpful.It's a little hard to explain, as shapeless has a wide range of features;  I'd probably find it easier to \"explain, in simple terms, what variables are for\".  You definitely want to start with the .Broadly speaking, shapeless is about programming with types.  Doing things at compile-time that would more commonly be done at runtime, keeping precise track of the type of each element in a list, being able to translate from tuples to HLists to case classes, creating polymorphic functions (as opposed to methods), etc.A typical usage scenario would go something like:For reference, an  will have a precise type, such as  (yes, that really  a single type) where everything is pinned down and the size is fixed.  So you either need to know at compile time exactly what will be going into your HList, or you need the type-safe cast.If you take the  of such an HList, you get a , and a compile-time guarantee that the head of this will be a .  Prepending a value to the head will similarly preserve all types involved.Shapeless also comes with the  type class, allowing you to use HList operations on tuples and case classes as well.The other features I tend to use are:Looking at an  is something that might seem baffling until you try to work with types and delegate or switch on types. Take a look at the following:What is the type of  here? If you were to inspect it, you'd see it was of type . That's not very helpful. What's even less helpful is if I tried to use the following  to  over it:At runtime, this might throw a  because I haven't actually told you what type  is. It could be of type .With an  you can know right at compile time if you've failed to capture one of the types of that list. In the above, if I had defined  when I accessed the 3rd element, it's type would be  and this would be known at compile time.As @KevinWright states, there's more to it than that with Shapeless but  is one of the defining features of the library. Everything in Shapeless has two things in common:First, it isn't in the Scala standard library, but arguably should be. Therefore, asking what Shapeless is for is a bit like asking with the Scala standard library is for! It's . It's a grab bag.(but it isn't a totally arbitrary grab bag, because:)Second, everything in Shapeless provides increased checking and safety . Nothing in Shapeless (that I can think of?) actually \u201cdoes\u201d anything at runtime. All of the interesting action happens when your code is compiled. The goal is always increased confidence that if your code compiles at all, it won't crash or do the wrong thing at runtime. (Hence this notable quip: )There is a nice introduction to what type-level programming is all about, with links to further resources, at ."},
Scala

I've recently started learning scala, and I've come across the  (cons) function, which prepends to a list.\nIn the book \"Programming in Scala\" it states that there is no append function because appending to a list has performance o(n) whereas prepending has a performance of o(1)Something just strikes me as wrong about that statement.Isn't performance dependent on implementation?  Isn't it possible to simply implement the list with both forward and backward links and store the first and last element in the container?The second question I suppose is what I'm supposed to do when I have a list, say 1,2,3 and I want to add 4 to the end of it?The key is that  does not mutate , but instead creates a new list, which contains x followed by all elements of . This can be done in O(1) time because you only need to set  as the successor of  in the newly created, singly linked list. If doubly linked lists were used instead,  would also have to be set as the predecessor of 's head, which would modify . So if we want to be able to do  in O(1) without modifying the original list, we can only use singly linked lists.Regarding the second question: You can use  to concatenate a single-element list to the end of your list. This is an O(n) operation.Other answers have given good explanations for this phenomenon. If you are appending many items to a list in a subroutine, or if you are creating a list by appending elements, a functional idiom is to build up the list in reverse order, cons'ing the items on the  of the list, then reverse it at the end. This gives you O(n) performance instead of O(n\u00b2).Prepending is faster because it only requires two operations:Appending requires more operations because you have to traverse to the end of the list since you only have a pointer to the head.I've never programmed in Scala before, but you could try a In today's Scala, you can simply use  to append an item at the end of any sequential collection.  (There is also  to prepend. The mnemonic for many of Scala's 2.8+ collection operations is that the on goes next to the lection.)This will be O() with the default linked implementation of  or , but if you use  or , this will be effectively constant time.  Scala's  is probably Scala's most useful list-like collection\u2014unlike Java's  which is mostly useless these days.If you are working in Scala 2.8 or higher, the  is an absolute must read.Most functional languages prominently figure a singly-linked-list data structure, as it's a handy immutable collection type.  When you say \"list\" in a functional language, that's typically what you mean (a singly-linked list, usually immutable).  For such a type, append is O(n) whereas cons is O(1)."},
Scala

There is a relatively-new lightweight JVM called  that can produce executables for iOS targets.There isn't too much documentation on the website (and not much can be found searching with Google). I was wondering if anybody was aware of a step-by-step tutorial on how to get a basic Scala program running on iOS, using .Another alternative JVM to iOS compiler is . Although it is at an early stage, it looks quite promising, with examples on how to compile Scala for iOS. This was an old answer, valid at that time, but, as @JamesMoore points out, RoboVM is no more. What looks very promising now, and may well be the way to run Scala code in iOS in the near future is Compiled Scala sources are completely standard class files. You should be able to follow the  (look for \u201cEmbedding\u201d) on the website without large changes, just treat  as a dependency of your code.I managed to bootstrap the complete compiler and the standard library running on Avian a few days ago.Some parts might still be a bit rough around the edges, e. g. there is  which will be part of the next release of Scala (2.10.1) but is not in 2.10.0. If you want to play with it right now, you need to use a nightly build until 2.10.1 is released.If you encounter any additional issues, please report them!I may not need it anymore, now that !EDIT: Oracle updated the article to announce that they will not release a JVM, so it looks like JavaFX+Avian may be the way to go.Running Java byte code on iOS (not-rooted) is not only running that or those JVM. As far as I understand iOS memory management doesn't allow executable memory pages to be writable in user mode. That basically prohibits any JIT compilation.\nSo even if it's possible to run some compiled (either from Java or Scala) classes on specific Java VM I would carefully check how this VM supports Ahead-Of-Time compilation in order to be runnable on iOS.\nAs I have seen Avian AOT works well on a desktop. For iOS you will have to check it yourself, although the project looks promising in AOT area."},
Scala

I have an application where I would like to have mixed Java and Scala source (actually its migrating a java app to scala - but a bit at a time). I can make this work in IDEs just fine, very nice. But I am not sure how to do this with maven - scalac can compile java and scala intertwined, but how to I set up maven for the module? Also, does my scala source have to be a different folder to the java? Using the maven scala plugin, a config like the one below will work for a project that mixes java and scala source (scala source of course goes in the /scala directory, as mentioned by someone else). You can run run mvn compile, test etc... and it will all work as normal. Very nice (it will run scalac first automatically). For a great IDE, IntelliJ 8 works nicely: add in the scala plug in, then add a scala facet, and then adjust the compile setting for scala to run scalac first (critical if you have circular dependencies with scala and java source). Yeah, the scala part has to be in a separate module and in  directory. Maven regards mixed source like this as heresy. You enable scala compilation by importing the . The  page as a good example.I once asked a  about how to include non-Java code in a Maven project. The gist of the answer was to have under src a different directory for each programming language, and to find/write a Maven plugin that would know what to do with each. Eg:Look at Sonatype Maven Cookbook  I solved this some time ago by having one Maven module written in Scala and the other in Java. But since Scala and Java can cross depend on one another (Java -> Scala -> Java or the other way around), then this is something very desirable without multi module projects.There is work underway in solving this, you can read about it  and a new version of the maven-scala-plugin will be released soon.Here's a small project link() that I did using scala, java and mongo db. Note in the pom.xml of the project one can specify the source folder of scala files it can be same as that of java or a different folder like src/main/scala. There is no mandate for scala classes to be on a separate src folders. I have tried both of them and both of them work great. The snipped of the pom that I am referring to is You need to combine several approaches in order to mix scala and java classes freely. This solution worked for me:  "},
Scala

I'm using  with a  2.1 and I have some troubles.Given the following entity......I have to import a package for a  database driver, but I want to use  for  and  in . How should I proceed?I was able to workaround this by  the driver settings in my unit test:I don't like this solution and I'm wondering if there is an elegant way to write DB-agnostic code so there are two different database engines used - one in testing and another in production?I don't want to use evolution, either, and prefer to let Slick create the database tables for me:The first time I start the application, everything works fine... then, of course, the second time I start the application it crashes because the tables already exist in the PostgreSQL database.That said, my last two questions are:You find an example on how to use the cake pattern / dependency injection to decouple the Slick driver from the database access layer here: .A few days ago I wrote a Slick integration library for play, which moves the driver dependency to the application.conf of the Play project: .With the help of this library your example would be implemented as follows:Add snapshot repositoryOr local repository, if slick-integration is published locallyIn the case of slick-integration, it is assumed that you use primary keys of type Long which are auto incremented. The pk name is 'id'. The Table/Mapper implementation has default methods (delete, findAll, findById, insert, update). Your entities have to implement 'withId' which is needed by the 'insert' method.This is the Data Access Layer (DAL) which is used by the controllers to access the database. Transactions are handled by the Table/Mapper implementation within the corresponding Component.I cannot give you a sufficient answer to this question...... but perhaps this is not really s.th you want to do. What if you add an attribute to an table, say ? If you want to safe the data currently stored within your tables, then an alter script would do the job. Currently, such an alter script has to be written by hand. The  could be used to retrieve the create statements. They should be sorted to be better comparable with previous versions. Then a diff (with previous version) is used to manually create the alter script. Here, evolutions are used to alter the db schema.Here's an example on how to generate (the first) evolution:I was also trying to address this problem: the ability to switch databases between test and production. The idea of wrapping each table object in a trait was unappealing. I am not trying to discuss the pros and cons of the cake pattern here, but I found another solution, for those who are interested.Basically, make an object like this:Obviously, you can do any decision logic you like here. It does not have to be based on system properties.Now, instead of:You can sayUPDATE: A Slick 3.0 Version, courtesy of trent-ahrens:The  does exactly the same as what is proposed in the other answers, and it seems to be under the umbrella of Play/Typesafe.You just can import \nand it will choose the appropriate driver according to .It also offers some more things like connection pooling, DDL generation...If, like me, you're not using Play! for the project, a solution is provided by Nishruu  "},
Scala

Does anyone know how to show a custom failure message in ScalaTest?For example:Shows the following message when it fails:But i want more descriptive message like:You're the first to ask for such a feature. One way to achieve this is with withClue. Something like:That should get you this error message:NumberOfElements: 10 was not equal to 5If you want to control the message completely you can write a custom matcher. Or you could use an assertion, like this:Can you elaborate on what your use case is? Why is it that 10 did not equal 5 is not up to snuff, and how often have you had this need? Here's the kind of thing you're requesting:So this way you can write:"},
Scala

As prompted by a comment on my For example:Looking in the scaladoc, all of these use the  operation inherited from , so how come it's always able to return the most specific valid collection? Even , which provides  via an implicit conversion.Scala collections are clever things...Internals of the collection library is one of the more advanced topics in the land of Scala. It involves higher-kinded types, inference, variance, implicits, and the  mechanism - all to make it incredibly generic, easy to use, and powerful from a user-facing perspective. Understanding it from the point-of-view of an API designer is not a light-hearted task to be taken on by a beginner.On the other hand, it's incredibly rare that you'll ever actually need to work with collections at this depth.So let us begin...With the release of Scala 2.8, the collection library was completely rewritten to remove duplication, a great many methods were moved to just one place so that ongoing maintenance and the addition of new collection methods would be far easier, but it also makes the hierarchy harder to understand.Take  for example, this inherits from (in turn)That's quite a handful! So why this deep hierarchy? Ignoring the  traits briefly, each tier in that hierarchy adds a little bit of functionality, or provides a more optimised version of inherited functionality (for example, fetching an element by index on a  requires a combination of  and  operations, grossly inefficient on an indexed sequence).  Where possible, all functionality is pushed as far up the hierarchy as it can possibly go, maximising the number of subclasses that can use it and removing duplication. is just one such example.  The method is implemented in  (Though the  traits only really exist for library designers, so it's generally considered to be a method on  for most intents and purposes - I'll come to that part shortly), and is widely inherited.  It's possible to define an optimised version in some subclass, but it must still conform to the same signature.  Consider the following uses of  (as also mentioned in the question):In each case, the output is of the same type as the input wherever possible.  When it's not possible, superclasses of the input type are checked until one is found that  offer a valid return type. Getting this right took a lot of work, especially when you consider that  isn't even a collection, it's just implicitly convertible to one.So how is it done?One half of the puzzle is the  traits (I  say I'd get to them...), whose main function is to take a  type param (short for \"Representation\") so that they'll know the true subclass actually being operated on.  So e.g.  is the same as , but abstracted over the  type param.  This param is then used by the second half of the puzzle; the  type class that captures source collection type, target element type and target collection type to be used by collection-transforming operations.It's easier to explain with an example!BitSet defines an implicit instance of  like this:When compiling , the compiler will attempt an implicit lookup of This is the clever part... There's only one implicit in scope that matches the first two type parameters. The first parameter is , as captured by the  trait, and the second is the element type, as captured by the current collection trait (e.g. ). The  operation is then also parameterised with a type, this type  is inferred based on the third type parameter to the  instance that was implicitly located.  in this case.So the first two type parameters to  are inputs, to be used for implicit lookup, and the third parameter is an output, to be used for inference. in  therefore matches the two types  and , so the lookup will succeed, and inferred return type will also be .When compiling , the compiler will attempt an implicit lookup of .  This will fail for the implicit in BitSet, so the compiler will next try its superclass -  - This contains the implicit:Which matches, because Coll is a type alias that's initialised to be  when  derives from . The  will match anything, as  is parameterised with the type , in this case it's inferred to be ... Thus yielding a return type of .So to correctly implement a collection type, you not only need to provide a correct implicit of type , but you also need to ensure that the concrete type of that of that collection is supplied as the  param to the correct parent traits (for example, this would be  in the case of subclassing ). is a little more complicated as it provides  by an implicit conversion. The implicit conversion is to , which subclasses , which ultimately derives  -  being the  type param.There's also a  in scope so that the compiler knows that when mapping the elements of a  to s, then the return type should also be a string. From this point onwards, the same mechanism is used.The  online pages have a detailed explanation geared towards the practical aspects of creating new collections based on the 2.8 collection design.Quote:It uses as example a collection for encoding RNA sequences and one for Patricia trie. Look for the  section for the explanation of what to do to return the appropriate collection type."},
Scala

What are all the instances of syntactic sugar in Scala?They are hard to search for since most/all of them are purely symbols and are thus hard to search for without knowing the name of the concept.TODO:  In addition to Jaxkson's answer:For example:For exampleAs mentioned by , tuples and symbols get a slightly special syntax.For example, the following two are equivalent.There are two methods used for extractors,  and . These are used in multiple variable assignments and pattern matching.Honestly, I don't really get the purpose of the above syntax since it can be done almost just as easily by just putting the code in the  statements. Of course if you have a better example, leave a comment below  do all those / definitions for you (as well as other stuff) so use them whenver possible to save time and reduce code.As a quick example,Context bounds desugar into  parameters, e.g. consider a function that leverages the  type class:where the  part is a context bound, gets translated to:therefore the following compiles, too:Anonymous functions: is short for "},
Scala

How can I convert immutable.Map to mutable.Map in Scala so I can update the values in Map?The cleanest way would be to use the  varargs factory.  Unlike the  approach, this uses the  mechanism, and so has the potential to be more efficient if library code was written to take advantage of this:This works because a  can also be viewed as a sequence of Pairs.How about using collection.breakOut?There is a variant to create an empty mutable  that has default values taken from the immutable . You may store a value and override the default at any time: (see the comment by Rex Kerr): You will not be able to remove the elements coming from the immutable map:"},
Scala

I am getting introduced to Functional Programming [FP] (using Scala). One thing that is coming out from my initial learnings is that FPs rely heavily on recursion. And also it seems like, in  FPs the only way to do iterative stuff is by writing recursive functions.And because of the heavy usage of recursion seems the next thing that FPs had to worry about were  typically due to long winding recursive calls. This was tackled by introducing some optimizations (tail recursion related optimizations in maintenance of stackframes and  annotation from Scala v2.8 onwards) Can someone please enlighten me why recursion is so important to functional programming paradigm? Is there something in the specifications of functional programming languages which gets \"violated\" if we do stuff iteratively? If yes, then I am keen to know that as well.PS: Note that I am newbie to functional programming so feel free to point me to existing resources if they explain/answer my question. Also I do understand that Scala in particular provides support for doing iterative stuff as well. highlights the equivalence between different computability models. Using recursion we don't need a  while solving  problem, and this make possible to specify a semantic in simpler terms. Thus solutions can be simpler, in a formal sense.I think that Prolog shows better than functional languages the effectiveness of recursion (it doesn't have iteration), and the practical limits we encounter when using it.Pure functional programming means programming without side effects. Which means, if you write a loop for instance, the body of your loop can't produce side effects. Thus, if you want your loop to do something, it has to reuse the result of the previous iteration and produce something for the next iteration. Thus, the body of your loop is a function, taking as parameter the result of previous execution and calling itself for the next iteration with its own result. This does not have a huge advantage over directly writing a recursive function for the loop.A program which doesn't do something trivial will have to iterate over something at some point. For functional programming this means the program has to use recursive functions.The feature that brings about the  that you do things recursively is immutable variables.Consider a simple function for calculating the sum of a list (in pseudocode):Now, the  in each iteration of the list is different, but we can rewrite this to use a  function with a lambda argument to get rid of this problem:Still, the value of the  variable has to be altered in each run of the lambda. This is illegal in a language with immutable variables, so you have to rewrite it in a way that doesn't mutate state:Now, this implementation will require pushing to and popping from the call stack a lot, and a program where all small operations would do this would not run very quickly. Therefore, we rewrite it to be tail recursive, so the compiler can do tail call optimization:Of course, if you want to loop indefinitely, you absolutely need a tail recursive call, or else it would stack overflow.The  annotation in Scala is a tool to help you analyse which functions are tail recursive. You claim \"This function is tail recursive\" and then the compiler can tell you if you are mistaken. This is especially important in Scala as compared to other functional languages because the machine it runs on, the JVM, does not support tail call optimization well, so it is not possible to get tail call optimization in Scala in all the same circumstances you would get it in other functional languages.: recursion is used to handle inductively defined data, which are Recursion is natural, when you operate on higher levels of abstraction. Functional programming is not just about coding with functions; it is about operating on higher levels of abstraction, where you naturally use functions. Using functions, it is only natural to reuse the same function (to call it again), from whatever context where it makes sense. The world is built by repetition of similar/same building blocks. If you cut a piece of fabric in two, you have two pieces of fabric. Mathematical induction is at the heart of maths. We, humans, count (as in, ). Any  (like, , and ) is natural to handle/analyze by a recursive function, according to same cases by which that thing is defined/constructed.Recursion is everywhere. Any iterative loop is a recursion in disguise anyway, because when you reenter that loop, you reenter  loop again (just with maybe different loop variables). So it's not like  new concepts about computing, it's more like  the foundations, and making it .So, recursion is natural. We just write down some laws about our problem, some equations  involving the function we're defining which preserve some invariant (under the assumption that the function is coherently defined), re-specifying the problem in simplified terms, and voila! We have the solution.An example, a function to calculate the length of list (an inductively defined recursive data type). Assume it is defined, and returns the list's length, non-surprisingly. What are the laws it must obey? What invariant is preserved under what simplification of a problem?The most immediate is taking the list apart to its head element, and the rest - a.k.a. the list's tail (according to how a list is defined/constructed). The law is,D'uh! But what about the empty list? It must be thatSo how do we write such a function?... Wait... We've written it already! (In Haskell, if you were wondering, where function application is expressed by juxtaposition, parentheses are used just for grouping, and  is a list with  its first element, and  the rest of them).All we need of a language to allow for such style of programming is that it has  (and perhaps, a bit luxuriously,  ), so there's no stack blow-up, and we're set.Another thing is purity - immutability of code variables and/or data structure (records' fields etc). What that does, besides freeing our minds from having to track what is changing when, is it makes time explicitly apparent in our code, instead of hiding in our \"changing\" mutable variables/data. We can only \"change\" in the imperative code the value of a variable  - we can't very well change its value in the past, can we?And so we end up with lists of recorded change history, with change explicitly apparent in the code: instead of  we write . It makes reasoning about code so much easier.To address immutability in the context of tail recursion with , consider this tail recursive re-write of the above function  under accumulator argument paradigm:Here TCO means call frame reuse, in addition to the direct jump, and so the call chain for  can be seen as actually mutating the call stack frame's entries corresponding to the function's parameters:In a pure language, without any value-mutating primitives, the only way to express change is to pass updated values as arguments to , to be processed further. If the further processing is the same as before, than naturally we have to invoke the same function for that, passing the updated values to it as arguments. And that's recursion.And the following makes the whole history of calculating the length of an argument list  (and available for reuse, if need be):In Haskell this is variably known as guarded recursion, or corecursion (at least I think it is). There is nothing 'special' in recursion. It is widespread tool in programming and mathematics and nothing more. However, functional languages are usually minimalistic. They do introduce many fancy concepts like pattern matching, type system, list comprehension and so on, but it is nothing more then syntactic sugar for very general and very powerful, but simple and primitive tools. This tools are: function abstraction and function application. This is conscious choice, as simplicity of the language core makes reasoning about it much easier. It also makes writing compilers easier. The only way to describe a loop in terms of this tools is to use recursion, so imperative programmers may think, that functional programming is about recursion. It is not, it is simply required to imitate that fancy loops for poor ones that cannot drop this syntactic sugar over  statement and so it is one of the first things they stuck into. Another point where (may be indirect) recursion required is processing of recursively defined data structures. Most common example is  ADT. In FP it is usually defined like this  . Since definition of the ADT here is recursive, the processing function for it should be recursive too. Again, recursion here is not anyway special: processing of such ADT in recursive manner looks naturally in both imperative and functional languages. Well, In case of list-like ADT imperative loops still can be adopted, but in case of different tree-like structures they can't.So there is no anything special in recursion. It is simply another type of function application. However, because of limitations of modern computing systems (that comes from poorly made design decisions in C language, which is de-facto standard cross-platform assembler) function calls cannot be nested infinitely even if they are tail calls. Because of it, designers of functional programming languages have to either limit allowed tail-calls to tail recursion (scala) or use complicated techniques like trampoling (old ghc codegen) or compile directly to asm (modern ghc codegen).TL;DR: There is no anything special in recursion in FP, no more than in IP at least, however, tail recursion is the only type of tail calls allowed in scala because of limitations of JVM.Avoiding side effects is one of the pillars of functional programming (the other is using higher order functions).Imagine how you might make use of imperative flow control  relying on mutation. Is it possible?Of course  depends on mutation (). In fact, any conditional loop construct does. In  the  will depend on some mutable state. Sure,  doesn't use mutation. But if you ever want out of that loop you'll need an . Really, try to think of a (non-infinite) looping mechanism other than recursion that doesn't rely on mutation.What about ? Now we're getting closer to functional programming. The  can be thought of as a  to the body of the loop. Reusing the name isn't the same as reassigning a value. Perhaps in the body of the loop you're ing values as an expression in terms of  (no mutation).Exactly equivalently, you could move the body of the  loop into the body of a function  and then map that over  using a higher order function - replacing your loop construct with something like .But then how is the library function  implemented without mutation? Well, using recursion of course! It's done for you. It becomes less common to have to implement recursive functions yourself once you begin making use of the second pilar of higher order functions to replace your looping constructs.Additionally, with tail call optimization a recursive definition is equivalent to an iterative process. You might also enjoy this blog post: There are two properties that I consider essential to functional programming:Now if you program in an imperative style you have to use assignment.Consider a for loop. It has an index and on each iteration the index has a different value. So you could define a function that returns this index. If you call that function twice you might  get different results. Thus breaking the principle no 2.If you break principle no 2. passing around functions (principle no 1) becomes something extremely dangerous, because now the result of the function might depend on when and how often a function gets called.Last time I used a Functional language (Clojure) I was never even tempted to use recursion.  Everything could be dealt with as a set of things, to which a function was applied to get part products, to which another function was applied, until the final result was reached.Recursion is only one way, and not necessarily the clearest way, to handle the multiple items you usually have to handle to deal with any gFor the sake of new FP learners I would like to add my 2 cents.As mentioned in some of the answers, recursion is their to make use of immutable variables but why we need to do that ? its because it makes it easy to run the program on multiple cores in parallel, but why we want that ? Can't we run it in single core and be happy as always we have been ? No because content to process is increasing day by day and CPU Clock cycle can't be increased so significantly than adding more cores. From past one decade the clock speed has been around upto 2.7 ghz to 3.0 ghz for consumer computers and chip designers are having issues in fitting more and more transistors in their.Also FP has been their from very long time, but didn't pick up as it used recursion and memory was very expensive in those days but as clock speeds were soaring year after year so community decided to keep on going with OOP\nEdit: it was quite fast, I had only couple of minutes"},
Scala

I'm attempting to print the contents of a collection to the Spark console.I have a type:And I use the command:But this is printed : How can I write the RDD to console or save it to disk so I can view its contents?If you want to view the content of a RDD, one way is to use :That's not a good idea, though, when the RDD has billions of lines. Use  to take just a few to print out:The  function is a , which means that Spark will not actually evaluate your RDD until you run an  on it. To print it, you can use  (which is an action):To write it to disk you can use one of the  functions (still actions) from the If you're running this on a cluster then  won't print back to your context. You need to bring the  data to your session. To do this you can force it to local array and then print it out:You can convert your  to a  then  it.This will show the top 20 lines of your data, so the size of your data should not be an issue.In python This will printout all the contents of the RDDYou can also save as a file: There are probably many architectural differences between  and  (not only 'collect', but also other actions). One the differences I saw is when doing , the output will be in a random order. For ex: if my rdd is coming from a text file where each line has a number, the output will have a different order. But when I did , order remains just like the text file.Instead of typing each time, you can; [1] Create a generic print method inside Spark Shell.[2] Or even better, using implicits, you can add the function to RDD class to print its contents.Example usage:Output:PS. These only makes sense if you are working in local mode and with a small amount of data set. Otherwise, you either will not be able to see the results on the client or run out of memory because of the big dataset result."},
Scala

I was thinking about a nice way to convert a List of tuple with duplicate key  into map . Normally (in python), I'd create an empty map and for-loop over the list and check for duplicate key. But I am looking for something more scala-ish and clever solution here.btw, actual type of key-value I use here is  and I want to turn into a map of Group and then project:More scalish way to use fold, in the way like  (skip  step).For Googlers that don't expect duplicates or are fine with the :As of 2.12, the default policy reads:Here's another alternative:For Googlers that do care about duplicates:Here is a more Scala idiomatic way to convert a list of tuples to a map handling duplicate keys. You want to use a fold.You can try this"},
Scala

How in Scala to find unique items in List?The most efficient order-preserving way of doing this would be to use a  as an ancillary data structure:We can wrap this in some nicer syntax using an implicit conversion:In 2.8, it's:Roll your own uniq filter with order retention:If you refer to the Since  is immutable, you wont modify the initial  by calling Warning: as mentioned by (!), this does not preserve the order:For a , that method should be available in Scala2.8, according to .\nIn the meantime, you will need to define an ad-hoc static method as the  Imho, all the interpretations of the question are false:Given this list:the only unique item in the list is . The other items aren't unique. will find it.A simple ad-hoc method is just to add the List to a Set, and use from there:Produces:This works for a Seq (or any Iterable), but is not necessary in 2.8, where the removeDuplicates method will probably be more readable.  Also, not sure about the runtime performance vs a more thought-out conversion.Also, note the lost ordering.list.toSet will do it since Set by definition only contains unique elements"},
Scala

What are the most commonly held misconceptions about the Scala language, and what counter-examples exist to these?UPDATEI was thinking more about various claims I've seen, such as \"Scala is dynamically typed\" and \"Scala is a scripting language\".I accept that \"Scala is [Simple/Complex]\" might be considered a myth, but it's also a viewpoint that's very dependent on context.  My personal belief is that it's the  that can make Scala appear either simple or complex depending oh who's using them.  Ultimately, the language just offers abstractions, and it's the way that these are used that shapes perceptions.Not only that, but it has a certain tendency to inflame arguments, and I've not yet seen anyone change a strongly-held viewpoint on the topic...Myth: Scala supports operator overloading.Actually, Scala just has very flexible method naming rules and infix syntax for method invocation, with special rules for determining method precedence when the infix syntax is used with 'operators'. This subtle distinction has critical implications for the utility and potential for abuse of this language feature compared to true operator overloading (a la C++), as explained more thoroughly in James Iry's answer to .Myth: That . :-)Debunked:  by James Iry.I disagree with the argument that Scala is hard because you can use very advanced features to do hard stuff with it. The scalability of Scala means that you can write DSL abstractions and high-level APIs in Scala itself that otherwise would need a language extension. So to be fair you need to compare Scala libraries to other languages compilers. People don't say that C# is hard because (I assume, don't have first hand knowledge on this) the C# compiler is pretty impenetrable. For Scala it's all out in the open. But we need to get to a point where we make clear that most people don't need to write code on this level, nor should they do it.I think a common misconception amongst many scala developers, those at EPFL (and yourself, Kevin) is that . The argument usually goes something like this:My personal opinion is that . Scala's type system taken together with implicits allows one to write . Any suggestion otherwise is just preposterous, regardless of what the above \"metrics\" might lead you to think. ().The obvious arguments against this are (of course):Of these, it seems to me that only #2 is valid. Whether or not you write code quite as complex as , I think it's just silly to use the language (and continue to use it) with no real understanding of the type system. How else can one get the best out of the language?Myth: methods and functions are the same thing.In fact, a function is a value (an instance of one of the  classes), while a method is not.  . The most important practical distinctions are:There is a myth that Scala is difficult because Scala is a complex language.This is false--by a variety of metrics, Scala is no more complex than Java.  (Size of grammar, lines of code or number of classes or number of methods in the standard API, etc..)But it is undeniably the case that Scala code can be ferociously difficult to understand.  How can this be, if Scala is not a complex language?The answer is that Scala is a  language.  Unlike Java, which has many special constructs (like enums) that accomplish one particular thing--and requires you to learn specialized syntax that applies just to that one thing, Scala has a variety of very general constructs.  By mixing and matching these constructs, one can express very complex ideas with very little code.  And, unsurprisingly, if someone comes along who has not had the same complex idea and tries to figure out what you're doing with this very compact code, they may find it daunting--more daunting, even, than if they saw a couple of pages of code to do the same thing, since then at least they'd realize how much conceptual stuff there was to understand!There is also an issue of whether things are more complex than they really need to be.  For example, some of the type gymnastics present in the collections library make the collections a joy to use but perplexing to implement or extend.  The  here are not particularly complicated (e.g. subclasses should return their own types), but the  required (higher-kinded types, implicit builders, etc.) are complex.  (So complex, in fact, that Java just gives up and doesn't try, rather than doing it \"properly\" as in Scala.  Also, in principle, there is hope that this will improve in the future, since the method can evolve to more closely match the goal.)  In other cases, the  are complex;  is a bit of a mess, but if you really want to take all numbers less than 5, and then take every 2nd number out of 10 in the remaining list, well, that's just a somewhat complicated idea, and the code pretty much says what it does if you know the basic collections operations.Summary: Scala is not complex, but it allows you to compactly express complex ideas.  Compact expression of complex ideas can be daunting.There is a myth that Scala is non-deployable, whereas a wide range of third-party Java libraries can be deployed without a second thought.To the extent that this myth exists, I suspect it exists among people who are not accustomed to separating a virtual machine and API from a language and compiler.  If java == javac == Java API in your mind, you might get a little nervous if someone suggests using scalac instead of javac, because you see how nicely your JVM runs.Scala ends up as JVM bytecode, plus its own custom library.  There's no reason to be any more worried about deploying Scala on a small scale or as part of some other large project as there is in deploying any other library that may or may not stay compatible with whichever JVM you prefer.  Granted, the Scala development team is not backed by quite as much force as the Google collections, or Apache Commons, but its got at least as much weight behind it as things like the Java Advanced Imaging project.Some common misconceptions related to Actors library:Myth:andis the same.It is not; you can call , but  tries to call the apply method of StringLike with no arguments (results in an error).Myth: You can replace a fold with a reduce when computing something like a sum from zero.This is a common mistake/misconception among new users of Scala, particularly those without prior functional programming experience.  The following expressions are  equivalent:The two expressions differ in how they handle the empty sequence: the fold produces a valid result (0), while the reduce throws an exception.Myth: .Debunked  by Martin Odersky himself. (Also see this paper -  - by Odersky et al.)Myth:  refers to the same type represented by .As an example of this misconception, one might assume that in the following code the type of  is :In reality,  refers to the type whose only instance is . In general,  is the singleton type whose only instance is . So in the example above, the type of  is .  The following session demonstrates the principle:Scala has type inference and refinement types (structural types), whereas Java does not.The myth is  by James Iry.Myth: that Scala is highly scalable, without qualifying what forms of scalability.Scala may indeed be highly scalable in terms of the ability to express higher-level denotational semantics, and this makes it a very good language for experimentation and even for scaling production at the project-level scale of  compositionality.However, every referentially opaque language (i.e. allows mutable data structures), is imperative (and not declarative) and will not scale to WAN  compositionality and security. In other words, imperative languages are compositional (and security) spaghetti w.r.t. uncoordinated development of modules. I realize such uncoordinated development is perhaps currently considered by most to be a \"pipe dream\" and thus perhaps not a high priority. And this is not to disparage the benefit to compositionality (i.e. eliminating corner cases) that higher-level semantic unification can provide, e.g. .There will possibly be significant cognitive dissonance for many readers, and they are likely to prematurely press the \"down\" vote, before fully understanding the issue I raise, especially since there are popular misconceptions about imperative vs. declarative (i.e. mutable vs. immutable), (and ,) e.g. the monadic semantic is never inherently imperative . Yes in Haskell the IO monad is imperative, but it being imperative has nothing to with it being a monad.I explained this in more detail in the \"Copute Tutorial\" and \"Purity\" sections, which is either at the home page or temporarily at .My point is I am very grateful Scala exists, but I want to clarify what Scala scales and what is does not. I need Scala for what it does well, i.e. for me it is the ideal platform to prototype a new declarative language, but Scala itself is not exclusively declarative and afaik referential transparency can't be enforced by the Scala compiler, other than remembering to use  everywhere.I think my point applies to the complexity debate about Scala. I have found (so far and mostly conceptually, since so far limited in actual experience with my new language) that removing mutability and loops, while retaining  subtyping (which Haskell doesn't have), radically simplifies the language. For example, the  fiction disappears, and afaics, a slew of other issues and constructs become unnecessary, e.g. non-category theory standard library, for comprehensions, etc.."},
Scala

I've got an sbt (Scala) project that currently pulls artifacts from the web. We'd like to move towards a corporate-standardized Nexus repository that would cache artifacts. From the Nexus documentation, I understand how to do that for Maven projects. But sbt obviously uses a different approach. (I understand Ivy is involved somehow, but I've never used it and don't understand how it works.)How do I tell sbt and/or the underlying Ivy to use the corporate Nexus repository system for all dependencies? I'd like the answer to use some sort of project-level configuration file, so that new clones of our source repository will automatically use the proxy. (I.e., mucking about with per-user config files in a dot-directory is not viable.) Thanks!Step 1: Follow the instructions  at , which I have summarised and added to below:: Even though, in the sbt 0.12.0 launcher jar at least, the boot properties files for older sbt versions don't contain the required line (the one that mentions ), it will still work for those versions of sbt if you edit those files to add the required line, and repackage them into the sbt 0.12.0 launcher jar! This is because the feature is implemented in the launcher, not in sbt itself. And the sbt 0.12.0 launcher is claimed to be able to launch all versions of sbt, right back to 0.7!Step 2: To make sure external repositories are not being used, remove the default repositories from your resolvers. This can be done in one of two ways:OK, with some help from Mark Harrah on the sbt mailing list, I have an answer that works.My build class now looks like the following (plus some other repos):Now, if I delete the Squeryl tree from my machine's  directory, sbt tries to grab it from the Nexus tree with the appropriate URL. Problem solved!All you need is to define a property file  which will allow you to:Note: this  file is inspired from:I have commented any  Maven repository definition, and added a reference to my own Nexus Maven repo.Define a sbt.bat wrapper (in order to be sure to specify   ) like:And your sbt will download artifacts  from:Just tested at home with an old Nexus opensource 1.6 I had running, java 1.6, sbt07.4That gives:If I try a funny value in the sbt.boot.properties file:So it does limit itself to the two repo I defined:(I commented everything else: , , ...)If I comment  repositories and put a funny value (2.7.9) for the scala version in the , I do get (like the OP did)If I put 2.7.7 (while still having  repo commented), yes, it won't generate an error:\nIf I remove that library from my  directory, then it will throw an Exception:Well this has bugged me for a while so I found a guy that has written an SBT plugin for maven out on github called  so all you have to do is include it in your plugins project and make your project mixin with  maven.MavenDependencies and all your operations like update and publish-local work with your local maven. The nice thing about that is if you are like me, your org is all maven.  So, all you libs are in you local maven repo but if for some reason you build with sbt first, then you start getting a bunch or jars in ivy too.  What a waste of space, and time since you will still need to get them for your maven builds.That said, I wish this were built into sbt so I would not need to add it to every project.  Maybe as a processor at least.  He mentioned in one thing I read that he would like to add it to 0.9 but I have not been able to find it.edit the config file in sbt_home/conf \"sbtconfig.txt\"add two line the repo.properties content is"},
Scala

I'm still at the beginning in learning scala in addition to java and i didn't get it how is one supposed to do DI there? can or should i use an existing DI library, should it be done manually or is there another way?Standard Java DI frameworks will usually work with Scala, but you can also use language constructs to  without external dependencies.A new dependency injection library specifically for Scala is Dick Wall's .Whereas the Jonas Bon\u00e9r article referenced in Dan Story's answer emphasizes compile-time bound instances and static injection (via mix-ins), SubCut is based on runtime initialization of immutable modules, and dynamic injection by querying the bound modules by type, string names, or scala.Symbol names.You can read more about the comparison with the Cake pattern in the  document.Dependency Injection itself can be done without any tool, framework or container support. You only need to remove s from your code and move them to constructors. The one tedious part that remains is wiring the objects at \"the end of the world\", where containers help a lot.Though with Scala's 2.10 macros, you can generate the wiring code at compile-time and have auto-wiring and type-safety.See the I haven't done so myself, but most DI frameworks work at the bytecode level (AFAIK), so it should be possible to use them with any JVM language.A recent project illustrates a DI based purely on constructor injection: In addition to the answer of Dan Story, I blogged about a DI variant that also uses language constructs only but is not mentioned in Jonas's post: .\nThis pattern is working very well for me.I have shown how I created a very simple functional DI container in scala using 2.10 Previous posts covered the techniques. I wanted to add a link to Martin Odersky's May 2014 talk on the Scala language objectives. He identifies languages that \"require\" a DI container to inject dependencies as poorly implemented. I agree with this personally, but it is only an opinion. It does seem to indicate that including a DI dependency in your Scala project is non-idiomatic, but again this is opinion. Practically speaking, even with a language designed to inject dependencies natively, there is a certain amount of consistency gained by using a container. It is worth considering both points of view for your purposes."},
Scala

Scala has symbols - names that start with a single quote ' and which are a kind of string constants.I know symbols from Ruby (where they start with a colon). In Ruby they are used for some meta-programming tasks, like generating getters and setters for member variables (for example  to generate a getter for ).I haven't seen a lot of use of symbols in Scala code yet. What are practical uses for symbols in Scala?Do symbols really fit into Scala?In the wonderful land of Lisp, code is represented as nested lists of literal objects that denote themselves (strings, numbers, and so on), and symbols, which are used as identifiers for things like classes, functions, and variables.  As Lisp code has a very simple structure, Lisp allows the programmer to manipulate it (both at compile-time and run-time).  Clearly, when doing this, the programmer will inevitably encounter symbols as data objects.So symbols are (and need to be) objects in Lisp in any case, so why not use them as hash table keys or as enums as well?  It's the natural way of doing things, and it keeps the language simple, as you don't have to define a special enumeration type.To summarise, symbols are naturally used for code manipulation, enumeration, and keying.  But Java people don't use identity as the equivalence relation between hash keys by default (which your traditional Lisp does), so they can just use strings as their keys.  Enum types are defined separately in Scala.  And finally, code as data isn't supported by the language at all.So no, my impression is that symbols don't belong in the Scala language.  That said, I'm going to keep an eye on the replies to this question.  They might still demonstrate a genuine use of symbols in Scala that I can't think of right now.( Depending on the Lisp dialect, Lisp symbols may also be namespace-qualified, which is, of course, an immensely useful feature when manipulating code, and a feature that strings don't have.)Searching a bit around the web it seems that the sense of symbols (symbol literals) in (a language like) Scala in comparision with Strings is a matter of semantics, and thus possibly even compiler awareness.'String' is a datatype, consisting of a sequence of characters. You can operate on strings and so manipulate them. Strings can semantically be any text data, from a filename to a message to be printed on screen, a line in a CSV file, or whatever.For the compiler -and thus the IDE- strings are values of a data type String, like numbers (sequences of digits) are values of a data type say: Integer .\nThere is on the program level no difference between \"foo\" and \"bar\".OTOH Symbols are identifiers, i.e. semantically identifying an item in the program.\nIn this matter they are like class names, method names or attribute names. \nBut while a class name identifies the class -i.e. the set of properties declaring the class' structure and behaviour- and a method name identifies the method -i.e. the parameters and statements- , a symbol name identifies the symbol -i.e. itsself, nothing more- .So the compiler can explicitly distinguish between the symbols 'foo and 'bar, like he distinguishes between the classes  Foo and Bar. As part of the compiler's symbol table, you can apply the same mechanisms in an IDE e.g. to search for the usage of 'foo (i.e. the references to this symbol) like you search for the usage of class Foo.In comparision, searching for a string \"foo\" would require different approaches, like a full text scan. It follows the same semantics as searching for all occurrences of 4711 in the program code.That's how I understand it, someone may correct me if I'm wrong.According to the Scala book, Symbols are interned: \"\"In contrast, s are only interned if they appear in literal form (at least in Java they are, not entirely sure about Scala). So I guess if you do a lot of serialization of s that are then put into collections, you might use symbols instead and save yourself some memory.But I agree with skaffman, I'm not totally convinced of their use.(In Ruby, s are, apart from the meta-programming example you give, often used as keys in es. In Ruby this is useful because there, s are never interned: every  allocates new memory. In Scala it might be useful, as I mentioned, if you combine it with a lot of (de)serialization so the Java s don't get interned as well.)I guess Scala added them because functional languages use them.They forgot, though, to add the ability of referencing an identifier through a symbol, which is kind of the central point of their existence. There's an experimental feature in Scala 2.8 that gives some of that. I'll quote the relevant part of the API documentation in full:A more convenient syntax for reflective invocation.\nExample usage: You can call it reflectively one of two ways: If you call the  method and do not give the type inferencer enough help, it will most likely infer , which will result in a . Author\nPaul PhillipsI believe comparisons between symbols is faster. If you've used Erlang, symbols are used a tonne when passing around messages and you want something cheap, and fast, that works well ACROSS machine boundaries. I'm not sure in what state remote actors are in Scala, IIRC, they were rather dodgy, but in the future when them in place, symbols could well be very useful in much the same way as they are in Erlang. Also case classes, some of the benefits aren't as apparent, then again, symbols are still cheaper.I suppose you would use them when you want to refer to the name of a thing that isn't an existing identifier in the code. The Scala book gives the example of referring to the name of a database column - it isn't an arbitrary string, it's actually the name of a thing.It's a bit tenuous, though, I'm not altogether convinced.I can name one case when symbols are really used in Scala.\nPlay 2.2 uses  to access database.\nHere goes a code sample for the simple add entity method:so you can see the usage of symbols in the .on(bla bla bla)\nIt is also absolutely valid to use String literals instead of symbols and some guys are doing so, but in the anorm source code the corresponding method signature really use Symbol paremeter type.As already noted, symbols carry-over from other (more) functional languages. Something others have not mentioned is that not only do they fill the role of symbols, but they are also the closest equivalent of keywords (minus the performance advantage maybe). In my opinion, they are more useful as keywords, meaning explicit identifiers.Below I will include a court description from  of keywords and symbols.Scala symbols are not as powerful as symbols in some languages. Therefore, they are not as useful either. However, I don't see why they couldn't offer the same meta-programming and performance advantages as keywords. At the very least, they can make your code easier to read."},
Scala

I want to be able to declare something like this:That it, the type  should be both a subtype of   . Is this possible?Use Compound Type:"},
Scala

How to explain Scala's type system to a Haskell expert?\nWhat examples show Scala's advantages?How to explain Haskell's type system to an advanced Scala practitioner?\nWhat can be done in Haskell that can't be done in Scala?Scala is a strict and impure language with first-class modules. New types are declared as modules (\"classes\"/\"traits\" with subtle differences). Modules can be type constructors taking universally quantified type parameters. Modules have members which consist of values, mutable variables, and functions (called \"methods\", to which the module is implicitly passed as a variable called ). Modules may have type members which can also take parameters. Type members are existentially quantified and type parameters can be higher-kinded. Because types can be members of first-class values, Scala provides a flavour of dependent typing called .First-class functions are also modules. A function is a module with a method named . A method is not first-class, but a syntax is provided to wrap a method in a first-class function. Unfortunately, a module requires all of its type parameters up front, hence a partially applied first-class function is not allowed to be universally quantified. More generally, Scala completely lacks a direct mechanism for types of rank higher than 1, but modules parameterized on higher-kinded types can be exploited to simulate rank-n types.Instead of type classes with global scope, Scala lets you declare an implicit value of any given type. This includes function types, which provides implicit conversion, and therefore type extension. In addition to implicit conversions, type extension is provided by the \"extends\" mechanism which lets you declare a subtype/supertype relation among modules. This mechanism can be used to simulate algebraic datatypes where the supertype can be seen as the type on the left-hand side of a data declaration, and its subtypes as the value constructors on the right-hand side. This also means that ADTs are not really closed. Scala has extensive pattern-matching capabilities using a virtualized pattern matcher with first-class patterns.Scala supports subtyping, and this limits type inference considerably. But type inference has improved over time. Inference of higher kinded types is supported. However, Scala lacks any meaningful kind system, and therefore has no kind inference and no kind unification. If a type variable is introduced, it is of kind  unless annotated otherwise. Certain types like  (the supertype of all types) and  (a subtype of every type) are technically of  although they cannot be applied to type arguments.Haskell is a purely functional language. This means that functions are not allowed to have any side-effects at all. For example, a Haskell program doesn't print to the screen as such, but is a function that returns a value of the  datatype which describes a sequence of actions for the IO subsystem to perform.Whereas Scala is strict by default and provides \"by-name\" annotation for nonstrict function arguments, Haskell is lazy by default using \"by-need\" semantics, and provides annotation for strict arguments.Type inference in Haskell is more complete than in Scala, having full inference, even for partially applied polymorphic type constructors. This means that type annotation is almost never necessary.Recent extensions to the GHC compiler allow advanced type system features that have no equivalent in Scala, such as rank-n types, type families, and polykinds.In Haskell, a module is a collection of types and functions, but modules are not first-class entities. Implicits are provided by type classes, but these are globally scoped once declared, and they cannot be passed explicitly as in Scala. Multiple instances of a given type class for a given type are resolved by the  mechanism whereas in Scala this would be solved simply by scoping or by passing instances explicitly.Since Haskell isn't \"object-oriented\", there's no method/function dichotomy. Every function is first class and every function is curried by default (no Function1, Function2, etc).I don't believe anyone has systematically compared Haskell (as exemplified by GHC's type system) with Scalas. The main points of difference are the degree of type inference, and support for higher-rank types. But a full treatment of the differences would be a publishable result."},
Scala

Assume I have a Regex pattern I want to match many Strings to.I just want to check whether a given String fully matches the Regex. What is a good and idiomatic way to do this in Scala?I know that I can pattern match on Regexes, but this is syntactically not very pleasing in this case, because I have no groups to extract:Or I could fall back to the underlying Java pattern:which is not elegant, either.Is there a better solution?Answering my own question I'll use the \"pimp my library pattern\"and use it like thisunless someone comes up with a better (standard) solution.I don't know Scala all that well, but it looks like you can just do:For the full match you may use . This method tries to match target (whole match) and returns the matches.The answer is in the regex:Then use the one of the existing methods."},
Scala

I have a very simple question - when should we apply the new keyword when creating objects in Scala? Is it when we try to instantiate Java objects only?Use the  keyword when you want to refer to a 's own constructor:Omit  if you are referring to the companion object's  method:If you've made a case class:Scala secretly creates a companion object for you, turning it into this:So you can doLastly, keep in mind that there's no rule that says that the companion \nmethod has to be a proxy for the constructor:And, since you mentioned Java classes: yes -- Java classes rarely have\ncompanion objects with an  method, so you must use  and the actual\nclass's constructor.Not at all. There is two general cases when you ommit  in scala.\nWith singleton objects (that are oftenly used to store static functions and as a kind of factory similar to what you may seen in java):With a  (actually, underneath there are class + object =  pattern, e.g. having class and object with the same name):So when you work with a simple classes, rules are the same as with Java.Bonus, there is a anonymous classes in scala, which can be constructed like this: "},
Scala

I have an application based on Squeryl. I define my models as case classes, mostly since I find convenient to have copy methods.I have two models that are strictly related. The fields are the same, many operations are in common, and they are to be stored in the same DB table.  there is some behaviour that only makes sense in one of the two cases, or that makes sense in both cases but is different.Until now I only have used a single case class, with a flag that distinguishes the type of the model, and all methods that differ based on the type of the model start with an if. This is annoying and not quite type safe.What I would like to do is factor the common behaviour and fields in an ancestor case class and have the two actual models inherit from it. But, as far as I understand, inheriting from case classes is frowned upon in Scala, and is even prohibited if the subclass is itself a case class (not my case).My preferred way of avoiding case class inheritance without code duplication is somewhat obvious: create a common (abstract) base class:\nIf you want to be more fine-grained, group the properties into individual traits:Since this is an interesting topic to many, let me shed some light here.You could go with the following approach:Yes, you have to duplicate the fields. If you don't, it simply would not be possible to implement correct equality .However, you don't need to duplicate methods/functions.If the duplication of a few properties is that much of an importance to you, then use regular classes, but remember that they don't fit FP well.Alternatively, you could use composition instead of inheritance:Composition is a valid and a sound strategy that you should consider as well.And in case you wonder what a sealed trait means \u2014 it is something that can be extended only in the same file. That is, the two case classes above have to be in the same file. This allows for exhaustive compiler checks:Gives an error:Which is really useful. Now you won't forget to deal with the other types of s (people). This is essentially what the  class in Scala does.If that does not matter to you, then you could make it non-sealed and throw the case classes into their own files. And perhaps go with composition.case classes are perfect for value objects, i.e. objects that don't change any properties and can be compared with equals. But implementing equals in the presence of inheritance is rather complicated. Consider a two classes: and So according to the definition the ColorPoint(1,4,red) should be equal to the Point(1,4) they are the same Point after all. So ColorPoint(1,4,blue) should also be equal to Point(1,4), right? But of course ColorPoint(1,4,red) should not equal ColorPoint(1,4,blue), because they have different colors. There you go, one basic property of the equality relation is broken.You can use inheritance from traits solving lots of problems as described in another answer. An even more flexible alternative is often to use type classes. See  or In these situations I tend to use composition instead of inheritance i.e.Obviously you can use a more sophisticated hierarchy and matches but hopefully this gives you an idea. The key is to take advantage of the nested extractors that case classes provide"},
Scala

Say I have an  likeNow I would like to append an element to the array, say the value , as in the following example: I can of course use  and do this on my own, but there must be a Scala library function for this, which I simply could not find. Thanks for any pointers!Notes:Thanks for the answers pointing to the  operator method. This is what I was looking for. Unfortunately, it is rather slower than a custom append() method implementation using  -- about two to three times slower. Looking at the implementation in , a builder is created, then the array is added to it, then the append is done via the builder, then the builder is rendered. Not a good implementation for arrays. I did a quick benchmark comparing the two methods, looking at the fastest time out of ten cycles. Doing 10 million repetitions of a single-item append to an 8-element array instance of some class  takes 3.1 sec with  and 1.7 sec with a simple  method that uses  doing 10 million single-item append repetitions on 8-element arrays of Long takes 2.1 sec with  and 0.78 sec with the simple  method. Wonder if this couldn't be fixed in the library with a custom implementation for ?For what it's worth, I filed a ticket:\nYou can use  to append element to array and  to prepend it:should produce:It's the same as with any other Scala collection. Works also \"reversed\":There is also an \"in-place\" version:The easiest might be:Actually, Array can be implcitly transformed in a "},
Scala

I'm starting to explore Scala, and one of the things I'm intrigued by is the  type and the promise of being able to eliminate  related errors.However I haven't been able to work out how to transform a list (or other collection) of, say, , to a collection of  (obviously filtering out any values that are ).In other words, how do I get from this:... to this:I'm using Scala 2.8 if that has any impact on the answer.For educational purposes, you might like some alternatives:With Scalaz, you can perform a slightly different operation called , that returns ."},
Scala

Is there a function that can truncate or round a Double?  At one point in my code I would like a number like:  to be rounded to You can use :There are a number of other , which unfortunately aren't very well documented at present (although ).Here's another solution without BigDecimalsTruncate:Round: Or for any double n and precision p:Similar can be done for the rounding function, this time using currying:which is more reusable, e.g. when rounding money amounts the following could be used:Since no-one mentioned the  operator yet, here comes. It only does truncation, and you cannot rely on the return value not to have floating point inaccuracies, but sometimes it's handy:Edit: fixed the problem that @ryryguy pointed out.  (Thanks!)If you want it to be fast, Kaito has the right idea.   is slow, though.  For any standard use you're better off with a recursive function:This is about 10x faster if you're within the range of  (i.e 18 digits), so you can round at anywhere between 10^18 and 10^-18.How about : Recently, I faced similar problem and I solved it using following approachI used  SO issue. I have couple of overloaded functions for both Float\\Double and implicit\\explicit options. Note that, you need to explicitly mention the return type in case of overloaded functions.For those how are interested, here are some times for the suggested solutions...You may use implicit classes:I wouldn't use BigDecimal if you care about performance. BigDecimal converts numbers to string and then parses it back again:I'm going to stick to math manipulations as  suggested."},
Scala

 I've been looking for a good solution to developing a service in Scala that will sit between mobile devices and existing web services.The current list of viable options are:There are probably more options out there. How does one decide which one to use? What are the traits (excuse the pun ;-) of a good Scala middleware choice. On the one side, I would like to go for Akka, because it is part of the TypeSafe Scala stack, but on the other, something like Finagle has a rich set of libraries and makes plumbing so easy. Spray looks nice and simple to use.Any advice, insights or experience would be greatly appreciated. I'm sure someone out there must have some experience with some of these that they won't mind sharing.I would love for this question to be reopened. A good answer to this question will help new Scalateers to avoid related pitfalls.These are my own experiences since asking this question: - I used Finagle for a project and it's rock solid. - In my latest project I'm using Spray and I'm extremely happy. The latest releases are built on Akka 2 and you can run it directly with the Spray-can library which removes the need for a web server. Spray is a set of libraries, rather than a framework and is very modular. The  gives a great overview, and  shows a really nice development approach and architecture.Life moves pretty fast. If you don't stop and look around once in a while, you could miss it. - These days the choice has become simpler. In my humble opinion Spray has won the battle. It is being  to become the next Akka HTTP. I have been using Spray now on multiple projects and can honestly say that it's fantastic and best supported software I have ever encountered.This does not answer the initial question, but at least gives some indication on why Spray seems like the best choice in most cases. It is extremely flexible, non-blocking and very stable. It has both client-side and server-side libraries and a great testkit. Also, have a look at these stats to get an idea on performance: I personally started with spray a long time ago and tried everything else there was out there for Scala. While Scala, spray, akka, shapeless, and scalaz certainly have a bit of a learning curve, once you start digging in and really learning how you are supposed to use the technologies, they make sense and I immediately saw the benefits especially for the kind of work I'm doing right now.Personally I think nothing really stands up to spray for building both servers, rest apis, http clients, and whatever else you want. What I love about spray is that they built with akka in mind. It may have been a really early project when I first started using it, but the architecture made sense. Those guys knew what they were doing in terms of exploiting the benefits of using an actor model and not having any blocking operations.While actors might take a bit getting used to, I do like them. They have made my systems very scalable and cheap to run because I don't need as beefy hardware as in the past. Plus, spray has that spray-routing DSL so making a rest api is relatively simple as long as you follow the rules ... don't block. That of course means don't go and pull in apache commons http client to make client requests from the api or actors because you will be going back to blocking models.So far I am very happy with spray, typesafe, and akka. Their models just naturally lend themselves to building very resilient systems that come back up on their own if anything should happen and you take a fail-fast approach. The one beef that I have with spray (and it's not spray's fault) is the damn IDE support for the routing DSL. I absolutely despise Eclipse and have always been an IDEA user. When I started using the Scala plugin, everything seemed ok. Then my routing dsl naturally evolved into way bigger beasts. Something about the way IDEA parses that code makes it shit its pants anytime it encounters anything with spray-routing or shapeless. It's to the point where it's unusable (I type 2-3 letters and have to wait 5 minutes to regain control).So, for any spray-routing or heavy shapeless code, I fire up emacs with ensime, ensime-sbt, and scala-mode2. Now if I could only get a Cassandra library with the quality of astyanax and built using a more non-blocking architecture. you can find a great list of scala resources with a brief description of all the alternatives you listed. From my own experience, I use Scalatra and it is tiny, simple and effective for things like uri mapping and calling web services."},
Scala

I found the following code snippet:The  looks like a method, but my friend told me it's a keyword.I googled it, but found few documents about . What does it mean, and where can I get some documents about it?The  keyword is used to define existential types in Scala. There's this Scala  page explaining what they are. I couldn't find a place in the Scala docs explaining them in detail, so  is a blog article I found on Google explaining how they are useful.Update: you can find a precise definition of existential types in the  but it is quite dense.To summarize some of the posts I linked to, existential types are useful when you want to operate on something but don't care about the details of the type in it. For example, you want to operate on arrays but don't care  of array:which you could also do with a type variable on the method:but you may not want to add the type variable in some cases. You can also add a bound to the type variable:Also see  which is where I got this example from.I don't know Scala, but your question picked up my interest and started Googling.I found that in :"},
Scala

How does  relate to ? The Cats project mentions it is descended from scalaz.  I would like to keep this from getting too political*, but cats is for all intents and purposes scalaz. It has not reached full parity as of yet, but keep in mind it was only created a few months ago. The goal is for it to be a more pragmatic approach and more democratic when it comes to its evolution. So, naming of operators and classes is hopefully going to be a little more straightforward, as well as it has no qualms with using mutable data within a method if it means better performance. Last, they are HOPING to have better documentation....all of this means that it may end up becoming a replacement for scalaz with a better beginner's approach for those not embroiled in the math world. If you want a fuller answer, then maybe head over to their gitter board and Erik (non) could answer it himself :)*The gist is that scalaz has some social baggage with it that causes a number of big names to shy away from using and/or contributing."},
Scala

By suitable, I mean:In no particular order.Which GUI toolkits satisfy which conditions?Scala has its own Swing library. This will use the standard Swing library under the hood but it has some nice additions and most notably, because it's made for Scala, it can be used in a much more concise way than the standard Swing library:See how nice and easy it is to set widget properties?Except for the nicer syntax and the small additions (like the  class), I think the advantages and disadvantages are pretty much the same as with vanilla Swing.Here's an .ScalaFX is a mature wrapper around JavaFX 2. It is superficially similar to Scala Swing in some regards, but has some features that make it stand out:I use Java Swing. Here's how it stacks up against your requirements:Now that some time has passed, it's worth noting that ScalaJS is also an option to consider. Against your requirements:The downside is that it takes your GUI off the JVM and into the browser, so you can't use all those Java libraries.I'd say use .Net its mature and used extensively. But ...I assume that you require to use Scala. For that I'd stick to Java as it has better tool support like in IDEA or NetBeans. You can of course mix Java and Scala. So your GUI can be done in Java that calls Scala backend. Also take a look at JGoodies they have lot of nice stuff to build UI in Swing. At this moment there is no tool support for Scala GUI applications (and for non GUI it is still behind Java)."},
Scala

What's the best way to terminate a fold early? As a simplified example, imagine I want to sum up the numbers in an , but if I encounter something I'm not expecting (say an odd number) I might want to terminate. This is a first approximationHowever, this solution is pretty ugly (as in, if I did a .foreach and a return -- it'd be much cleaner and clearer) and worst of all, it traverses the entire iterable even if it encounters a non-even number.So what would be the best way to write a fold like this, that terminates early? Should I just go and write this recursively, or is there a more accepted way?My first choice would usually be to use recursion.  It is only moderately less compact, is potentially faster (certainly no slower), and in early termination can make the logic more clear.  In this case you need nested defs which is a little awkward:My second choice would be to use , as it keeps everything else intact and you only need to wrap the fold in a  so you have something to return from--in this case, you already have a method, so:which in this particular case is a lot more compact than recursion (though we got especially unlucky with recursion since we had to do an iterable/iterator transformation).  The jumpy control flow is something to avoid when all else is equal, but here it's not.  No harm in using it in cases where it's valuable.If I was doing this often and wanted it within the middle of a method somewhere (so I couldn't just use return), I would probably use exception-handling to generate non-local control flow.  That is, after all, what it is good at, and error handling is not the only time it's useful.  The only trick is to avoid generating a stack trace (which is really slow), and that's easy because the trait  and its child trait  already do that for you.  Scala already uses this internally (in fact, that's how it implements the return from inside the fold!).  Let's make our own (can't be nested, though one could fix that):Here of course using  is better, but note that you could put  anywhere, not just wrapping an entire method.Next in line for me would be to re-implement fold (either myself or to find a library that does it) so that it could signal early termination.  The two natural ways of doing this are to not propagate the value but an  containing the value, where  signifies termination; or to use a second indicator function that signals completion.  The Scalaz lazy fold shown by Kim Stebel already covers the first case, so I'll show the second (with a mutable implementation):(Whether you implement the termination by recursion, return, laziness, etc. is up to you.)I think that covers the main reasonable variants; there are some other options also, but I'm not sure why one would use them in this case.  ( itself would work well if it had a , but it doesn't, and the extra work it takes to do that by hand makes it a silly option to use here.)The scenario you describe (exit upon some unwanted condition) seems like a good use case for the  method. It is essentially , but should end upon encountering an element that doesn't meet the condition.For example:This will work just fine for s/s too. The solution I suggest for your \"sum of even numbers, but break on odd\" is:And just to prove that it's not wasting your time once it hits an odd number...You can do what you want in a functional style using the lazy version of foldRight in scalaz. For a more in depth explanation, see . While this solution uses a , you can convert an  into a  efficiently with .This only printswhich clearly shows that the anonymous function is only called twice (i.e. until it encounters the odd number). That is due to the definition of foldr, whose signature (in case of ) is . Note that the anonymous function takes a by name parameter as its second argument, so it need no be evaluated.Btw, you can still write this with the OP's pattern matching solution, but I find if/else and map more elegant.Well, Scala does allow non local returns. There are differing opinions on whether or not this is a good style.In this particular case, as @Arjan suggested, you can also do:@Rex Kerr your answer helped me, but I needed to tweak it to use EitherYou could try using a temporary var and using takeWhile. Here is a version. The  should be  in this case. You can throw a well-chosen exception upon encountering your termination criterion, handling it in the calling code.A more beutiful solution would be using span:... but it traverses the list two times if all the numbers are evenJust for an \"academic\" reasons (:Takes twice then it should but it is a nice one liner.\nIf \"Close\" not found it will return Another (better) is this one:"},
Scala

I need a mature HTTP client library that is idiomatic to scala, concise in usage, simple semantics. I looked at the Apache HTTP and the Scala Dispatch and numerous new libraries that promise an idiomatic Scala wrapping. Apache HTTP client sure demands verbosity, while Dispatch was easily confusing.What is a suitable HTTP client for Scala usage?I've recently started using , a bit arcane (great general intro, serious lack of detailed scenario/use-case based docs).  Dispatch 0.9.1 is a Scala wrapper around Ning's ; to fully understand what going on requires introducing one's self to that library.  In practice, the only thing I really had to look at was the  - everything else falling nicely into my understanding of HTTP.I give the 0.9 release a solid thumbs up (so far!) on getting the job done very simply.. once you get past that initial learning curve.Dispatch's Http \"builder\" is immutable, and seems to work well in a threaded environment.  Though I can't find anything in docs to state that it is thread-safe; general reading of source suggests that it is.Do be aware that the 's are mutable, and therefore are NOT thread-safe.Here are some additional links I've found helpful:A little late to the party here, but I've been impressed with .It's got a nice DSL for building requests, supports both sync and async execution, as well as a variety of (un)marshalling types (JSON, XML, forms). It plays very nicely with , too.I did a Dispatch, and a few others libraries, .\nThe only serious ones currently are  and . is a bit arcane in its syntax.  is quite easy to use :(build.sbt)(basic usage)Having had some unhappy experiences with the Apache client, I set about writing my own. The built-in HttpURLConnection is widely asserted to be buggy. But that's not my experience of it. In fact, the reverse has been so, the Apache client having a somewhat problematic threading model. Since Java6 (or 5?), HttpURLConnection has provided efficient HTTP1.1 connections with essentials like keep-alive being built in, and it handles concurrent usage without fuss.So, to compensate for the inconvenient API offered by HttpURLConnection, I set about writing a new API in Scala, as an open-source project. It's just a wrapper for HttpURLConnection, but unlike HttpURLConnection, it aims to be easy to use. Unlike Apache client, it should fit easily into an existing project. Unlike Dispatch, it should be easy to learn.It's called Bee ClientMy apologies for the shameless plug. :)Besides Dispatch there is not much out there.  had a attempt at building a functional http client. But it is outdated for a while an no version of it exists in the scalaz7 branch. Additionally there is a useful  of the ning async-http-client within the playframework. There your can do calls like:You can use this API as inspiration if you don't use play! in your project and dislike the Dispatch API. Two years after originally responding to this post, I would have a different answer.I'd start by taking a hard look at , which a collaboration between the spray and akka teams.  As of today, it hasn't reached it 1.0 release; it's coming soon, is backed by typesafe, and is looking good.You really should consider using . In my opinion it have a bit tricky syntax, but it is still pretty usable is you aimed to build high-perfomance http client. Main advantage of using spray is that it based on  actor library which is really extremly scalable and powerfull (you can scale out your http client to several machines only by changing conf files). One more option is play2 ws lib usage (). As far as I know it is still not separated from play distribution, but due it's extremely simplicity it worth it to spent some time for attaching whole play framework for the only part. There are some issues with providing configuration to it, so this is not too good for drop-and-use, but we have used it in few not play-based projects and everything was fine.ScalaJ-Http is a very simple synchronous http client I'd recommend it if you need a no-ceremony barebones Scala client. I've used Dispatch, Spray Client and the Play WS Client Library...None of them were simply to use or configure. So I created a simpler HTTP Client library which lets you perform all the classic HTTP requests in simple one-liners.See an example:... produces ...The library is called Cirrus and is available via Maven CentralThe documentation is available on GitHubSurprised that no one mentioned finagle here. It is super simple to use:See quick start guid for more detail: "},
Scala

I haven't seen many examples of the scalaz state monad. There is  but it is hard to understand and there is only one  on stack overflow it seems.I'm going to post a few examples I've played with but I would welcome additional ones. Also if somebody can provide example on why , ,  and  are used for that would be great.I assume,  and the following imports (look at answer history for ):The state type is defined as  where  is type of the state and  is the type of the value being decorated. The basic syntax to create a state value makes use of the  function:To run the state computation on a initial value:The state can be threaded through function calls. To do this instead of , define . Use the  function...Then the  syntax can be used to compose functions:Here is another example. Fill a list with  state computations.Use sequence to get a . We can provide a type alias.Or we can use  which will infer the types:Another example with  to compute frequency of sums on the list above.  computes the sum of the throws and counts frequencies.Now use traverse to apply  over .  is equivalent to .Or more succinctly by using  to infer the types:Note that because  is a type alias for , tenDoubleThrows2 ends up being typed as . I use  to turn it back into a  type. In short, it seems the key to use state is to have functions returning a function modifying the state and the actual result value desired... I gave up on trying using  may be someone else can show if  or  can be augmented to perform the combined computation. What I found instead is that the composition of the two state transformers can be combined like this:It's predicated on  being a one parameter function taking the result of the first state transformer and returning a state transformer. Then the following would work:I stumbled on an interesting blog post  from sigfp that has an example of applying two state monads through a monad transformer. Here is a scalaz translation. The  shows a  monad:So I have here an example of using  and . After playing with it a bit,  turns out to be really convenient to generate a  value, but the other thing it allows is to access the state inside the for comprehension.  is a convenient way to transform the state inside the for comprehension. So the example above can be read as:The for comprehension syntax already makes it trivial to work on the  side in . , ,  and  provide some tools to work on the  side in .The  in the blog post translates to:Very much the same explanation as .The  is more tricky and I hope there is something simpler that I have yet to discover. In that code,  takes care of the transformation of both states (increment and suffix with ) as well as pulling out the  state.  allows us to add state transformation on an arbitrary monad . In this case the state is an  that is incremented. If we called  we would end up with . In our example,  is , so we'll end up with  which is .   The tricky part here is that we want to pull out the  state value out from . This is what  is for. It just creates an object that gives access to the state in a way we can flatMap with . Edit: Turns out all of that awkwardness can be avoided if we truly reused  and  which conveniently store the wanted states in the  element of their returned tuples:Here is a very small example on how  can be used:Let's define a small \"game\" where some game units are fighting the boss (who is also a game unit).When the play is on we want to keep track of the game state, so let's define our \"actions\" in terms of a state monad:Let's hit the boss hard so he loses 10 from his : And the boss can strike back! When he does everyone in a party loses 5 . Now we can  these actions into :Of course in the real life the play will be more dynamic, but it is food enough for my small example :)We can run it now to see the final state of the game:So we barely hit the boss and one of the units have died, RIP.The point here is the . \n (which is just a function ) allows you to define actions that produce results and as well manipulate some state without knowing too much where the state is coming from.\nThe  part gives you composition so your actions can be composed:and so on. As for differences between ,  and : can be seen as  and  together:or simplySo when you use  you conceptually use  and , or you can just use them alone."},
Scala

I've started using Spark SQL and DataFrames in Spark 1.4.0.  I'm wanting to define a custom partitioner on DataFrames, in Scala, but not seeing how to do this.One of the data tables I'm working with contains a list of transactions, by account, silimar to the following example.At least initially, most of the calculations will occur between the transactions within an account.  So I would want to have the data partitioned so that all of the transactions for an account are in the same Spark partition.But I'm not seeing a way to define this.  The DataFrame class has a method called 'repartition(Int)', where you can specify the number of partitions to create.  But I'm not seeing any method available to define a custom partitioner for a DataFrame, such as can be specified for an RDD.The source data is stored in Parquet.  I did see that when writing a DataFrame to Parquet, you can specify a column to partition by, so presumably I could tell Parquet to  partition it's data by the 'Account' column.  But there could be millions of accounts, and if I'm understanding Parquet correctly, it would create a distinct directory for each Account, so that didn't sound like a reasonable solution.Is there a way to get Spark to partition this DataFrame so that all data for an Account is in the same partition?In Spark >= 1.6 it is possible to use partitioning by column for query and caching. See:  and  using  method:Unlike  Spark  (including  a.k.a ) cannot use custom partitioner as for now. You can typically address that by creating an artificial partitioning column but it won't give you the same flexibility. :One thing you can do is to pre-partition input data before you create a Since  creation from an  requires only a simple map phase existing partition layout should be preserved*:The same way you can repartition existing :So it looks like it is not impossible. The question remains if it make sense at all. I will argue that most of the time it doesn't::JDBC data sources support . It can be used as follows:It creates a single JDBC partition per predicate. Keep in mind that if sets created using individual predicates are not disjoint you'll see duplicates in the resulting table.:Spark  provides  method which can be used to \"partition\" data on write. It separates data on write using provided set of columnsThis enables predicate push down on read for queries based on key:but it is not equivalent to . In particular aggregations like:will still require : (Spark >= 2.0): has similar applications as  but it is available only for tables (). As of today (Spark 2.1.0) it doesn't look like there are any execution plan optimizations applied on bucketed tables.* By  I mean only a data distribution.  RDD has no longer a partitioner.\n** Assuming no early projection. If aggregation covers only small subset of columns there is probably no gain whatsoever.In Spark < 1.6 If you create a , not the plain old  you can use the   (ensures each of N reducers gets non-overlapping ranges of x) &  (shortcut for Distribute By and Sort By) for example; Not sure how this fits in with Spark DF api. These keywords aren't supported in the normal SqlContext (note you dont need to have a hive meta store to use the HiveContext) Spark 1.6+ now has this in the native DataFrame APIUse the DataFrame returned by:There is no explicit way to use partitionBy on a DataFrame, only on a PairRDD, but when you sort a DataFrame, it will use that in it's LogicalPlan and that will help when you need to make calculations on each Account.I just stumbled upon the same exact issue, with a dataframe that I want to partition by account.\nI assume that when you say \"want to have the data partitioned so that all of the transactions for an account are in the same Spark partition\", you want it for scale and performance, but your code doesn't depend on it (like using mapPartitions() etc), right?I was able to do this using RDD. But I don't know if this is an acceptable solution for you.\nOnce you have the DF available as an RDD, you can apply  to perform custom repartitioning of data. Here is a sample I used:So to start with some kind of answer : ) - You can'tI am not an expert, but as far as I understand DataFrames, they are not equal to rdd and DataFrame has no such thing as Partitioner.Generally DataFrame's idea is to provide another level of abstraction that handles such problems itself. The queries on DataFrame are translated into logical plan that is further translated to operations on RDDs. The partitioning you suggested will probably be applied automatically or at least should be.If you don't trust SparkSQL that it will provide some kind of optimal job, you can always transform DataFrame to RDD[Row] as suggested in of the comments."},
Scala

Multiple parameters lists, e.g.  and multiple parameters per list, e.g.  are semantically equivalent so far as I can tell, and most functional languages have only one way of declaring multiple parameters, e.g. F#.The only reason I can figure out for supporting both these styles of function definitions is to allow syntax-like language extensions using a parameter list that has only one parameter in it.can now be called with the syntax-lookingHowever, there could be other ways of supporting the use of curly braces without having multiple parameter lists.A related question: why is the use of multiple parameter lists in Scala called \"currying\"? Currying is usually defined as a technique for making an n-ary function unary for the sake of supporting partial application. However, in Scala one can partially apply a function without making a \"curried\" (multiple parameter lists with one param each) version of the function.It makes you able to do e.g.:As well as allowing you to write methods that look like part of the language (which you already spotted), it's worth noting that the type inferencer will work with one block at a time.So in this: will first be inferred as , which will then be used as the type of the two underscores in the closure.\nThis is how the compiler then knows, with complete type safety, that the + operation is valid.To answer your \"related question,\" currying is simply a way of turning a function of multiple arguments, for example , into a function which takes one argument and returns a function, e.g.  (parentheses shown but not necessary).The tuple-ized form and the curried form are isomorphic, and we may translate freely between them. All of these are equivalent, but have different syntactic implications:When you declare separate parameter groups, this is the kind of currying you're doing. The multi-parameter-group method is a method which returns a function... you can see this in the REPL:Back references in default arguments:I know one of the motivations was implicit parameter lists.  \"implicit\" is a property of the list, not the parameter.  Another was probably case classes: only the first parameter list become case fields."},
Scala

I have a List, which may contain elements that will compare as equal. I would like a similar List, but with one element removed. So from (A, B, C, B, D) I would like to be able to \"remove\" just one B to get e.g. (A, C, B, D). The order of the elements in the result does not matter.I have working code, written in a Lisp-inspired way in Scala. Is there a more idiomatic way\nto do this?The context is a card game where two decks of standard cards are in play, so there may\nbe duplicate cards but still played one at a time.I haven't seen this possibility in the answers above, so:Edit:Like a charm :-).You could use the filterNot method.You could try this:And as method:Unfortunately, the collections hierarchy got itself into a bit of a mess with  on .  For  it works just like you might hope:but, sadly,  ended up with a -style implementation and thus does the \"wrong thing\"  throws a deprecation warning at you (sensible enough, since it is actually ing):So arguably the easiest thing to do is convert  into a collection that does this right, and then convert back again:Alternatively, you could keep the logic of the code you've got but make the style more idiomatic:As one possible solutions you can find index of the first suitable element and then remove element at this index:How aboutIf you see , there's something wrong.Just another thought on how to do this using a fold:"},
Scala

I have Intellij ultimate 11.1, with the scala plugin installed.I installed scala 2.9.2 using homebrew, which put scala in:Creating a new java module project, I get this:Can someone help me fix these issues, why didn't the scala plugin make this work out of the box? :)You need to specify  directory on your first screenshot. This is Mac  specific, the same case is valid for  installed via .Standard  has different layout which IDEA understands correctly,  is creating  directory where it writes  and  directories expected by IDEA.Here's a step by step for any of those who are trying to get Scala in IntelliJ up and running. IntelliJ > Preferences > Plugins > Browse Repositories... > Scala\nClick Ok and allow IntelliJ to restartIn Terminal enterHere you are going to create a Java project from scratch as you normally would.  However, in the last step, you will select Scala in the \"Technologies\" page.  In the  enter  In the  dropdown select Click Ok and you are ready to create your first Scala objectFor reference ->\nThe latest Brew has already realized this problem and created automatic symlinks upon installing Scala.Firstly, install Scala with DocumentationSecondly, provide the following path in IntelliJRather than downloading the docs separately you can use the  option when installing scala with homebrew:Then in IntelliJ point your JavaDocs path in the scala-library to .I'm just found another way to configure scala with intelJIdea.\nIf scala installed with brew then just write in terminal:you will see smth like that:Then just include  into your idea config panel.I am using Yosemite, and the following worked for me.Then I tested IntelliJ by creating a new project, using the Java SDK, and for compiler putting in:I tested compiling a Hello World program via  and it compiled correctly to the console.Note, I ignored what @Zagorulkin said above even though it seems logical that if Homebrew is saying so my compile path should be different to the above.Change  to  and you are good to go."},
Scala

I found there is also an Akka actor model, so I am wondering what's the difference between the Akka's Actor and Scala's Actor model?Well, there isn't. There is just Actor model, and Akka actors and Scala actors are two  of that model.All Actor model says that your concurrency primitives are actors, which can:and provides certain guarantees, e.g.:There is no difference between Scala and Akka actors on this level.For differences in what they can do, see . The biggest one, for me, is that Akka supports supervisors and ActorRegistry.There is also a historical answer. The creators of Scala thought there should be an actor framework. Jonas Bon\u00e9r tried it out, but was not completely satisfied so he started working on a new - which evolved into Akka. However, the Scala people thought it was better than their own - so at Jfokus 2011 they announced that Akka was to become the standard actor framework of Scala. However, that migration will take some time.This depends a little on what you mean with \"model\" - you can either refer to the \"execution model\" or the \"programming model\" (and perhaps other models as well).For execution models, there are basically two: thread-based or event-based. The Scala standard actor library contains both. The thread-based uses one thread for each actor, whereas the event-based uses a thread-pool. The former is more intuitive to understand, the latter is more efficient. Akka is built on the event-based model.For programming model, there is a big difference between the scala standard library and Akka. In the scala standard library, you basically implement the \"run\" method - and if you want to wait for an incoming message, you get yourself into a waiting state (by calling \"receive\" or \"react\"). So, the programming model follow the \"thread-metaphor\". However, in Akka, the programming metaphor is that you implement a few life-cycle methods - but the \"run\"-method is written inside the framework. It actually turns out that this programming model works a lot better with the event-based execution model as well.If you are interested in the different execution models and programming models of scala standard actors I have written    on the issue. "},
Scala

Where can I find a list of Scala's \"magic\" functions, such as , , , , etc.?By magic-functions I mean functions which are used by some syntactic sugar of the compiler, for exampleI googled for some combination of   and synonyms of , but I didn't find anything.I'm not interested with the  of magic functions in the standard library, but in which magic functions exists.As far as I know:Getters/setters related:Pattern matching:For-comprehensions:Prefixed operators:Beyond that, any implicit from A to B. Scala will also convert  into , if the former operator isn't defined, \"op\" is not alphanumeric, and  isn't , ,  or .And I don't believe there's any single place where all of Scala's syntactic sugars are listed.In addition to  and , there are also a number of unary operators which (I believe) qualify as magical:Add to that the regular infix/suffix operators (which can be almost anything) and you've got yourself the complete package.You really should take a look at the Scala Language Specification.  It is the only authoritative source on this stuff.  It's not that hard to read (as long as you're comfortable with context-free grammars), and very easily searchable.  The only thing it doesn't specify well is the XML support.Sorry if it's not exactly answering your question, but my favorite WTF moment so far is @ as assignment operator inside pattern match. Thanks to soft copy of \"Programming in Scala\" I found out what it was pretty quickly.Using @ we can bind any part of a pattern to a variable, and if the pattern match succeeds, the variable will capture the value of the sub-pattern. Here's the example from  (Section 15.2 - Variable Binding):And 's what  says about it.They are defined in the Scala Language Specification.\nAs far as I know, there are just three \"magic\" functions as you mentioned.Scalas Getter and Setter may also relate to your \"magic\":I'll also add  for  likeAnd  rule, from Odersky-Spoon-Venners book:Maybe we should also mention syntactic desugaring of  which can be found And (of course!), (as correctly pointed out, this one is just an  done through a library, so it's probably not eligible, but I find it's a common puzzler for newcomers)I'd like to add that there is also a \"magic\" trait - :So you can do stuff like"},
Scala

I have heard this time and again, and I am trying to understand and validate the idea that FP and OO are orthogonal.First of all, what does it mean for 2 concepts to be orthogonal?FP encourages immutability and purity as much as possible, while OO seems built for state and mutation \u2013 a slightly organized version of imperative programming?  I realize that objects can be immutable, but OO seems to imply state/change to me.They seem like opposites. How does that affect their orthogonality?A language like Scala makes it easy to do OO and FP both, does this affect the orthogonality of the two methods? implies that two things are unrelated. It comes from mathematics where it means . In common usage it can mean two decisions are unrelated or that one subject is irrelevant when considering another subject. As used here, orthogonal means that one concept doesn't either imply or exclude the other.The two concepts  and  are not incompatible with each other. Object orientedness does not imply mutability. Many people who are introduced to object oriented programs the traditional way often first use C++, Java, C# or similar languages where mutability is common and even encouraged (standard libraries provide a varierty of mutable classes for people to use). Therefore it is understandable that many people associate object oriented programming with imperative programming and mutability, as this is how they have learned it.However object oriented programming covers topics like:None of this implies mutability, and none of it excludes functional programming. So yes they are  in that they are different concepts. They are not opposites - you can use one, or the other, or both (or even neither). Languages like Scala and F# attempt to combine both paradigms into a single language:It means they don't affect each other. I.e. a functional language isn't less functional because it's also object oriented.If they were opposites (i.e. a purely functional language could not possibly be object oriented), they would by definition not be orthogonal. However I do not believe that this is the case.While this is true for most mainstream OO languages, there is no reason that an OO language needs to have mutable state.If a language has objects, methods, virtual inheritance and ad-hoc polymorphism, it's an object oriented language - whether it also has mutable state or not.It means that the two concepts do not have contrasting ideas or are not incompatible with each other.OO is about encapsulation, object composition, data abstraction, polymorphism via subtyping, and  (immutability is encouraged in OO as well). FP is about function composition, control abstraction, and constrained polymorphism (aka parametric polymorphism). Thus the two ideas are not contradictory. They both provide you with different kinds of powers and abstraction mechanisms, which are certainly possible to have in one language. In fact, this is the thesis on which  was built!In his  talk at Google, Martin Odersky explains it very well how he believes the two concepts - OO and FP - are orthogonal to each other and how Scala unifies the two paradigms elegantly and seamlessly into a new paradigm popularly known in Scala community as object-functional paradigm. Must watch talk for you. :-)Other examples of object-functional languages: , , .For two concepts to be orthogonal means that they can be independently realized to any degree in any given manifestation. Considering music, for instance, you can classify a musical piece as to how harmonic it is and how rhythmic it is. The two concepts \"harmonic\" and \"rhythmic\" are orthogonal in the sense that there are harmonic and rhythmic pieces, disharmonic and arrythmic pieces, but also disharmonic and rhythmic pieces as well as harmonic and arrhythmic pieces.Applied to original question this means that there are purely functional, non-object oriented  programming lanuages such as Haskell, purely object-oriented, \"non-functional\" languages such as Eiffel, but also languages which are neither such as C and languages which are both such as Scala.Simply speaking, Scala being object-oriented means that you can define data structures (\"classes\" and \"traits\") which encapsulate data with the methods that manipulate this data, guaranteeing that instances of these structures (\"objects\") are always in a defined state (the object's contract laid out in its class).On the other hand, Scala being a functional language means that it favors immutable over mutable state and that functions are first class objects, which can be used just like any other object as local variables, fields or parameters to other functions. In addition to this, almost every statement in Scala has a value, which encourages you to use a functional programming style.Orthogonality of object-orientated programming and functional programming in Scala additionaly means that you as a programmer are free to choose any mixture of these two concepts you see fit for your purpose. You can write your programs in a purely imperative style, using mutable objects only and not using functions as objects at all, on the other hand you can also write purely functional programs in Scala not using any of its object-oriented features. Scala really does not require you to use one style or the other. It lets you choose the best of both worlds to solve your problem.Like all classifications, the division of programming languages into functional, object-oriented, procedural, etc. is fictional. But we do need classifications, and in programming languages we classify by a set of language features and the philosophical approach of those who use the language (where the later is influenced by the former). So sometimes \"object-oriented\" languages can have success adopting the features and philosophies of \"functional\" programming languages and vice-versa. But certainly not all programming language features and philosophies are compatible. For example, a functional language like OCaml accomplishes encapsulation through lexical scoping and closures, whereas a object-oriented languages use public/private access modifiers. These are not incompatible mechanisms per-se, but they are redundant, and a language like F# (a mostly functional language which seeks to live in harmony with the decidedly object-oriented .NET library and language stack) has to go to lengths to bridge the gap.As another example, OCaml uses a structural type system for object-orientation, whereas most object-oriented languages use a nominal type system. These are pretty-much incompatible, and interestingly represent incompatibility within the realm of object-oriented languages. The idea of objects can be implemented in an immutable fashion. An example is the book \"\", by Abadi and Cardelli, that aims at formalizing these ideas, and where objects are first given immutable semantics because that makes reasoning about object-oriented programs simpler.In this case, a method that would traditionally have modified the object in-place instead returns a new object, while the previous object persists.You can implement functions as objects and objects as collections of functions, so there is clearly some relationship between the two concepts.You are talking about  functional programming.There is no requirement for objects to be mutable. I would say that objects and mutation were orthogonal concepts. For example, the OCaml programming language provides a syntax for purely functional object update.Not really. The lack of tail call optimization means that the majority of idiomatic purely functional code will stack overflow in Scala because it leaks stack frames. For example,  (CPS) and all of the techniques described in the paper  by Bruce McAdam. There is no easy way to fix that because the JVM itself is incapable of tail call optimization.Regarding the orthogonality of purely functional programming and object oriented programming, I would say that they are at least close to being orthogonal simply because purely functional programming deals only with programs in the small (e.g. higher order functions) whereas object oriented programming deals with the large-scale structuring of programs. This is why functional programming languages usually provide some other mechanism for large-scale structuring, e.g. the higher-order module systems of Standard ML and OCaml, or CLOS for Common Lisp or typeclasses for Haskell.One thing that helped me understand the relationship between FP and OO was the SICP book, particularly the section  If you are thinking about these issues and you have a spare weekend, it might be worth reading through the first three chapters, its pretty eye opening.Orthogonal. It sounds good. If you got an education you can band it about a bit and pretend. Its a bit like paradigm. It all depends in which circles you travel in and what each type of programming technique will give you. I have read a few posts on SS and most who come from a functional programming language usual persist on the fact that you can only go functional and anything else goes against the thinking and the mind set. Object Oriented programming is mainly about capturing state and keeping this state as localised as possible as not to be affected by anything that is not part of the object that you manage the state with. On the other hand, functional programming looks at the problem of state from a different perspective and tries to separate state from the system and reduce it down to functions. Yes you can use both techniques in your code but they both are looking at the design of software from different angles. There has been a great deal of interest in the techniques of Functional Programming, mainly because of the management required of state when dealing with multi-core chips and parallel programming. It seems at this point in time that functional programming does have the upper hand in dealing with this however you can achieve the same effect using Objects. You just think of the problem differently. Instead of scratching you head, trying to get rid of state as much as possible, you look at objects in the design and see how you can pair them down to what the core of what they are expected to do, using design patterns, CRC and Object Analysis. Where Objects do come into there own though, and where functional programming is a lot more difficult is in analysing the real world and mapping it to an understandable computerised system. In OO for example, a person object would be an encapsulation of state with methods that act upon the persons state. In Functional programming, a person would be broken down into data parts and functions that act upon the person data, with the added proviso that data should be created once and only once and be immutable.I must admit though coming from an OO background, that in most OO languages when dealing with Multi-core chips, I have gone the functional route, mainly by core programming design  structures (such as threads and delegates) and pass pseudo data objects around. This has led me to question the techniques of OO programming as it does not seem to map well to this threaded design. "},
Scala

Suppose I have a method  but you don't know whether it will return you a string or a null, because it comes from Java. Is there an easier way to treat this in Scala instead of  ? Maybe some magic apply like  and then I can treat it in Scala way like The  companion object's  method serves as a conversion function from nullable references:The  object has an method that does exactly that:"},
Scala

When asked about Dependency Injection in Scala, quite a lot of answers point to the using the Reader Monad, either the one from Scalaz or just rolling your own. There are a number of very clear articles describing the basics of the approach (e.g. , ), but I didn't manage to find a more complete example, and I fail to see the advantages of that approach over e.g. a more traditional \"manual\" DI (see ). Most probably I'm missing some important point, hence the question.Just as an example, let's imagine we have these classes:Here I'm modelling things using classes and constructor parameters, which plays very nicely with \"traditional\" DI approaches, however this design has a couple of good sides:How could this be modelled with the Reader monad? It would be good to retain the characteristics above, so that it is clear what kind of dependencies each functionality needs, and hide dependencies of one functionality from another. Note that using es is more of an implementation detail; maybe the \"correct\" solution using the Reader monad would use something else.I did find a  which suggests either:However, apart from being (but that's subjective) a bit too complex as for such a simple thing, in all of these solutions e.g. the  method (which calls , which calls  to find the inactive users) would need to know about the  dependency, to be able to properly call the nested functions - or am I wrong?In what aspects would using the Reader Monad for such a \"business application\" be better than just using constructor parameters? I'm not sure if this  be modelled with the Reader, yet it can be by:Just right before the start I need to tell you about small sample code adjustments that I felt beneficial for this answer.\nFirst change is about  method. I let it return  so the list of addresses can be used\nin  method. I've also added simple implementations to methods. Finally, the sample will use a \nfollowing hand-rolled version of Reader monad:Maybe that's optional, I'm not sure, but later it makes the for comprehension look better.\nNote, that resulting function is curried. It also takes former constructor argument(s) as their first parameter (parameter list).\nThat waybecomesKeep in mind that each of , ,  types can be completely arbitrary: a tuple, a function or a simple type.Here's the sample code after the initial adjustments, transformed into functions:One thing to notice here is that particular functions don't depend on the whole objects, but only on the directly used parts.\nWhere in OOP version  instance would call  here it just calls \n- a function passed to it in the first parameter.Please note, that the code exhibits the three desirable properties from the question:Reader monad lets you only compose functions that all depend on the same type. This is often not a case. In our example\n depends on  and  on . To solve that problem\none could introduce a new type (often referred to as Config) that contains all of the dependencies, then change \nthe functions so they all depend on it and only take from it the relevant data. \nThat obviously is wrong from dependency management perspective because that way you make these functions also dependent \non types that they shouldn't know about in the first place.Fortunately it turns out, that there exist a way to make the function work with  even if it accepts only some part of it as a parameter.\nIt's a method called , defined in Reader. It needs to be provided with a way to extract the relevant part from the .This knowledge applied to the example at hand would look like that:I hope that by preparing this answer I made it easier to judge for yourself in what aspects would it beat plain constructors.\nYet if I were to enumerate these, here's my list. Disclaimer: I have OOP background and I may not appreciate Reader and Kleisli \nfully as I don't use them.I would also like to tell what I don't like in Reader.You want. You technically  avoid that, but just look what would happen if I didn't convert  class to object. The respective line of for comprehension would look like:which is not that readable, is that? The point is that Reader operates on functions, so if you don't have them already, you need to construct them inline, which often isn't that pretty.I think the main difference is that in your example you are injecting all dependencies when objects are instantiated. The Reader monad basically builds a more and more complex functions to call given the dependencies, wich are then returned to the highest layers. In this case, the injection happens when the function is finally called. One immediate advantage is flexibility, especially if you can construct your monad once and then want to use it with different injected dependencies. One disadvantage is, as you say, potentially less clarity. In both cases, the intermediate layer only need to know about their immediate dependencies, so they both work as advertised for DI."},
Scala

Lets say I have the following code:How do I fix the last line of this code?  Basically, I just want to do what, in a C-like language would be done:I figured this out myself.  There are two solutions:1) Do the explicit cast:2) Use pattern matching to cast it for you, this also catches errors:"},
Scala

How can I convert an RDD () to a Dataframe . I converted a dataframe to rdd using . After processing it I want it back in dataframe. How can I do this ? has a number of  methods that create a  given an . I imagine one of these will work for your context.For example:Assuming your RDD[row] is called rdd, you can use:Suppose you have a  and you want to do some modification on the fields data by converting it to .To convert back to  from  we need to define the  of the .If the datatype was   then it will become as  in structure.If  then  in structure.Now you can convert the RDD to DataFrame using the  method.  To create a DataFrame from an RDD of Rows, there are two main options: As already pointed out, you could use  which can be imported by . However, this approach only works for the following types of RDDs:(source:  of the  object)The last signature actually means that it can work for an RDD of tuples or an RDD of case classes (because tuples and case classes are subclasses of ).So, to use this approach for an , you have to map it to an . This can be done by mapping each row to a custom case class or to a tuple, as in the following code snippets:orThe main drawback of this approach (in my opinion) is that you have to explicitly set the schema of the resulting DataFrame in the map function, column by column. Maybe this can be done programatically if you don't know the schema in advance, but things can get a little messy there. So, alternatively, there is another option: You can use  as in the accepted answer, which is available in the  object. Example for converting an RDD of an old DataFrame:Note that there is no need to explicitly set any schema column. We reuse the old DF's schema, which is of  class and can be easily extended. However, this approach sometimes is not possible, and in some cases can be less efficient than the first one.This code works perfectly from Import necessary classesCreate SparkSession ObjectLet's an  to make it Using . Using  and specifying column names. This way requires the input  should be of type .create the schema Now apply both  and  to Here is a simple example of converting your List into Spark RDD and then converting that Spark RDD into Dataframe.Please note that I have used Spark-shell's scala REPL to execute following code, Here sc is an instance of SparkContext which is implicitly available in Spark-shell. Hope it answer your question.Method 1: (Scala)Method 2: (Scala)Method 1: (Python)Method 2: (Python)Extracted the value from the row object and then applied the case class to convert rdd to DFThere are 4 ways to create dataframes.Simple way you can use toDF() method, before apply toDF(), you have to make structured format, than only apply toDF() method. I think this Video will help you  Assuming val spark is a product of a SparkSession.builder...Same steps, but with fewer val declarations:"},
Scala

Suppose I'm doing something like:but I really wanted the  as  (and perhaps transform some other columns).The best I could come up with iswhich is a bit convoluted.I'm coming from R, and I'm used to being able to write, e.g.I'm likely missing something, since there should be a better way to do this in spark/scala...[EDIT: March 2016: thanks for the votes! Though really, this is not the best answer, I think the solutions based on ,  and  put forward by msemelman, Martin Senne and others are simpler and cleaner].I think your approach is ok, recall that a Spark  is an (immutable) RDD of Rows, so we're never really  a column, just creating new  each time with a new schema.Assuming you have an original df with the following schema: And some UDF's defined on one or several columns: Changing column types or even building a new DataFrame from another can be written like this:which yields: This is pretty close to your own solution. Simply, keeping the type changes and other transformations as separate s make the code more readable and re-usable.Since Spark version 1.4 you can apply the cast method with DataType on the column:If you are using sql expressions you can also do:For more info check the docs:\nAs the  operation is available for Spark s (and as I personally do not favour s as proposed by Svend at this point), how aboutto cast to the requested type? As a neat side effect, values not castable / \"convertable\" in that sense, will become .In case you need this as , usewhich is used likethe Scala code most similar to R that I can achieve :Though the length is a little longer than R's.\nNote that the  is a function for R data frame , so Scala is very good enough in expressive power given without using a special function . ( is surprisingly a Array[String] instead of Array[Column], maybe they want it look like Python pandas's dataframe.)To convert the year from string to int, you can add the following option to the csv reader: \"inferSchema\" -> \"true\", see You can use  to make it a little cleaner:So this only really works if your having issues saving to a jdbc driver like sqlserver, but it's really helpful for errors you will run into with syntax and types.the answers suggesting to use cast, FYI, the cast method in spark 1.4.1 is broken.for example, a dataframe with a string column having value \"8182175552014127960\" when casted to bigint has value \"8182175552014128100\"We had to face a lot of issue before finding this bug because we had bigint columns in production.Java code for modifying the datatype of the DataFrame from String to IntegerIt will simply cast the existing(String datatype) to Integer.One can change data type of a column by using cast in spark sql.\ntable name is table and it has two columns only column1 and column2 and column1 data type is to be changed.\nex-spark.sql(\"select cast(column1 as Double) column1NewName,column2 from table\")\nIn the place of double write your data type.This method will drop the old column and create new columns with same values and new datatype. My original datatypes when the DataFrame was created were:-After this I ran following code to change the datatype:-After this my result came out to be:-"},
Scala

Given the following Scala List:How can I get:Since zip can only be used to combine two Lists, I think you would need to iterate/reduce the main List somehow. Not surprisingly, the following doesn't work:Any suggestions one how to do this? I think I'm missing a very simple way to do it. I'm looking for a solution that can take a List of N Lists with M elements each and create a List of M TupleNs. As it turns out it is better for my specific use-case to have a list of lists, rather than a list of tuples, so I am accepting pumpkin's response. It is also the simplest, as it uses a native method.I don't believe it's possible to generate a list of tuples of arbitrary size, but the  does exactly what you need if you don't mind getting a list of lists instead.For future reference.So this piece of code won't answer the needs of the OP, and not only because this is a four year old thread, but it does answer the title question, and perhaps someone may even find it useful.To zip 3 collections:Yes, with .Scala treats all of its different tuple sizes as different classes (, , , ,...,) while they do all inherit from the  trait, that trait doesn't carry enough information to actually use the data values from the different sizes of tuples if they could all be returned by the same function. (And scala's generics aren't powerful enough to handle this case either.)Your best bet is to write overloads of the zip function for all 22 Tuple sizes. A code generator would probably help you with this.I don't believe that's possible without being repetitive. For one simple reason: you can't define the returning type of the function you are asking for.For instance, if your input was List(List(1,2), List(3,4)), then the return type would be List[Tuple2[Int]]. If it had three elements, the return type would be List[Tuple3[Int]], and so on.You could return List[AnyRef], or even List[Product], and then make a bunch of cases, one for each condition.As for general List transposition, this works: does the trick. A possible algorithm is:For example:The answer is truncated to the size of the shortest list in the input.If you don't want to go down the applicative scalaz/cats/(insert your favourite functional lib here) route, pattern matching is the way to go, although the  syntax is a bit awkward with nesting, so let's change it:The  is an arbitrary choice here, anything that looks nice infix should do it. You'll likely get a few raised eyebrows during code review, though.It should also work with anything you can  (e.g. s) has a operation up to arity 22.With Scalaz:For more than 5:"},
Scala

What's the difference between an   and  method? And does  behave like  or like ? Thanks.(edit)\ni.e. what is the difference (either semantically or in terms of execution) betweenAnd:The method  converts each  of the source RDD into a single element of the result RDD by applying a function.  converts each  of the source RDD into multiple elements of the result (possibly none).Neither,  works on a single element (as ) and produces multiple elements of the result (as ).Yes. please see example 2 of .. its self explanatory.  if we have 100K elements in a particular  partition then we will fire off the function being used by the mapping transformation 100K times when we use .  Conversely, if we use  then we will only call the particular function one time, but we will pass in all 100K records and get back all responses in one function call.Example :Example 1Example 2The above program can also be written using flatMap as follows.Example 2 using flatmap transformation is faster than  since it calls your function once/partition, not once/element.. :  "},
Scala

How do I escape a dollar sign in string interpolation?Just double it"},
Scala

What exactly does  initialize a value to? Is this a typed null? Thanks. is a compile error. For example:What does work is  (note  instead of ). As Chuck says in his answer, this initialises the variable to a default value. From the Scala Language Specification:It initializes  to the default value of the type . For example, the default value of an Int is 0 and the default value of a reference type is null."},
Scala

Is there a way to build tests with SBT without running them?My own use case is to run static analysis on the test code by using a scalac plugin. Another possible use case is to run some or all of the test code using a separate runner than the one built into SBT.Ideally there would be a solution to this problem that applies to any SBT project. For example, Maven has a test-compile command that can be used just to compile the tests without running them. It would be great if SBT had the same thing.Less ideal, but still very helpful, would be solutions that involve modifying the project's build files.Just use the  command. works for compiling your unit tests.To compile integration tests you can use .Another hint to continuously compile on every file change: "},
Scala

In Scala one can write (curried?) functions like thisWhat is the difference between the above  function definition with two parameters lists and functions with multiple parameters in a single parameter list: From a mathematical point of view this is  and  but I can write  and the same will be I know only one difference - this is partially applied functions. But both ways are equivalent for me.Are there any other differences?Strictly speaking, this is not a curried function, but a method with multiple argument lists, although admittedly it looks like a function.As you said, the multiple arguments lists allow the method to be used in the place of a partially applied function. (Sorry for the generally silly examples I use)Another benefit is that you can use curly braces instead of parenthesis which looks nice if the second argument list consists of a single function, or thunk. E.g.versusOr for the thunk:Another advantage is, you can refer to arguments of a previous argument list for defining default argument values (although you could also say it's a disadvantage that you cannot do that in single list :)Finally, there are three other application in an answer to related post  . I will just copy them here, but the credit goes to Knut Arne Vedaa, Kevin Wright, and extempore.First: you can have multiple var args:...which would not be possible in a single argument list.Second, it aids the type inference:And last, this is the only way you can have implicit and non implicit args, as  is a modifier for a whole argument list:There's another difference that was not covered by 0__'s excellent : default parameters. A parameter from one parameter list can be used when computing the default in another parameter list, but not in the same one. For example:That's the whole point, is that the curried and uncurried forms are equivalent! As others have pointed out, one or the other form can be  more convenient to work with depending on the situation, and that is the only reason to prefer one over the other.It's important to understand that even if Scala didn't have special syntax for declaring curried functions, you could still construct them; this is just a mathematical inevitability once you have the ability to create functions which return functions. To demonstrate this, imagine that the  syntax didn't exist. Then you could still achieve the exact same thing like so: . Like many features in Scala, this is just a syntactic convenience for doing something that would be possible anyway, but with slightly more verbosity.The two forms are isomorphic. The main difference is that curried functions are easier to apply partially, while non-curried functions have slightly nicer syntax, at least in Scala."},
Scala

What are package objects, not so much the concept but their usage?I've tried to get an example working and the only form I got to work was as follows:Observations I've made so far are:is disallowed (which is reasonable),is also disallowed.It seems that a package object must be declared in the immediate parent package and, if written as above, the brace delimited package declaration form is required.Are they in common use? If so, how?Normally you would put your package object in a separate file called  in the package that it corresponds to. You can also use the nested package syntax but that is quite unusual.The main use case for package objects is when you need definitions in various places inside your package as well as outside the package when you use the API defined by the package. Here is an example:Now the definitions inside that package object are available inside the whole package . Furthermore the definitions get imported when someone outside of that package imports .This way you can prevent to require the API client to issue additional imports to use your library effectively - e.g. in scala-swing you need to writeto have all the goodness like  and implicit conversions from  to .While Moritz's answer is spot on, one additional thing to note is that package objects are objects.  Among other things, this means you can build them up from traits, using mix-in inheritance.  Moritz's example could be written as Here Versioning is an abstract trait, which says that the package object must have a \"version\" method, while JodaAliases and JavaAliases are concrete traits containing handy type aliases.   All of these traits can be reused by many different package objects.You could do worse than to go straight to the source. :)"},
Scala

I'm new to Play! Framework 2.1 (java version) and have no experience with scala, so sorry for my noob question. I don't understand what are and what does  and  mean in Build.scala. I googled about them but couldn't find their meaning.In my Build.scala file I have:Why the first line uses a single % symbol and the second one uses two percent symbols ?\nWhat are they for?Thanks for your help!From the official documentation:As you can see above, if you use , you don't have to specify the\nversion.This is part of SBT which play uses as a build tool.  Specifically this is an import statement. The percent symbol  is a actually a method used to build dependencies. The double percent sign  injects the current Scala version - this allows you to get the correct library for the version of scala you are running. This is to avoid having to change your build file when you update Scala. More information "},
Scala

Sorry for the newbie question. I realize that there are several questions on here about  currying and partially applied functions are, but I'm asking about how they are different. As a simple example, here is a curried function for finding even numbers:So you could write the following to use this:which returns: .  But I've found that I can do the same thing this way:which also returns: . So my question is, what's the main difference between the two, and when would you use one over the other? Is this just too simplistic of an example to show why one would be used over the other? Thanks so much for your help.The semantic difference has been explained fairly well in .In terms of functionality, there doesn't seem much of a difference, though. Let's look at some examples to verify that. First, a normal function:So we get a partially applied  that takes an , because we've already given it the first integer. So far so good. Now to currying:With this notation, you'd naively expect the following to work:So the  notation doesn't really seem to create a curried function right away (assumingly to avoid unnecessary overhead) but waits for you to explicitly state that you want it curried (the notation has some  as well):Which is exactly the same thing we got before, so no difference here, except for notation. Another example:This demonstrates how partially applying a \"normal\" function results in a function that takes all parameters, whereas partially applying a function with multiple parameter lists creates a chain of functions,  which, all return a new function:As you can see, because the first parameter list of  has two parameters, the first function in the curried chain has two parameters. In summary, partially applied functions aren't really different form curried functions in terms of functionality. This is easily verified given that you can convert any function to a curried one: The reason that your example  works without the underscore after  seems to be that the Scala compiler simply assumes that underscore as a convenience for the programmer. As @asflierl has correctly pointed out, Scala doesn't seem to be able to infer the type when partially applying \"normal\" functions:Whereas that information is available for functions written using multiple parameter list notation: shows how this can be very useful.Currying is to do with tuples: . Remembering this is the key to distinguishing curry vs partial application, even in languages that don't cleanly support currying.Partial application is the ability to .It is easy to remember if you just think currying is the transformation to do with tuples.In languages that are curried by default (such as Haskell) the difference is clear -- you have to actually do something to pass arguments in a tuple. But most other languages, including Scala, are uncurried by default -- all args are passed as tuples, so curry/uncurry is far less useful, and less obvious. And people even end up thinking that partial application and currying are the same thing -- just because they can't represent curried functions easily!Multivariable function:Currying (or the curried function):So it's not partially applied function that's comparable to currying. It's the multivariable function.\nWhat's comparable to partially applied function is the invocation result of a curried function, which is a function with the same parameter list that the partially applied function has.Just to clarify on the last point Scala can infer types if all parameters are wildcards but not when some of them are specified and some of them not."},
Scala

I am trying to avoid constructs like this:Ok, in this example the  and  branch are simple, but you can image complex ones.\nI built the following:Defined that, I can replace the above simple example with:But how can I get rid of the ? I want something like that:I guess the compiler needs the extra stuff to infer types.We can combine  with the answer to  to getIs this adequate for your needs?From :I hear this question a lot. Yes it does. Instead of , it is written .This may not be preferable. Perhaps you\u2019d like to write it using the same syntax as Java. Sadly, you can\u2019t. This is because  is not a valid identifier. Fear not,  is! Would you settle for this?Then you\u2019ll need the following code. Notice the call-by-name () annotations on the arguments. This evaluation strategy is required to correctly rewrite Java\u2019s ternary operator. This cannot be done in Java itself.Here is an example using the new operator that we just defined:Have fun ;) expressed in basic Scala:although I\u2019m not sure what part of the if\u2013else construct you want to optimise.Since : by itself won't be a valid operator unless you are ok with always escaping it with back ticks , you could go with another character, e.g. \"|\" as in one of the answers above. But how about elvis with a goatee ?::Of course this again won't work if you values are lists, since they have :: operator themselves."},
Scala

I think there is  annotation to ensure the compiler will optimize a tail recursive function. Do you just put it in front of the declaration? Does it also work if Scala is used in scripting mode (for instance using  under REPL)?From the \"\" blog post:Example:And it works from the REPL (example from the ):The Scala compiler will automatically optimize any truly tail-recursive method.  If you annotate a method that you believe is tail-recursive with the  annotation, then the compiler will warn you if the method is actually not tail-recursive.  This makes the  annotation a good idea, both to ensure that a method is currently optimizable and that it remains optimizable as it is modified.Note that Scala does not consider a method to be tail-recursive if it can be overridden.  Thus the method must either be private, final, on an object (as opposed to a class or trait), or inside another method to be optimized.  The annotation is . It triggers a compiler error if the method can't be tail call optimized, which happens if:It is placed just before the  in a method definition. It works in the REPL.Here we import the annotation, and try to mark a method as .Oops! The last invocation is , not ! Let's reformulate the method:Note that  is automatically private because it is defined in the scope of another method."},
Scala

I have this Scala method with below error. Cannot convert into a Scala list.type mismatch; found :  required: \n  will do implicit conversion for you; e.g.:You can simply convert the List using Scala's :"},
Scala

I just read and enjoyed . However, to my mind, one of the key reasons to use dependency injection is that you can vary the components being used by either an XML file or command-line arguments.How is that aspect of DI handled with the Cake pattern? The examples I've seen all involve mixing traits in statically.Since mixing in traits is done statically in Scala, if you want to vary the traits mixed in to an object, create different objects based on some condition. Let's take a canonical cake pattern example.  Your modules are defined as traits, and your application is constructed as a simple Object with a bunch of functionality mixed inNow all of those modules have nice self-type declarations which define their inter-module dependencies, so that line only compiles if your all inter-module dependencies exist, are unique, and well-typed.  In particular, the Persistence module has a self-type which says that anything implementing Persistence must also implement DataSource, an abstract module trait.  Since ProductionDataSource inherits from DataSource, everything's great, and that application construction line compiles.  But what if you want to use a different DataSource, pointing at some local database for testing purposes?  Assume further that you can't just reuse ProductionDataSource with different configuration parameters, loaded from some properties file.   What you would do in that case is define a new trait TestDataSource which extends DataSource, and mix it in instead.  You could even do so dynamically based on a command line flag.Now that looks a bit more verbose than we would like, particularly if your application needs to vary its construction on multiple axes.  On the plus side, you usually you only have one chunk of conditional construction logic like that in an application (or at worst once per identifiable component lifecycle), so at least the pain is minimized and fenced off from the rest of your logic.  Scala is also a script language. So your configuration XML can be a Scala script. It is type-safe and not-a-different-language.Simply look at startup:is not so different than:You can always use DI, but you have one more tool.The short answer is that Scala doesn't currently have any built-in support for dynamic mixins.I am working on the autoproxy-plugin to support this, although it's currently on hold until the 2.9 release, when the compiler will have new features making it a much easier task.In the meantime, the best way to achieve almost exactly the same functionality is by implementing your dynamically added behavior as a wrapper class, then adding an implicit conversion back to the wrapped member.Until the AutoProxy plugin becomes available, one way to achieve the effect is to use delegation:But beware, the downside of this is that it's more verbose, and you have to be careful about the initialization order if you use s inside a trait. Another downside is that if there are path dependent types within  above, you won't be able to use delegation that easily.But if there is a large number of different implementations that can be varied, it will probably cost you less code than listing cases with all possible combinations.Lift has something along those lines built in. It's mostly in scala code, but you have some runtime control. "},
Scala

I usually end up trying every combination until it compiles. Can somebody explain what I should use where?I'll disagree with   in one regard. The classes ,  and   classes. But they don't appear as classes in bytecode, because of intrinsic limitations of the JVM.This arises out of the fact that not everything in Java is an object. In addition to objects, there are primitives. All objects in Java are descendant from , but primitives are set apart and, presently, not extensible by a programmer. Note also that primitives have \"operators\", not methods.In Scala, on the other hand, everything  an object, all objects belong to a class, and they interact through methods. The JVM bytecode generated does not reflect this, but that doesn't make them any less so, just as Java has generics, even though the bytecode doesn't have them.So, in Scala, all objects are descendant from , and that includes both what Java considers objects and what Java considers primitives. There's no equivalent in Java because there is no such unification.Everything that is considered a primitive in Java is descendant from  in Scala. Until Scala 2.10.0,  was sealed, and programmers were unable to extend it. It should be interesting to see what will happen with Scala on .Net, since interoperability alone calls for Scala to at least recognize user-defined \"primitives\".Also extending  is , which is equivalent to  (on the JVM at any rate).Up to Scala 2.9.x, a user could not extend  or , nor reference them from Java, but there  other uses they could be put to in Scala. Specifically, type signatures:What each means should be obvious from the class hierarchy. Of note, however, is that  and  will auto-box, but  will not. That is a bit the opposite of what Java does, in that  and  cannot be specified, and  (defined with ) would cause auto-boxing.Starting with Scala 2.10.0, though, the user can extend  or , with the following semantics:PS: In my own view, Java is likely to follow C# in allowing \"struct\" primitives, and maybe typedefs, as parallelism without resorting to them is proving difficult to accomplish with good performance.Seen this?  The text of the page has some java interoperability remarks.\n and  are, I believe, part of the scala  and  (in the same way that  is a type, not a class). You cannot use them explicitly from within Java code.Howwever, in Java/Scala interoperation, a method which accepts a Java  will expect a scala  / . "},
Scala

How can I define a function with multiple implicit arguments.They must all go in one parameter list, and this list must be the last one."},
Scala

I know this question has come up many times in different ways. But it is still not clear to me. Is there a way to achieve the following.It's a two step procedure.  First turn foo into a function,  then call tupled on it to make it a function of a tuple.@dave-griffith is dead on.You can also call:If you want to wander into \"way more information than I asked for\" territory, there are also methods built into partially applied functions (and on ) for currying. A few input/output examples:Wherein the curried version is invoked with multiple argument lists:Finally, you can also uncurry/untuple if needed.   has builtins for this: or the one suggested by Dave.\n\nTo respond to your comment:In that case, this trick won't work.You can write a factory method in the companion object of your class and then obtain the tupled version of its  method using one of the aforementioned techniques.With es you get a companion object with an  method for free, and thus this technique is more convenient to use with es.I know that's a lot of code duplication but alas... we don't have macros (yet)! ;)I appreciate some of the other answers which were closer to what you asked for, but I found it easier for a current project to add another function which converts tuple parameters into the split parameters:Now, you can implement foo and make it take a param of the Tuple2 class like so."},
Scala

I have a list of simple scala case class instances and I want to print them in predictable, lexicographical order using , but receive \"No implicit Ordering defined for ...\".Is there exist an implicit that provides lexicographical ordering for case classes?Is there simple idiomatic way to mix-in lexicographical ordering into case class?I am not happy with a 'hack':My personal favorite method is to make use of the provided implicit ordering for Tuples, as it is clear, concise, and correct:This works because the  defines an implicit conversion from  to  which is in scope for any class implementing . The existence of implicit s for s enables a conversion from  to  provided an implicit  exists for all elements  of the tuple, which should always be the case because it makes no sense to sort on a data type with no .The implicit ordering for Tuples is your go-to for any sorting scenario involving a composite sort key:As this answer has proven popular I would like to expand on it, noting that a solution resembling the following could under some circumstances be considered enterprise-grade\u2122:Given ,  will sort by name, and  will sort by id. This has a few benefits:This has the benefit that it is updated automatically whenever A changes. But, A's fields need to be placed in the order by which the ordering will use them.To summarize, there are three ways to do this: Answering your question There is a set of , e.g. for String, tuples up to 9 arity and so on.No such thing exists for case classes, since it is not easy thing to roll off, given that field names are not known a-priori (at least without macros magic) and you can't access case class fields in a way other than by name/using product iterator.The sortBy method would be one typical way of doing this, eg (sort on  field):Since you used a  you could extend with  like such:The  method of the companion object provides a conversion from your case class to an , where the  is the tuple corresponding to the first argument list of the case class. In other words:"},
Scala

How to convert Scala's  into Java's ?Scala List and Java List are two different beasts, because the former is immutable and the latter is mutable. So, to get from one to another, you first have to convert the Scala List into a mutable collection.On Scala 2.7:From Scala 2.8 onwards:However,  in that example is not necessary if the type expected is a Java , as the conversion is implicit, as demonstrated by the last line.Not sure why this hasn't been mentioned before but I think the most intuitive way is to invoke the  decorator method of  directly on the Scala list:Assuming we have the following :If you want to be  and  what you want to convert:If you  and let compiler make  work for you:It's up to you how you want to control your code.with scala 2.9.2:resultPretty old questions, though I will answer, given but most of suggestions are deprecated.  For single invocations, doing it by hand might be the simplest solution:I didn't measure performance. Just doing as proposed above produces immutable list even on Java side.\nThe only working solution I've found is this:Since Scala 2.12.0 So the simplest solution for me was :"},
Scala

I've been doing dev in F# for a while and I like it.  However one buzzword I know doesn't exist in F# is higher-kinded types.  I've read material on higher-kinded types, and I think I understand their definition.  I'm just not sure why they're useful.  Can someone provide some examples of what higher-kinded types make easy in Scala or Haskell, that require workarounds in F#?  Also for these examples, what would the workarounds be without higher-kinded types (or vice-versa in F#)?  Maybe I'm just so used to working around it that I don't notice the absence of that feature.(I think) I get that instead of  or  higher kinded types allow you to simply write  and it'll return a .  That's great (assuming it's correct), but seems kind of petty?  (And couldn't it be done simply by allowing function overloading?)  I usually convert to  anyway and then I can convert to whatever I want afterwards.  Again, maybe I'm just too used to working around it. But is there any example where higher-kinded types  saves you either in keystrokes or in type safety?So the kind of a type is its simple type. For instance  has kind  which means it's a base type and can be instantiated by values. By some loose definition of higher-kinded type (and I'm not sure where F# draws the line, so let's just include it)  are a great example of a higher-kinded type.The type constructor  has kind  which means that it must be passed a concrete type in order to result in a concrete type:  can have inhabitants like  but  itself cannot.I'm going to assume that the benefits of polymorphic containers are obvious, but more useful kind  types exist than just the containers. For instance, the relationsor parsersboth also have kind .We can take this further in Haskell, however, by having types with even higher-order kinds. For instance we could look for a type with kind . A simple example of this might be  which tries to fill a container of kind .This is useful for characterizing s in Haskell, for instance, as they can always be divided into their shape and contents.As another example, let's consider a tree that's parameterized on the kind of branch it has. For instance, a normal tree might beBut we can see that the branch type contains a  of s and so we can extract that piece out of the type parametricallyThis  type constructor has kind . We can use it to make interesting other variations like a Or pathological ones like a Or a Another place this shows up is in \"algebras of functors\". If we drop a few layers of abstractness this might be better considered as a fold, such as . Algebras are parameterized over the  and the . The  has kind  and the carrier kind  so altogetherhas kind .  useful because of its relation to datatypes and recursion schemes built atop them.Finally, though they're theoretically possible, I've never see an  higher-kinded type constructor. We sometimes see functions of that type such as , but I think you'll have to dig into type prolog or dependently typed literature to see that level of complexity in types.Consider the  type class in Haskell, where  is a higher-kinded type variable:What this type signature says is that fmap changes the type parameter of an  from  to , but leaves  as it was.  So if you use  over a list you get a list, if you use it over a parser you get a parser, and so on.  And these are , compile-time guarantees.I don't know F#, but let's consider what happens if we try to express the  abstraction in a language like Java or C#, with inheritance and generics, but no higher-kinded generics.  First try:The problem with this first try is that an implementation of the interface is allowed to return  class that implements .  Somebody could write a  whose  method returns a different kind of collection, or even something else that's not a collection at all but is still a .  Also, when you use the  method you can't invoke any subtype-specific methods on the result unless you downcast it to the type that you're actually expecting.  So we have two problems:There are other, more complicated ways you can try, but none of them really works.  For example, you could try augment the first try by defining subtypes of  that restrict the result type:This helps to forbid implementers of those narrower interfaces from returning the wrong type of  from the  method, but since there is no limit to how many  implementations you can have, there is no limit to how many narrower interfaces you'll need.( And note that this only works because  appears as the result type, and so the child interfaces can narrow it.  So AFAIK we can't narrow both uses of  in the following interface:In Haskell, with higher-rank type variables, this is .)Yet another try is to use recursive generics to try and have the interface restrict the result type of the subtype to the subtype itself.  Toy example:But this sort of technique (which is rather arcane to your run-of-the-mill OOP developer, heck to your run-of-the-mill functional developer as well) still can't express the desired  constraint either:The problem here is this doesn't restrict  to have the same  as \u2014so that when you declare a type , the  method can  return a .Final try, in Java, using raw types (unparametrized containers):Here  will get instantiated to unparametrized types like just  or .  This guarantees that a  can only return a \u2014but you've abandoned the use of type variables to track the element types of the lists.The heart of the problem here is that languages like Java and C# don't allow type parameters to have parameters.  In Java, if  is a type variable, you can write  and , but not .  Higher-kinded types remove this restriction, so that you could have something like this (not fully thought out):And addressing this bit in particular:There are many languages that generalize the idea of the  function this way, by modeling it as if, at heart, mapping is about sequences.  This remark of yours is in that spirit: if you have a type that supports conversion to and from , you get the map operation \"for free\" by reusing .In Haskell, however, the  class is more general than that; it isn't tied to the notion of sequences.  You can implement  for types that have no good mapping to sequences, like  actions, parser combinators, functions, etc.:The concept of \"mapping\" really isn't tied to sequences.  It's best to understand the functor laws:Very informally:This is why you want  to preserve the type\u2014because as soon as you get  operations that produce a different result type, it becomes much, much harder to make guarantees like this.I don't want to repeat information in some excellent answers already here, but there's a key point I'd like to add.You usually don't need higher-kinded types to implement any one particular monad, or functor (or applicative functor, or arrow, or ...). But doing so is mostly missing the point.In general I've found that when people don't see the usefulness of functors/monads/whatevers, it's often because they're thinking of these things . Functor/monad/etc operations really add nothing to any one instance (instead of calling bind, fmap, etc I could just call whatever operations I used to  bind, fmap, etc). What you really want these abstractions for is so you can have code that works generically with  functor/monad/etc.In a context where such generic code is widely used, this means any time you write a new monad instance your type immediately gains access to a large number of useful operations .  the point of seeing monads (and functors, and ...) everywhere; not so that I can use  rather than  and  to implement  (which gains me nothing in itself), but rather so that when I come to need  and  I can re-use the code I originally saw in terms of lists because it's actually monad-generic.But to abstract across a parameterised type like a monad , you need higher-kinded types (as well explained in other answers here).The most-used example of higher-kinded type polymorphism in Haskell is the  interface.  and  are higher-kinded in the same way, so I'll show  in order to show something concise.Now, examine that definition, looking at how the type variable  is used.  You'll see that  can't mean a type that has value.  You can identify values in that type signature because they're arguments to and results of a functions. So the type variables  and  are types that can have values.  So are the type expressions  and .  But not  itself.   is an example of a higher-kinded type variable.  Given that  is the kind of types that can have values,  must have the kind .  That is, it takes a type that can have values, because we know from previous examination that  and  must have values.  And we also know that  and  must have values, so it returns a type that must have values.This makes the  used in the definition of  a higher-kinded type variable.The  and  interfaces add more, but they're compatible. This means that they work on type variables with kind  as well.Working on higher-kinded types introduces an additional level of abstraction - you aren't restricted to just creating abstractions over basic types.  You can also create abstractions over types that modify other types.For a more .NET-specific perspective, I wrote a  about this a while back.  The crux of it is, with higher-kinded types, you could potentially reuse the same LINQ blocks between  and , but without higher-kinded types this is impossible. The closest you could get (I figured out after posting the blog) is to make your own  and  and extended them both from an .  This would allow you to reuse your LINQ blocks if they're denoted , but then it's no longer typesafe because it allows you to mix-and-match  and  within the same block, which while it may sound intriguing to enable this, you'd basically just get some undefined behavior.I wrote a  on how Haskell makes this easy.  (A no-op, really--restricting a block to a certain kind of monad requires code; enabling reuse is the default)."},
Scala

My application does large data arrays processing and needs more memory than JVM gives by default. I know in Java it's specified by \"-Xmx\" option. How do I set SBT up to use particular \"-Xmx\" value to run an application with \"run\" action?Try this: To modify the java options for forked processes you need to specify them in the Build.scala (or whatever you've named your build) like this: This will give you the proper options without modifying JAVA_OPTS globally,  it will put custom JAVA_OPTS in an For  processes it's most convenient to set the config via  or  depending on your sbt version.Since sbt 0.13.6 . Modify  along these lines:You can also create an .sbtopts file in the root of your SBT project using the same syntax as in the /usr/local/etc/sbtopts file. This makes the project self-contained. you could set the options in .sbtconfig for  processes:If you want to set SBT_OPTS only for the current run of sbt you can use  as suggested by Googol Shan. Or you can use the option added in Sbt 12: . This gets unwieldy for longer lists of options, but it might help if you have different projects with different needs.Note that CMSClassUnloadingEnabled in concert with UseConcMarkSweepGC helps keep the PermGen space clean, but depending on what frameworks you use you might have an actual leak on PermGen, which eventually forces a restart. In sbt version 12 onwards there is an option for this:If you run sbt on linux shell, you can use:This is my usually used command to run my sbt project. is deprecated starting with SBT . Instead, I configured these options in  in the following way:There's one way I know of. Set the environment variable JAVA_OPTS.I have not found a way to do this as a command parameter.Use JAVA_OPTS for setting with environment variable. Use -J-X options to sbt for individual options, e.g. -J-Xmx2048 -J-XX:MaxPermSize=512Newer versions of sbt have a \"-mem\" option. The  in our build.sbt as referenced by @iwein above worked for us when we were seeing a java.lang.OutOfMemoryError thrown while running Specs2 tests through sbt.The environment variable is _JAVA_OPTIONS, which needs to be set.\nOnce you set _JAVA_OPTIONS, and when you sbt, sbt will show the message using JAVA_OPTIONS and the values.Alternatively you could set javaOption in the sbt or .scala file\ne.g From sbt shell you could run show javaOptions to see the values that are set.This sets the JVM options for tests. Works also with jvm forking ()."},
Scala

Can you implement a Matrix class and an * operator that will work on two matrices?:and just so people don't say that it's hard, here is the Scala implementation (courtesy of ): I understood that strictly speaking the answer is No: overloading * is not possible without side-effects of defining also a + and others or special tricks. The  describes it best:It'll be perfectly safe with a smart constructor and stored dimensions. Of course there are no natural implementations for the operations  and  (or maybe a diagonal matrix would be fine for the latter).Test it in ghci:Since my  instance is generic, it even works for complex matrices out of the box:Oh, you want to just override the  function without any  stuff. That's possible to o but you'll have to remember that the Haskell standard library has reserved  for use in the  class.Testing in ghci:There. Now if a third module wants to use both the  version of  and the  version of  it'll have to of course import one or the other qualified. But that's just business as usual.I could've done all of this without the  type class but this implementation leaves our new shiny  open for extension in other modules.Alright, there's a lot of confusion about what's happening here floating around, and it's not being helped by the fact that the Haskell term \"class\" does  line up with the OO term \"class\" in any meaningful way. So let's try to make a careful answer. This answer starts with Haskell's module system.In Haskell, when you import a module , it creates a new set of bindings. For each variable  exported by the module , you get a new name . In addition, you may:Furthermore, names may be . For example, if  and  both export the variable , and I import both modules without qualification, then the name  refers to   and . If the name  is never used in the resulting module, this clash is ignored; otherwise, a compiler error asks you to provide more qualification.Finally, if none of your imports mention the module , the following implicit import is added:This imports the  without qualification, with no additional prefix, and without hiding any names. So it defines \"bare\" names and names prefixed by , and nothing more.Here ends the bare basics you need to understand about the module system. Now let's discuss the bare basics you need to understand about typeclasses.A typeclass includes a class name, a list of type variables bound by that class, and a collection of variables with type signatures that refer to the bound variables. Here's an example:The class name is , the bound type variable is , and there is only one variable in the collection, namely , with type signature . This class declares that some types have a binary operation, named , which computes an . Any type may later (even in another module) be declared to be an  of this class: this involves defining the binary operation above, where the bound type variable  is substituted with the type you are creating an instance for. As an example, we might implement this for integers by the instance:Here ends the bare basics you need to understand about typeclasses. We may now answer your question. The only reason the question is tricky is because it falls smack dab on the intersection between two name management techniques: modules and typeclasses. Below I discuss what this means for your specific question.The module  defines a typeclass named , which includes in its collection of variables a variable named . Therefore, we have several options for the name :You might alternately choose to leave the implicit import of , and use a qualified  everywhere you use it. Other solutions are also possible.The main point I want you to take away from this is: . It is just a name defined by the , and all of the tools we have available for namespace control are available.You can implement * as matrix multiplication by defining an instance of Num class for Matrix. But the code won't be type-safe:  * (and other arithmetic operations) on matrices as you define them is not total, because of size mismatch or in case of '/' non-existence of inverse matrices.As for 'the hierarchy is not defined precisely' - there is also  type class, exactly for the cases when only one operation is defined.There are too many things to be 'added', sometimes in rather exotic ways (think of permutation groups). Haskell designers designed to reserve arithmetical operations for different representations of numbers, and use other names for more exotic cases."},
Scala

I have 2 datasets. \nOne is a dataframe with a bunch of data, one column has comments (a string). \nThe other is a list of words.If a comment contains a word in the list, I want to replace the word in the comment with @@@@@ and return the comment in full with the replaced words.Here's some sample data:CommentSample.txtProfanitySample.txtHere's my code so far:It compiles, it runs, but the words are not replaced.\nI don't know how to debug in scala.\nI'm totally new! This is my first project ever!Many thanks for any pointers.\n-MFirst, I think the usecase you describe here won't benefit much from the use of DataFrames - it's simpler to implement using RDDs only (DataFrames are mostly convenient when your transformations can easily be described using SQL, which isn't the case here). So - here's a possible implementation using RDDs. This  the list of profanities isn't too large (i.e. up to ~thousands), so we can collect it into non-distributed memory. If that's not the case, a different approach (involving a join) might be needed.Note that the case-insensitivity and the \"words only\" limitations are implemented in the regex itself: . "},
Scala

How do I \"join\" an iterable of strings by another string in Scala?I want this code to output  (join the elements by \",\").How about  ?A variant exists in which you can specify a prefix and suffix too.See  for an implementation using , which is much more verbose, but perhaps worth looking at for education's sake."},
Scala

I've been programming in Scala for a while and I like it but one thing I'm annoyed by is the time it takes to compile programs.  It's seems like a small thing but with Java I could make small changes to my program, click the run button in netbeans, and BOOM, it's running, and over time compiling in scala seems to consume a lot of time.  I hear that with many large projects a scripting language becomes very important because of the time compiling takes, a need that I didn't see arising when I was using Java.But I'm coming from Java which as I understand it, is faster than any other compiled language, and is fast because of the reasons I switched to Scala(It's a very simple language).  So I wanted to ask, can I make Scala compile faster and will scalac ever be as fast as javac.The Scala compiler is more sophisticated than Java's, providing type inference, implicit conversion, and a much more powerful type system.  These features don't come for free, so I wouldn't expect scalac to ever be as fast as javac.  This reflects a trade-off between the programmer doing the work and the compiler doing the work.That said, compile times have already improved noticeably going from Scala 2.7 to Scala 2.8, and I expect the improvements to continue now that the dust has settled on 2.8.  documents some of the ongoing efforts and ideas to improve the performance of the Scala compiler.There are two aspects to the (lack of) speed for the Scala compiler.You should be aware that Scala compilation takes at least an order of magnitude longer than Java to compile. The reasons for this are as follows:The best way to do Scala is with IDEA and SBT. Set up an elementary SBT project (which it'll do for you, if you like) and run it in automatic compile mode (command ) and when you save your project, SBT will recompile it.You can also use the SBT plug-in for IDEA and attach an SBT action to each of your Run Configurations. The SBT plug-in also gives you an interactive SBT console within IDEA.Either way (SBT running externally or SBT plug-in), SBT stays running and thus all the classes used in building your project get \"warmed up\" and JIT-ed and the start-up overhead is eliminated. Additionally, SBT compiles only source files that need it. It is by far the most efficient way to build Scala programs.The latest revisions of  (Eclipse) are much better atmanaging incremental compilation.See \"\" for more.The other solution is to integrate  - (as illustrated in this ) as a builder in your IDE.But not in  Eclipse though, as  mentions in the comments:Finally, as  reminds me in the comments: also include some kind of \"incremental\" compilation (through ), even though it , and enhanced incremental compilation is in the work for the upcoming 0.9 sbt version.Use  - it is a fast scala compiler that sits as a background task and does not need loading all the time. It can reuse previous compiler instance.I'm not sure if Netbeans scala plugin supports fsc (documentation says so), but I couldn't make it work. Try nightly builds of the plugin.You can use the JRebel plugin which is free for Scala. So you can kind of \"develop in the debugger\" and JRebel would always reload the changed class on the spot. I read some statement somewhere by Martin Odersky himself where he is saying that the searches for implicits (the compiler must make sure there is not more than one single implicit for the same conversion to rule out ambiguities) can keep the compiler busy. So it might be a good idea to handle implicits with care.If it doesn't have to be 100% Scala, but also something similar, you might give  a try.-- OliverI'm sure this will be down-voted, but extremely rapid turn-around is not always conducive to quality or productivity.Take time to think more carefully and execute fewer development micro-cycles. Good Scala code is denser and more essential (i.e., free from incidental details and complexity). It demands more thought and that takes time (at least at first). You can progress well with fewer code / test / debug cycles that are individually a little longer and still improve your productivity and the quality of your work.In short: Seek an optimum working pattern better suited to Scala."},
Scala

One way that has  to deal with double definitions of overloaded methods is to replace overloading with pattern matching:This approach requires that we surrender static type checking on the arguments to . It would be much nicer to be able to writeI can get close with , but it gets ugly fast with more than two types:It looks like a general (elegant, efficient) solution would require defining , , ....  Does anyone know of an alternate solution to achieve the same end? To my knowledge, Scala does not have built-in \"type disjunction\". Also, are the implicit conversions defined above lurking in the standard library somewhere so that I can just import them?Well, in the specific case of , this trick below won't work, as it will not accept mixed types. However, since mixed types wouldn't work with overloading either, this may be what you want.First, declare a class with the types you wish to accept as below:Next, declare  like this:And that's it. You can call  or , and it will work, but try  and it will fail. This could be side-stepped by the client code by creating a , unless, as noted by  below, you make  a  class.It works because  means there's an implicit parameter of type , and because Scala looks inside companion objects of a type to see if there are implicits there to make code asking for that type work.Miles Sabin describes a very nice way to get union type in his recent blog post :He first defines negation of types asusing De Morgan's law this allows him to define union typesWith the following auxiliary constructs you can write union types as follows:Here is the Rex Kerr way to encode union types. Straight and simple! Comment #27 under  excellent blog post by Miles Sabin which provides another way of encoding union types in Scala., a new experimental Scala compiler, supports union types (written ), so you can do exactly what you wanted:It's possible to generalize  as follows:The main drawbacks of this approach are Mitch Blevins   and shows how to generalize it to more than two types, dubbing it the \"stuttering or\".A type class solution is probably the nicest way to go here, using implicits.\nThis is similar to the monoid approach mentioned in the Odersky/Spoon/Venners book:If you then run this in the REPL:I have sort of stumbled on a relatively clean implementation of n-ary union types by combining the notion of type lists with a simplification of , which someone mentions in another answer.Given type  which is contravariant on , by definition given  we can write\n, inverting the ordering of types.Given types , , and , we want to express .\nApplying contravariance, we get . This can in turn\nbe expressed as  in which one of  or  must be a supertype of  or  itself (think about function arguments).I did spend some time trying to combine this idea with an upper bound on member types as seen in the s of , however the implementation of  with type bounds has thus far proved challenging.There is also this :See .You might take a look at , which has something called . I get the impression that this doesn't work well with  statements but that you can simulate matching using higher-order functions. Take a look at , for instance, but note that the \"simulated matching\" part is commented out, maybe because it doesn't quite work yet.Now for some editorializing: I don't think there's anything egregious about defining Either3, Either4, etc. as you describe. This is essentially dual to the standard 22 tuple types built in to Scala. It'd certainly be nice if Scala had built-in disjunctive types, and perhaps some nice syntax for them like .I am thinking that the first class disjoint type is a sealed supertype, with the alternate subtypes, and implicit conversions to/from the desired types of the disjunction to these alternative subtypes.I assume this addresses  - 36 of Miles Sabin's solution, so the first class type that can be employed at the use site, but I didn't test it.One problem is Scala will not employ in case matching context, an implicit conversion from  to  (and  to ), so must define extractors and use  instead of .ADD: I responded to Miles Sabin at his blog as follows. Perhaps there are several improvements over Either:UPDATE: Logical negation of the disjunction for the above pattern follows, and I .ANOTHER UPDATE: Regarding comments 23 and 35 of , here is a way to declare a union type at the use site. Note it is unboxed after the first level, i.e. it has the advantage being , whereas  needs nested boxing and the paradigm in my prior comment 41 was not extensible. In other words, a  is assignable to (i.e. is a subtype of) a .Apparently the Scala compiler has three bugs.3.The get method isn't constrained properly on input type, because the compiler won't allow  in the covariant position. One might argue that is a bug because all we want is evidence, we don't ever access the evidence in the function. And I made the choice not to test for  in the  method, so I wouldn't have to unbox an  in the  in .March 05, 2012: The prior update needs an improvement.  worked correctly with subtyping.My prior update's proposal (for near first-class union type) broke subtyping.The problem is that  in  appears in both the covariant (return type) and contravariant (function input, or in this case a return value of function which is a function input) positions, thus substitutions can only be invariant.Note that  is necessary only because we want  in the contravariant position, so that supertypes of   of  nor  (). Since we only need double contravariance, we can achieve equivalent to Miles' solution even if we can discard the  and .So the complete fix is.Note the prior 2 bugs in Scala remain, but the 3rd one is avoided as  is now constrained to be subtype of .We can confirm the subtyping works.I have been thinking that first-class intersection types are very important, both for the , and because instead of  to  which means unboxing with a  on expected types can generate a runtime error, the unboxing of a ( containing a) disjunction can be type checked (Scala has to fix the bugs I noted). Unions are more straightforward than the  the experimental  of  for heterogeneous collections.We\u2019d like a type operator  that can be used to constrain a type parameters  in such a way that either  or . Here's a definition that comes about as close as we can get:Here is how it's used:This uses a few Scala type tricks. The main one is the use of . Given types  and , the Scala compiler provides a class called  (and an implicit object of that class) if and only if the Scala compiler can prove that  is a subtype of . Here\u2019s a simpler example using generalized type constraints that works for some cases:This example works when  an instance of class , a , or has a type that is neither a supertype nor a subtype of  or . In the first two cases, it\u2019s true by the definition of the  keyword that  and , so Scala will provide an implicit object that will be passed in as : the Scala compiler will correctly accept  and . In the last case, I\u2019m relying on the fact that if , then  or . It seems intuitively true, and I\u2019m simply assuming it. It\u2019s clear from this assumption why this simple example fails when  is a supertype or subtype of either  or : for example, in the example above,  is incorrectly accepted and  is incorrectly rejected. Again, what we want is some kind of type expression on the variables , , and  that is true exactly when  or .Scala\u2019s notion of contravariance can help here. Remember the trait ? Because it is contravariant in its type parameter ,  if and only if . That means that we can replace the example above with one that actually will work: That\u2019s because the expression  is true, by the same assumption above, exactly when  or , and by the definition of contravariance, this is true exactly when  or .It\u2019s possible to make things a little more reusable by declaring a parametrizable type  and using it as follows:Scala will now attempt to construct the type  for every  that  is called with, and the type will be constructed precisely when  is a subtype of either  or . That works, and there is a shorthand notation. The syntax below is equivalent (except that  must now be referenced in the method body as  rather than simply ) and uses  as a :What we\u2019d really like is a flexible way to create a type context bound. A type context must be a parametrizable type, and we want a parametrizable way to create one. That sounds like we\u2019re trying to curry functions on types just like we curry functions on values. In other words, we\u2019d like something like the following:That\u2019s  in Scala, but there is a trick we can use to get pretty close. That brings us to the definition of  above:Here we use  and Scala\u2019s  to create a structural type  that is guaranteed to have one internal type. This is a strange beast. To give some context, the function  must be called with subclasses of  that have a type  defined in them:Using the pound operator allows us to refer to the inner type , and using  for the type operator , we arrive at our original definition of :We can use the fact that function types are contravariant in their first type parameter in order to avoid defining the trait :There is another way which is slightly easier to understand if you do not grok Curry-Howard:I use similar Well, that's all very clever, but I'm pretty sure you know already that the answers to your leading questions are various varieties of \"No\".  Scala handles overloading differently and, it must be admitted, somewhat less elegantly than you describe.  Some of that's due to Java interoperability,  some of that is due to not wanting to hit edged cases of the type inferencing algorithm, and some of that's due to it simply not being Haskell.  Adding to the already great answers here. Here's a gist that builds on Miles Sabin union types (and Josh's ideas) but also makes them recursively defined, so you can have >2 types in the union ()NB: I should add that after playing around with the above for a project, I ended up going back to plain-old-sum-types (i.e. sealed trait with subclasses). Miles Sabin union types are great for restricting the type parameter, but if you need to return a union type then it doesn't offer much.From , with the addition of :Regarding the  part:"},
Scala

What are the hidden features of Scala that every Scala developer should be aware of?One hidden feature per answer, please.Okay, I had to add one more.  Every  object in Scala has an extractor (see answer from oxbox_lakes above) that gives you access to the match groups.  So you can do something like:The second line looks confusing if you're not used to using pattern matching and extractors.  Whenever you define a  or , what comes after the keyword is not simply an identifier but rather a pattern.  That's why this works:The right hand expression creates a  which can match the pattern .Most of the time your patterns use extractors that are members of singleton objects.  For example, if you write a pattern likethen you're implicitly calling the extractor .But you can also use class instances in patterns, and that is what's happening here.  The val regex is an instance of , and when you use it in a pattern, you're implicitly calling  ( versus  is beyond the scope of this answer), which extracts the match groups into a , the elements of which are assigned in order to the variables year, month, and day. type definitions - i.e. a type described by what methods it supports. For example:Notice that the  of the parameter  is not defined other than it has a  methodWithout this feature you can, for example, express the idea of mapping a function over a list to return another list, or mapping a function over a tree to return another tree. But you can't express this idea  without higher kinds.With higher kinds, you can capture the idea of  that's parameterised with another type. A type constructor that takes one parameter is said to be of kind . For example, . A type constructor that returns another type constructor is said to be of kind . For example, . But in Scala, we have  kinds, so we can have type constructors that are parameterised with other type constructors. So they're of kinds like .For example:Now, if you have a , you can map over lists. If you have a , you can map over trees. But more importantly, if you have  , you can map a function over . which allow you to replace messy  style code with patterns. I know that these are not exactly  but I've been using Scala for a few months without really understanding the power of them. For (a long) example I can replace:With this, which is  clearer in my opinionI have to do a bit of legwork in the background...But the legwork is worth it for the fact that it separates a piece of business logic into a sensible place. I can implement my  methods as follows.. which are a sort of way at getting the type information at runtime, as if Scala had reified types.In scala 2.8 you can have tail-recursive methods by using the package scala.util.control.TailCalls (in fact it's trampolining).An example:Case classes automatically mixin the Product trait, providing untyped, indexed access to the fields without any reflection:This feature also provides a simplified way to alter the output of the  method:It's not exactly hidden, but certainly a under advertised feature: . As a illustration of the use consider the following source:Compiling this with  outputs:Notice , which is a the application of the  present in Predef.scala. will print the syntax tree after some compiler phase. To see the available phases use .This is a great way to learn what is going on behind the scenes. Try with  using the  phase to really feel how useful it is.You can define your own control structures. It's really just functions and objects and some syntactic sugar, but they look and behave like the real thing.For example, the following code defines  and :Now you can do the following: annotation in Scala 2.8:Example:Dunno if this is really hidden, but I find it quite nice.Typeconstructors that take 2 type parameters can be written in infix notationScala 2.8 introduced default and named arguments, which made possible the addition of a new \"copy\" method that Scala adds to case classes.  If you define this:and you want to create a new Foo that's like an existing Foo, only with a different \"n\" value, then you can just say:in scala 2.8 you can add @specialized to your generic classes/methods. This will create special versions of the class for primitive types (extending AnyVal) and save the cost of un-necessary boxing/unboxing :\nYou can select a subset of AnyVals :\nExtending the language. I always wanted to do something like this in Java (couldn't). But in Scala I can have:and then write:and getYou can designate a call-by-name parameter (EDITED: this is different then a lazy parameter!) to a function and it will not be evaluated until used by the function (EDIT: in fact, it will be reevaluated every time it is used).  See  for detailsYou can use  to introduce a local block without causing semicolon inference issues. is defined in \"Predef.scala\" as:Being inline, it does not impose any additional overhead.Output:You can compose structural types with the 'with' keywordFrom The Scala Language Specification:From :Using this you could do something like:Implicit definitions, particularly conversions.For example, assume a function which will format an input string to fit to a size, by replacing the middle of it with \"...\":You can use that with any String, and, of course, use the toString method to convert anything. But you could also write it like this:And then, you could pass classes of other types by doing this:Now you can call that function passing a double:The last argument is implicit, and is being passed automatically because of the implicit de declaration. Furthermore, \"s\" is being  like a String inside sizeBoundedString because there is an implicit conversion from it to String.Implicits of this type are better defined for uncommon types to avoid unexpected conversions. You can also explictly pass a conversion, and it will still be implicitly used inside sizeBoundedString:You can also have multiple implicit arguments, but then you must either pass all of them, or not pass any of them. There is also a shortcut syntax for implicit conversions:This is used exactly the same way.Implicits can have any value. They can be used, for instance, to hide library information. Take the following example, for instance:In this example, calling \"f\" in an Y object will send the log to the default daemon, and on an instance of X to the Daemon X daemon. But calling g on an instance of X will send the log to the explicitly given DefaultDaemon.While this simple example can be re-written with overload and private state, implicits do not require private state, and can be brought into context with imports.Maybe not too hidden, but I think this is useful:This will automatically generate a getter and setter for the field that matches bean convention.Further description at Implicit arguments in closures.A function argument can be marked as implicit just as with methods. Within the scope of the body of the function the implicit parameter is visible and eligible for implicit resolution:Build infinite data structures with Scala's s :\nResult types are dependent on implicit resolution.   This can give you a form of multiple dispatch:Scala allows you to create an anonymous subclass with the body of the class (the constructor) containing statements to initialize the instance of that class. This pattern is very useful when building component-based user interfaces (for example Swing , Vaadin) as it allows to create UI components and declare their properties more concisely.See  for more information.Here is an example of creating a Vaadin button:Suppose you want to use a  that contains a  and a  method, but you only want to use the one for error messages, and keep the good old  for standard output. You could do this:but if  also contains another twelve methods that you would like to import and use, it becomes inconvenient to list them. You could instead try:but this still \"pollutes\" the list of imported members. Enter the \u00fcber-powerful wildcard:and that will do \u2122. method (defined in ) that allow you to define additional function constraints that would be checked during run-time. Imagine that you developing yet another twitter client and you need to limit tweet length up to 140 symbols. Moreover you can't post empty tweet.Now calling post with inappropriate length argument will cause an exception:You can write multiple requirements or even add description to each:Now exceptions are verbose: One more example is .You can perform an action every time requirement fails:Traits with  methods are a feature in Scala that is as not widely advertised as many others. The intend of methods with the  modifier is to do some operations and delegating the call to . Then these traits have to be mixed-in with concrete implementations of their  methods.While my example is really not much more than a poor mans AOP, I used these  much to my liking to build Scala interpreter instances with predefined imports, custom bindings and classpathes. The  made it possible to create my factory along the lines of  and then have useful imports and scope varibles for the users scripts."},
Scala

As i understand it, in Scala, a function may be called eitherFor example, given the following declarations, do we know how the function will be called?Declaration:CallWhat are the rules please?The example you have given only uses call-by-value, so I will give a new, simpler, example that shows the difference.First, let's assume we have a function with a side-effect.  This function prints something out and then returns an .Now we are going to define two function that accept  arguments that are exactly the same except that one takes the argument in a call-by-value style () and the other in a call-by-name style ().Now what happens when we call them with our side-effecting function?So you can see that in the call-by-value version, the side-effect of the passed-in function call () only happened once.  However, in the call-by-name version, the side-effect happened twice.This is because call-by-value functions compute the passed-in expression's value before calling the function, thus the  value is accessed every time.  However, call-by-name functions  the passed-in expression's value every time it is accessed.Here is an example from Martin Odersky:We want to examine the evaluation strategy and determine which one is faster (less steps) in these conditions:call by value: test(2,3) -> 2*2 -> 4\ncall by name:  test(2,3) -> 2*2 -> 4\nHere the result is reached with the same number of steps.call by value: test (7,8) -> 7*7 -> 49\ncall by name: (3+4) (3+4)-> 7*7 ->49\nHere call by value is faster.call by value: test(7,8) -> 7*7 -> 49\ncall by name: 7 *  7 -> 49\nHere call by name is fastercall by value: test(7,2*4) -> test(7, 8) -> 7*7 -> 49\ncall by name: (3+4)(3+4) -> 7*7 ->  49\nThe result is reached within the same steps.  In the case of your example all the parameters will be evaluated  it's called in the function , as you're only defining them .\nIf you want to define your parameters  you should pass a code block:This way the parameter  will not be evaluated  it's called in the function.This  here explains this nicely too.**I will try to explain by a simple use case rather than by just providing an example **Imagine you want to build a  that will Nag you every time since time last you got nagged.**Examine the following implementations: ****In the above implementation the nagger will work only when passing by name \nthe reason is that, when passing by value it will re-used and therefore the value will not be re-evaluated while when passing by name the value will be re-evaluated every time the variables is accessed\n**To iteratate @Ben's point in the above comments, I think it's best to think of \"call-by-name\" as just syntactic sugar. The parser just wraps the expressions in anonymous functions, so that they can be called at a later point, when they are used.In effect, instead of definingand running:You could also write:And run it as follows for the same effect:As i assume, the  function as discuss above pass just the values to the function. According to  It is a Evaluation strategy follow by a Scala that play the important role in function evaluation. But, Make it simple to . its like a pass the function as a argument to the method also know as . When the method access the value of passed parameter, it call the implementation of passed functions. as Below: According to @dhg example, create the method first as: This function contain one  statement and return an integer value. Create the function, who have arguments as a : This function parameter, is define an anonymous function who have return one integer value. In this  contain an definition of function who have  passed arguments but return  value and our  function contain same signature. When we call the function, we pass the function as a argument to . But in the case of  its only pass the integer value to the function. We call the function as below: In this our  method called twice, because when we access the value of  in  method, its call to the defintion of  method. Typically, parameters to functions are by-value parameters; that is, the value of the parameter is determined before it is passed to the function. But what if we need to write a function that accepts as a parameter an expression that we don't want evaluated until it's called within our function? For this circumstance, Scala offers call-by-name parameters.A call-by-name mechanism passes a code block to the callee and each time the callee accesses the parameter, the code block is executed and the value is calculated.Parameters are usually pass by value, which means that they'll be evaluated before being substituted in the function body.You can force a parameter to be call by name by using the double arrow when defining the function.  is invoked when used and  is invoked whenever the statement is encountered. For example:- I have a infinite loop i.e. if you execute this function we will never get  prompt.a  function takes above  method as an argument and it is never used inside its body.On execution of  method we don't find any problem ( we get  prompt back ) as we are no where using the loop function inside  function.a  function takes above  method as a parameter as a result inside function or expression is evaluated before executing outer function there by  function executed recursively and we never get  prompt back.I don't think all the answers here do the correct justification:In call by value the arguments are computed just once:you can see above that all the arguments are evaluated whether needed are not, normally  can be fast but not always like in this case.If the evaluation strategy was  then the decomposition would have been:as you can see above we never needed to evaluate  and hence saved a bit of computation which may be beneficial sometimes.See this:y: => Int is call by name. What is passed as call by name is add(2, 1). This will be evaluated lazily. So output on console will be \"mul\" followed by \"add\", although add seems to be called first. Call by name acts as kind of passing a function pointer.\nNow change from y: => Int to y: Int. Console will show \"add\" followed by \"mul\"! Usual way of evaluation."},
Scala

Let's say I have a case class that represents personas, people on different social networks. Instances of that class are fully immutable, and are held in immutable collections, to be eventually modified by an Akka actor.Now, I have a case class with many fields, and I receive a message that says I must update one of the fields, something like this:Notice I have to specify all fields, even though only one changes. Is there a way to clone existingPersona and replace only one field, without specifying all the fields that don't change? Can I write that as a trait and use it for all my case classes?If Persona was a Map-like instance, it would be easy to do.comes with a  method that is dedicated exactly to this usage:Since 2.8, Scala case classes have a  method that takes advantage of named/default params to work its magic:You can also create a method on  to simplify usage:then"},
Scala

I can see in the API docs for Predef that they're subclasses of a generic function type (From) => To, but that's all it says.  Um, what?  Maybe there's documentation somewhere, but search engines don't handle \"names\" like \"<:<\" very well, so I haven't been able to find it.Follow-up question: when should I use these funky symbols/classes, and why?These are called . They allow you, from within a type-parameterized class or trait, to  one of its type parameters. Here's an example:The implicit argument  is supplied by the compiler, iff  is . You can think of it as a  that  is --the argument itself isn't important, only knowing that it exists. Now I can use it like so:But if I tried use it with a  containing something other than a :You can read that error as \"could not find evidence that Int == String\"... that's as it should be!  is imposing  on the type of  than what  in general requires; namely, you can only invoke  on a . This constraint is enforced at compile-time, which is cool! and  work similarly, but with slight variations: by @retronym is a good explanation of how this sort of thing used to be accomplished and how generalized type constraints make it easier now.To answer your follow-up question, admittedly the example I gave is pretty contrived and not obviously useful. But imagine using it to define something like a  method, which adds up a list of integers. You don't want to allow this method to be invoked on any old , just a . However the  type constructor can't be so constrainted; you still want to be able to have lists of strings, foos, bars, and whatnots. So by placing a generalized type constraint on , you can ensure that  has an additional constraint that it can only be used on a . Essentially you're writing special-case code for certain kinds of lists.Not a complete answer (others have already answered this), I just wanted to note the following, which maybe helps to understand the syntax better: The way you normally use these \"operators\", as for example in pelotom's example:makes use of Scala's alternative .So,  is the same as  (and  is just a class or trait with a fancy-looking name). Note that this syntax also works with \"regular\" classes, for example you can write:like this:It's similar to the two syntaxes for method calls, the \"normal\" with  and  and the operator syntax.Read the other answers to understand what these constructs are. Here is  you should use them. You use them when you need to constrain a method for specific types only.Here is an example. Suppose you want to define a homogeneous Pair, like this:Now you want to add a method , like this:That only works if  is ordered. You could restrict the entire class:But that seems a shame--there could be uses for the class when  isn't ordered. With a type constraint, you can still define the  method:It's ok to instantiate, say, a ,   on it.In the case of , the implementors wanted an  method, even though it doesn't make sense for . By using a type constraint, all is well. You can use  on an , and you can form an  and use it, as long as you don't call  on it. If you try , you get the charming messageIt depends on where they are being used. Most often, when used while declaring types of implicit parameters, they are classes. They can be objects too in rare instances. Finally, they can be operators on  objects. They are defined inside  in the first two cases, though not particularly well documented.They are meant to provide a way to test the relationship between the classes, just like  and  do, in situations when the latter cannot be used.As for the question \"when should I use them?\", the answer is you shouldn't, unless you know you should. :-) : Ok, ok, here are some examples from the library. On , you have:On , you have:You'll find some other examples on the collections."},
Scala

Is there any difference between case object and object in scala?Case classes differ from regular classes in that they get:Pattern matching, equals and hashCode don't matter much for singletons (unless you do something really degenerate), so you're pretty much just getting serialization, a nice , and some methods you probably won't ever use.Here's one difference - case objects extend the  trait, so they can be serialized. Regular objects cannot by default:It's similar with  and  ,we just use  instead of  when there isn't any fields representing additional state information."},
Scala

In , there are two very similar objects  and .  provide a series of implicit methods that convert between a Java collection and the closest corresponding Scala collection, and vice versa. This is done by creating wrappers that implement either the Scala interface and forward the calls to the underlying Java collection, or the Java interface, forwarding the calls to the underlying Scala collection. uses the pimp-my-library pattern to \u201cadd\u201d the  method to the Java collections and the  method to the Scala collections, which return the appropriate wrappers discussed above. It is newer (since version 2.8.1) than  (since 2.8) and makes the conversion between Scala and Java collection explicit. Contrary to what David writes in his answer, I'd recommend you make it a habit to use  as you'll be much less likely to write code that makes a lot of implicit conversions, as you can control the only spot where that will happen: where you write  or .Here's the conversion methods that  provide:To use the conversions directly from Java, though, you're better off calling methods from  directly; e.g.:For anyone landing on this question since Scala 2.12.x,  is now deprecated and  is the preferred method.As explained in the API (http://www.scala-lang.org/api/current/index.html#scala.collection.JavaConversions$),  is a set of implicit conversions that transforms java collections into related scala collection.You can use it with an . When necessary, the compiler will automatically transform the java collection into the right scala type. are a set of decorator (http://www.scala-lang.org/api/current/index.html#scala.collection.JavaConverters$)that helps transform java or scala collections to scala or java collections using  or  methods that will be implicitly added to the collection that you want to transform. In order to use these converters, you need to import :You should prefer  as it's generally easier to use (no need to use  or )."},
Scala

Newbie question of Akka - I'm reading over Akka Essentials, could someone please explain the difference between Akka Stop/Poison Pill vs. Kill ? The book offers just a small explaination \"Kill is synchronous vs. Poison pill is asynchronous.\" But in what way? Does the calling actor thread lock during this time? Are the children actors notified during kill, post-stop envoked, etc? Example uses of one concept vs. the other?Many thanks!Both  and  will terminate the actor and stop the message queue.  They will cause the actor to cease processing messages, send a stop call to all its children, wait for them to terminate, then call its  hook.  All further messages are sent to the dead letters mailbox.The difference is in which messages get processed before this sequence starts.  In the case of the  call, the message currently being processed is completed first, with all others discarded.  When sending a , this is simply another message in the queue, so the sequence will start when the  is received.  All messages that are ahead of it in the queue will be processed first.By contrast, the  message causes the actor to throw an  which gets handled using the normal supervisor mechanism.  So the behaviour here depends on what you've defined in your supervisor strategy. The default is to stop the actor. But the mailbox persists, so when the actor restarts it will still have the old messages except for the one that caused the failure.Also see the 'Stopping an Actor', 'Killing an Actor' section in the docs:And more on supervision strategies:PoisonPill asynchronously stops the actor after it\u2019s done with all messages that were received into mailbox, prior to PoisonPill."},
Scala

I noticed that Scala provide . But I don't get what they do.The  shows that  is a , but how is it different from a normal ?The difference between them is, that a  is executed when it is defined whereas a  is executed when it is accessed the first time.In contrast to a method (defined with ) a  is executed once and then never again. This can be useful when an operation takes long time to complete and when it is not sure if it is later used.Here, when the values  and  are never used, only  unnecessarily wasting resources. If we suppose that  has no side effects and that we do not know how often it is accessed (never, once, thousands of times) it is useless to declare it as  since we don't want to execute it several times.If you want to know how  are implemented, see this .This feature helps not only delaying expensive calculations, but is also useful to construct mutual dependent or cyclic structures. E.g. this leads to an stack overflow:But with lazy vals it works fineAlso  is useful without cyclic dependencies, as in the following code:Accessing  will now throw null pointer exception, because  is not yet initialized.\nThe following, however, works fine:EDIT: the following will also work: This is called an \"early initializer\". See  for more details. A lazy val is most easily understood as a \" def\".Like a def, a lazy val is not evaluated until it is invoked.  But the result is saved so that subsequent invocations return the saved value.  The memoized result takes up space in your data structure, like a val.As others have mentioned, the use cases for a lazy val are to defer expensive computations until they are needed and store their results, and to solve certain circular dependencies between values.Lazy vals are in fact implemented more or less as memoized defs.  You can read about the details of their implementation here:I understand that the answer is given but I wrote a simple example to make it easy to understand for beginners like me:Output of above code is:As it can be seen, x is printed when it's initialized, but y is not printed when it's initialized in same way (I have taken x as var intentionally here - to explain when y gets initialized). Next when y is called, it's initialized as well as value of last 'x' is taken into consideration but not the old one.Hope this helps."},
Scala

I have just started learning scala .I want to print $ using String InterpolationInput is 2.7255 I get output as .You owe 2.73 while i want it as You owe $2.73\nany pointers will be of a great helpJust double itResult: "},
Scala

How does case class work in Scala?Is is some magic that goes behind this..Here is the answer to the question..When we create a case class saywhat is that goes behind this case class?Case classes are special because Scala automatically creates a companion object for them: a singleton object that contains not only an apply method for creating new instances of the case class, but also an unapply method The the method that needs to be implemented by an object in order for it to be an extractor.When u create a case class a extractor method apply and unapply are created in the companion object.For example when u create a case class say Module constructed with a json objectIf your extractor is supposed to only extract a single parameter from a given object, the signature of an unapply method looks like this:This expands as followsNow when we match this everything that has an unapply will always workSo in this scenario the Module.unapply method is called and the module object is passed to this unapply method that checks whether this is the the instance of Module and the case evaluates.}"},
Scala

Given a String, how to get the last word in Scala, assuming words divided by space?Example:Expected output: I would go by a . But keep in mind that other blank chars may be used instead of spaceNah, just kidding. Just do this:Or this:Or this: Or maybe: OrEtc."},
Scala

I want to return the union of two sets in the following way:I get the error \"Cannot resolve symbol ++\". What happened? defines  to mean a function from  to . There is no  method on functions. That's it.You need to specify the type parameter of  if you are using Scala Set:"},
Scala

I am trying to execute the simple wordcount using scala in Spark. But i get these two errors. I am relatively new to scala and am unable to figure it out. The code i am trying to run is,I haven't been able to figure it out. I did check on a few docs for scala syntax but do not understand the issue there. Thanks to balaji, I did solve that issue.Just wrap the spark master URL inside double quotes as its just a string.\nHence it should look like,"},
Scala

I am learning Scala language in university, and as homework for \"Functions as data\" topic, he asked us to write a function plus(x,y) \u2261 x + y without the use of operation +.How do I need to start thinking to solve this task?I am not sure what your professor intended, but a simple way to do it is just to subtract the negative of :You could always make passes through the bits:1) AND X and Y together into a different variable (c):2) Bit shift (c) one bit to the (left/right) depending on your endian. Check for 0 value.3) XOR X and Y together into another variable (d). If step 2 was a zero value, this is your correct answer.If step 2 was not a zero value:4) Repeat 1-3 on (c) and (d).This is very recursive, and it can't handle numbers which approach the limit of an integer, nor can it handle negative numbers without modification. It's not a perfect solution, but at least it's enough to help you start thinking in terms outside of strict mathematics."},
Scala

How to join two lists such that:and result will be Ok. So first you will need to convert first list to map."},
Scala

I am suprised by this error : \nHow should I transform my timestamp string into a TimeStamp object ? Looking for current timestamp here : ?\nI got the value 1485783591 =  30/1/2017  14:39:51   But my java program doesn't : output : why ?? (a subclass of ) uses milliseconds for time while the Unix timestamp counts seconds.  If you have a Unix timestamp you need to multiply it by 1000 (and divide by 1000 to get a Unix timestamp from a Java Date).As the page says, it considers the timestamp to be the number of  since midnight January 1 1970. Just looking at  tells you  expects the number of -seconds. So multiply it by 1000.  is also unlikely to be the type you want to use: it's SQL-specific. Consider  types instead."},
Scala

In the functional programming world, when I want to design an API, i will encounter the word algebra api. \nCould someone please describe, what an algebra is in FP in context of designing API.Which components build an algebra api? Laws, operations, etc..?There is a word primitive, what is a primitive exactly? Please with show me an example. I think what you are referring to is .A common class of ADT is the product type.  As an example, a \"user\" can be described as a combination of \"name\", \"email address\", and \"age\":This is called a \"product\" type because we can count the number of possible distinct Users using multiplication:The other common ADT class is the sum type.  As an example, a user can either be a common user or an adminstrator:This is called the sume type because we can count the number of possible distinct Users using addition:"},
Scala

What does mean this line in java:Thanks.You can get this done in java using any reader. e.g- BufferedReader, FileReader anything like this. If you are using a list use Iterator.  is perhaps an iterable collection of  objects. The code that you've posted accesses the next element in sequence and converts it to an integer.If you can post the surrounding code as well, we could get more context on the same."},
Scala

A detailed information on what does the above statement (the one enclosed in quotes) does in Scala would be greatly appreciated.That is a recursive method that just calls itself. It creates an infinite loop."},
Scala

I can use Array to make the List of the Songs.Because Array supports Random Access.i.e I can play the songs in different index in the same time.In the same way I need the real life examples of List,Tuple,Set and Map.You can use a List to store the steps necessary to cook a chicken, because Lists support sequential access and you can access the steps in order.You can use a Tuple to store the latitude and longitude of your home, because a tuple always has a predefined number of elements (in this specific example, two). The same Tuple type can be used to store the coordinates of other locations.You can use a Set to store passport numbers, because a Set enforces uniqueness among its elements. Passport numbers are always unique and two people can't have the same one.You can use a Map to convert a list of Imperial/US measurements to their Metric (SI) equivalents because a Map takes a list and applies an operation to each member of the list and returns a new list ( )"},
Scala

I understand that RDD is the base of Spark's HighAvailability concept.  In how many different ways we can create this 'RDD' in Spark using Scala.I may be NOT reaching you by asking this question!  But all I wanted to know is what are the methods (or any) result in giving RDD.It is not about an operation/action on RDD is again giving RDD.  I understand that one on the ways is with sc.textFile(\"fileName\")There are 2 waysYou can read their documentation and can practice some exercises described here  (Full disclosure: That is my Spark notes I prepared while learning it myself.)"},
Scala

ouput :\n               List(List('a, 'a, 'a, 'a), List('b, 'b, 'b), List('c, 'c, 'c, \n               'c), List('d), List('e, 'e, 'e), List('f), List('a))Can anyone explain this code how it works.span the list here is the ls parameter and ls.head is the first item of the list\nThe two lists are then assigned to packed (containing the longest prefix) and next which contains the rest. if next is empty the prefix list is returned otherwise there's a recursive call concatenating the prefix list with the result of the recurse"},
Scala

Complier showsi think  the problem is"},
Scala

iam having small problem with my code, i make the code at java and its works but for some reason it wont work in Scala. any idea ?You should break the line after  or use . Otherwise, you are simply calling the member  on  which is of type ."},
Scala

In scala, the following generic type, is replaceable with the polymorphic definitionWhen should we prefer the 1st style and 2nd style? Any scenarios?Consider the following method:Now the precise type of  will be preserved in the return type. In the other style you would always have  as the return type, not something more specific.So basically you need the first style if you need access to the most precise type of  known to the compiler. \nAnother example:"},
Scala

NOTE: I know we can do it in simpleway \nBut i want to know why above code is not workingLet us first start with how will you do this in any other language,JavaJavaScript,And you can do it the more or less same way in Scala with . (Not to be confused with the concept of )If you want to use  then,As for \"why your code does not work ?\". The reason is that you are trying to use for-comprehension without really understanding these, which lead to a very strange looking and incorrect code. in Scala works by using combinations of  /  /  /  in various ways depending on the usage.In this case, the above for-comprehension version is equivalent to the following  based version,"},
Scala

I am doing the first assignment of Big Data Analysis with Scala and Spark on Coursera. I got stuck at implementing the following method:And the List is defined earlier in the program:My understanding is that for each element in the list, I should pass it to the RDD so that it can do the filtering and count the number of occurrence of programming languages appearin the Wikipedia articles. I am thinking to do a for loop / foreach in the RDD to loop over the list. Is it doable? If not, could you suggest what to do in order to achieve the functionality? Here is the snapshot of the problem description: \n My implementation of occurrencesOfLang is as follows:Thank you for help!You are looking for this answer.I tnik you are looking for something like this:     "},
Scala

I have multiples dataframes loaded from csv files i would like to join them based on a column , here what i did .i took just i would like to generelize and make it automatic.The problem it took just two of them not all them .The result is joining two of them\nThanksHere is a solution for the answer"},
Scala

Assume below are directory structures in a list, how to find lowest common ancestor for these.  Below function helped!!"},
Scala

Here is an example of what I mean.I got two multidimensional arrays w and z.\nz is a 3x3 matrix.\nNow I want to controll if z is part of the bigger multidimensional array w.\nLike z= (1,2,3),\n        (1,2,3),\n        (1,2,3)w= (4,7,1,2,3)\n   (7,8,1,2,3)\n   (9,0,1,2,3)\n   (8,1,5,3,6)\n   (4,6,6,6,6)In that case my function would give me a true.\nI know how to acess all elements and single rows and columns.\nCould someone give me a little push in the right direction?\nMy tryHere is the function that return 1 if sub matrix of order 3x3 exist , else returns 0.    "},
Scala

I have a spark (scala) dataframe \"Marketing\" with approx 17 columns with 1 of them as \"Balance\". The data type of this column is Int. I need to find the median Balance. I can do upto arranging it in ascending order, but how to proceed after that? I have a given hint that the percentile function of scala can be used. I don't have any idea about this percentile function. Can anyone help?Median is the same thing as the 50th percentile. If you do not mind using hive functions you can do one of the following:If you do not need an exact figure you can look into using percentile_approx() instead. Documentation for both functions is located ."},
Scala

I am searching in an rdd textfile a word say \"Scala\":Works fine.But:Does not work, It freezes the program without error.It seems to be because of a local variable but can't figure out why.Thanks Jasper-M,worked just fine. But I am very surprised this is not better known at least from all searches I did.I would like in fact to do something like the following (not sure of the syntax) which does not work:But final does't seem to work for a list. I will look more closely at the link provided, but a direct answer would quite ease my pain.Also sorry for my ignorance, but I am interested also in an \"scala\" answer in the fact that I don't see how we can refactor or write a code without passing variables in lambda expression. I am still learning... but I'm curious to see how this list example can be solved.Many thanks,\nEz"},
Scala

Going over a course in Scala. WhIle reading  functions, it says we can convert methods to a function object. Like :Where  is a method. \nMethods exist in a class. Functions are independent objects. I am trying think. Of situations  where a method has to be assigned to a function object. Please believe me. I Googled before I am posting this.\nThanksYou didn't pose an actual question. Is this what you're looking for?The result of all this is, as expected, 3.14....You might find my blog article helpful: .The most complete and understandable post about methods vs functions I ever read was this one: hope it can help you"},
Scala

here iam getting illegal start of statement. plz give me ans why it is "},
Scala

I am reading Scala for the Impatient and now I am on chapter 4, I got a feeling that this book only introduce programming syntax of scala instead of focusing on functional programming paradigm, or what is functional programming.I could be wrong or the author has mixed functional programming syntax in the content but I could not tell because I am 100% new to functional programming.Here is the table of content:It looks like scala is very similar to Java in terms of what it provides and scala has more. But I heard that we could do both object-oriented or functional programming and I want to know what features of scala is functional. I know scala is base on Java.I want to jump to the chapter of this book which is related to scala's functional programming instead of going through all the chapter one by one."},
Scala

I try to compile a scala example in the book: \"Play for Scala\" but get a following compilation error on Play console:sbt start: \n               [info] Compiling 8 Scala sources and 1 Java source to \n                C:\\Users\\karthik.a.arumugam\\kt\\target\\scala-2.10\\classes...\n               [error] \n               C:\\Users\\karthik.a.arumugam\\kt\\conf\\routes:8: \n                 object Products is not a member of package \n                controllers\n                 [error] GET     /prod\n                    controllers.Products.list\n          [error] C:\\Users\\karthik.a.arumugam\\kt\\conf\\routes:8: \n            object Products is not a member of package \n                 controllers\n                     [error] GET     /prod\n                controllers.Products.list\n                     [error] `enter code File: controllers->Products.scalaFile :models->Product.scalaFile: views -> list.scala.htmlFile : views- > main.scala.htmlFile: Routes: \n                   GET     /prod                       controllers.Products.list"},
Scala

trying to pass a dynamic variable based on the input to an object.input : table1getting the below error :Your function  requires parameter of following types\n but you are trying to passIn case of (this is a string) pass a valid  According to your example you need to pass  or  as which table are you reading."},
Scala

Here is what I would like to doThe above is a sort of pseudocode not respecting the Spark API but I think it gives an idea of what should be the outcome, running the aggregations asynchronously in parallel producing a list of Futures and combining the results of each future with df.unionAll to have the result dataframe.Do you have any idea on how to implement that?Thanks"},
Scala

I am trying to define a custom input format to spark's dataframereader object: In PySpark:Spark currently supports csv and a few other file types as an argument to the format function. How can I add another my custom file type to the types of files it can read? Specifically I would like: "},
Scala

I have a class called Piece that have two attributes: x, y and color. These x and y attributes are integers representing indexes in a matrix. So I want to set those coordinates in a decent way.\nThat's the pattern:\n "},
Scala

I want to define a function in Scala in which I can pass my training and test datasets and then it perform a simple machine learning algorithm and returns some statistics. How should do that? What will be the parameters data type?Imagine, you need to define a function which by taking training and test datasets performs a simple classification algorithm and then return the accuracy.What I expect to have is like as follow:I need just the declaration of the functions and not the code that produce the results1, results2, and results3.Thanks.In case you're using supervised learning you should opt for . Excerpt from mllib doc: And example is:"},
Scala

I'm looking for the exact implementation not just references to libraries so I posted the answer by myself. I'm coding in Scala but at first I asked for Java to increase the chance of getting an answer as quickly as possible, so the implementation is in Scala language.Thanks to the comments, here is the Scala implementation which works exactly the same as the above PHP code:It uses bouncycastle which can be added to build.sbt:"},
Scala

When playing with something in Scala, I typically spend a bunch of time trying combinations of dependency versions, Scala versions,  vs , etc. And when it starts working, I am not quite sure why, or for how long...It would be great if someone could explain the Scala ecosystem's way(s) of dealing with versions of sbt, scala, and libraries. Or perhaps point me to some documentation. I struggled with this extensively when i started out. These days i start every project with a boiler-plate  with just scalaVersion and whatever sbt is currently on my machine:Pick the latest 2.10 or 2.11, dependening on your need. Most libraries of note are cross-published into both.Now, as you find libraries you want to use, head over to  and search for them there. Look for a  or  postfix (depending on your version). If it has neither, you are likely fine.Once you find your library and the version you want, mavenrepository even provides you the sbt link you need to use in its  tab like this:And from there you can even explore the dependencies that library will bring along with it. This should cover most of your day to day needs."},
Scala

I have a specific requirement where I have to write few hadoop MR code in scala and then to fire those codes using a web-app and then finally show the results in a web page.Is this possible ?If yes is there any framework which I can make use of ?Regards,RahulYour question is not clear. If you mean Hadoop MR jobs then you should look at   and . How big is your data? You should be able to do MR on normal or Parallel Scala collections if the size of your data it not big. "},
Scala

i am new in Scala and i would like to ask what is the MOST EFFICIENT way to implement this problem. Imagine that we have a stadium, which has X sectors and each sector has Y rows and each row has Z seats. Imagine that we have random number of occupied seats. a) Given a row, return the amount of occupied seats. b) Given a sector, return the amount of occupied seats. c) Given a sector and a row, make sure the chair is vacant x (1 <= x <= n). d) Given a row, returns an array with the positions of the vacant chairs. e) Given a sector, return the row with the greatest amount of vacant chairs. f) Return the amount of occupied stadium chairs. g) Suppose the entrance to the stadium has two values: $ 75.00 for the two closest rows to the field and $ 50.00 for the other rows . Write a function that returns the income of a game. Thank for your solutions in advanceMost efficiently can mean in terms of your effort writing the code or in terms of runtime speed. In the former case, I would use something like a nested . In the latter case, probably a flat  would perform best.Accordingly for three or more dimensions.Unless this is for your exercise, I would use an existing optimised library such as .I think that most efficient way to map s is  it comes in two flavors:  and . Immutable are little bit more efficient, but it's efficiency is disappearing in any concurrent\\distributed situation.\nHere is the implementation :So. If you like to define your stadium like:Income with standard price $50 will be calculated easilyAnd could be increased for first two rows"},
Scala

While reading from InputStream, how do I convert the InputStream to a java/scala object? An example use case being, receive a CSV file as stream and parse the CSV row by row, on the fly.For example: I haveand a sample CSV file's single row is (Andy, Morgan, Male). Now suppose I receive this CSV InputStream and this CSV has millions of rows and can't be held into memory. Is it possible to cast the InputStream to the above mentioned case class, use it for my purpose, discard the instance of this case class and repeat this process for the entire stream.A vague example would be on the lines of:I want to understand the internals, so I'd be very thankful to a solution in native java/scala without any 3rd party libraries.There's actually a Java inputstream called  that you could use for this exact purpose of casting as a class.Of course this assumes that your inputStream is streaming these  objects, otherwise you'd have to go about this differently. If the file is to big to fit in memory to begin with, you may want to consider streaming these  objects rather than to do this on the receiving end.I did, however find this , which seems fairly versatile that has constructors like so (among many others):There is a method to read in by line ( which returns a ) which may help you in converting to the object.Hope this helps!"},
Scala

When I create an Spark context using scala, this trace is shown:I read anything about netty version conflict, but I cannot resolve this topic.This is my set of dependencies:Sorry but I cannot be more verbose because I am totally missing with this topic.If anything knows what happened with this ...I am just initializing an spark context with cassandra support :There was a dependency problem. Avro-Tools jar file was being imported to the project and it caused the ERROR. Thanks to everybody.Had a similar problem but using maven instead of sbt. Since i'm including avro-ipc as one of my dependencies, i need to exclude netty, thus, it looked like this."},
Scala

I have a string  that I need to parse into an associative array like .  What is the best way in Scala to parse this text?Your question is unclear because you ask for, as commented by @heenenee, a map, but show something that is nothing in scala.A very dirty way to have a List or Array of Arrays, as you're showing, would be:(replace toList by toArray if you prefer an array...)"},
Scala

I am using Spark scala API. \nprods_grpd has this type: String, mutable.HashSet[String] val prods_grpd = all_meds.aggregateByKey(initialSet)(addToSet, mergePartitionSets)\nprods_grpd.saveAsTextFile(\"scratch/prods_grpdby_users.tsv\")When I save this rdd, I get this o/p. The first value is key and then I get a set of keys.(8635214,Set(2013-01-01))(3580112,Set(2013-01-01))(146086,Set(2010-01-01, 2012-01-01))(112220,Set(2013-01-01))(2020,Set(2013-01-01))(24218,Set(2013-01-01))However, I want o/p like:(8635214, 2013-01-01)(3580112, 2013-01-01)(146086, 2010-01-01, 2012-01-01)(112220, 2013-01-01)(2020, 2013-01-01)(24218, 2013-01-01)I which like to know how do  I unnest/flatten the 2nd parameter of RDD. You cannot simply convert  to  because tuples are not collections and don't support arbitrary number of elements. Instead you can map entries to strings with desired format:"},
Scala

I want to use the   in an SBT project. I'm on Linux. How can I do that?In your build script you probably need to specify an artifact explicitly for the dependency (the module id parameters are jus):import sbt._\nimport Keys._"},
Scala

I want to implement an async rest via scala dispatch but i get an error, and i don't know why.\nAny ideas?Thanks in advanceCompiler:[error] file.scala:11: not found: object dispatch[error] import dispatch._[error] file.scala:47: not found: value host[error]     val request = host(s)[error]  A friend of mine helped me out, \nthx to anyone who gave it a thought.The problem was, that my intelliJ had the library dependencies in its build.sbt, but not imported.I just imported the lib, and the problem was solved. "},
Scala

I am struggling to join two tables in mongodb.  I understood from google search that there is no joins concept in mongo.  However, we can achieve this by doing map reduce.  I am also new to scala.\nI have two tables in mongodb.I want to combine data from both tables to represent like belowSample Data will beCan anyone please help to add some sample scala code here to achieve this map reduce functionality?I tried this below code which works good, but I have millions of records and finding one by one is timing out.  First fetch userid from user table and then try to find the corresponding roleid.  Instead of querying on scala side, i followed this approach to resolve.This may not the trivial solution, but this is one of the approach suggested forthis kind of issues."},
Scala

I have a scala code snippet given below: is expected to collate all nameToPlaces from all countries.\nHowever, while running this code, i am getting a classcastexception I have tried adding  but of no use. I am also importing \nAny help will be appreciated.NOTE: I don't see this question as a duplicate of a generic classcast exception as noted below: Please revise your judgement.You have several java collections in your outer map, you have to make sure to convert them all. As far as I can see, the following should work for you:"},
Scala

I have problem parsing JSon into RDD{\"data\":\"{\\\"orderID\\\":\\\"3\\\",\\\"products\\\":[{\\\"productID\\\":10028,\\\"category\\\":\\\"342\\\",\\\"name\\\":\\\"Kids Coats\\\",\\\"gender\\\":\\\"Kids\\\",\\\"sport\\\":\\\"Basketball\\\",\\\"color\\\":\\\"Blue\\\",\\\"retailPrice\\\":268.0,\\\"sellPrice\\\":268.0,\\\"sellQuantity\\\":1,\\\"taxablePrice\\\":268.0,\\\"brand\\\":\\\"Inno Fashion\\\",\\\"stockQuantity\\\":999,\\\"subTotal\\\":268.0,\\\"ancesstorCategories\\\":[\\\"2426\\\",\\\"2454\\\",\\\"241\\\",\\\"342\\\",\\\"24\\\",\\\"34\\\",\\\"2439\\\",\\\"21\\\",\\\"3\\\",\\\"2\\\",\\\"1\\\",\\\"2412\\\",\\\"2430\\\",\\\"2503\\\"]},{\\\"productID\\\":10031,\\\"category\\\":\\\"334\\\",\\\"name\\\":\\\"Kids Tshirt\\\",\\\"gender\\\":\\\"Kids\\\",\\\"sport\\\":\\\"Cycling\\\",\\\"color\\\":\\\"Blue\\\",\\\"retailPrice\\\":59.0,\\\"sellPrice\\\":59.0,\\\"sellQuantity\\\":6,\\\"taxablePrice\\\":59.0,\\\"brand\\\":\\\"361 Sports\\\",\\\"stockQuantity\\\":994,\\\"subTotal\\\":354.0,\\\"ancesstorCategories\\\":[\\\"2426\\\",\\\"241\\\",\\\"33\\\",\\\"24\\\",\\\"2429\\\",\\\"334\\\",\\\"2439\\\",\\\"21\\\",\\\"3\\\",\\\"2\\\",\\\"1\\\",\\\"2412\\\",\\\"2503\\\",\\\"2451\\\"]}}When I read this information into RDD,I got an error at line 9, when processing category\nI would like to get the 'ancestorCategories' of JSON into the 'category' or RDD like a list\nList(2426, 2454, 241, 342, 24, 34, 2439, 21, 3, 2, 1, 2412, 2430, 2503)Error: found   : List[org.json4s.JsonAST.JValue]\n[ERROR] [Console$] [error]  required: Array[String]Can anyone help me to convert from List[org.json4s.JsonAST.JValue] to List[String]? \nThank you very much.you could use render to get raw String out of Valuethus you could:I can not run it locally now ,hope it helps.I think this might works , as you can do what ever you can in the x=>{} bolock"},
Scala

I created an  wtih the following format using Scala : How can I get the list of the  from this ?The data for the first data line is:Assuming you have something like this (just paste into a ):then you get the first array usingwhich means the first row (which is a Tuple2), then the 2nd element of the tuple (which is again a Tuple2), then the 1st element.Using pattern matchingIf you want to get it of , just use :which puts the results of all rows into an array.Another option is to use pattern matching in :"},
Scala

I learn Scala programming language and \nI have interest in machine learning.Which ML toolboxes are popular in Scala programming?you can use spark which is part of Hadoop and has a scala API and machine Learning Library (ML LIB).\n"},
Scala

So the problem that I am having is that I don't seem to be able to create a sparkcontext. And I have no idea why not.Here is my code:And here is the result that I am getting:Any thoughts?Your scala version is too new and spark-core version is too old . I am using scala 2.11.8 and spark-core_2.11:2.0.1\uff0cyou can try it!"},
Scala

I'm a complete newbie to Play framework as well as Scala. I'm stuck at the following scenario.My frontend is coded in html. The input from a user and then reads the data in scala using HashMaps. In html, there's a textbox by the id=\"replayZkUrlActual\"Scala Code on calling this page so as to read the text.I get the values correctly and I store the value from the textfield successfully. However, I need to display this value again whenever I click on submit button of my form in the same textbox (kind of autofill the previous value). I need \"replayZkUrlActual\" to display its value after clicking the submit button. \nThe same page opens on clicking the submit button.\nCan anyone please help.\nThanksJust follow these documentation to get rid of it\nI hope it will solve your problem"},
Scala

I am building HTTP service with scala-play. I want to serve the JSON response.\nTo serve JSON response, I created case classes and created instance of Writes[T] class which is similar to followingI can server response like: I followed above approach from play documentation.Why do I need to define class and create Writes[T] instance for  serve JSON response.\nIf I have to create JSON for dozens of classes, do I have to define all classes and create instances for Writes[T]?I can easily convert any class data to JSON with following method:All I need do is create Map[String, String] for any class to serve JSON.Why play documentation recommends to define case class and create instance of Writes[T] to create JSON representation?Is there any other way to serve create JSON in scala? I want to keep response time minimal so that JSON creation must be lightening fast.You don't need to create the Writes instance. Play already have a default formatter for all the regular types (Integer/String/Boolean..)You just need to write the case class and add an implicit formatter in the companion object.See json.scala format[A] description from play:Back to your example, you only need:to get the json text just do:val json = Point.fmtJson.writes(Point(10, 20)).toString()will result: json = {\"X\":10,\"Y\":20}"},
Scala

Env: Spark 1.6, ScalaHi\nI need to run to process parallel. First one, for receiving data and second one for transformation and saving in Hive table. I want to repeat first process with a interval of 1 min and second process with interval of 2 min.  How can I run this two process parallel and with desired interval in Scala?\nThanks\nHossainWrite two separate Spark applications.Then use cron to execute each app per your desired schedule. Alternatively, you can use  for scheduling your Spark apps.Refer to the following question for how to use cron with Spark: "},
Scala

I get an  when I try to compile and package my code with  and Java 1.8.0_112.My code compiles well with Java 7.I tried to set  and tried with 1G as well but always get the same error.The code is written in Scala and I am using these versions in my pom.xml:I tried also with Scala version 2.12.0 because 2.10.x is not compatible with Java 8.part of the error stack: One more thing, stackoverflow error is usually a runtime execution error, how is it possible to get it during compilation ?[Added 1]   I found that this error is caused by scala classes with at least 150 properties [Added 2] The function throwing this error is equals function, i developed it like this: Thank you.I solved the problem by splitting the logical operation in manyThe approach to solve this type of problems is to compile the code gradually till finding the code bloc that throws the errorI hope this will help someone "},
Scala

I am a scala beginner. Now I have to convert some codes I wrote in Pyspark to scala. The codes are just to extract fields for modeling. \nCould someone point out to me how to write the following code into scala? At least where and how I could get the quick answer. Thanks so much!!!Here are my previous codes...It goes like this:There may be a direct method for above logic.Test:"},
Scala

I am creating a Companion Objects, How do i traverse these objects?, i have written but not working, error thrownPlease help hereHow do i traverse these objects?, i have written but not working, error thrownThe declaration of  variable is not correct.That's the correct way to declare a variable in Scala. Or you can just ignore the type and let Scala interpret it."},
Scala

I filter a dataset to get a list of datasets which I then want to persist in parallel.Code:Currently the  runs sequentially. I can convert the  to   but then it won't be using spark for the parallelisation How can I do this with spark?The question is regarding nested parallization in spark. The following link answers it."},
Scala

Im very new to spark... \nI have set up a standalone cluster using 3 centos vms...\nnow i want to develope some simple scala program and run it in the cluster...\nI am working on windows 7 station without network connection...\nI want to use eclis with scala plugin\nI have on this computer:scala.msi sbt.msi spark.gz hadoop.gzwhat do i do next?\ncan somwone please instruct me how to start a new simple project in eclipse and create a scala program i can send to the cluster \ni need a detaild instruction from what type of project to create and what refereces to add and how\nwhat project structure to use and how to set it\nand how to send it to the clustershowing me how to do that with both maven and without maven (so i deceide what best fit for me since i working without internet) will be most helpfullThanksIf you have set up of cluster then for starting point I suggest you to place text file in hdfs of your cluster and use simple app in order to read words and counts them.\nFor built you can use Maven-pom or SBT. In order to have less troubles use  with scala plugin. The dependency would be org.apache.spark:spark-core_2.10:{your_version_of_spark}. After packaging your app launch with required params with --master . More details which parameters can be used I am using IntelliJ and SBT on Windows to build my project but I think the key aspect here is to use a plugin like  for you (jar containing all dependencies except spark). Then all you need is to copy that jar to your CentOS cluster and from there run spark-submit with whatever mode (standalone, yarn, client) you need. See also  and Regarding the use of Maven vs. SBT, my recommendation is use whatever you're familiar with. Personally I find SBT quite concise and easy to use. For your first project just follow the recommendations in www.scala-sbt.org.As you are already have eclipse with scala plugin , then you can start directly creating maven project . The easiest way to go ahead is to download any sample spark maven project (in scala) from github and import in your eclipse as an existing maven project. \nInstead of running the code in cluster, you can run and check in eclipse itself if you provide .setmaster(\"local\") in spark configuration. This way testing and learning will be more easier . \nComing to deploying on cluster, you need to create a jar file out of your project (Right click on project->export as jar) and then copy this on to your cluster . Then use spark-submit to submit spark application by specifying master and other configuration settings . "},
Scala

I cannot find documentation for json4s Scala library.\nI've found  or  but it's not exhaustive doc.\nI would expect complete documentation like Does anyone know where to find it? Google did not help me.\nThanks.You might be looking for this: "},
Scala

I've seen my people stuck on this problem. And so as I. And many people said using sbt. And currently I've already downloaded sbt. But I don't know where the directories are, such as dir \"/src/main/scala\" or dir \n\"/src/test/scala\", could anybody tell me where are the directories? Thanks"},
Scala

I want to setup a Spark-Scala-Sbt dev environment on UbuntuSo i have installed SBT, Scala Seperately before installing IntelliJ.But after installing intelliJ i have installed the  plugin for intelliJ as well.Now how to avoid conflicts between the 2 sbt's which one to use and how to setup properly to avoid conflict.Also wanted to know HOW .. the installed Scala & SBT is different from the scala & sbt plugin that comes with itelliJ IDEAThe standalone sbt plugin is obsolete with IntelliJ Scala Plugin 2017.1, which includes an  and supports building through that shell.To avoid any conflicts between different instances of sbt shells, it is best to have only one running at a time - either from the terminal or from IDEA. Other than that you don't need any special setup."},
Scala

this is part of my code:I need to write a new file into my bucket using Scala. \nI get this error:When I try to save it locally, it works:How could I solve it?\nThanks in advanceS3 being an object store, you cannot write strings. You can probably write the strings to a local file and periodically upload the file to S3.S3A being a Hadoop Filesystem client, you can't use the java File API to work with it."},
Scala

I have a requirement where I have to pull parquet file from S3 process it and convert into another object format and store it in S3 in json and Parquet format.I have done the below changes for this problem statement, but the Spark job is taking too much time when collect statement is called Please Let me know how this can be optimized, Below is the complete Code which reads Parquet file from S3 and process it and store it to S3. I am very new to Spark and BigData technologyFirst, you really should improve your questions, with a minimal code example. It's really hard to see whats going on in your code...Collect retrieves all elements of your RDD into a single RDD on the driver. If your RDD is large, then this will of course take a lot of time (and maybe cause an  if the content does not fit into the driver's main memory).You can directly  the content of a / using parquet. This will surely be much faster and more scalable.Use s3a:// URLs . S3n// has a bug which really kills ORC/Parquet performance, and has been superceded by s3a now"},
Scala

How to write a function can take  Array[Array[T]] or List[List[T]] or List[Array[T]] or SeqLike[SeqLike[T]] as parameter? Some function like:matrix is List[Array[String]], but matrix can be anyof Array[Array[T]] or List[List[T]] or List[Array[T]] or SeqLike[SeqLike[T]]or in another way, very similar as  method of  trait of scala libraryBTW : right now I got error \"Error:(48, 26) type mismatch;\n found   )\" during runningYou could use higher kinds I guess, and play around with the lower bound to get the semantics you want. You can also enable  in  by explicitly passing  to ."},
Scala

How do I complete the declaration of the val:This is to help understand how to iterate over it, with say .Edit: I restated the same question in a different way.Seems that's what you're asking for. "},
Scala

I am new to scala. I have a case class. The code is given below.I also have a function which returns an  of objects of the class. This is what is being returned.Now I want to read values from the object. I have looked at some resources in google. This are what I have tried. BTW,  is the  of obejcts. None are working. I don't know what to do. Please help me. I am stuck for hours.Your question is pretty vague.  Do you just mean this?prints:"},
Scala

now I have two rdds ,the first is  like this 1,23,45,6 and the other one is like this 7,8 9,10 11,12 now I want to union these two rdds like this 1,2,7,8 3,4,9,10 5,6,11,12 how can I do this? the rdd.union can't get this resultIf you can warranty that the two RDDs have the same number of elements and partitions, you can achieve the desired result with , and then re-shaping the resulting pairs:If the two RDDs differ in the number of elements or partitions, you will need some key to join them. Indexing them is not very efficient but would serve the purpose, although a domain-specific solution (if existing) will be much better :"},
Scala

I want to change the format of my data, from RDD(Label:String,(ID:String,Data:Array[Double])) to an RDD Object with the label, id and data as components.\nBut when I print my RDD consecutively twice, the references of objects change :I think that explains why the  method doesn't work. So can I use  with objects as values, or do I return to my classic model ?Unless you specify otherwise, objects in Scala (and Java) are compared using reference equality (i.e. their memory address). They are also printed out according to this address, hence the  and so on.Using reference equality means that two  instances with identical properties will NOT compare as equal unless they are exactly the same object. Also, their references will change from one run to the next.  Particularly in a distributed system like Spark, this is no good - we need to be able to tell whether two objects in two  JVMs are the same or not, according to their properties. Until this is fixed, RDD operations like  will not give the results you expect.Fortunately, this is usually easy to fix in Scala/Spark - define your class as a . This automatically generates  and  and  methods derived from all of the properties of the class. For example:If you want to compare your objects according to only  of the properties, you'll have to define your own  and  methods, though. See , for example."},
Scala

I am familiar with \"\"I also have read  which states that a programmer is able to produce only so many lines of code per day and therefore a language with a \"better\" syntax can only help in this direction.As there is nothing perfect in the world, the syntax of Scala has its  (of course someone can see these as pure advantages). I am talking about stuff like:If one has Java background (or even C++, C#, etc.) it is kind of weird to have import statements in the middle of a function, to have nested functions and I am not even going into other language constructs.I am a bit sceptical about the real productivity gain coming with Scala. How do you experience this? Do you apply all (as much as possible) of the coding conventions and is this a real benefit? Is there a better way to wrap ones head around this style of code?P.S. maybe this whole post can be moved to Programmers or similar...I can share only my experience and I don't know whether other people's experiences are similar. It certainly depends on personal preferences. I came to Scala from Java, so my preference in general is to have all imports at the top of the file. This makes it easier for me to faster see the dependencies of the files. Sometimes however I do use local import in places where I want to import a name only locally and not to pollute the namespace of the whole file.After few weeks in Scala I really enjoy the the lack of mandatory semicolons. In Scala they are mostly not needed, but they can be helpful when you want to write more short statements on one line. Scala actually changes my attitude towards semicolons and now in new projects I don't use semicolons even in JavaScript.This is one of the best features of Scala: Functional programming. It allows to write much simpler code consisting of small easily understandable functions working with immutable data. This decreases the complexity of the code, reduces bugs and increases the productivity.Again, lack of return statements feels just natural. The function returns the value of its expression, where the value of a sequence of statements/expressions is the last one of them. Return statements just feel very unnatural in Scala.Scala has a learning curve and of course when I have started my productivity had a dent caused by my lack of familiarity with the language and the standard library. Now, after few months of Java and Scala work, I can say that I am in more productive in Scala than in Java. Even though I consider myself a Java expert but only a Scala novice.I'll go step by step, although some points could be subject to personal opinion:Using such imports for implicits is useful in many cases.For this usage, importing makes code safer and more readable.Second case would be ambiguous class and package names (can be solved via aliases). Showing explicite which one is using can be helpful.In Scala you can do many things in many ways, a little bit like with C++. You have more responsibility for your coding style. Watch this: Nested methods are great for recurrence and when such method should not be used even as private at class level. With nesting you can also reduce amount of passed arguments.If you can you then you should place you nested methods on the top of method body. Giving comments on where is constructor body at big class is also helpful.Scala gives to community the ability to develop the language, scala can change in fundamental ways due to our experiments, good practices."},
Scala

As per this example will the calculation for someValue be ran only once for each instance of the class? Would the same rules apply to an If you have an immutable case class (and of course objects are immutable by virtue of being a single instance) then there is no sense in re-running calculations that have been ran, even if they use values in the class itself (I'm thinking of custom hashCode calculations for example). Is the compiler smart enough to handle that or would it be better to place the val outside of the def? (Making it lazy so it only gets called when needed...)  The literal is inlined at compile time:Generally, the Scala compiler doesn't optimize such cases when there are no literals involved:When you write , then you mean , i.e. every time you call the method everything in it is evaluated. Anything that should be cached needs to be done manually on your side.In the above example however, it is very likely that the JVM itself will inline  and , with the result that the first and the second example will be optimized to the same machine code.Simply put: No. is only evaluated once. is evaluated every time.That is the difference between those keywords in the Scala language.As  has no parameters and is not affected by side-effects, it should be changed to  or as you say  so it is only ran when needed.It is more productive to program with intent rather than rely on compiler optimisation."},
Scala

Why this  line shows compile time error??Im pretty sure it should be , since Member is a class, not a function"},
Scala

My two scala lists are as below. The two lists may have different lengths.andnow I want to filter like this:but when I execute above code it returns me as:The result mixes the tuples, and it returns wrong results. Actually the result should be the empty list because both lists of tuples contain the same data. If I check for  like  it returns expected results but for  it mixes data.Does anyone know the exact problem here? What I am missing? Another problem is that every time both lists not same check this new lists with less data .and \n and expected output as Basically I want to find out  Trying testing with a simpler and smaller data set so it's easier to see what's going on.You're mapping over the product of the two lists. It sounds like what you want instead is the zip of the lists.Add back the filter, and we're done:You need to zip your  and  list firstly and  with condition:"},
Scala

I am implementing my own  collection using a generic abstract class . I want to add a  function which changes the list according to a given function :I am getting the following error in : Tt first you can read architecture of scala collection\nImplementation of map in TraversableLike:With  you are trying to match your own  against Scala standard library . If you want to use pattern matching, you need to define your own extractor. You can read more about infix extractors at , paragraph .Another nice explanation can be found at :"},
Scala

Using Spark 1.4 I have two dataframes of different schemas. Let's say:DF1: stringA, stringB\nDF2: stringCI'd like to merge/combine the two into a single dataframe like:DF3: stringA, stringB, stringCI can't seem to find a way to combine the two when they have no key for me to use.You are looking for "},
Scala

I want to initialize a java object within scala class, so this works:But this one doesn't work:My question is, how I can pass arguments to a java object declared inside a scala class?Your code is correct, You can check it by the next one code:Java class  takes argument from the scala. You definitely have problem with the class . Check if the class correct and if you have a correct class version of the  in your class path"},
Scala

I want to create a  function which can later be used by three different RDD data sets.\nFunction takes key and value and converts to seq[String]when I tried to apply by one data set its ok because it has one key with  6 values example:-but I tried to apply on another data set I need to we write the function because other data set contains 7 values with one key this makes to re write the function with same logic but different name.Is there a way to write one function for both which accepts 6 or 7 values of string with just one key ? or can I extend my function ? classes inherit from , so I would define the function like this:Note that  classes have a  that I'm using here to create the string (I found your way somewhat verbose and more difficult to read) and I'm also delaying the  call until after converting the values, so the map operation is run in parallel.Finially, I have changed the name of the function, since it converts to a  and not a .Yep go the answer need to use data type of any"},
Scala

I want to replace all the consecutive underscore with a single space character. I am able to do so with the following  code. But I am not able to do so with . Below is given my  code.Below is given my scala codeI am given the following error.What am I doing wrong?In Scala, as in Java, a single backslash is an escape character in a (standard) string literal, so you need to double it to put an actual backslash in the string to be used to initialise the Regex:Alternatively, you can 'triple-quote' the string, to prevent the usual escaping behaviour:"},
Scala

I have a piece of code as such (simplified): \n    import scala.concurrent.FutureIt works fine, but when I have a huge \"BigCase\" class with 15 fields, it would be nice to be able to write , instead of , especially during the stub-out phase. But once I did , id became type \"Nothing\" , which makes further steps hard to compose. Is there a way around it? I am not sure how your code is supposed to work but you are defining your  instance for the first time within your comprehension. There is no way to shorten the declaration itself but I think your code makes more sense if the  instance is defined before the for comprehension:Assuming I understand the question correctly,  will compile and work everywhere you want a . If you want to use the placeholder in multiple places, you can use . In fact, given the type of ,  should already work fine, so it isn't clear what you mean in this comment:If you just want arbitrary int fields,Then go back later and fix the number of fields?or, more arbitrarily,"},
Scala

I have the two following objects (in scala and using spark):\n1. The main object2. The object odbscanWhen I execute this code I obtain an infinite loop, until I change:filter(_._2.size >= param_user_minimal_rating_count)to filter(_._2.size >= 1)or any other numerical value, in this case the code work, and I have my result displayed What I  is happening here is that Spark serializes functions to send them over the wire. And that because your function (the one you're passing to ) calls the accessor  of object , the entire object  will need to get serialized and sent along with it. Deserializing and then using that deserialized object will cause the code in its body to get executed again which causes an infinite loop of serializing-->sending-->deserializing-->executing-->serializing-->...Probably the easiest thing to do here is changing that  to  so the compiler will inline the value. But note that this will only be a solution for literal constants. For more information see  and .An other and better solution would be to refactor your code so that no instance variables are used in lambda expressions. Referencing vals that are defined in an object or class will get the whole object serialized. So try to only refer to vals that are local (to a method). And most importantly don't execute your business logic from within a constructor/the body of an object or class.The only difference between the 2 snippets is the definition of  outside of the  which does not change at all the control flow of your code.Please post more context so we can help."},
Scala

I have an rdd which has 50 million elements all of which are strings. I have to filter and make a new rdd which has any of the following terms: SO, if a string in original rdd contains any of the string from above array, it should be in the filtered rdd.\nWhat's the efficient way to do it in scala?\nIs there an one line way of doing it or do I have to traverse through each element and find out?Something like:"},
Scala

I am learning Scala and running below code .I knew functions, that do not return anything is procedures in Scala but when running below code why extra () is coming in output. Here in procedure i am just printing the value of 'value'.\nCan someone explain about this.The so-called \"procedure syntax\" is just \"syntactic sugar\" for a method that returns  (what you would call  in Java).Is semantically equivalent (and gets actually translated) to:Notice the explicit type and the equal sign right after the method signature.The type  has a single value which is written  (and read unit, just like it's type). That's what you see: the method  prints  and then produces  of type , which you then move on to print on the screen itself.As noted in a comment, the \"procedure syntax\" is deprecated and will removed in a future version of the language.Procedure syntax compiles to a method that returns unit.calling toString on  produces You are printing out the result of test (which is ) so you see its string representation,  in the output."},
Scala

I have a type of set and union function as followWhen i use the union operation,It should return me another set which contains all the elements of both sets  and I am sorry i was not clear on my question, i have my own implementation of the iterator for both Set xs and ysBut i was not satisfied with this implementation and found that you can implement the condition with the function (after some googling) but i was unable to get it to work in my eclipse worksheet. I am guessing it returns a function. so my questions,\n1. is it possible to implement as described above in the edited section? if so, then what am i missing to get it working?\n2. I don't understand how the element  in  is iterating over the elements in both the sets Look at your  type: . So it takes an  and returns a . What that means is that it is  a collection that you can iterate over to retrieve all its values, because it actually contains no values.If you want to know what  values return  then you have to iterate over the entire range of possible inputs (or some subset thereof) and filter for the condition you're looking for.Your confusion stems from the fact that you've named your function after an existing collection in the standard library.  works because  is  an example of your , it is a  from the standard library with all the associated methods. Rename your type alias to something like  and you'll see what I mean."},
Scala

... is not the same thing as ...For one thing, the underscore, , represents a passed parameter only once. If you encounter something like  it does not mean the parameter is added to itself, it represents the addition of two different passed parameters.So what is ? It is an anonymous function that takes one parameter of type  and attempts to find the index where the sub-string \"123\" can be found. In this case the underscore is unrelated to the parameter sent to the  lambda."},
Scala

How can I remove empty Array?expected Output isYou can just use . If you have a list:If you have a RDD:"},
Scala

I used  to combine the source DF (with negative weights) and the target DF (with positive weights) into a node DF. Then I perform  to sum all the weights of the same nodes, but i don't know why  didn't work for the unioned DF at all. Did anyone face the same problem ?:You're simply ignoring the result of the  operation: just like all DataFrame transformations,  doesn't  the original DataFrame (), it produces a new one. I suspect that if you actually use the return value from  you'll see the result you're looking for:"},
Scala

So, if I convert this ListBuffer to a list, it is not retaining the type.Is there a way to do this? is a   from your declaration When you convert buffer to a list, the same \"inner type\" is maintained, meaning you get a  from a scala \"native\" collections don't support collections of unrelated types (String, Int, Option[X]), you get to lose important type informationA solution would be to use a tuple instead, if your variable is of finite length (a tuple of 2 elements has a different type of a tuple with 3 elements for instance)Another solution is to use  HList.  is very good to explain what is an HList, why would you want one, and how to use"},
Scala

Why None: Option[A] in the first parameter in headOptionViaFoldRight?Why Stream[A] in the first parameter in takeWhileViaFoldRight?Why true in the first parameter in forAll?Just confused on what to use in the first parameter in foldRight?The initial value: what you'd get on an empty sequence. It is by convention, and historical precedent, that   on an empty collection returns  while  on an empty collection returns ."},
Scala

The server will be processing large amounts of data daily and needs to be fast. The best language is the language that you, and your team, know the best - you will do a better job writing your server in a language you are an expert in than a language you just picked up.It also depends wildly on the details of your problem.  You mentioned \"lots of data\", but not what that means.  That could be 100MB a day, 1TB a day, 15PB a day?Is this big batch processing, or lots of little interactive operations?Of the three specific languages you tagged in, Java, Scala, and Ruby, all three are reasonable choices that real companies have been successful in the market.JVM hosted languages are generally going to be \"faster\" than traditional MRI Ruby, and both Java and Scala are generally \"faster\" than JRuby, when it comes to raw CPU capabilities.Of the three, Scala probably offers the least familiar, most challenging paradigm for developers unfamiliar with it, but also has very good parallel and concurrent programming tools available in the core compared to the other options.Finally, your end results will be influenced as substantially, if not more so, by the rest of the ecosystem you choose - the web or message handling stack, the data storage engine, and other concerns.  They, perhaps, should dictate your language more than your language dictates your ecosystem."},
Scala

i have a problem in my projecthow do I retrieve data from the value: [some (test)] and only take the value of (test) only. and using the get method?orhow do i change the form of value: [some (test)] to \"test\" justBasically, don't use get() ever.  There's no situation in which it is a better choice than the alternatives.  Option is a way of indicating in the type system that a function might not return what you want.  You might think of it as a collection containing 0 or 1 things.Take a look at the  which show several different ways to handle Option; as a collection using map/flatMap, getOrElse, for comprehensions, and pattern matching.e.g. map:If maybeData is None, nothing happens.  If it is Some() you will get back an Option containing the result of doSomethingWithAString().  Note that this will be Option[B] where B is the return type of doSomethingWithAString.e.g. getOrElse:If data is Some, result is \"test\", otherwise it is \"N/A\".e.g. pattern matching:You get the picture (note this assumes doSomethingWithAString returns String).If you use get() and maybeData is None, you get the joy of handling the equivalent of nullpointers.  Nobody wants that."},
Scala

 can be instantiated with or without parentheses:Which form is (more) idiomatic? Should the parentheses be included since, as I understand, creating an object is a , similarly to a ? I wrote a similar answer here:\nIt's especially relevant that constructors are not like methods with respect to parens.A constructor always has a non-implicit parameter list.  If you omit it in the definition, then it is supplied. is idiomatic. (If there's a need to rationalize it, consider the instance as a result.  If instantiation is a side effect, nothing non-primitive could be pure.) requires the parens, so they are useful syntactically.You must supply parens if an implicit follows; see the link."},
Scala

I'm trying to call my Scala  object from Java code:Here's the compile-time error:From reading these Java to Scala Collections , I am using a  Set rather than the default, immutable Set:But, I don't understand the error message. By using a  (boxed ) in my Java code, why is a  found?Demonstrating what the commenter said:Working with  and type aliases from  (not the converse, as  showed :) is going to be at least nasty, most likely very painful, and quite possibly impossible. If you're able to modify the Scala side of the API, I'd recommend adding a Java-friendlier API to it.  If not, I guess you could build an adapter layer in Scala that proxies Java clients through to the native Scala API.So, something like:"},
Scala

I have a json data as from above., I am interested only in data I extracted it as a Map,}I got output as followsFrom Here, How can I  bind a Map to scala properties, Thanks in advanceThere are many different ways of doing this, here is a straightforward one using . For more ways of handling JSON in Scala, see  and Note: You probably want to handle date and time in a slightly more sophisticated manner, e.g., using locales, etc.If you don't mind the fields of  being all of type  (which is what the JSON delivers them as), you can also use the simpler versionand then first parse the whole JSONand access and decode the relevant part"},
Scala

I'm trying to define an array of numbers with the last being a function. It'll probably be better to give an example:Is this possible using Scala? If so, how?Thanks in advance.Your question as stated is nonsensical, because a function is not a number. But if you meant an array of numbers and also a function, then you can do:or if you prefer efficiency over  type safety:But it would really make more sense to do:Replace  and  with appropriate types in the above.Yes it is possible but you cannot use an ; you need something like a .  This is further answered here: You can define  with an element that is a function as long as the function returns an  since all elements in a Scala  must have the same type."},
Scala

i'm writing a method that take a  ,  and a  parameters and return a List[(String, Int)]\nThe  parameter represents the input list, the  element represents the element to add to the list, the  represents the maximum dimension of the list.The method has the following behavior:I've implemented the method as the following:Exist a way to express this behavior in a more clean way??First, a corrected version of what you posted (but it appears, not what you intended)And some testsNeater version (but still not meeting the spec as mentioned in a comment from the OP)Another version that always removes the minimum, if that's less than x.and its test resultsbut as I say in a comment, better to use a method that processes the whole sequence of Xs and returns the top N.I would separate the ordering from the method itself:What do you want to do if the list contains more than one element less than x? If you're happy with replacing all of them, you could use  rather than your handwritten loop:If you only want to replace the smallest element of the list, maybe it's neater to use ?"},
Scala

first Listsecond ListThe above are my two lists now i have to combine these two lists like below.Expected OutPut =>)The similar question "},
Scala

I'm trying to insert data into a table called users.\nI'm only passing a value for the name field and this exception pops up.I'm not even passing any Timestamp in the parameter.The data still gets inserted into the database even if this happens. Why though?Here is the error I'm getting: Here's the code:joined is a field of data type timestamp with time zone.My scala version is 2.11.1java version is 1.8.0_25My postgres jdbc driver is 9.3-1102-jdbc41I guess the pk returned by INSERT is a timestamp, and you ask it to be parsed as ."},
Scala

I am considering using the Blue eyes framework in order to build HTTPS RESTful webservices in Scala for a project. However, as the documentation is pretty poor, I can't figure out if we can configure it in order to work with SSL or not?Many thanks for the answers!Blueeyes is unmaintained; I would not recommend it for a new project. I'm a big fan of Spray myself, but if you want something that's very similar to Blueeyes you might like to use Redeyes."},
Scala

I have a Scala project built with SBT.This is my project structure:I want to read the content of  in . How should I write code in parser.scala or I should do more setting in build.sbt?Just getResource should be good"},
Scala

I have a class called Rational:I've written this function, which is a subfunction of a bigger one. I'm just debugging it.\nAssume b is the Rational 3/4 and we pass the Rational 2/4 into iter.And here's denomDec: The problem is that the iter function does not stop and runs into Stack Overflow. Here's what happens inside iter(). It gets 2/4 as argument. Then itake 2/4 + 2/3 + when it reaches 2/2, it calls denomDec to get 2/1 after 2/2 because the latter fails to be smaller than 3/4. Then denomDec gets to 2/0 and here it is supposed to return new Rational(0,0) but it fails to do so which in its turn causes Stack Overflow.My question is that why doesn't the function stop when recurring when it hits the base case which is For clarification: example iter(2/4) should do this: 2/4 + 2/3 + 0/0. \n2/2 and 2/1 are skipped as they are both greater than 3/4.maybe your problem is out of the presented scope;\nI have tested code and I do not get error:Rational(0,0) is not zero. When you do math on it you are getting bad results. Consider the case Rational(0,0) < Rational(1,2). It should be true, but your < operator evaluates it like this: 0*2 < 1*0, which is the same as 0 < 0 which is false.In iter() our second if statement does not work correct when it evaluates Rational(0,0) and the Rational(0,0) gets passed to the denonDec and its denominator goes negative. Once that happens you're sunk.I would put a guard in the Rational constructor to prevent denoms less than 1. I would use Rational(0,1) as zero. Remember from basic arithmetic that the fraction 0/0 is undefined.I figured out what is wrong with my code above. \nInstead of  I should do  so that I actually call the  function again with a smaller argument.\nAnother mistake of mine was trying to add 0/0 to another . The problem is that if you look at my code for add  you can see that adding 0/0 to any  will always return 0/0. Hence, I need to return something other than  when the base case is reached."},
Scala

I'm having a situation like this:I have a sequence that I need to match. Actually, in the \"case\" I only need to match against a sequence whose elements are of tuple (String, Seq[String])..., but I couldn't find a way to do that..., so I resorted to the technique I read on web: decapitate the seq, match against the first element, and re-attach inside the block to get the original seq.The problem with that approach is: type erasure.The resulting seq from the expression \"head +: rest\" is a Seq[Any] instead of Seq[(String, Seq[String])]That's why the \"tuple_.1\" gives compile error (line 153 in the attached image).How to work around this situation?It was my bad, there are a couple of coding errors in the above screenshot; from the case block of sequence matching I should have added another line to the end: complexSeqReconstructed.Apart from that, there's a little detail: from the \"case Nil\", I also have to return an empty Seq of type Seq[(String, Seq[String])] ... that matches the return from the other case. That way Scala will correctly perform type inference. Otherwise the line hhh.map wouldn't compile (it will say, Object hhh doesn't have map method).So here's the updated (working) code:"},
Scala

I am working on a web project using scala on play framework. I will need to import an external package to use the classes defined in it. I have no problem to do it in my .scala file. But I don't find a way to import that package in view/..scala.html file. As a result, when it is built, it reports error not found the definition of that class. I tried to import that package like the below way. @import myPackage._ But it doesn't seems to work. How can I do that? if you want to use any method of model or controller or any of your package you can tryi have not tried your way"},
Scala

The following template displays a PNG image by taking the image as a byte array and encoding it into Base64:The template works for a Play project that uses Scala as its main language:However, if a project uses Java as its main language:The following error is seen when running the project:This is with Scala 2.11.4 and Play 2.3.6Why does the template expect a Scala Byte instead of a Java Byte here, even though the Play project is configured to use Java?Twirl, the Play template compiler, is Scala based. It reads in the template and generates Scala source code. It doesn't matter that you enabled PlayJava, that doesn't change what the Twirl compiler generates.  I suggest you look at the source code under target/scala_2.X/twirl to see what Twirl generated and what the Scala compiler is attempting to compile. Twirl has likely interpreted  in your template as  and output a fully qualified class name. You will need to be more specific in your template if you meant to use the java version of Byte."},
Scala

So I have  key value pairs. From this, I can easily create  key value pairs as well as  key value pairs. However, I require  key value pairs for persons who share the same surnames. The way I solve this now is to pass a function to the  function that takes  as input and return  by iterating through the list of firstnames against a surname. However, I notice that spark is not properly able to parallelize my program with this. I want to know if this result is possible only by using  and  functions, that is, without requiring us to write a special function for this with ?In other words, this is an example of my inputfor which, we should have the following output to  pairs, then ?"},
Scala

Below is some really rudimentary sample code to illustrate the question.This will reliably return the same first value always. Every time getRandom is called.However,This will return a different random value every time.I suspect this is because by re-initializing rand every single time (as in the first one) we end up getting the first number for that seed. Since the seed guarantees that we will get the same \"set\" of random numbers each time this is expected behavior. By moving the generator outside of the function it will exist as long as the class does, and as a result continue generating numbers in that \"set\". Is this the correct way to think about this?It's not a \"set\" so much as a \"stream\", but yes, that's it."},
Scala

I am relatively new to Spark and scala programming.I was trying to execute the simple pagerank algorithm using scala. But I encountered this error when compiling.I have attached the code I am using.foreach is, as Ryan pointed out, solely for side-effects. It returns Unit and not the List itself. Ergo no chaining. Now what you are actually doing is the following: is not a member of  and you get your error messageYou should be doing:or "},
Scala

If I have the following tuple:Is it possible using distinct()?, with the first element by tupleYou need to introduce some concept of \"first\": an RDD is a (distributed) set, not an ordered list. So given a function like: You can simply: Yes, it's possible. However it's not , but .(Assuming you use Scala for your spark job)\nOnce you get an array of these tuples, create RDD with  and call  method of resulting RDD. At reduceByKey, you can specify how you want to prioritize the values in second element of these tuples. For other RDD related operations, you can refer .With spark-shell you can interactively try your function.I formatted the last output. Hope this helps."},
Scala

i build tests on my Scala Spark App, but i get the exception below on Intellij while running the test.  Other tests, without SparkContext are running fine. If i run the test on the terminal with \"sbt test-only\" the tests with sparkcontext works? Need i to specially configure intellij for tests with sparkcontext?The most likely problem is that spark-core version doesn't match.Check your sbt file to make sure using the corresponding spark core version you have."},
Scala

I'm a tester and fairly new to both play and scala. I have some source code to test, which I've managed to compile and have installed elastic search, which is being used as my data source. I'm getting an error when I try to run the code:I've seen other threads on this but they all refer to checking the elastic search nodes are configured in . However, the app I'm testing has no such file. Is there anywhere else the node could be configured? I'm at a loss to where the elasticsearch node is defined. I have elasticsearch 1.4.1 installed. Any help would be much appreciated, I have exhausted all avenues within my current knowledge! Basically you need to tell Play where (IP and port) of your ElasticSearch instance. This is typically done in the . Here are a few things you can try: "},
Scala

and this is my insert statement:There are two main modifications you need:It's hard to tell from the code you posted exactly what you have in mind. It would be helpful next time to simplify your example first. I've assumed your model is something like this:I've left out one of the byte arrays and the created and updated fields as they don't seem relevant to the question. In other words, I've simplified.The  seems ok.  I'm ignoring the foreign key as that doesn't seem relevant. Oh, the  are now deprecated (in Slick 3 at least). You can leave them off because your columns are not  values.What we need is the table query, which I'd add inside :You could use  to insert data. But you've asked for the IDs back, so you want to use .Putting it all together (again, using Slick 3 here):Produces: "},
Scala

I'm stepping through my first Scala project, and looking at parser combinators in particular. I'm having trouble getting a simple unit test scenario to work, and trying to understand what I'm missing.I'm stuck on pattern matching a ParseResult into the case classes of Success, Failure and Error. I can't get Scala to resolve the case classes. There's a few examples around of this, but they all seem to be using them inside something that extends of of the parser classes. For example the  are inside the same package. The example  is inside a class extending a parser.The test i'm trying to write looks like:and the method I'm calling is designed to let me exersize each of my parsers on my SUT:The fundamental issue is getting the case classes resolved in my test scope. Based on the  for the Parsers class, how can I get them defined? Can I resolve this with some additional import statements, or are they only accessible via inheritance? I've tried all the combinations that should resolve this issue, but I'm obviously missing something here.Right hand column FTW! I stumbled on an answer in this . The problem was identifying the case classes as nested classes of Parsers."},
Scala

I am trying to run some scala code in eclipse but i got stuck with a weird problem. If no errors exist, it runs fine, otherwise it just gives the error: could not find or load main class ....\nWhat may cause such an annoying problem?this snippet outputs:Error: Could not find or load main class p.MainI want to see something like this:Error:(15, 5) not found: value --try omitting the .  If that works, then it's the capture into In my estimation, the odds are high that you have a case mismatch.  You defined , which is  but your error is for not finding .  Many systems are case sensitive, so if you are used to Windows style case insensitivity, you'll have to be vigilant."},
Scala

I'm admittedly new to Scala and Android programming and in all my searching I haven't been able to find answer to help me understand and resolve my problem.Here's a gist of my two scala classes I'm running through the tutorial found here: which I'm trying to adapt to scala code (I have need for understanding Scala for work and a personal desire to mess around with Android development so I figured I'd try and combine these efforts).The problem is seen in DisplayMessageActivity.scala in which the IDE reports that it cannot resolve MyActivity in this line:I feel like this should work. I can get it to resolve if I change MyActivity to an object, but then that breaks other pieces of the application that expects MyActivity to be a class.An help in getting me to understand my problem would be appreciated.You cannot reference the  field from  as though it was a 'static' field (in Java terminology). To access  in your other activity you will need to either obtain an instance of  that you can then de-reference, or add a companion object (defined using the  keyword in the same file in which the class is defined) for  and define the field there:then your call as above will work."},
Scala

I'm trying to get Slick 3.0 running with MySql. I've made the following changes to the hello-slick-3.0 activator project:It compiles fine, but running gives the error  coming from the line .How can I get Slick 3.0 running with MySql? Am I missing something simple here, or are there any other working examples? Thanks.Fixed it. The URL in  was in the wrong format. Should be where you've already created  in your database. (That fixes the db access issue that I was asking about, but you'll still get a key-spec error. To fix that you need to remove the  entry from  for , which is described here: .)"},
Scala

I've created a cookie in Scala, which I would like Javascript to be able to delete and/or modify.Here is how I created the cookie in Scala ensuring the httpOnly param is set to false: (\n\n)I used the following method to delete the cookie in JavaScript, but the cookie does not delete.\n(  )Aside from attempting to delete the cookie, it doesn't seem like I can modify the contents of the cookie either.How can I ensure the JavaScript can modify and delete the cookie created in Scala?I fixed the issue. \nI had to ensure that both the cookie created in Scala and the one deleted/modified in JavaScript both had the same path.For example, in Scala:In JavaScript:Notice the path in both examples used \"/\". Once I used the same path, I was able to delete/modify the cookies in JavaScript. Before this I hadn't explicitly set the path in the JavaScript code."},
Scala

When I am using play framework, every time I've changed the code, it will take effect automatically by re-compile the code.However, when I'm using sbt to run a project without play-plugin, it won't take effect.I'm wondering if there were a way to make sbt project hot swap the changed code.My build.sbt is as below:And what I have configured in intellij idea is like below as a sbt task(I can't post images by now):However, every time I've changed the code in backend, It won't take effect after I've call backend from the frontend.I'm wondering how I can solve the problem. Thanks for your guys' help.You can have sbt automatically recompiling any changes by invoking it like this:\n    If you use ~run, on every change the changeed classes will be compiled and project rerun again. \nIf it does not work, you might explain more about your project and structure."},
Scala

I'm pretty new into development and I'm going to be building a Proxy server for work. I'm not really sure what goes into a building a Proxy server and anything I can find is just telling me to install something and set one up; but I want to be able to build my own. I'm going to be working in Scala so what exactly goes into making one and what does it do?There are two major kinds of proxies:Both kinds of proxies may or may not have the following value-added capabilities (this is a sample and nowhere near exhaustive):I'm going to assume you want to build an HTTP/HTTPS forward or reverse proxy.Is it a reverse proxy?An HTTP load balancer in front one or more application servers is a reverse proxy.  In this case the backend server is either fixed, selected based on headers (Host is a popular one), or selected from a pool when load balancing.   The backend may use the same protocol or may use a custom load balancing protocol.  For your case I'd recommend using the same protocol unless there's a very compelling reason not to.Is it a forward proxy?An HTTP proxy between end-users and the Internet is a forward proxy.  In this case the proxy establishes a new connection to the requested domain and sends its own HTTP request possibly directly copying the headers and content of the user.  The proxy may choose to allow or deny requests based on domain names, URLs, IP addresses, or content.Both kinds of proxies do essentially the same thing: take an inbound request and make it to the destination on the requestors behalf.The basic procedure for a simple proxy is as follows:To make that work for a reverse proxy the destination needs to be a parameter of the proxy process (configuration, code, etc.).To make that work for a forward proxy the requestor needs to have a protocol for expressing the destination.  There are many protocols for this: HTTP. HTTP CONNECT, and SOCKS being the major ones.  In the simplest case the client connects to the proxy server over HTTP and sends the same request they would normally send directly to the destination server.A novel (as far as I know) thing to enable would be a reverse proxy that accepts connections from backends.  This would allow a DMZ that can't be easily used to attack the backends in the secure zone.Kate Madsudaira provides  in the book ."},
Scala

I recently downloaded source code of com.github.nscala_time package version 2.11,\nAfter set up dependency in Maven, I got lots of errors, I checked one file\ncom.github.nscala_time.time.DurationBuilder, it got a line like:There are no class or type named \"Super\" in the same package or imported packages. I am wondering scala has a type called \"Super\"? the Eclipse scala 2.11 compiler complains about cannot find type \"Super\"I think you should find it in the object time in package com.github.nscala_time. Try to add this import:the solution I have is to add a trait named \"Super\"        `package com.github.nscala_time.timetrait Super {}`It seems to me the author of the library forgot to upload the class file"},
Scala

I am trying to create a controller that extracts a file on the fly from an archive and then then renders it as a static asset with the default Asset controllerI get these errors at compileYou either have to make sure your action returns a :Or change it so it's not  anymore:"},
Scala

Using geotools version 11.2Ended up using this function. You can see something similar for maxX and minY in the source code for GridGeometry2D.java worldToGrid function"},
Scala

Given:The following call takes roughly 15 seconds to run (5 seconds per 's application to each element).I can use  to, as I incompletely understand, parallelize it. If I use it, then the execution time shrinks to roughly 5 seconds.Is this parallelization the recommended way in Scala? What are alternatives?  creates an already completed future and to do it it must evaluate its argument. What you want is slightly different and consists in running each future and then wait for completion of each oneAnd then"},
Scala

I am trying this:This is not giving expected output, how can I achieve it in fastest way?You can just group by both the columns instead of grouping by a single column and then filtering. Because I am not fluent enough in Scala, below is the code snippet in Python. Note, I have changed your col names from \"stream\" and \"class\" to \"dept\" and \"name\" to avoid name conflicts with Spark's \"stream\" and \"class\" types.This results in the following output -It is not exactly clear what is the expected output but I guess you want something like this:If you don't care about names and have only one group column you can simply use :"},
Scala

I tried to add a ChangeListener to a TextField but I get an error. Here is the Example I triedAnd these are the packages I've importedBut I get the following error in eclipse:The reason might be the  and  but I'm not sure about this.In Java,  means  (if there are no imports saying otherwise). In Scala, it means . , being a JavaFX method, obviously can't know anything about ."},
Scala

I have parquet file locally saved,\nIt is loaded...val catDF = sqlContext.read.parquet(\"data.lzo.parquet\") It recognize the schema but each query or actions return the same error...parquet.io.ParquetDecodingException: Can not read value at 0 in block -1Thanks in advanceLoading a parquet file as dataframe is as simple as you've statedYour above code should work. Please check whether the parquet location is correctLZO (parquet) compression issues, resolved adding depend. to sbt config:libraryDependencies ++= Seq(\n  \"org.anarres.lzo\"   %  \"lzo-hadoop\"              % \"1.0.0\"\n)Hope will be usefull for someone."},
Scala

I am using node.js for writing restful service. I want to trigger clustering algorithm written in scala from this service.How can i call scala function from nodejs apiIt's a broad question to answer it. \nBut one way to achieve it is using a web service on top of your clustering algorithm. You can check  as a lightweigt webservice toolkit. It has embedded web server so you can start your application standalone. Implement a simple rest service and make a http request to it from your node.js application.   "},
Scala

How do I detect if a method is called by unit test in ScalaTest?Edit: sorry, I was expressing wrongly the thing I wanted. I have a code block in a method which takes very long to finish (I cannot mock it) and it does not affect any logic. I want to skip that code block in the unit test. So I want to know whether it is called by unit test or normal running. If it is called by unit test, I skip it, otherwise, I let it runs normally.I have a simple workaround by adding a trait like this: use it in the places where I needs to check whether it is in debug mode:Use a code coverage library such as  for instance. It will generate reports that indicate you which parts of your code are used by unit tests."},
Scala

I am using a fastutill ObjectArrayList[object] instead of ArrayBuffer in scala in my spark streamign applicatiuon (inside a mapwithstae function)I use the lates version..using below sbt However, it throws an exceptionOk..just added as jars parameter in spark submit and it resolved that.."},
Scala

I have looked at a number of questions online, but they don't seem to do what I'm trying to achieve.I'm using Apache Spark 2.0.2 with Scala.I have a dataframe:which I want to transpose to I've tried using  but I couldn't get to the right answer. I ended up looping through my  columns, and pivoting each as per below, but this is proving to be very slow.Then using  on each iteration of  to my first dataframe.Is there a more efficient way of a transpose where I do not want to aggregate data?Thanks :)Unfortunately there is no case when:You have to remember that , as implemented in Spark, is a distributed collection of rows and each row is stored and processed on a single node.You could express transposition on a  as :but it is merely a toy code with no practical applications. In practice it is not better than collecting data:For  defined as:both would you give you the desired result:That being said if you need an efficient transpositions on distributed data structure you'll have to look somewhere else. There is a number of structures, including core  and , which can distribute data across both dimensions and can be transposed. "},
Scala

For a while I was looking for a fast and simple solution for a microservice framework. I am quite new to all Lightbend products & scala but since its looks very interesting I decided to give it a try. 1)  I don\u2019t understand why there is a need for the new framework Lagom ? If play can already give me the same solution (to serve as microservice) then why there is a need for another framework ? 2)  With play I manage to create an \u201cHello World\u201d project very fast and also the deployment was very easy and straight forward(via dist). I like the fact that I can merge all in one ZIP and run it via script . In Lagom from what I understand I need to use ConductR. For my current needs its look like a big overhead. Is there a simple why to deploy it something like in play ?Thank you allLagom is built on top of Play. Whereas Play is intended to be a general-purpose (asynchronous) web framework, Lagom's more specific goal is to add some tools/opinions focussed on deploying your app as microservices.A couple of examples that Lagom provides that helps you realise a microservices style architecture (that Play does not):-One thing it adds, for example, is an API for -based persistence on top of the persistence support Play currently provides - this (if you do not know) is a pattern which helps you realize a microservices architecture by decoupling queries and commands.Let's say you have a Play application that has 25 different microservices - which is probably a conservative number for say even a relatively small corporate application - how do you manage the deployment/orchestration of all those JVM's? Well containers are all the rage. How do you manage all those containers? ConductR is a tool which takes some of the pain away from that task, and Lagom provides you integration tools for ConductR to make it easier for you to use it with your Lagom project - something you do not get with Play on it's own.Ok, there are loads of SBT modules that you could use in your Play project to help you realise the same thing but then you need to choose what tools you need, figure out which of the many modules available are right for your project, configure and wire them as necessary - this is one of Lagom's goals - to take these decisions and configuration tasks away from you so you can focus on writing your application logic.If my application was small, maybe just 5 services, then you could argue quite convincingly that you really don't need Lagom (or any other microservice framework for that matter). However, if your application is likely to grow, then Play on it's own will cost you more time in the long run.There are obviously many more considerations when designing microservices but you get the jist of Play vs Lagom."},
Scala

The code below prints '1' and never prints '2', as a result the browser hangs when it requests the page served by the  method. The future is never invoked. If the  statement is replaced with  the code works correctly. What is the problem?First of all you shouldn't create db connection on each http request. \nSecond your finally clause executes probably before you future has chance to be executed and this may be the reason of your problem.Other than that, it's looking good. Try to initialize resource on application startup or via DI, close db on application stop and then see if problem still occurs."},
Scala

my problem is creating a sqrt function for integer via Scalaf.e.: sqrt ( 26 ) = 6 , s\u00b2 >= n \nsqrt (0) = 0, sqrt (1) = 1, sqrt (2) = 2, sqrt (3) = 2, sqrt (4) = 2, sqrt (5) to sqrt (9) = 3 .... here is my code i came up with:however it doesn't work with all the numbers n >= 0. \nf.e.: for 6 its 2, how do i tweak my formula?Try change type to Double. Result should be obvious.here is an easy and nice solution. I have added minor improvements to Pavel's Code:  function does not really add up and it gives the wrong results. As square root values will mostly contain decimals, I have limited the decimal by 2 digits. "},
Scala

I am writing a simple function to  compute the value of a bag of coins.  It consumes four numbers: the number of pennies, nickels, dimes, and quarters in the bag; it produces the amount of money in the bag.Here is the function:Why does the result look like this?I expect the result should be 0.41This is trivial Double \"problem\"For exact numbers, like money, use BigDecimal, as Mr D propose. Literals , , ,  are floating point  by default, you should use  instead. The following implementation uses instead."},
Scala

Suppose I have two RDDs: rdd1=(Double,Int,String), rdd2=(Double,String) and a function:fun1 wrote by myself and it would take both rdd1 and rdd2 as its inputs. how could I get the result like rdd1.fun1( val1) or rdd1.fun1( rdd2)?For example,\nAnd fun1 would return a new rdd3 from rdd1 where each element in rdd2 replaced each corresponding parameter in rdd1,the expected output is as follows,Maybe one way to call fun1 is rdd2.fun1(rdd1) or some other calling methods.    I'v tried \"join\", but it doesn't work for my problem, because \"join\" only return those pairs with the same key. \nBut I don't know how to make fun1 work when rdd1 and rdd2 are the inputs. You can do this with implicit conversions or implicit classes.Here's an example with integers:"},
Scala

How can I create Dataframe with all my json files, when after reading each file I need to add fileName as field in dataframe? it seems Variable in for loop is not recognized outside loop. How to overcome this issue?Thank in advance\nHossainI think you are new to programming itself.\nAnyways here you go.Basically you specify the type and initialise it before loop.Ok you are completely new to programming, even loops.Suppose fileArray is having values as [1.json, 2.json, 3.json, 4.json]So, the loop actually created 4 dataframe, by reading 4 json files.\nWhich one you want to register as temp table.If all of them,And reason for df being empty before this update is, your fileArray is empty or Spark failed to read that file. Print it and check.To query any of those registered LandingTable\nQuestion has changed to making a single dataFrame from all the json files.Insure, that fileArray is not empty and all json files in fileArray are having same schema."},
Scala

I just started learning Spark and Scala. I wish to know how to use this conversion method from Unix timestamp to data in spark-shellIt only shows top 20 rows. Why does spark-shell only show 20 rows? Is it possible to remove this limitation?One more question, how can I save the result to my home directory and HDFS location? By default the  method is  , where the first argument is the number of rows to display and second argument truncates the output to 20 rows. So you can simply use  or  to display all of the rows.\nTo save the  you can use\n  or\nits not spark-shell limit you can call show with number of rows you want like belowand to save the result in you home directory you can simply convert dataframe into rdd and call saveAsTextFile action on it as belowyou can also save file in hdfs using saveAsTextFile actionYou can use This should work to convert Milliseconds to Date"},
Scala

I'm attempting the Kaggle  using SparkML and Scala.  I'm attempting to load the first training file but I am running into a strange error:The file is a  so I'm not sure why its expecting a Parquet file.Here is my code:You're missing input format. Either:orIt is expecting a parquet file because that is what the .If you are using Spark < 2.0, you will need to use . Otherwise if you are using Spark 2.0+ you will be able to use the  by using  instead of .You have to add a dependency jar from databricks into your pom . Lower version spark doesn't provide api to read csv. Once you download you can write something like below.. Ref url: I seem to have had a conflict with Scala versions in my  NOT my original code.  My  had multiple Scala versions seemingly causing issues.  I updated all dependencies that used Scala to the same version using a dynamic property  and that fixed the problem."},
Scala

In our application , most of our code is just apply  ,  and  operations on  and save the DF to Cassandra database.Like the below code, we have several methods which do the same kind of operations[] on different number of fields and returns an DF and that will be saved to Cassandra tables.Since i am calling the action by saving the DF to Cassandra, i hope i need to handle the exception only on that line as per  thread.If i get any exception, i can see the exception in the Spark detailed log by default.Do i have to really surround the filter, group by code with  or I don't see any example on Spark SQL DataFrame API examples with exception handling.How do i use the  on  method? it returns You don't really need to surround the ,  code with  or  , . Since, all of these operations are transformations, they don't get execute until an  is performed on them, like  in your case.However, if an error occurs while ,  or  the dataframe, the catch clause in  function will log it as action is being performed there."},
Scala

I'm trying to select the last element from a map and compare it against the other last elements in the map to say if the selected element is higher or lower.So far I can get it to select the element from user input but cannot work out how to loop through the map and get it to compare against the other elements:Here is the map which the elements are coming from:for example I select H8 and its last element is 6I then want to compare it to all last elements and say if it is higher or lower than each of the last elements.Thanks in advanceI'm not sure if I understand you correctly. You can access last element of the list by calling last.Result:Is this what you need ?Note that I still learn Scala so there's probably better way of doing this.\nI also don't know if any list in mapdata can be empty so use Option if necessary.// EDIT\nIf you want the letters you may try sth like this:You just need to remember that when you iterate through mapdata you get entry. entry._1 is the key (your string), entry._2 is the list."},
Scala

I'm using the Scala language.\nLibraries used are: Akka, LWJGL (includes GLFW)When testing at high fps, like 4000 for example, everything works as expected. But as I lower the fps to 30 by adding 100k cubes, the key polling of glfw seems to get issues.When I release a key, the callback gets called instantly with a new key_pressed event, and then a new keyrelease a few seconds later. Please see this video here for a detailled example:I made sure that there is only 1 callback active, and there is only 1 glPollEvents() call.\nIf that is not weird enough, calling glPollEvents() 20 times per update loops seems to reduce the time between the key release and the second key_released event...Thanks!I didn't exactly found what was causing it, but the issue is gone. From what I understood, running glfw and opengl in the same thread on a multithreaded game running at lower than 60 fps causes weird behaviour in the glfw polling internal threading. To fix it, I created a subthread under the main window thread and put a fast ticking loop that calls glfwPollKeys at a faster rate than the window refresh rate. The problem is now gone, at the price of a loop and a thread."},
Scala

Help ,I have two RDDs, i want to merge to one RDD.This is my code.Just use union:Documentation is Shotcut in Scala is:You need the These don't join on a key. Union doesn't really do anything itself, so it is low overhead. Note that the combined RDD will have all the partitions of the original RDDs, so you may want to coalesce after the union.APIReturn the union of this RDD and another one.Return the union of this RDD and another one. Any identical elements will appear multiple times (use .distinct() to eliminate them)."},
Scala

I'm trying to save an rdd by as below,\ndata.coalesce(1).saveAsTextFile(outputPath)but i'm getting java.lang.OutOfMemoryError: Unable to acquire 76 bytes of memory, got 0Has anyone faced the similar issue, if so, i would like to learn how did you fix itcan you please provide of more details on you are getting OOM on driver of executor ?By the code you posted coalesce(1) will force all executor to send data to a single executor and  if you are data size is huge , you will start seeing failures . coalesce is resulting in shuffle.  (All mapperTask sending data to a single Task).Follow  for getting a in-depth understanding "},
Scala

I've got a collection of projects that all have a large third party dependency in common, it seems like a waste of space to copy this jar to all the projects during the build, is it possible to have maven just create a hard or soft link to a single cached copy?This is not a duplicate of  which relates to how to manage common dependencies from a pom perspective. This is about how to avoid copying the same dependent files to the target of multiple projects and just creating links to a single instance to save space.Simpler version of the question is: is there an equivalent to the maven-dependency-plugin's copy-dependencies goal that creates links vs. copying the files. Yes, Maven already does. It puts all your dependencies in your .m2/repository/... folder. In Windows it's c: \\ Users \\ [your_name] \\ .m2 \\ repository. So there is no need for linking it with simlinks or st like that. Just have your maven project search for the dependencies in your maven repository and your dependencies will be reused by all projects which need these dependencies. If you use the same maven all the time, the Maven settings are the same and for every project your repository folder is the same, so you're done already.Al different jars are saved here, so every single version you depend on. If more pojects depend on the same dependency, with the same version, it's that one jar being used for all your projects.You can remove all dependencies and re\u00efmport your dependencies, if you used an old version before, and you use a newer version now, you just deleted the old version, and the new one is back where it's needed."},
Scala

I just started learning scala, I installed it through \"brew install scala\" and when I type scala MYSCRIPT.scala or scalac MYSCRIPT.scala I get this error:I've tried looking for a solution to this but found nothing,Please help.OK I got it I have to write \"scala\" keyword outside of the scala terminal while trying to compile.So instead of what I was doing which was typing \"scala\" to bring up the scala interpreter and then again writing scala MYSCRIPT.scala I have to skip the first step which was opening the scala interpreter.Post can be removed."},
Scala

Simple problem:\nFor the following RDD I want to print out an output text file with the following format and header (UserID,MovieID,Pred_rating )Simple enough. right? so I am using this function:The above function is not working with the following errorWith your code the FileWriter object would be send to all nodes and executed in parallel, which does not work with the reference to the local file. Therefore you get the NotSerializableException.You would typically save the RDD to a file by saveAsTextFile:This writes out the file in multiple parts. You could add the header and combine the parts manually later.This worked like sweet lords will:"},
Scala

Hey I'm new to the language and trying to make a map that contains values used alot within the code, but currently having trouble calling the map into a parameter. heres and example of what it looks likethat part is fine but when i want to add them all to the parameter it says there is too many arguments?had to addto the end of the strings and ints, for example"},
Scala

I am writing parsing a JSON Strings and splitting them with a comma, but the Free also contains commas.I am unable to get my Pattern working for this. Tried various combinations but could not succeed.\n        I am using this as part of the Spark streaming, I could not use the JSON parsers for the reason these data come randomly from 750+ random sources, so splitting and getting the text as key-value pairs was a reason to use splitting.here is my String(Shortened for Stackoverflow use and readability).Can someone throw some help on this, please!This answer appears to have a valid regex for parsing JSON:"},
Scala

After I change the function name from something else to addOptitrans and recompile, I get the following error:I have confirmed that the updated class is produced in the expected place in the classpath. What could be going wrong?Delete temporary files with . Then rerun the command."},
Scala

I want to convert a rdd to DataFrame, it gave me type mismatch error, but actually the type is defined in the case class. how to fix it ?Error: is of type  so the map operation fails to convert a  to a  or a .Why not make  an  already, in order to have a strongly typed object?The problem is because your array has many different datatypes in it. The first value is a string, then two numbers and another string. So when it cant match it with one data type, by default it takes it as \"Any\".This can typically be forced to take up a specific datatype by saying something like,var data: Array[String] = new Array(\"abc\",\"123\")But this wouldnt work for you since you have values of different datatype in your array. Either pass them all as strings and then typecase them inside the class, or use something more sophisticated than an array which can only hold one datatype."},
Scala

I have a rdd:what I need is: now I'm trying ???is something I have difficulty with, I don't know how can I get access to the tuple inside iterable and only take each of them to a array. Or did I do something wrong from choosing mapValue method?If you don't need an Array as a result, and it is ok with any type of Seq, maybe it is ok with something like this:Given this example of data set:You can use a mapValue like this:That it is equivalent to: is the iterable object and It's in the  where you take the second part of the tuple.In this point, you now how to access and manipulate the iterable. If you need, force an Array, you can do it:"},
Scala

I would like to generate unique date range between current date to say like 2050.Not sure how can i create a function for it. Any inputs here please. The difference between the start and end dates can be anything.Unique date range means the function would never return me a date range which it has already returned.I have this solution in mind:We will use the  and  imports to achieve this:"},
Scala

Listing below is my code Here the plain text(\"E:\\plaintext.txt\") I'd like to encrypt is about 1 Mb.  The max length of RSA keys is 4096 bits and the max size it can encrypt is 501 bytes. I decided to divide my text into 2093 arrays(1024*1024/501=2092.1)I changed the plain text(E:\\plaintext.txt) and the amount of the plain text changed as well. But I got the same amount of cipher with two different amounts of plain text.Anyone who can help me? Use symmetric encryption such as AES to encrypt data.If you need a public/private key pair encrypt the symmetric (AES) key with asymmetric encryption (RSA). Then package the AES encrypted data and RSA encrypted key as a unit.  This is commonly known as hybrid encryption and is in essence how HTTPs works."},
Scala

I need to build Spark DataTypes manually from string depends on DataType of the column.\nI've tried it in different ways like:But can't find the way to do it correctly. Is this possible? \nI need to compare value given me as string with the value in the column.As I understand, you already have a data structure but want a conversion of the data types according to Spark's . I assume, there are no nested sequences or arrays."},
Scala

I have a dataframe with N lines in it and it has only one column. I want to copy it N times and concatenate. So at the end I want to create another dataframe with N^2 lines.How can I achieve that simply using Scala? I do not want to use for loops etc. because N is large.You can do this using a fold function:The only constraint is that N must be less than Int.Max_Value. Hope this helps :)You can test with a small df:"},
Scala

I am reading from a CSV file and I want only certain fields from the entire CSV my commands are as follows:Now I want to change the type of column 15 from String to Double. So i did this,Now i need to take only top 10 values from column 15, so i have used takeOrdered funtionBut When I run the last command i get ArrayIndexOutOfBound Exception 17.Please help me out.\nThanks.The second line is equivalent to That says, your Tuple has 7 fields.Your problem is here.you are expecting tuple fields  which does not exist  on   that means it got just 7 fields but you are using upto .I'm wondering, how you did not get any compile time error for   "},
Scala

I want to be able to easily replace one Spark Estimator with another.\nI've created method that uses generic estimator:Here's one of the classes that returns generic estimator that should be passed into above-mentioned method:The last line gives this error:How that can be fixed?The problem appears to have nothing to do with your higher-kinded type.  Your problem is that  declares that it will return an , but you are returning a  instead. You need to return an instance of  to match the declaration. This is a Scala issue--not Spark--and it's independent of the  function you want to use later."},
Scala

I am new to Scala and this is the first time I'm using it. I want to read in a textfile with with two columns of numbers and store each column items in a separate list or array that will have to be cast as integer. For example the textfile looks like this:I want to separate the two columns so that each column is stored in its on list or array.Lets say you named the file as \"columns\", this would be a solution:Here is one possible way of doing this:"},
Scala

I'm using Spark and Graphx on IntelliJ IDEA for the first time. I'm trying to create a graph and running queries on it but I'm getting the following error: java.lang.IllegalAccessError: tried to access class org.apache.spark.util.collection.Sorter from class org.apache.spark.graphx.impl.EdgePartitionBuilderHere's my code:The problem was with the scala version I was using, 2.10.6, because I had read from an installation guide that spark worked well only with 2.10.x versions. But after installing the latest version, 2.11.x, everything worked fine"},
Scala

I am new to Scala (Akka Actors. I am aware there are benefits of avoiding mutable state in actors, but a found a solution to incrementing a var total\nsimilar to that given by the SO question:    My code is below.The solution would appear simple: my Calculator actor maintains a local var total, and the appropriate match on a case class in receive()  => increments this total with an amount extracted from the matching case class.My case statements are working. A println shows that each time my input matches the case statement, the amount to be added to the total (amt) is yielded by the match. I.e. this works as expected:case MyCaseClass(_, amt) => println(amt)But this line:  case MyCaseClass(_, amt) => total += amtfails. The local var total is never incremented. I tried using a list, and adding the new amt as a new member to a var List, but this fails also. In each case increment of the local var, be it type Double or List[Double] fails. Why is this? and what can I do to get the increment to work inside receive()? Code:The  from your  is a different actor than the  from the . Each  creates a new instance of this actor, each with its own state. You send the  messages to one actor instance and ask a completely different instance for the state, which hasn't seen any  messages at all.You can modify the RoomActor to take an actorRef as a parameter and pass the  to the Props, this way you're using the same actor instance for the state.Also, since everything is asynchronous, the 'total' message might be lost if you shut down the system immediately after sending the message."},
Scala

This one is not duplicate I have new question. I tried to write thisCan I use na or IsNull in  to check whether or not that  is null?Code resultSomething like that:"},
Scala

I'm working with  and when i compile my proyect, show me the next errors:The lines 90 and 120 are are in bold:How can i fix this?Just add parentheses to  method. This will be work. "},
Scala

I'm reading a book \"Scala in action\" to learn scala. On page 59, the author provide following code. But when I run it, it doesn't compile.It reports:This book use scala 2.10. I'm using scala 2.11.Does scala change the usage of setter method in 2.11?I'm not sure what the context of  or what the author is trying to demonstrate with that line. Parameters of the constructor are public by default so removing  allows you to use the setter for free."},
Scala

I have the following RDDAn example would be:And I want to insert into my Cassandra table with the following schemaIn the end, for the given example, I will have the following in my DBWhat is the Scala code which does this? I tried to use , but my input isn't in the form of . Should I first flatten it?All you need here is a :"},
Scala

This was query written in slick using a for loop. Here  is table name and I am trying to update firstName, lastName of a user . When update completes successfully I am trying to return userId, firstName, lastName, false to user.I am trying to get equivalent query without using a for comprehension. Can anyone help me through this?I found equivalent query which works same as previous query without using for comprehension."},
Scala

This question is there on stackoverflow, the solution is in Python. Please help me with a solution in SCALA.Quoting the query below:So starting with a list of strings, as belowI want to remove any element from the list that is a substring of another element, giving the result for instance...How to achieve this in SCALA?You can do it the following way:"},
Scala

I am using Scala on Spark and need some help splitting a sequence of sets based on specific values within the sets.Here is an example:I am trying to split each sequence within the array based off the criteria that the first integer within each set is between the two integers within the other sets in the same sequence and return the character value of the sets grouped together. So for the first sequence you can see that we have the integers 15 and 20 in the first set and in the second set 17 and 21. So those sets would be grouped together because 17 is between 15 and 20 and the third set would not be left alone.In the second sequence I have 15 and 20 overlaps with 17 and 21. Also 17 and 21 will overlap with 21 and 23 and then the last set would be left alone.Essentially I would like to have it return , , , ,  I realize this is not great phrasing but if someone could give me a hand that would be very appreciated.As noted by the zero323,  should probably not be a set. I suggest converting it to a case class:With this class, if you described your problem correctly it could be solved like this:"},
Scala

I have this code :The return value of this function is (Long, String, String, String), I am trying to save the result of this function to a text file using saveAsTextFile and I cant since the result is not an RDD,any idea how to implement this ?You can convert the return value to an  and then call  on it."},
Scala

Find below the imperative style code:     Here I am interested in knowing how to convert changes made to offset within the loop in a functional way, how to do early break from the loop etc.This is a nice demonstration of one of Scala's great strengths - gradual, easy migration from imperative Java code to functional code.To convert to Scala, you don't need to go 100% functional straight away.  You can easily convert what you have to Scala as follows:Note we already have some small improvements in verbosity: no more s, no redundant type signatures, mutable variables converted to constants where possible, eliminated return statements and function brackets.  Note I changed the argument type of  to a scala list, you'll need to use the  at the call site to make this compile.Next, we can start making this more functional... however, this function probably isn't the place you should start, as you are calling state-mutating functions in several places.  For example, you could start with ChessLayout:These methods mutate ChessLayout, which is not functional style.   You could modify  to return a new  with the piece removed, and  could return a tuple of .  Once you have stopped any functions called from  from mutating state, you can then convert it to functional style."},
Scala

How can I have my custom exceptions include a text message when thrown?\nThis code snippet demonstrates a wishful intent:But running in sbt, the custom text is not shown.\nWhat might be the idiomatic way to accomplish that? Of course I could generically catch any exception and print its details from that catch code, but that would be a little tedious.Technically speaking this is just , the superclass being java's  in this case. "},
Scala

I am trying to create my first project using Play2 and Scala.Unfortunately, my controller does not see my model and my view.Controller:Model:View:I am getting the following errors in my Controller.\nWhere I access the model:Where I access the view:\nI changed the signature of wikiArticle.queryApi()You call without parameters:while you have defined queryApi as function with parameter:Also, note upper/lower case"},
Scala

I just started playing with scala and i cross the following issue. I want to simply return a Map with Int as key and List of Tuples for values. That is my method:However my IDE shows error as:Does it mean that  creates  instead of Map? If so, how can i make it return Map?// editI'm trying to write a bot to javascript game. I'm mapping a board of tiles. In the mentioned method I am trying to find all \"open tiles\" (tiles which are not fully surounded by other tiles, thus can be moved) and in the return i would like to have a Map where key is a tile number with coordinates as values. In next step i want to find if it is possible to find path between \"open\" tiles with the same number. I think the problem is the lineYou should try this:Your version assigns the type  to the value ."},
Scala

I have an RDD as a tuple where its key as an integer and value as List of integers:Data contains userId, the list of items the user have bought.I want to convert this to string such that:I did the following: But when I look at the part files the structure was completely different, which was: Try this:"},
Scala

Here is a code structure:Now, a method in another class needs to refer to the method makeACopy.I get a complying error for invoking the makeACopy method although I already specify the parameter as a sub-type of Foo and Intellij IDEA doesn't complain the line:Why? And how to solve it?Also, I am not sure why I have to have a full path for returned data type of makeACopy in Bar. Otherwise, the IDE will complain returned type mismatch.You're defining  separate type parameters named , and only one of them as a subclass of Foo:A method defined within a trait (or class) with a type parameter  shouldn't declare  again, so you probably want to change this to: Then, wherever you call / override , you don't need to specify the type, you already did when you created / extended , e.g.: "},
Scala

It's possible that this question has been answered before, but I have not found it via search engine or this site's search.I'm trying to implement soft deletes in my DAO object. My table has a column, , which is either null or a timestamp. If it's a timestamp it has been soft deleted.I'm trying to write the query that will perform the soft delete, and this is what I came up with (note that it doesn't work):The error I get is , which I suspect is for the update, why isn't this valid, and what's the correct version of what I'm trying to do here?You do not post the table definition but I assume that is Option[Timestamp] if is the case you need to do: Some(new Timestamp(System.currentTimeMillis))"},
Scala

I have simple Scala Play Framework and Angular application. I tried to render JSON data on play's \"xxx.scala.html\" template but don't know what is the problem it is not rendering as expeted.My route entryScala Controller:When I am calling my page using urlI was getting response on page as below,Please can you explain what am I doing wrong here?Thanks !!There are some problems in the code. The  one is this:What has changed: is what you would expect:I have corrected code as you mentioned above but still I can't see response on my UI as below,Still don't know what am I doing wrong here."},
Scala

In my current environment,  doesn't work. I would like to make sbt print \"This doesn't work, do the following instead: [...]\" until we get  sorted out. How do I do this?You really should have read the sbt docs for this. "},
Scala

I have 2 rddCompare the two rdd and once which match the with the id will be updated with the value from the rdd2 to the rdd1.\nI understand that rdd are immutable so I consider that the new rdd will be made.\nThe output rdd will look something like thisIts a basic thing but, I am new to spark and scala and trying things.Use  to match two RDDs by key, then use  to choose the \"new value\" (from ) if it exists, or keep the \"old\" one otherwise:"},
Scala

How to solve the error  for the following case. is in the format , where the first  is actually .I want to save  into the text file, which works fine for non-vector parameters. However, when I add , it stops working.UPDATE:The command  gives the following output:Ok after a small discussion with you in chat, the issue lies in the way you are actually working with your parameters grid.So, first, I'll re-defined my gridParams as an object and not a MapThen I can compute the evaluations with the parameters : If you want to convert the list to an RDD, go ahead, it seems rather small, so you can actually use plain Scala, as for the format now that we have error with, you can save them doing the following :"},
Scala

I'm trying to concat all distinct values of a Spark RDD, separating them with comma. This is my code:But it returns to me just , why? Which is my mistake?It works if I write  and iterate on that. Why?Running a similar example on PySpark, I get \"lambda cannot contain assignment\", so I assume Scala would work the same. You should be able to  the RDD, and then do the comma-join. That is essentially what you are doing anyway. The reason you probably can't do assignment is because Spark can't pass your string to all the worker nodes and concatenate it with the diffrent partitions of data, then accumulate the result to pass it back to the running code.  "},
Scala

I have the following arrays:I want to remove Arrays having different Strings. E.g:  needs to be removed.  How can I do it?  You could simply use:Instead of distinct, you can use simple custom function, that will be little bit more efficient, since it should not traverse whole array, if duplicate is in the beginning of an array:"},
Scala

To be more specific, how can i convert a  to a  ?I have an RDD of \nand i want this to be converted into an  of , so that i can apply a reduceByKey function to the internal .e.g\ni have an RDD where key is 2-lettered prefix of a person's name and the value is List of pairs of Person name and hours that they spent in an eventmy RDD is :i need the List to be converted to RDD so that i can use accumulate each person's total hours spent. Applying reduceByKey and make the result as \nBut i counldn't find any such transformation function. How can i do this ? Thanks in advance.You can achieve this by using a  and . Something like this:"},
Scala

I am trying to define a function in scala to iterate on it with Spark.\nHere is my code :With this code I get this error : I don't know what means this error...You are not showing your imports, but you are probably importing Scala standard collections' (this one takes a type parameter, e.g. ) instead of the SparkML , which is a different type and you should import like this:"},
Scala

I want to call value of '' variable. How do I do that? \nIf i pass static value like \"actionId\":1368201 to myActionID then it works, but If I use \"actionId\" : ${actionIdd} it gives error.Here's the relevant code:Everything works fine If I put value 13682002351 instead of myActionID. Thanks in Advanced. While executing this script in Gatling I am Getting this errorScala has various mechanisms for String Interpolation (see ), which can be used to embed variables in strings. All of them can be used in conjunction with the triple quotes  used to create multi-line strings.In this case, you can use:Notice the  prepended to the string literal, and the dollar sign prepended to the variable names. "},
Scala

I got this far:but get  as a result (with no error). The file is  How do I go on from here?After consulting  I triedand gotI see that you tried the Learning Spark examples.\nHere the reference to the complete code \n \nE.Instead of you can try this(i write it in java cuz i don't know scala but the API is the same):spark will read your json file and convert it as a dataframe. If your json file is nested, you could use for example, see my answer Hope this help you."},
Scala

How to navigate in a Map[String, Any] in Scala ?e.g.: Which will be equivalent of .But what i want to do is  and navigate in the Map.Is this possible?P.S.: I have this made in Java, but it's like  cast to Map, get the new value and recursive call the  with remaining tokens.For the record, I think, this is a very wrong thing to do, but, if you insist, here you go:"},
Scala

Two sets, s1 and s2, of Foo objects, whereThe equals and hashCode methods are override for a data comparison.Now, I need to find out all objects in the s1, but not in the s2. I can't usedue to the equals/hashCode method override. It likely shall use the filteror creating a map with the ID field as its key and its object as the value for the first set and remove any entries in the second set.What is a good approach to solve this problem in the Scala way(s)?Update:I was thinking of something like the followings:The second line of code doesn't work, however."},
Scala

I have installed the spark in cluster mode. 1 master and 2 workers.And When I start spark shell in master node it is countinously running without getting the scala shell.\nBut when I run spark-shell on a worker node I am getting scala shell.And I am able to do the jobs.And for this I got the output.So My doubt is actually where to run the spark jobs.\nIs it in worker nodes?Based on the , you need to connect your  to the master node with the following command : . This url can be retrieved from the master's UI or log file. You should be able to launch the spark-shell on the master node (machine), make sure to check out the UI to see if the  is effectively running and that the prompt is shown (you might need to press enter on your keyboard after issuing spark-shell).Please note that when you are using  in  mode, the driver will be submitted directly from one of the worker nodes, contrary to  mode where it will run as a client process. Refer to the documentation for more details. "},
Scala

I have an array, for example:and I want to create a new array containing just the integers called .I tried something like:I hope the idea is clear, but of course that didn't work.You are looking for A good resource for answering questions like this in the future: "},
Scala

I have a Scala/Spark project (built with Maven) in which I want to do the following.I would like to modify , so I've copied the source code of that file into my own package: . However, it relies on some classes like , which are declared as .I had hoped that by putting my code inside of , it would be able to access the private members. But it is complaining, perhaps because Spark is imported via a Maven module? How can I work around this?Here is how the pom.xml imports spark-mllib:Here is an example of an error message I run into:Looking in the source of org.apache.spark.SparkContext, I see that checkpointDir is declared as private to org.apache.spark:Why is it that I can't access this member even though my code is in org.apache.spark.mllib.myrecommendation.ALS, a child of org.apache.spark?It works for me.Since packages are open, adding to them in the way you describe is perfectly fine (modulo loading from sealed jar files).A trivial sbt project with ALS.scala modified to reside in package  (and fixing a couple of ) and importing .build.sbt:ThenPlease do not try to violate visibility and accessibility rules, in any programming language. If you really need to change something in Spark source code where it was not designed for, the safe approach is to :Spark tests are executed as a part of the build and hopefully if your modifications introduce bugs, you will discover it because a test fail.  "},
Scala

I am getting a compile error at \n.\nIt says . Any idea about this issue?\nAlso is this the correct way to use Scala generics? is a map whose values are of type \"some unknown subtype of \". So you can't put  into such a map, because  might be a different subtype of  from the particular subtype that that map uses.You probably want a , though to be honest most of your generics look unnecessary - if you just want to store and retrieve s, why not just keep them as that? If you want a cache of some specific subtype of  then  should be a type parameter on the class, not on the individual methods. What is it you're trying to achieve?"},
Scala

I'm getting this error:I don't get error when I do  instead of just  , but in this case, it is shadowing the variable. Please help, how to resolve this.I get error When you say , you're saying that the type parameter  of  must have a lower type bound of . That means that  can be  or any super-type of it, which would break the type bounds that .For example , so  in this hypothetical situation could be , but  is not also not true, so the type bounds break.When you say , then  has a  and an . The upper bound of  for  is important, because the contained type of  also has an upper bound of . Without that, it would try to allow  (or some other super-type that isn't ), which of course it can't.How can you solve this? You have you pick one way to do it. You can't have  and  at the same time. It just won't work, because the type bounds conflict."},
Scala

What does :: mean here ?Specially I don't understand the \"\" operator.Its the list  operator. It creates a new list whose head is first argument and whose tail is contents of the second argument."},
Scala

I am trying to sort an Array of Strings in alphabetical order using scala. The Strings are passed in an array when the method is called. The method must also return an array with the sorted Strings. How would I do this? ThanksMikeYou just need to call ."},
Scala

I am trying to install SBT for scala developing. I follow the guid in The errors show as followsThe link \"\" cannot be accessed even in the browser. Are there any solutions?As the commenter said, it looks like you are just having a network connection problem.However, if you are not using a package manager, I recommend to use the \"sbt-extras\" script from . I.e."},
Scala

How can I make the following function tail recursive and fully streaming?The goal process the stream with some lookahead. As an example let's say we have a stream of sequential numbers: . Now I'd like to calculate the sum of 5 sequential elements of this stream beginning at every element. With the function above it would look like this: , producing the stream of . But this will break the stack on large input. How can I optimize this function?Why do you say this will break the stack on larger input? Have you tried this? Please refer to , where Ken Bloom points out that streams don't need tail recursion. In fact, I ran this on a take 1,000,000 and it returned in < 1 second."},
Scala

Am trying to send the table query object from local actor to remote actor,\nbut akka gives serialization exceptionRemote Actor looks like this and am using active slick pattern hereLocal Actor looks like this. Local Actor builds TableWithIdQuery and passes it to the Remote Actor mentioned above.It's not safe to assume that any thing like a Query is serializable.  You really ought to run the query in a local context, map the results to a set of serializable types (e.g. immutable collections, case classes), and send that."},
Scala

I know there is two ways to run a scala code in Apache-Spark:Is there any other way to run a scala code in Apache-Spark? for example, can I run a scala object (ex: object.scala) in Apache-Spark directly?ThanksScala version:for more detail refer to ."},
Scala

Everytime I change code in the project I would like to run two separate sbt actions in this order:I thought it is possible with activator/sbt commands like , but it sticks to \"run\" and don't do any testing until I break sequence with Ctrl-D.Is this possible to run \"test\" action before \"run\" in triggered execution mode?Because of the nature of  it won't re-run  on a code change. What perhaps might work for you is to have 2 sbt shells open, one with  and one with .A note of warning though, multiple sbt shells, especially in trigger execution,  trip over itself because there's limited locking on the relevant files - which is one of the things sbt server hopes to solve."},
Scala

Here are the codes (I'm using Slick 2.1):I tried to create two mappings  and  in the Table class, however, Slick complains about this:I saw a  about this, but it looks quite complex and has no explanation..Does anyone have ideas about this? Thanks!Slick expects Username to be Option[String] in the 'profile' projectionClearly Slick here doesn't know how to map the columns with the case class ."},
Scala

In scala, if we have a class say,would give an error saying, when compile with  Everything is fine till here.However, if I have a java class :first compile it with ,\nthen use it in scala with :compile  with  and run with . No error occurs.Does it break intention of  in scala?If I want to, when using java class in scala, maintain the fixed value of instance , what can I do?Or there actually is some documentation mentioning this behavior? Thank you everyone for your reply.While I am well aware that by making the field final:\n, immutability can be achieved.I'm not hoping to solve this problem by modifying java code.\nImagine that I'm using third party java libraries that I can no way modify their code, yet I want making sure my code won't accidentally modify third-party's internal state, hence come the .In addition, by disassembling the  file using , it can be seen clearly that scala is not making  immutable by inserting  to class . Or maybe someone explaining the \"magic\" behind  would be helpfulClearly in your Java class , the member  is both public and mutable. To treat a Java variable as Scala , you can make it  in your Java class.Also remember that Scala too has  which has essentially same behaviour as Java variables ( except for  ones ).Define  like so:And then check the compiled class definitionThing to note here is that for member 'c' you will have  but for member  there is no such method. In fact in Scala, the assignment turns out to be a method call.I hope that makes it clearer.Your confusion comes from line  in . It means that you cannot reassign value to your variable  but it's completely ok to reassign any field of . This can be limited by marking a filed be finalTry making   in your java class as following It will enforce that field  of class  cannot be reassigned. "},
Scala

I have the following scala script:When I am trying to compile it, I am getting the following errors:I have a file simple.sbt, which lists the dependencies:Does anyone know how I can fix this? Thanks in advance!After fixing the quote problem, as correctly pointed out, I am getting this error:TryIt looks like you have the wrong kind of quotation mark in the offending line ( instead of )."},
Scala

I have to make a connect-four game using scala. I have attached the code but everytime the game runs and gets to row 3 it just continues to change the second rows entry instead of going to the next row. Any help would be appreciated. I found this code on  on here and couldn't figure out how to get it to work:I've tried to make your code readable and compiling and also tried to fix some logic.However, I've never worked with Scala so this is just a first sketch where you might want to continue ...Some functions can be merged and the currentRow needed a fix. See here:"},
Scala

So basically I'm starting scala and I'm trying to build a simple RPG script to get accustomed to the language. The first problem I encountered is how do I declare a class Character and a class Ennemy, knowing each have methods using instances of the other class as arguments. I haven't encountered this problem in other languages (Or they have a way of saying: Hey I'm using this other class but don't instantiate anything unless you're called), here in Scala I have the following error: not found: type Ennemy. I guess there is a key word to use somewhere but I just can't find it.ThanksEdit: Sorry I didn't incorporate the code, BUt basically I stripped it down to this:And the code still doesn't compile and return the mentioned error.If you're in the scala repl, you need to define them at the same time to avoid this. This is because each expression is run one at a time, and if you can't reference something that isn't defined yet.Note that this is not a problem for classes defined in .scala source files.You can use  to define multiple things at once.Other notes:This does mean that characters and enemies can kill their own kind. There's ways you can define it differently to avoid this, but I'll omit them since I think it's more complicated than you need right now."},
Scala

I am converting my Scala code to pyspark like below, but got different counts for the final RDD.My Scala code:where I then tried to convert them to pyspark code as below:where I have:and and BTW,  is converted from a data frame. i.e. However, I got different counts for  and . I checked the codes many times but couldn't figure out what I missed. Does anyone have any ideas? Thanks!Consider this:and this:"},
Scala

How can I define this function recursively?Somehow k has to stay the same, but as we can't use a j, we have to change k for the next recursion stepAs usual for recursive functions you have to pass ,  and  as well with every call. This is very logical especially if you think about one particular function execution. It only calculates one step of the incremental product. As a consequence the function signature looks as follows:You have to increment the j after every particular calculation to pass the next  to the following execution. Furthermore you have to add a termination condition which looks like the following:If you have to do this as a recursive function, try something like:It is worth checking searching for foldLeft and foldRight and reading about the differences."},
Scala

I have a dataframe and I'd like to add an extra column to it based on a simple condition which basically says whether the value sof another column is equal to a given string or not. I know I can create an UDF and register it and use it then, however I think there must be an easier way of doing it. This is the psuedocode of what I'm about to doYou are pretty much there:Note that you will need  and  imported for the above to work."},
Scala

Just learning Scala.Tried this:def ! : Int => Boolean = (p : Int => Boolean) => !pGetting a compiler error:error is highlighted for \"!p\"Shouldn't the compiler automatically figure out that the result of p is a Boolean ?Thanks in advanceEDIT: Based on comments, tried the following also. Have accomplished my task using other methods, nonetheless, am trying to learn how to define an unary operatordef unary_! : Int => Boolean = (p : Int => Boolean) => !(p(_))still getting a compiler error at \"!(p(_))\"Maybe you intend something like:"},
Scala

I am trying to get avg of ratings of all json objects in a file. I loaded the file and converted to data frame but getting error while parsing for avg. \nSample Request :so for this json, US avg rating will be  (2.3 + 3.3)/2  = 2.8for this avg for us= (3.3 +1.3)/2 = 2.3so over all, the average rating will be :  (2.8 + 2.3)/2 = 2.55    (only two requests have 'US' in their visited list)My schema :When doing : Can someone tell me what I am doing wrong here ?Assuming  is a  (your code example isn't comprehensible... you create a  variable and query an  variable), you shouldn't call  in order to select from it: would call a function on each record (of type ). That is useful mostly for invoking some side-effect (e.g. print to console / send to external service etc.). Mostly, you wouldn't use it for selecting / transforming Dataframes.:As for the original question of how to calculate the average of US-only visits:"},
Scala

I am creating a web application which will accept some inputs from user (like name, age, address etc) and generate some predefined forms with filled information for user to download and print.For example, an Application Form for driving license or something along those lines. The backend will have the format information about the document to be generated and other information will be gathered from user from front-end.I am going to use  for this and  as programming language. But right now I am not aware if there are any free libraries/APIs that I can use to achieve this document generation.I should be able to manipulate the  some other basic stuff. And I need documents in format that are widely supported for editing and printing purposes. Like  for example. DOCX is preferred so user can edit something after downloading the document before taking a print out.I have used the apache POI library  to parse and create ms word documents (including docx) files:It's not amazing but it's the best I've found :)I have used  which simply converts xhtml to docx.What you can do for your requirement is save your format information as xhtml template and place input from form (like name,age,address etc) into the template at runtime.This is a sample code to refer from this "},
Scala

I have the following data in a CSV file(actually, my real data is larger but this is a good simplification):I am reading it the following way, where  is the location of the file:For reading, I am using Then, I am applying a map on it:However, when I am referencing the column like this:  I am getting a type mismatch:Why is this occurring? Shouldn't every row of  be a Map?when you reference a perticular column in datafram's row, you have several methods to do this. \nif you are using apply method then you need to pass the index of column.\nor if you want to get a column by name you need to use getAs[T] function of Row.so you can use :or hope it will help you."},
Scala

I've got and I want to get it zipped. Is there any succinct way to do it instead of accessing each element of main list by index and zip it together with  command?This works, under the assumption that the outer list has exacly two inner lists.In order to take into account the possibility of failure, you can wrap the result into an ."},
Scala

Hi i am new to apache spark and scala. I am trying to convert \n to Could you please help me in conversion.In the absence of concrete types in the question I have made an assumption that the values in your array are Char and Int tuples respectively. Here is how we can transform to the desired output:Basically we can traverse the elements in a Tuple using a productIterator. We also need to map each value to an Integer so so to compute the sum.Also have a look at this question: "},
Scala

i am new to spark and to its relevant concepts, so please be kind with me and help me to clear up my doubts, i'll give you an example to help you to understand my question.i have one javaPairRDD \"rdd\" which contains tuples likelets assume that String[].length =3, means it contains 3 elements besides the key,what i want to do is to update each element of the vector using 3 RDDs and 3 operations,\"R1\" and \"operation1\" is used to modify the first element,\"R2\" and \"operation2\" is used to modify the second element and \"R3\" and \"operation3\" is used to modify the third element,i know that spark devides the data (in this example is \"rdd\") into many partitions, but what i am asking about : is it possible to do different operations in the same partition and at the same time?according to my example,and because i have 3 operations, it means that i can take 3 tuples at the same time instead of taking only one to operate it:the treatment that i want it is :(t refers the time)at t=1:at t=2:After finish updating the 3 first tuples, i take others (3 tuples) from the same partion to treat them, and so on..Spark doesn't guarantee the order of execution.You decide how individual elements of RDD should be transformed and Spark is responsible for applying the transformation to all elements in a way that it decides is the most efficient.Depending on how many executors (i.e. thread or servers or both) are available in your environment Spark will actually process as many tuples as possible at the same time.First of all, welcome to the Spark community.To add to @Tomasz B\u0142achut answer, Spark's execution context does not identify nodes (e.g. one computing PC) as individual processing units but instead their cores. Therefore, one job may be assigned to two cores on a 22-core Xeon instead of the whole node.Spark EC does consider nodes as computing units when it comes to their efficiency and performance, though; as this is relevant for dividing bigger jobs among nodes of varying performance or blacklisting them if they are slow or fail often."},
Scala

I want to build a recommendation application using spark mllib and the ALS algorithm in collaborative filtering technique. My data set has the user and product features in string form like :But the  method seems to accept only int values for both user and product features. Does that mean I will have to build a separate dictionary to map each string to an int? My dataset will have duplicate entries for both user and product.Is there a built-in solution for this in the mllib library itself?Thanks and any help appreciated!Edit: No, this is not a duplicate as the answer in that question doesn't seem to fit my scenario.  library doesn't seem to support String values for  or . I need this support.Let me try. Assuming that That should do it. Basically, you just create a mapping from string to long and then convert long to int."},
Scala

I have created a unlabeled Dataset which has some columns. The values in one of the Column are France,Germany,France and UKI know how to filter and count using below code.However, I am not sure how to count values other than France.I tried below code but it is giving me wrong resultPS: My question is a bit similar to  but I am looking for some simpler answer.You are trying to filter those elements which is equal to \"France\". \nTry thisTo cricket_007 's point, should be something like thisI am not sure what column your data is in, so the row._1 would change to the correct number.  You can run the following to see all of your columns:"},
Scala

I have seq i want to do the iterate automaticYou could use  with . Here is a simplified example:This code would return . If you just care about the correct result and don't care whether or not all futures get executed, you could chain them with :This would give you a  that would complete with  with my example predicate .As I found myself with some extra time, I took the liberty to combine some comments and suggestions in other answers (especially from ) with a  approach:You can now use this function with any kind of futures you want and provide an operation that should be executed with the first valid result or the defaultValue (though IMHO in case of no valid result I'd prefer a  with proper error handling myself):As an extra tip, if you want to speed up the function you can have the iterator lazily evaluate two functions at a time with . This way, while one future result is being evaluated, the iterator will automatically start the next future.Method  will return the first  that matches the condition specified. The resulting  will be a  if none of the input s match. To return some default value otherwise, you would simply do the code here demonstrates basic principles and does not distinguish between planned or unplanned exceptions. this code is not tail-recursive.This will give you Iam not sure if there is another approach but for my understanding if you want to decide based on the result of the preceeding future you need to wait.\nHere is a recursive approach. But in my opinion the one with the iterator is good.It's tail recursive therefore your stack won't overflow that easy."},
Scala

I am trying to dig scala deeper but scaladocs is not straight as javadocs. While doing some mathematical operation I visited to scala.math  package.\nI am not able to understand value member in the docs.please suggest some guide line to decipher scaladocs. It may be a silly question but as a newbie please suggest something.See :So - the Scaladoc for  package divides members of this package to  (classes, just like in Java) and  (s, s, s and s). You can see these members in the source code at .In this package all member classes and  are  members,  and s are  members."},
Scala

I have the following case classso, I can do the followingand I would like to able to call parts of the LeftHandSide by name too, e.g:And then:Create an additional case class called :And use that in :And then:"},
Scala

I am trying to install SBT following the instructions mentioned in:\nBut I am getting an error while running command:The error is:I referred  with similar issue but I am not able to figure out what is the problem.I don't think it's really an issue with the filename. I was able to use that same command without a problem. If the filename was an issue, you could always use this to save it as a different filename: The other option is to use bitly and get a URL if the URL is just too long.But it could be a space issue. Do you have enough disk space? Check with  to see your available space."},
Scala

So suppose I have the following data (only the first few rows, this data covers an entire year) - I would like to filter the data so that I only see what the names are for a specific date (say, 2014-09-05). I've tried doing this using the filter function in Scala but I keep receiving the following error - Is there another way of doing this? The  method takes a function, called a predicate, that takes as parameter an element of your (I'm assuming) , and returns a .The returned  will keep only the rows for which the predicate evaluates to .In your case, it seems that what you want is something likeI presume from the tag your question is in the context of Spark and not pure Scala. Given that, you could filter a dataframe on a date and get the associated name(s) like this:Note that the  above is .Here's a function that takes a date, a list of datetime-name pairs, and returns a list of names for the date:..."},
Scala

Is there a way to get the dataframe that union dataframe in loop?this is a sample codeThanks againSteffen Schmitz's answer is the most concise one I believe. \nBelow is  a more detailed answer if you are looking for more customization (of field types, etc):references:In a for loop:you can first create a sequence and then use  to create .Well... I think your question is a bit mis-guided.As per my limited understanding of whatever you are trying to do, you should be doing following,And this should be sufficient.You could created a sequence of s and then use :"},
Scala

I was playing around with dependent types and run into this error:using this code:Could someone decrypt what value element stands for?The first problem is that you're using an abstract type member for no conceivable reason. It's not directly related to your error, but alas.Ok now for the actual failure, it's pretty obvious and straightforward, you have not provided an implementation for . Your  class , so any concrete implementor must provide an implementation for  by your very contract.A  or  can have abstract members, a normal  cannot. Ergo, kaboom, compiler is telling you to get your OOP up to scratch.Or better yet:"},
Scala

How can I convert type  to type  in scala?Right now I have this val:I am trying to extract the  objects associated with  and  and pass these maps into a function.example, following is  of to cast  to Then pass to the function. This way, you can handle a case when the result somehow is not . ()Example below"},
Scala

I have a  as mentioned below:I want to create a new , which will have only unique , but as  and  columns are different for same customer in data, so I want to pick those records which has highest priority for the same , so my final outcome should be:Can anyone please help me to achieve it using Spark scala. Any help will be appericiated.You basically want to select rows with extreme values in a column. This is a really common issue, so there's even a whole tag . Also see this question  which has a nice answer.Here's an example for your specific case.This example is in , but it should be straightforward to translate to To create  you have to first order  by  and then find unique customers by . Like this:It would give you expected output:Corey beat me to it, but here's the Scala version:You will have to use   on  column  the  by  and then  the  with the  and  the required columns. you should have the desired result"},
Scala

My problem is that I have to take a result permutation on Factorial.\n Print out all n! permutations of the n letters starting at a (26 letters). A permutation of n elements is one of the n! possible orderings of the elements. AS an example, when n = 3 you should get the following output. For Example: abc bac acb cab cba bcaIn scala 2.9, there is a method called permutations of Seq.Or just implement it yourself:"},
Scala

Why does the following code works:But not this one:Which fails with the following error:It seems to work if you help the type inferencer when calling the constructor for :So it doesn't look like a fundamental limitation. But the error message which you didn't include is very unhelpful . "},
Scala

When trying to hit an environment with improperly configured SSL certificates, I get the following error: I would like to ignore the certificates entirely. : I understand the technical concerns regarding improperly configured SSL certs and the issue isn't with our boxes but a service we're using. It happens mostly on test boxes rather than prod/stg so we're investigating but needed something to test the APIs. You can't 'ignore the certificates entirely' for the following reasons:The following was able to allow unsafe SSL certs. "},
Scala

Here is my code:It doesn't work. It just to totally skips over the if (values.get(\"x_card_num\") == None) and else statement, and card_num ends up as an empty string, as defined before the if else statement.Why would it totally ignore the if else statement?And how do I check to see whether the key exists in the array \"values\"?The problem here is that you are  the outer scope. That is, you are declaring  value called . In scala, , so you can simply do this:That is, the  itself evaluates to a value (as long as there is an )the other option is to use  as opposed to , but this is not idiomatic (you should avoid s):You could use  to simplify the test"},
Scala

I'm compiling the following code in scala:but it gives me the following error:And this:I think the problem is that I need some packages.I need help and I tell me please the following:Repository that I can download the packages that I needThe package versions:In my sbt I have the following packages:The problem is with: draft10, not where to get the package.Thanks for your attention, I hope you can help me.I'll point you to the javadoc: It says that the package draft10 is available since version 1.4. So update your sbt script to use version 1.4 instead:Also, make sure that you don't try to use several versions of the same library. The script that you posted refers both to version 1.10.0-beta and versiom 1.3.1-alpha of google-api-client.the solution is:\n\u00a0\nfor SBTand the repository:"},
Scala

I'm building several different web services, hosted on different machines, but I want a single set of users to be able to access all of these services, yet also have varying read/write permissions between the services. What is the best way to accomplish a secure authentication scheme for these multiple services?This is a very general question, so here's a general answer.What you are looking for is something with a single authentication scheme for all sites combined with different authorization and access control schemes on the different sites.The first part is pretty much what a \"single sign-on\" (SSO) system gives you, though you could do this without SSO.The second part can be achieved by separating the access rights management from the authorization scheme.  For example:(These are just examples ... not recommendations.  I'm not going to make specific recommendations because it is next to impossible to do objectively, especially since your requirements are so high level.  For instance, a lot depends on the technologies used to implement the websites.)Currently i'm building a registration system for our projects, similar to what you want. Although we have a different stack: Scala-Akka-Spray, authentication system is based on  and  with some custom internal logic for more REST style session managment. Strompath will give you a good user managment system with quite flexible group settings and Shiro, if you don't use Akka, gives you goog session managemant."},
Scala

Please let me know how to make the following bit of code work as intended.  The problem is that the Scala compiler doesn't understand that my factory is returning a concrete class, so my object can't be used later.  Can TypeTags or type parameters help?  Or do I need to refactor the code some other way?  I'm (obviously) new to Scala.The last line of code fails because the compiler thinks  is an , not a .You should create companion objects with  method for each subclass of  instaed of  trait. Also, it is considered a bad practice to use mutable field like you did with .You can do that, without changing anything else :But, i don't think it's a very good idea...I don't want to sound rude but the compiler is right about assuming that  is an  because that's what the  method returns. As already pointed out you could force the type of d with an explicit cast but it simply wouldn't be type safe. It would be leveraging your knowledge about the method implementation as a programmer, which will eventually become a source of bugs as your codebase grows and you possibly change previous code in unexpected ways. If you need to call a  method then you would better use a factory method that creates  objects, or at least check the object type before doing the type cast, usingOr better still, using pattern matching"},
Scala

I have a simple Jackson parser, that is supposed to return me values but instead am getting only  values. Any ideas will be appreciated? Sample Json data:Code:   Output:My Java code looks like this and works perfectly fine:"},
Scala

How can I parse a date string with  datetime which uses the correct timezone WITH daylight saving time?As an example in scala I try to parse the string \"2014-04-07 01:00:00.000\" (without timezone information). This date is coming from MySQL and is supposed to be in tz Europe/Berlin +01:00. What I like to have is a joda date time according to 2014-04-07 00:00:00+01:00 which is the timezone Europe/Berlin currently not on DST (GMT +1).Unfortunately Joda-Time parses the date to 2014-04-07T01:00:00.000+02:00 which is currently the wrong offset (02:00 instead if 01:00)Any ideas how to make Joda-Time parse the date with the correct DST offset?Joda-Time is correct. Your assumption of +01:00 for Berlin is incorrect. You did not account for Daylight Saving Time.According to  at TimeZoneConverter.com for the time zone \"Europe/Berlin\",  (DST) began on Sun 30-Mar-2014 at 02:00:00 A.M. when local clocks were set forward 1 hour. According to the Wikipedia list of , that means Berlin shifted from being one hour ahead of UTC (+01:00) to two hours ahead (+02:00)."},
Scala

If my code is:}It works, @main is my another template.\nBut if I want to do:}the compile get me error: How to passing variable string in scala template in this situation?Just use  instead of It is because u are using '' multiple times in a single row, answer is given by @serejja above"},
Scala

There used to be a helpful Scala Option cheatsheet on , but it seems to have been taken down. Has anyone saved it?You could get full version (with introduction) on archive.org.Note: , which includes the introduction and the cheatsheet (which is also below in this answer). (I'm unaffiliated). The ever helpful cheatsheet:flatMap:flatten:map:foreach:isDefined:isEmpty:forall:exists:orElse:getOrElse:toList:coflatMap*:duplicate*:*: Unfortunately coflatMap and duplicate is not part of the standard library. You will need to write it yourself or use Scalaz.End of excerpt"},
Scala

I have the following:But the assertions fail. Surely that is correct, but it says implementation is missing when running it.I think the implementation you are looking for is:What does the method  mean? It takes an  and returns a function .\nThe function  takes another  and returns an .So we want to return with a function that takes a  , that's why we need: .Type inference works nicely here, you don't need to write (but can): this returns Int while expecting Int => Intit should be"},
Scala

I want to print set in the order (8,9,5,2,6,4,3).But instead of printing in this order it gets printed in this order (9, 5, 2, 6, 3, 4, 8).Why does it so?Sets are traditionally unordered, so the insertion order of elements is usually lost. List are ordered, but differ from Sets in that they can have duplicate elements.You'll want to use a  if you wish to use a Set that maintains insertion order when iterating over its elements.Warning: LinkedHashSet is mutable,  is an immutable option that stores the reverse of the insertion ordering.Sets are not sorted inherently, but can you use a ? There is some decent documentation on sets Set is an unordered data type. Use an ordered set - such as SortedSet or TreeSet - and pass it a customized sorting algorithm to sort based on when it was added to the set.You will have to create your own data type which holds the integer value you're trying to store and a date attribute representing the entry time.\nYou could use an ArrayList or some other list type. And instead of directly adding an element, call your own add method which checks to see if the element is there already with the contains method.Hope this helps."},
Scala

Say I have a  and I want to get A.nameHow to write it shortly?Use :If you want to do nothing if it's , use updated:you can learn more usage of  in the API doc: "},
Scala

How can I make a function that is given a function as input and returns a function with the value tripled. Here is some pseudo code for what I'm looking for. Concrete examples in Python or Scala would be appreciated. In Scala:You can use the Python  syntax to do this;  is equivalent to assigning , allowing an arbitrary wrapper function to be applied:Note the  syntax to handle arbitrary arguments (positional and keyword, respectively). You can also create the  decorator directly, e.g.:or even apply it without the decorator syntax at all:"},
Scala

I have two list as given following-  I wants output as following:\n    o/p\n    (C:,46552070,433057), (E:,5435,1728)How do I get desired output using scala??Using  like this,Other similar approaches includeAnswering @Yogesh in case the data exists as a list within a list:Similar to Shyamendra but using exists operator on a list."},
Scala

I have to return the index of the first element in the list that contains the \u2019?\u2019 character.Why does it come up as -1 when it should be 8. Does indexOf not work on characters? Should I use indexWhere or will that have the same result?When I make the val a string it works correctlyTry  \"Finds index of first occurrence of some value in this list.\" Therefore it finds string that equals \"?\" in the list. works on Stringso tryfor each element of list you can use"},
Scala

The codes are pasted below:I know the first parentheses  means the parameter list of , and the second part  means a . But what does  mean? Is it a decorator to the superclass  or the defined class . Is there any document about this?It just calls the constructor of .Table's constructor takes a Tag and a String. extends Table( tag, \"suppliers ) just wires the required values into the constructor (optionally with added type ascription). This is a standard Scala mechanism.It is a constructor equivalent to something like below:"},
Scala

How in scala check that variable: Any is list?I need something like You can simply use  method\n"},
Scala

Doesn't the Play framework have any lenses support included by default?  Something like  or those with Scalaz. Maybe there are recommended alternative approaches (along with their rationale) that I'm not aware of.Scenario: I have an immutable, deeply nested object of a case class, and I want to copy it with a field changed somewhere in the object.I'm looking specifically to do this very simply without needing much boilerplate, much like what lenses libraries like Monocole do.I'm just surprised that Play framework doesn't have any support built in.  Have I missed something?  If not, is there any known plan for this support?Play doesn't include type unions and heterogeneous lists ().Play doesn't include automatic resource management ().Play doesn't include lenses ( or ).It's a MVC web framework, and limits itself to that problem space. However, any of these libraries would be easy to add to a Play project. Play uses SBT, so just add to the  of your build.sbt / Build.scala appropriately."},
Scala

Reading \"\" it states \" all messages sent over the wire must be serializable\" which in turn requires all messages sent to actor's are serializable. Why is it required that the actor be serializable ? Is the reason that messages are sent between actors using serialization and deserialization ? Reason messages are sent/received using serialization is that potentially message could be sent to actors that reside on different JVM's ?Messages don't technically need to be serializable unless they are actually sent across a process boundary. Best practice is that all messages should be serializable in order to maintain location transparency.To enforce serializability for testing purposes, you can use the configuration , which will cause akka to always attempt to serialize messages even when sent locally."},
Scala

I want to define , but my IDE (IntelliJ IDEA) complains that \"notify  cannot override final member\".I know that  is a member method of  and the IDE may confuse variable name for method name. I need a  field, how can I do that?This isn't a problem with the IDE.  A Scala class can't have conflicting symbols, whether or not they are methods or fields.  For example, the following won't compile: is defined on , and furthermore it is , so you don't really have any great options here!  You can name the variable something different, of course:If you insist on the variable name, you can also extends , but only if you have exactly one  parameter:You might be looking for the feature that allows you to escape keywords with the grave accent:This would allow you to use a keyword (and some other normally illegal variable names) as a variable name.  This doesn't apply to your example, since  isn't a keyword \u2013 it's an already used symbol on the class!You can also come up with a solution where  is private to the class, but that won't work with case classes or most reasonable use cases.Ignoring your use case, a field called notify:"},
Scala

I got some strange results when running the following code:Why does type inference in mutable and immutable sets behave so differently? The  part is most puzzling, why didn't we at least get a ?The problem can be simplified to something like this:Your use of  doesn't reveal what type it actually is. In fact, it doesn't even compile as-is. I'm operating under the assumption that you have some implicit  in scope you're not showing, where .On to the question:The simple answer is that you cannot have a  without an . If I try to combine  a  with a , their most common type is . A  is a type of , but how can we sort a set of ? By default, we can't, because it doesn't really make sense to sort a set of .I could contrive an  if I really wanted to, and I would end up with a :But this doesn't really make any sense.The technical answer is that in order to concatenate two s,  and , we need an implicit .There are  s generated by , but notice how they require an implicit . Because the  cannot be found, the compiler looks for something more generic, and finds . This makes sense, because if we put elements into a sorted set that we don't know how to sort, then we no longer have a sorted set. What is left is just a plain ."},
Scala

Lets say I have an array of vertices and I want to create edges from them in a way that each vertex connects to the next x vertices.\nx could have any integer value.\nIs there a way to do that with Spark?This is what I have with Scala so far:where vertices variable is an array of (Long, String). But the whole process is of course sequential.:For example, if I have vertices as such: , , ,  . I need the following edges: , , , ,  -> , , , , , , , , and so on.Do you mean something like this?If you want to run it on a RDD you simply adjust an initial step like this:and of course drop . If you want circular connections (tail connected to head) you can replace  with  and drop .So, I think this will get you, what you want:First off, I define a little helper function (note that I have set edge data here to the vertex names so it's easier to inspect visually):I do a  on your array to get a key, and then convert the array to an RDD:And then to generate the edges with :This will generate the following output:"},
Scala

I have the following array:I don't have experience with Scala but I believe this array is mutable because I am instantiating it with .However, when I try to assign a value to one of its elements(where  is an integer):I am getting the following error:In Scala, you cannot access or assign array elements using the  syntax. Instead,  has to be used: is solely used for type arguments:"},
Scala

I have the following Scala Class:I instantiate it like this:Then, I try to access one of its fields:At this point however, I am getting an error:Why is the field not recognized?Assuming  is declared as an array, you cannot access array elements using . Use  instead:The error is shown because Scala thinks you are trying to parameterize a  method, with the type parameter being . This would be valid if there was such a method and  had an inner type named ."},
Scala

I'm a Performance QC engineer, so far i used Visual Studio Ultimate to run load test bug now I'm going to change to gatling. So I'm a newbie on gatling and scala. I'm defining the simulation with step-load scenario here: Meaning: start with 5 users > after 10 seconds increase 5 users: repeat until maximum 100 user and run the test in 10 minutes.I tried some code and other injects but the result is not as expected: Could you please help me to simulate the step load on gatling?Can you be more specific about the result not being as expected?According to the documentation your situation should be:If test duration is the target then have a look at Throttling in the Gatling documentation."},
Scala

I'm a new Spark user and I'm trying to process a large file set of XML files sitting on a HDFS file system. There are about 150k files, totalling about 28GB, on a \"development\" cluster of 1 machine (actually a VM).The files are organised into a directory structure in HDFS such that there are about a hundred subdirectories under a single parent directory. Each \"child\" directory contains anything between a couple of hundred and a couple of thousand XML files. My task is to parse each XML file, extract a few values using XPath expressions, and save the result to HBase. I'm trying to do this with Apache Spark, and I'm not having much luck. My problem appears to be a combination of the Spark API, and the way RDDs work. At this point it might be prudent to share some pseudocode to express what I'm trying to do: So, discounting the part where I write to HBase for a moment, lets focus on the above. I cannot load a file from within the RDD map() call. I have tried this a number of different ways, and all have failed:Alternative approaches have included attempting to use  so I don't have to do the file load from within the map() call, fails because the program runs out of memory. This is presumably because it loads the files eagerly. Has anyone attempted anything similar in their own work, and if so, what approach did you use?Try using a wildcard to read the whole directory.\nActually, spark can read a whole hfs directory, quote from spark "},
Scala

I'm trying to include a JS script within my mustache template file.It is located in . Also I have a JS script in . A few words about backend. I'm using  framework with support of Mustache out of the box:So here is my question. How can I add a JS script to my Mustache template?I also tried to use But my app still doesn't see the script. (thx to @nuc)I didn't find any good solution but only this one:I placed all assets to And in my view it should be You need to have an additional route to serve your js file, named to the prefix/convention you're using.See "},
Scala

Installed Scala Language : 2.11.7\nScala SBT : 0.13.9I started scala project in a folder MySample and created  and given below commands And then created folder Project and created  file and added below code And then in the same Project Folder  created  file and added below codeand ran the below command in command window I tried that command with 2.5.0 , 2.3.0 etc trial and error but couldn't figure that outAll answers are sayting sbteclipse ect Do I need to insatll separately SBTECLIPSE plugin? If so provide any URL Try upgrading to the latest and greatest:See  for up to date version information."},
Scala

I am trying to start writing test for mongodb in my play application.It seems that I can not get it working because the connection is shutdown before the save is executed.Here are the resultsThis is the code of the test, which is not testing anything, but I am trying first to write the database.And the dao implementationWhat could be that I am doing wrong?Thank youAs says in the comments, it turns out that the mistake was that I was not waiting for the future completion. I decided to use ScalaTest specific function to make tests wait for the futures completionsHere is the codeand just in case, I override the default behaviour because the default time was not enoughThank you"},
Scala

My :My  (at the project root):My root :When I run  in SBT console, I get Have you put key=value in application.conf?? just define the key inside the application.conf because it search value of key inside application.conf\nlike example"},
Scala

I have an arrayI need to calculate all subtractions to get a new list It is very easy to implement if you are using  and But what If I want to calculate this via MR? Is it possible? As for me, I don't see any possibility to do that. Maybe there is some other ideas?Something like this, perhaps:You can also do it with : But may I ask what is it that you are really trying to do here?Or, if you insist on only using  and  for some obscure reason (what would that be), something like this will work:This really is cheating though, because the function you give to  must be commutative and associative, and this case it is neither. \nIt just happens to work in toy applications, because there is no parallelism, but do not attempt to use this in real life, because it will probably break very badly ... and also because there is no reason to do that."},
Scala

I am trying to make a basic http client posting some data to a REST API with Akka HTTP but I cannot make the following code work :I got the following errorHere is the code for the dataIngestFlow Here is the code on server side :I tried another simple client, it builds well but the ingestion stop after 160 events, the server doesn't receive anymore events.The first problem I see with your example is that  does not have a map function.  Therefore, the following lineshould not compile.Further, if  is actually a Future (which I infer from the map) then  is actually of type  because the stream materializes into its own Future.  To solve this problem you can use  instead of map.  Namely:This is the  within Futures."},
Scala

If I do something like this in Scala Play:Can I get an guarantee that the expression I'm passing won't get executed unless the warn log level is set? I see that Logger.warn is defined as pass by name, but does that mean the log message expression isn't executed until needed?It will be parsed/executed because the string has to be parsed when being passed as an argument to the  level. Here is a code that proves that:This codes will print:In other words, the string interpolation was executed."},
Scala

I am building an API service using Play Framework in Scala and I am using HBase as my database. I want to use HBase coprocessors and since my HBase version is 1.0.0 I have to implement my service to be compatible with Protocol Buffer. I am following cloudera documentation for endpoint coprocessor. I need to create a proto file and then use a protocol buffer compiler to generate the service interface that needs to be implemented by client. I could not find any Scala protocol buffer compiler that can generate scala code from a proto file that has (not only messages).  you can see an example of a proto file with service that is used for a coprocessor. What can I do?There is Scala implementation for . Google ."},
Scala

Code:I want to make  private and change all the reference to it to , is there a way to do this safely and hassle-free in intellij?I soon realized that for this specific case I could have handled it in a better way (by recursion):But I am still interested in finding out how to refactor the old problematic code because it might be useful in the future. I don't know if the fact you use it for Scala changes anything, but you should be able to right-click on a function, and  to the one you want (so you wouldn't replace function1 by function2 per se, but rather modify f1 to match f2).Edit: This won't work as per Ben comment. Leaving anyway for the sake of mentioning the functionality."},
Scala

I am trying to write a helper function that will allow my dashboard to check if MongoDB is running on not. Based on the result, it could warn admins on the visual dashboard. I read through the reactive mongo docs  and I have the following function so far but unfortunately its not working.UPDATE 1:I got it done this way:"},
Scala

I am reading JSON data from kafka and parsing the data  using spark. But I end up  with JSON parser issue. Code shown below:error details:\nerror: not found: value JSON\n[INFO]     val lineJson = lines.map(JSON.parseFull(_))Could you please help me to which maven dependency should use to sort out the error.Thanks.I think you are looking for this:ANd adding Maven:"},
Scala

Will there be any problems if you use GUICE with Akka Cluster with regard to that will run multiple JVMs? What problems may occur if actively to use GUICE? Or better get rid of it and try to do everything the built-in tools?Why are you concerned about Guice with Akka Cluster? Guice is for Dependency Injection; as long as your actors are injected correctly, using Guice or Spring, it does not matter. When you obtain your remote ActorRef the executing actor can reside in any of the nodes in the cluster."},
Scala

I've just been learning about floating point numbers and am having difficulty understanding how I am supposed to find 3 double values (let's say a, b, and c) so that:(a + b) + c == 1.0 and a + (b + c) == 0.0I've read several web pages and watched videos about what floating points are but I have no idea how I should find something like this. I tried different numbers but only get much smaller differences in my outcomes. e.g.(1.1 - 0.2) + 0.1 = 1.00000000000000021.1 +(-0.2 + 0.1) = 1.0In the general case, you can only compare the results of floating operations with respect to an error margin you trust.For example, using the  library:If you don't want this, you need to use  precise maths."},
Scala

I've refactored my code for  of advent of code by using monocle, a lens library in scala.Is it possible to improve this code :And here is another try, separating the modification of each fieldOne more question : is there a way to use  with monocle ?The full code is here : You might want to use the second approach, because it separates handling of two fields.\nHowever, the functions shouldn't be interpreted in sequence (), but rather they should be combined as s with .  (after the Yann Moisan comment)The execution may not terminate in case of infinite loop in user's program. So instead of the  we need some recursive function that will extract the next instruction by pointer:(The last line of  should be replaced with the above code)"},
Scala

I am building an Akka cluster and want to use Akka-HTTP server as an API server inside. How does one do that?I would imagine it will be a cluster singleton, as it is an access point to the cluster, but making it an actor seems weird, as it will need to have a receive() method, which will do nothing (i guess). Simplest example:To stop:"},
Scala

I'm trying to incorporate a class that I extracted from another Scala project into a class library that I can reference from multiple projects. However, I cannot seem to reference the class from inside my client project.  I'm newish to IntelliJ 15.0.6 and my background in Scala is limited to scripts.Any ideas how I can fix this?ThanksSince you are using SBT, I would suggest you to use it to manage you library dependencies. SBT is a build tool which will download the jar file and make it available in your project for you.To add a library dependency (in this case apache derby) add the following line towards the end of your \"build.sbt\" fileYou can find your dependency on this site - . Search for your library name, choose a version and copy the script from the sbt tab.I solved the JAR reference problem by creating src/main/scala/lib and copying the JAR to that folder. might need todo a project refresh (Different to a project rebuild), or build it via sbt instead. I've noticed intellij can be a bit sluggish on this. "},
Scala

I'm using the following code to generate association rules in FP Growth algorithm.But whenever i'm trying to run the algorithm on a big data table with 100 million records, it fails with java heap space error.What is the alternative of using the collect() method for executing the FP growth algorithm on big data datasets?I'm using spark 1.6.2 with scala 2.10Solution codeTry to increase driver memory if applicable. If you are running your app on yarn then it would be better to configure memory for driver according container memory which driver heap memory + memory over head (15% of heap memory) = (should be) yarn container memory"},
Scala

I'm using certain external library that has a method which is overloaded several times with different arguments, something like:And a certain case class I'm using whose data I want to pass onto said methods, say:Right now I'm using the library method like:But since I'm always using the index of the value in the case classes I figured that maybe I could could save up on some lines of code (around 10) with something like the following: because I'd be iterating a  and therefore the compiler complains that I'm not passing the correct argument type to  since  is not What would be the correct way of handling this? Thanks in advanceTry this. I am using Scala 2.9.3. In newer versions, you can use TypeTag and ClassTag. Check  So now you have the class type information. You can devise some mechanism to map class type value as string to  instance and then use  to cast it."},
Scala

I was looking at ActorLogging  and came across this syntax:What does this syntax  mean? I know that in scala  create a block of statements and the last line is assigned the variable. The comments explain it as :Is there a technical term for it so that I can learn its usage more?\nNote: I know what a partial function is. From the comments and answers I understood that LoggingReceive returns a partial function and the syntax of apply.In akka the  method has to have  as the result type. So here they're using an object  which has an  method defined like this:In Scala we have a syntax sugar construct so instead of calling:You can simply write: There's another thing - in Scala we can use  brackets instead of  parentheses, so the above expression can be write as:So at the end they're just simply wrapping the  method with the  method of  which calls the  method."},
Scala

I am new to spark. I need to change the date format in a spark dataframe which is in String. I need to remove / as well as 00:00:00. I tried to use     The format is changing as expected but with some random date. I found the issue is with \n  The dataframe is imported from CSV file. I got a solution using regex but it would be better to know why it is not working. Code used: (The code may not be exact but similar)Try something like this:See  for details. "},
Scala

I am on Spark 1.x, and attempting to read csv files. If I need to specify some data types, as per the , I need to import the types defined in the package .This works fine when I use this interactively in spark-shell, but as I want to run this thru spark-submit, I wrote some Scala code to do this. But, when I attempt to compile my Scala code, it gives me an error saying it could NOT find org.apache.spark.sql.types. I looked up the jar contents of , but couldn't find these types defined in there.So, which jar has org.apache.spark.sql.types?I looked at the  at GitHub to realize that these types can be found in the  jar. That didn't seem intuitive.Also, since  has this codewe end up with another dependent jar - json4s-core."},
Scala

In my development and qa environments, I will be hitting a rest endpoint using internally signed certs. The policy where I work is to put internal certs in a separate bundle on our Linux servers.The following works perfectly well in curl:My actual client for this endpoint is written in Scala, however. Currently I'm making my call using :I would like to figure out how, in my dev and qa environments, to use our internal bundle. Anyone doing that in Scala or Java?You need to configure the \"truststore\" used by the JVM, with the \"\" option when you launch java, i.e.( will take the same  argument if you are using SBT to launch your app)You'll need to get your CA certs into JKS format.See:I would entirely recommend you to use Gatling for this kind of things. Gatling is a really cool framework for load-testing and it provides support for many protocols like jms, jdbc, and of course http among others. Please take a look on it here  (This framework is build on Scala) and it provides support for the things that you are searching for"},
Scala

I have two dataframes DF1 and DF2. My task is to select the data which is present is only in DF1 but not present in DF2. Could any1 please help. \nI'm using Spark 1.6 shell. You can use this:Note that the two dataframes need to have the same structure (same columns)In Spark 2.0 you can do . Assume your records are identified by the common column  : How about..  where col1 is the column to join."},
Scala

I want to conditionally create a Binding of HTML node. However the code does not compile.You need an  block with an empty content, usually a HTML comment:"},
Scala

I am trying to write a function that returns a future. Within this future 3 other future functions are called, the third depends on the results of the first two. My instinct is to use a for comphrension, but when I try to match on the tuple I get this error:Which refers to the match of  below It can be solved by making whatever is under  return "},
Scala

Relevant request URI:How can I grab this query string ? You have to create a custom binder this is a Java implementation but it follows the same principle:"},
Scala

Good afternoon,I am trying to follow , however when running the command:I get the following error:As stated in the setup part of the tutorial I have checked my java version:My javac version:And my sbt version:I have trying running the command with my sbt version as the parameter:But it still throws the no template error, could you please point out what am I doing wrong?Which comply with the prerequisites for the tutorialTurns out I had to remove the -Dsbt.version=0.13.13 parameter of the commmand.Running it as:Removes the error and it works correctly.The problem was not the extra flag. The documentation is correct. You have to use it before the  command"},
Scala

I have a Future lazy val that obtains some object and a function which submits operations in the Future. The problem is when Future is completed it executes operations in reverse order than they have been submited. So for example if I execute sequentialy I get after Future completionThis order is important for me. Is there a way to preserve this order?Of course I can use an actor who asks for future and stashing strings while future is not ready, but it seems redundant for me.You can use  to ensure the order of execution.Something like this.. Im not sure how your func has a reference to the correct futureC, so I moved it inside."},
Scala

The following code:Does not compile. I get the following error:I don't really understand this as according to the  a  extends the trait . That is, .I thought it might be something to do with the contravariant type  but if I use  instead of , it still doesn't compile. What am I missing? The solution is to do:but this seems inelegant to me.OK - this has been figured out with the help of the scala console:So the type inference is inferring m's type as being an immutable map. The following code will compile OK:However, this is not much help as the map can not be added to in such a way as to return a . I think that they should have overridden the  method inherited from  with  as the return type.Could anyone comment on this? What use a ?I'm curious why you want m to be var rather than val - if you're not trying to reassign the Map to itself, things seem to work OK, as shown in the repl, and this is more in keeping with the scala philosophy of preferring immutability where possible:I see that the question is kind of old, it's possible that the behaviour you're seeing is different in Scala 2.8 given the major refactoring of the collections classes."},
Scala

I am trying to understand the IO provided by akka. I started another  for this issue.\nI found a  on how to use akka IO. I reimplemented it and started it. Now I am wondering why only the first message of the session is printed. \nCan somebody please explain what  is doing and how I could sent a message to another  of the  instead?I figured out, that the actor just takes a single input and process it by just printing it to the console. That leads me to another question: How can I make the actor take multiple inputs and process them? I connected to the server via putty and if I hit enter one time it processes the input as expected, but if I send another line of input it only stores the input. Where do I have to run , so it processes the next line of input? I tried it inside of the  case, but it didn't work.The example you are trying to understand is a bit more advanced, mainly because it is dealing with socket based communication. If you are actually interested in that kind of stuff, I suggest you read  where the example from the blog seems to originate from.In any case, before you do that, a good read would be  which explains the fundamentals of Akka actors and gives you some actors to play with."},
Scala

Why do I get a pattern matcher warning regarding type erasure with the following Scala Swing code:The warning is:Is this just horrible design of Scala Swing, or am I doing something wrong?This issue has disappeared with the new Scala 2.10 pattern matcher."},
Scala

I see lots of documents referencing the \"Within\" method on the TestKit.\nThere appears to be something wrong with my tooling because I'm not able to import that method.Examples of usage : \n\nShould be available as of at least 2.0\n"},
Scala

At my current place of work, we're considering using the 'Play' framework for our next project. I'm actually an advocate for sticking with the 'devil we know' (Java EE / Spring / Hibernate) but I'm rapidly losing faith due to the technical pot-holes in that tech-stack. I dread to think of the unknown pitfalls awaiting us in the all-new Play framework. I'd really appreciate feedback from anyone who is a  Java EE / Spring / Servlet / ORM engineer who has experience using Play. How does it compare? What are the major booby-traps awaiting us? If you're a newbie web hacker who's infinitely optimistic about 'Play', yet utterly naive about real-world software development and maintenance, I don't need your input thanks! ;-)Edit: I was asked to identify some of the technical-pot-holes I'm referring to. I don't know what these might be in the Play framework - which is why I'm asking the question. Some J2EE gotchas I suspect might have equivalents in Play could be: "},
Scala

Using Squeryl ORM and Scala. For the first time I did a JOIN statement that used grouping. Admittedly, I can't figure out how to start iterating through the contents.Here's the JOIN:How do I print out its contents?I tried:But got the compiler error:Max the great was able to help out on the mailing list. I almost had the syntax right.replace :by:then :Source: "},
Scala

So I'm writing a mini timeout library in scala, it looks very similar to the code here: The function I execute is either going to complete successfully, or block forever, so I need to make sure that on a timeout the executing thread is cancelled.Thus my question is: One alternative that I'm considering is to use the java Future library to do this as there is an explicit cancel() method one can call.[Disclaimer - I'm new to Scala actors myself]\nAs I read it,  waits until the list of futures are all resolved OR until the timeout.  It will not , , or otherwise attempt to terminate a ; you get to come back later and wait some more.The  may be suitable, however be aware that your code may need to participate in effecting the  operation - it doesn't necessarily come for free.   cancels a task that is scheduled, but not yet started.  It interrupts a running thread [setting a flag that can be checked]... which may or may not acknowledge the interrupt.  Review  and .  Your long-running task would normally check to see if it's being interrupted (your code), and self-terminate.  Various methods (i.e. ,  and others) respond to the interrupt by throwing .  You need to review & understand that mechanism to ensure your code will meet your needs within those constraints.  See ."},
Scala

I found a thread here that looks like it: But my version is relatively new already. How come it's still happening?Here comes my lift setting in maven:I don't have any clue here :("},
Scala

Could someone please help. I have Play2 project in which I need to test some DAO code.\nI used documentaion from  .\nThe test is very simple:And when I run 'sbt test' I get strange error:StackOverflow/Google knows nothing about this exception. Thanks in advance.The stacktrace makes me think that a library is incorrect or missing in your classpath. This is why you are seeing \"Helpers$.\" traces where the class constructor seems to be failing. You can validate this by writing a small app in your test directory, without specs2 but using Play2's helper classes and see what happens.I found solution - :\n should be added to actualy start Play app so DAO calls can work in test."},
Scala

I am coming from the Java EE world. New to scala and Play. Looking at some sample applications. I see scala code in html files. I am able to understand the framework but I could not get scala.html files. Do I need to learn scala to use Play framework. Any work around.You can use  without any scala skills. If you don't want to use scala.html templates you can get some module providing Java templates for Play20. Modules list can be found .Some examples with samples:"},
Scala

I have got a pogoplug an want to run an play2.0 application on this device. Pogoplug has 128mb ram und a dualcore processor. What is the best way to do this?What is the OS and connectivity options?I think the easiest way is to use  command to prepare zipped application, push it to the server and start there.  and  commands builds application from source and you probably don't want ot do that on 128m ram.Of course you need JRE and play installed there and HTTP server in front.This is quite a broad question, but here are some things you should consider:"},
Scala

In the following scenario, by-name parameters cause conflict with functions.Given some serialization infrastructure:And an example type along with its serializer:Now imagine a wrapper called  which deals with the recursive/mutual connectivity:And its serializer:Then the following fails:How can this be fixed without changing by-name parameters to functions (as far as possible)?It seems one can write the type :"},
Scala

I have an intensive task that can distributed but whose end result needs to be accumulated and passed on to another method down the line.For concreteness, let's say I'm doing word counts for individual files in a large collection of text files. The version I've worked out so far looks like this:I can think of several homebrewed methods to make the main method wait for collector to finish and then deal with the \"bin\" object.But what is the proper scala way to retrieve \"bin\" above and hand it back to main or what have you?With an actor, you don't \"retrieve\" anything as calling actor methods can be dangerous.Instead, you get the actor to send the answer out. You could add a case for a  object, or in your case you could have it send the  somewhere in the handler for .You could ping an actor using method  to create a future result. The actors receiving the message can fill in the result by using .However, you save a lot of management work by using executors instead, which are better for  tasks (you don't really have a  situation here where actors would be particularly useful).The following is based on Scala 2.10 (forthcoming, you can use 2.10.0-M6 right now), because it contains the improved concurrent framework:Example:"},
Scala

Using Scala, JodaTime, and Squeryl for ORM. There's an annoying problem where once the application starts up, a Timestamp generated using JodaTime doesn't re-initialize every time it's called. Instead it sets the time once and annoyingly doesn't re-initialize every time the SQL is called.Code below. First, the time parameter:And the Squeryl JOIN:The strange part is that if I generate the  timestamp  JodaTime, then it re-initializes every time. So what is JodaTime doing differently?Found the problem: apparently the thread managing the JOIN was never successfully being shutdown, and was being re-referenced inside Akka. This meant that the  variable had never been re-initialized.So the take-home lesson is: manage your threads.As I have further learned, the original object holding the time values were set as . As it turns out, they need to be .Bad:Good:"},
Scala

When I define a function inside the Scala REPL, I can see the created function's type, like this:How can I see the function  when I'm not in REPL? Say, I want to know a function type a library uses at runtime so I can use the same type.Thanks before."},
Scala

I am using the play-salat plugin with an app I am making with Play! 2.0 scala.I get the Duplicate Key error, and the compiler points here to the error:I have read that this can be fixed in PHP  doing an unset, please tell me how to do this with Play.I am able to post in my database the once, when I try again I get the error.I resolved this issue on my own. I am pretty new to Scala and the Play Framework.I changed my Application.scala file like this:I also changed my Post.scala file:"},
Scala

I'm trying to find the correct method of deleting a file from mongodb gridfs.Would the standard query suffice?Or is there a specific way of doing it properly?Thanks in advance, any help much appreciated :)GridFS doesn't store files as records. GridFS gives you handle to stored file that spans more than one document (in order to exceed document size limits). To delete file in GridFS you have to use its API. So in order to delete file you have to find it, for example using this method:\n)\nThen when you have reference to file you can delete it. Example code might look like:gridFsId is ObjectId stored in Lift record that keeps handle to file in GridFS.\nI hope that helps."},
Scala

We use jenkins for build automation of a Visual Studio 2008 C++ Project.\nIn essence it's a series of calls of:which works fine in general.To run everything out of a dos box I wrote a scala wrapper, which does the same with ProcessBuilder. It works, but I have the problem, there is not output on the console.My guess: devenv starts a bunch of processes to compile and linke the projects in parallel. My scala programm only outputs the stdout and stderr of the devenv process, which is none. All the other output of the subprocesses is shot into nirvana.for the sake of completness the source snippet:The List used to start the process looks like:Is there a way to record/output the output of the subprocesses?"},
Scala

I want to get the data from a database table using a regular expression.This is what i did:But i get nothing in result. \nWhat I'm doing wrong?PS: I'm using Well I succeded in getting a result. It gives me all the user that contains the inserted . I have just deleted  and  that were surrounding . Here is the code.  "},
Scala

I'm working on a homework assignment, modifying code created by my professor.  Unfortunately, he's not available to me currently so I'm reaching out to the stackoverflow crowd.This snippet is from a file \"Peer.scala\", which communicates with an actor from another class \"RemoteActorChat.scala\".  I have only included the snippet that I believe is the cause of my issue, for the sake of brevity.  Should the rest of the code be useful in finding a solution, I'll gladly post it.My intent is to have the Peer capture input from the console in a continuous loop, while simultaneously reacting to any messages received from the RemoteChatActor....}...When the inputText is matched to _ the post function is called, does it's thing and I get another prompt.  I can post messages all day long like this if I want.  However, when inputText is matched to \"Unsubscribe\", \"Subscribe\", or \"?\", the behavior is different.  The statements in the case are executed IE) the unsubscribe or subscribe functions are called and do their thing as expected. However, I don't get the prompt back to continue sending input from the console.  The peer basically just hangs at this point.  I expect another prompt but the console window is just empty and doesn't take any additional input.Clearly my understanding of how this should work is flawed.\nWhat am I misunderstanding, and how can I make this do what I intend?The actor is waiting for a  inside .  It won't continue until it gets one.  Since you only send one in one case, only that case gets through.If you want to make the other cases work, either have them also send a message that the  block can receive (at least as a  inside the react block), or move the react block so it will only be entered if there will in fact be a  coming back its way at some point."},
Scala

I am going through the Scala book i bought and am trying to get TextMate to cooperateI got the point where:Don't know why it gives you two run script options, but scala REPL is an interactive scala console. You can execute any scala statements on the fly with it. Option 4 will just start a console, option 5 I suppose with preload everything you have in your file, so you don't have to import everything yourself. 6 will start a console and let you execute whatever you selected.Here's more about REPL: "},
Scala

I'm trying to get the following Scala code to compile:The idea here is that I need a way to make doMath operate on any Integer and thus a type with an addition operator.  I want it to be agnostic of large number like BigInt or a very small number like Byte.When I try to compile this I get an error:Any ideas?Rex is right.  Since x : Long means x.asInstanceOf[Short] is invalid the routine fails when trying to cast initializer to T when T is short.  Yes, that seems legitimate.  Thanks Rex!  Wish you had answered instead of commented so I could give you a +1.I do have some control over the type of initializer and given all that Byte is its logical type but I need to think about this a bit to make sure that's the only issue because the actual implementation of doMath uses a parameter to get a lazy value type with a bunch of options controlling the output.  But above is in its simplest form and I think you hit the nail on the head.  Thank you Rex Kerr!Implicit object is no good.Try using case class insteadE.G:I'll explain:\nIn the above example doMath takes a single value of type NumericValue[T] (i.e. NumericValue[Long]) but if the received value is of type Long the compiler will look for implicit value for it, the case class.Note I don't have my computer on me so I can't test this but it did with in the past when I tried to initialize a variable in that way."},
Scala

Is it possible to configure Akka to use blocking or non blocking i/o?Thanks.Akka is an actor system for concurrency and parallel execution. As such, you pass event-based messages into actors to make them do things. When you send a message, it goes into the actor's input queue, leaving the sender to go and do something else. But the sender can hold a future instead and later block when it wants to collect a result.The actor itself may possibly use blocking i/o, but this doesn't block the actor's clients.Akka IO is non-blocking, please refer to the documentation: "},
Scala

I am a newbie to scala and I am writing scala code to implement pastry protocol. The protocol itself does not matter. There are nodes and each node has a routing table which I want to populate.\nHere is the part of the code:The problem is when the function call to getMatchingNode takes place then the actor dies suddenly by itself. 'list' is the list of all nodes. (list of node objects) \nAlso this behaviour is not consistent. The call to getMatchingNode should take place 15 times for each actor (for 10 nodes).\nBut while debugging the actor kills itself in the getMatchingNode function call after one call or sometimes after 3-4 calls.\nThe scala library code which gets executed is this :Eclipse shows that this code has been called from the for loop in the getMatchingNode functionThe strange thing is that sometimes the loop behaves normally and sometimes it goes to the scala code which kills the actor.Any inputs what wrong with the code??Any help would be appreciated.Got the error..\nThe 'continue' clause in the for loop caused the trouble.\nI thought we could use continue in Scala as we do in C++/Java but it does not seem so.\nRemoving the continue solved the issue.From the book: \"Programming in Scala 2ed\" by M.OderskyI really suggest reading the book if you want to learn scalaYour code is based on tons of nested , which can be more often than not be rewritten using the  available on the most appropriate .You can rewrite you function like the following [I'm trying to make it approachable for newcomers]:The potential to easily transform or operate on the 's elements is what makes , and  in general, less used in ScalaYou can convert the row iteration in a similar way, but I would suggest that if you need to work a lot with the collection's indexes, you want to use an  or one of its implementations, like ."},
Scala

I have written a couple of tests, very identical but different in only one way. One test has an international address and the other has domestic address: .scala & .scala.scala extends another class .scala that has a  method. Here I am validating that .scala has valid ship methods present. .scala does  extend .scala.Both test classes (.scala and .scala) have different users; the only similarity is that the address is stored in a val named 'address'. When I run these two tests some times (and only some times) the test fails for .scala because I see an international address in there.  My testng xml is preserving the order of tests, so this is more confusing that a race condition could occur especially since I am not sharing any resources among the tests.Why does your ShipMethods have a @Test annotation on it? Is it a test class? If it's not a test class (as opposed to a class which you want to test), then it shouldn't have a @Test annotation on it.Your classes under test shouldn't have test methods inside them."},
Scala

I'm trying to tie in an API for the St. Louis Federal Reserve data (FRED) into a Play2 web app. You can see the API here:  under java.I put the FREDAPI.jar into the scala/play classpath and I'm able to import com.uniservsolutions.stlouisfed.fred without a problem.But the API needs the API key to instantiate a 'session' and that is put into a file .properties (I have fred.properties). API docs instruct me to declare the following at the commandline:This will read the contents of fred.properties:But I'm not familiar how to do this in Play. I have found info on JAVA_OPTS but I'm unsure where to declare or if indeed that will work. Finally, when I deploy this (currently staging on Heroku) where will I declare this (heroku's Procfile?).I discovered quite by accident that you can declare java command line args for play e.g.:"},
Scala

I have the following build structure:in , I have the following declaration for Scala because my Scala depends upon external JAR's from , as well as it needs to compile first because my Java compilation is dependent on my scala code (not the other way around):When I run:I get compilation issues with  not finding the classes in someDependantJar-1.0.jar from .When I run:I get the following list of dependencies:So I dont see someDependantJar-1.0.jar and was hoping that someone can shed light on this issue so I dont have to define the transitive dependencies in subProjectA and subProjectB (duplicate)you havn't defined a compile dependency in subProjectB.\nNot sure if i got your setup correctly, I think you need to add the dependency to someDependantJar? an you try adding a dependency in projectB on projectAcheers,\nRen\u00e9"},
Scala

In my Play 2.0 app, I am calling a Java API which depends on certain environment variables being set to work properly. However, this can only be checked at runtime and what I would like to do is to throw a meaningful error message at the start of the application but unsure how to handle it. A possible approach is to use require likeThe problem with the above approach is that I get a  and stack trace (in dev mode) without the ability to display a meaningful error message. Anyone knows a better way to handle this?You can create a  which gets called automatically during startup.  See the "},
Scala

I am using ~;container:start; container:reload / with xsbt-web-plugin. Reloading works well, only it does not happen when I change static resources, pages, etc.How do I include them to change monitor, any ideas?Thanks.watchSources didn't work for some reason, even when directory is successfully added therewhat worked for me is unmanagedResourceDirectories in Compile <+= (baseDirectory) { _ / \"src/main/webapp\" }"},
Scala

I'm trying to port my maven-based docbook projects to sbt... but so far it is a nightmare :-(Given the standard project directory:... build.sbt looks like this:... and finally project/plugins.sbt looks like this:... I always get the following error:Any idea? Any help would be really appreciated. I'll try a bit further and then I'll give up.Thanks,\nj3dThe  seems not to be maintained anymore and it uses 0.10.0 which maybe outdated for you.There are  out there, this is the .But must build yourself and publish it local.By the way ."},
Scala

I want to write code that has a generic, possibly slow, implementation of a type parameterized method that works for all classes implementing a certain interface but still allow for subclasses to specialize this method with more efficient implementations if they so desire.However, the following code does not quite workbecause it treats A in class C as a type parameter not as something that overrides the function for the case where the type parameter is only A.Is there a way to write the code that I want without using match at runtime?What you're going for is this:But as the type system tells you, this is . You are violating the  here. What you can instead do is make  a class level type parameter or an abstract type member. Then you can constrain it in the subclasses as shown below:You haven't provided more information so I don't know if this will work in your particular case or not. Here's one way to speciailize things: using typeclasses. Code: (This turned out to be more convoluted than expected.)"},
Scala

I need to execute the same task many times as much as possible within given milliseconds. So I made it using scala.actors.threadpool.Executors as following code.But this is a bit complex. Instead, I think, Broker of Twitter and some Executor which connects with the Broker and sends a finished task to the Broker, if exists, could make it easier. The following is a pseudo codeIs there any Executor like this?If I am understanding you correctly, you may be able to use  like this:"},
Scala

I'm running into a compiler problem when using Scala7-M9 and json4s 3.0.1 with compiler versions 2.10.0 and 2.10.1When compiling the short snippet of JSON parsing code, I get the following compiler error:from this code:Changing the imports to:(in my real project I only need the / monad for some validation) fixes the issue. Just wondering if anyone from the Scalaz/compiler world would have an idea what was causing the compiler error when I import the whole scalaz namespace and if it's a BUG I need to file.Thanks."},
Scala

I am pretty new to Scala/Lift and ran into following problem:I get following error message:Sample JSON:I tried several things, but it seams I stuck here. Can any one point me in the right direction? BTW. I am using scala 2.7.7!Cheers, enzoIf you remove the  hint from your JSON input, it should parse. Something like:Otherwise, you can try adding  around your input like:I think it is looking for a collection since the  attribute is used to help determine which subtype to deserialize the current item to. There is probably a way of getting it to work with a single element, but I am not sure what that is.The reason I asked about the scala version is, 2.7.7 is pretty old at this point (2.10 is the latest) and a newer version may make finding things a bit easier.  "},
Scala

I've setup Emacs + Ensime for scala.I'm able to start sbt console inside emacs using C-c C-v sIf i start scala console inside emacs using C-c C-v z, I get the following errorWhat is the fix for this error? How do i get scala console running inside Emacs?I've ran into a similar error recently, but here's how I worked around it (but I don't know how to fix it, so this is only half the answer). What I did was to customize the  variable to have the value: . Which will indeed start the interactive Scala environment.EDIT:Here's relevant parts from , but I'm not sure it will matter / will be the same in every install:I've installed  from MELPA. Installed  version 0.12.0 by downloading an RPM from their site. I had previously JRE and JDK installed, the active version is OpenJDK 1.7. Scala installed is 2.9.2. I don't know how to identify Ensime's version :|"},
Scala

Is there anything out there that's similar to Scala worksheets? If not, I want to implement it, and would like advice on where to start.  "},
Scala

For my development machine, I'd like to disable SSL hostname checks for HTTPS connections. The exception that comes out of the dispatch code is this:I'm looking for a way to set the default hostname verifier in a way that will be used by dispatch. There's  to set the default hostname verifier, but that whole class is apparently deprecated. Is there a current correct way to do this?It's  that was deprecated in favor of ; the latter isn't deprecated.As to the ways to bypass this check, you could:"},
Scala

I am using BigQuery from Scala. I tried the sample Scala code to call Google bigQuery API Scala: Above BQ returns:Please help me parse the values from above the results in JSON Format or change the query to return the result of the format like this:I like .Look at the lotto example, it's straight forward with case classes"},
Scala

I'm using Play! framework to build my application. I have such dependency:Somewhere in the code, I'd like to get the version of the superLib. But is it possible to do with Play! tools? My code is dependent from the version of superLib. For example:As the version of superLib is changing quite often, I don't like to change the version of it in the build file and in the code. \nI could put it in the configuration file and read it from there both in build file and in the code, as well as parse the build.scala file in the code and get the version by extracting it from the build file. Is there any prettier way of doing this? I was trying to play around with play.api.Play, but didn't succeeded. Currently, I decided to get maven property file from classloader.Thanks in advance!In case someone will try to do something similar:"},
Scala

... for each article.Get Image name and Image (reactivemongo.bson.BSONValue) and put it in a form select?Does anyone know how to do this?The application is based on Play 2.1"},
Scala

I have the latest Scala IDE 3.0 installed on Eclipse 4.2.2I installed the latest SBT using When I run SBT and type the command  this is what I getWhere did the Scala REPL 2.9.2 come from?"},
Scala

I'm trying to use a regexp to parse a string of the form:\"a=10:30:00:b=2:c=3\"to yieldThe closest i've gotten is \n    (\\w+)=(\\S+?)(?=:|$), \nbut that chops off a's :30:00:Code is in scala:Modified the regex based on \n to handle:Or based the regex you quoted:"},
Scala

I am trying to write function that writes data to MongoDB using Casbah toolkit:I get the following errors:What's wrong?I'm not sure without full imports, but try to change  to  or add "},
Scala

I'm trying to use sbt-scalabuff to generate scala case class from proto file. I have added the plugin reference into plugins.sbt file of the Play project, added runtime dependencies too.If I do not add any settings to Build.scala referring to sbt-scalabuff then I assume that will go with default settings, expecting to find the files in src/main/protobuf.Do you know any Build.scala sample of proper settings of sbt-scalabuff?Thanks,\nGabiI haven't actually tested sbt-scalabuff much myself, but you can try raising an issue on the sbt-scalabuff github page."},
Scala

I made an eclipse project for my application using eclipsify. Then I added the code at  appHome/target/scala-2.9.1/src_managed/main to the dependency list and everything works fine except for the code that calls modules. It seems I am missing some classes that belong to them. Where can I find them? What is the place where Play places the code generated for those modules?I am currently running Play 2.0.2Jose!\nYou should not change any code at target folders. This folders are generated automatically from your source folders. \nSo, just try to remove target folders from the project, and then use compile and eclipsify again.\nHope it would help.  "},
Scala

I have a scala project (based around unfiltered and jetty) which uses bval. I've tried everything I can think of to get custom validation messages to load from a properties file, but it just doesn't work. I have a scala class like this:and a ValidationMessages.properties file containing the following:But the output from the validation results is  not matter what I try. I have tried placing the properties file in the project root, in a resource folder which is exported to the classpath by the run configurations. I've also tried placing it in the  folder and then running the project with ."},
Scala

I am trying to use pattern matching when querying a mysql database from a play2 module using anorm. Code looks like this:But the name:String is not matching anything (already tried to match just the integer and it works fine). On my db the entity table \"name\" column type is varchar(45).Anything I am missing?You can try to match  on an  and a named wild card.If name is nullable then this matching should work:"},
Scala

I have a play-template with javascript code in it. Everything works but it has two disadvantages:On the other hand, the advantage I have with his solution is:Any suggestion to improve the code is welcome! ThanksThe best way for correct implementation JS is ... checking the HTML code in the browser, most probably you are including jQuery at the end of doc, therefore it's not available. Create  stable HTML file and work on JS there, when you'll debug and finish it then move it to the view (place parts in proper places).Also consider moving JS scripts into separate  file ."},
Scala

I am experimenting with existential types.I was playing with a function that expects a sequence where the elements of that seq are all the same type. I had .. Where ...I then came across the \"forSome\" syntax and found I could achieve the same constraint with it.I wrote the following for comparison purposes ...What I am trying to understand is - am I missing something? \nWhat is the benefit of one signature over the other.One obvious diff is that the compilation errors are different.The difference is that in  you may not refer to type , whereas in  you can:"},
Scala

Can someone help me understand the compile error message below?  I've been looking at this for a while now and I don't understand what's wrong.Error message:EDIT:\nClass declarations look like:Works for me on scala 2.10.0then paste in the code you supply above.   compiles without error and seems to work in the intended way:"},
Scala

I'm making a little web project with scala, scalate and jade templates. The problem is when i'm changing .scala or .conf files, sbt automatically recompiles them and reloads project, but it doesn't do it when i'm changing my .jade files. All my templates lies under the  folder in src/main and it is added on the project classpath, also i've added this line to  file in  folder:Just had a similar problem. You should change your line in the scala build file on this one:This should solve your problem."},
Scala

I have a given (and impossible to change Java class from external Jar) for this question we will call it: I also have Java class which will be used as a Type Parameter: Now I want to create a  class called  And we also have our main method in  object.Hrmmm.. I'm trying to picture your code and what it's doing. It's reminding me of using Hibernate with generic DAOs which I've done quite a bit so I would say you should look at  which would print SomeClass the way you set it up. There is also TypeTools here  I  this should get you on the right path if I'm understanding your problem correctly."},
Scala

I'm creating an authentication action that wraps other actions, using the Play Zentasks sample app as a template. One of the things that this needs to be able to do, is hit a webservice in certain circumstances, in order to retrieve a user's details. I want to do this in a non-blocking fashion, but I don't want to have to pass a future back to the action that I'm wrapping.The only way that I can think of doing this is by using Enumerator.fromStream() with an InputStream pulled from a URL object. I'm guessing this isn't the best way though, since it seems like a duplication of efforts (considering the ws object). The async ws api (and underlying asynchttpclient) returns a Future for everything however. I don't suppose anyone has tackled this issue before and could point me in another direction? Is there something that I'm missing? Also, would using a Enumerator.fromStream() as I've suggested definitely not block?Thanks in advance,SucheYou can use the async WS api. When it returns a future, you can call map on that, and pass the value to the action you're wrapping. Now you have a future containing the result of your wrapped action. Turn that into an AsyncResult or just wrap the whole thing in an Async{} block and it should work."},
Scala

In below code the filter code is extracted to a local val : I can pass this then into a filter function like so : But if the .filter function is within a method and the filter is defined outside the method I need something like this :  is part of the method signature of  method. Above code does not compile because type A is not set. How can the code be updated so that method  accepts a filter definition as one of its parameters and then runs this code within  method ?Edit : When I make the change : I receive the error on line   :The error is : def myMethod[A](p: A => Boolean)As already said in comments: If you know the type of collection you're running filter against, why don't you define p type as ?"},
Scala

I want to create a maven scala spring hibernate project . Im following this tutorial : \nNow I'm stuck in the 4th step : Start the Webapp with Maven using the Jetty Plugin. This is what the browser is displaying : And this is the log im having during the initialisation :first here s pom.xml:Here is my web.xml : This the web-context.xml :My JSP is containing the following code : My scala class :Can you help me please ?Actually when i input this url : localhost:8080/ i have this display :when clicking on web-inf I have an HTTP ERROR 404 Not Found"},
Scala

I am trying to call a implicit function inside a test case but seems eclipse UI is not able to recognize it, I am getting compilation error, using Eclipse - Build id: 2.1-M2-20121018-1623-Typesafe Eclipse SDK Version: 3.7.2Am I missing something ?Getting compilation error at .brokeragePricing\nI tried cleaning the project & restarting eclipse but all in vain.The problem is that you are importing piece by piece of the  object. You can fix it by importing all elements of the object:Or by importing the missing element:"},
Scala

The above is creating a column family meant to be used as a counter in Cassandra.  For whatever reason, compilation is failing with the following:Astyanax ColumnFamily syntax with description Now in your case, you have mentioned your rowkey as Long type and column as String and while updating the counter you are using key as your string, that's why this ."},
Scala

I'm writing a Play 2 application with a Postgres backend.My code has a sql string which is a concatenation of two inserts and a select. Then when I try to execute my query, anorm blows up and says me no results have been returned. I could break it up into two separate queries but then I'd be making an unnecessary trip to the database?The sql string is pretty simple.Then the code that throws the exception just tries to get the gameid from query. This should work right?Here is the error As the other comments have said, this is caused by issuing a composite statement to JDBC.  You have a couple options.This would reduce your round trips to some extent."},
Scala

I'm having trouble with an HTTP Request from my scala code.giveswhich is what I want.When I try to do this from my code like:givesWhich is not what I want.\nI'm tired and dont know what am I doing wrong here? Should I go for some other solution? I'm stuck and would really appreciate some answers for my problem. \nBTW. I'm doing my request from local, maybe this is my problem?\nThanks!When I ran this code, I got an exception indicating that the access token was not valid (expected).  If you plug in a valid token it should work:"},
Scala

I need something like this:"},
Scala

Given is the following constructHow do I append to the linked list?If I use  or  the list is not appended but a new list containing the value is returned. Does HashMap only return a copy of the associated value instead of a reference to the value? To answer myself after trying around a lot: it worked using a  instead of a .Using your second solution it works for me:although, better than  iswhich won't throw an exception if it can't find the value."},
Scala

Could anyone please advise me what is the best framework/library for web browser automatisation? The task is to open web browsers page, sign in, perform some long searches, and save gathered information to excel. Now I'm using IE references in C#, but at work I could use only IE8. If I've upgraded it to IE9, but some scripts on target sites started working with errors. I tried to use awesomium, but I couldn't parse page with help of it, as I understand. Are there any variants to do this with high speed? Size of libs - doesn't matter.If there are any solutions compatible with Scala it would be great.As om-nom-nom hinted already, your best bet is probably a webdriver implementation like . It has bindings for c# and java and can use IE, FF, Chrome, phantomjs (great if you want to go headless) and others.Note that it might be not the best idea to do also the gathering of information directly with the webdriver, especially if the site content is changing fast. In such cases it might be useful to save the html page source with webdriver and then switch to some more efficient library for static content, like ."},
Scala

I am having a clean closed type class system with serialization (detached from POJO serialization woes). For example:But in situations I need to capture a closure. For example:Now, I had solved this once with POJO serialization ( etc.) for the . I got badly bitten in the feet, because I couldn't read in Scala 2.10 what I had serialised in 2.9. And in this case, I really need to make sure I can get my stuff back independent of the Scala version.So... I have been thinking that I could use a macro to make a \"backup\" of the source code, so that if POJO deserialisation fails, I can regenerate the function from source (using an in-place compiler/interpreter).My idea would be(My guess is the def-macro needs to be already in the  function of ).Text replacement macros are awesome at this kind of thing.  Scala doesn't come with them, but consider writing your own!  Transforming e.g.toshould be pretty easy; then you just have to preprocess before you compile.  If you want your IDE to not get confused by different line lengths, you can store the strings in a separate object, e.g.goes to (For best results, base-64 encode the captured text.  Nesting will work fine as long as you work recursively and are aware that nesting might happen.)"},
Scala

Recently trying to upgrade some oldish Scala code to use the Scala ARM library, in particular I like the continuations approach.My code is throwing a java.lang.NoSuchMethodError on the resource.ManagedResource.managed object.Here is my code:Where ConnectionPool.getConnection returns a java.sql.Connection to my database, the connection pool is based on BoneCP and works fine without using managed.This line of code returns the errors:Any help much appreciated. It's starting to seem I should just create my own ARM library as it's obviously very easy. However I do prefer to use community projects for my team's ease of future maitenance.I should add that BoneCP is not the cause and the same error is returned when I create the connection manually.Thanks\nRich"},
Scala

In a Play 2.0 application, I need to deserialize some JSON from a source which I don't control which uses single-quotes around strings -- where the JSON spec calls for double-quotes.The solution using Jackson is here:\nBut trying to implement this solution in play2.0 I hit a wall of static objects and private classes... it should be enough to replace object JerksonJson with one implementing the solution linked above at initialization, but because it is a static object it can't be extended, and id I try to copy it into my code I need to drag along classes PlaySerializers, PlayDeserializers, JsValueDeserializer,... I stopped here, as it looked like too much.Is there a clean solution?How about trying to fix the invalid json string by replacing every ' in it with a \"?That would work if 's are only used for specifying strings.I realize that this may not help too much with Play framework part, but perhaps you could use  instead of Jerkson? Doing that should make it easier to just use , with Scala module registered, instead of having to use Jerkson-specific handlers."},
Scala

I have a simple mongo application that happens to be async (using Akka).\nI send a message to an actor, which in turn write 3 records to a database.\nI'm using WriteConcern.SAFE because I want to be sure the write happened (also tried WriteConcern.FSYNC_SAFE).I pause for a second to let the writes happen then do a read--and get nothing.So my write code might be:then in my test code (running outside the actor--in another thread) I print out the # of records I find:My output looks like this:Indeed if I look in the database I see no records.   and the test works.  Async code can be tricky and it's possible the test code is being hit before the writes happen, so I also tried printing out timestamps to ensure these are being executed in the order presented--they are.  The data should be there.  Sample output below w/timestamps:So the 3 saves clearly happened (and should have written) a full 2 seconds before the read was attempted.I understand for more liberal WriteConcerns you could get this behavior, but I thought the two safest ones would assure me the write actually happened before proceeding.Subtle but simple problem.  I was using a def to create my connection... which I then proceeded to call twice as if it was a val.  So I actually had 2 different writers so that explained the sometimes-difference in my results.  Refactored to a val and all was predictable.  Agonizing to identify, easy to understand/fix."},
Scala

Pretty simple scenario here.  I've got:... (I have Json.read and Json.writes defined for both classes, and the necessary apply/unapply methods (which do the straightforward thing - just as if they were case classes.)In a controller, in a post I have:I can post JSON like this:or any other subclass, but Jerkson always gives me a straight Thing back.Also, when Things are serialized out, @type is not included, making it impossible for the client to instantiate the correct type of object on the other end.Note that virtually the exact same code works fine with Jackson under a Java EE server.  Even older versions of Jackson.(I am trying to justify a move to all-Scala & Play from Java EE. For the most part it's gone wonderful but things like this have to be made to work.  It would really be a shame for us to have to handle our own polymorphic JSON serialization - there must be a way to do this but I can't find it easily.  And I'm puzzled as to why this doesn't simply work, as Jackson is Jackson.)Well, I was able to solve the problem, by using the Jackson API directly:It hit me that Play's JSON libraries are probably not using Jackson in a way that I am familiar with - if they were a no-arg ctor would be necessary, instead of the apply/unapply that Json reads/writes make use of.I don't want to use this mechanism because makes immutable objects difficult or impossible, so I would still appreciate someone demonstrating to me how polymorphic JSON de-serialization can be achieved using Play's JSON library directly."},
Scala

I'm pretty new to scala and programming in general (just for fun) and I'm trying to understand tail-recursion and collections but debugg is really hard.I've 2 lists :ex : \"quoters\" quote \"quoted\" and \"quoted\" also quote \"quoters\".In the example, :the output should be something like :1/I think I'm misusing collections (it seems too much Json like...)2/I can get intersection with just List of Lists with :but not with the structure of List of Maps.3/I tried this for the recursion but it's not working because ... well i don't really know :I hope I'm clear enough :/Thank you in advance !FelixI think you have one extra layer in your data structures.  And I would probably use the name \"authors\" instead of \"quoted\", to avoid confusion because of the assonance between quoter / quoted:With this in place, and a small function like this:You can then start experimenting with different ways of collecting and reporting who has quoted which author and where, e.g.:which prints output like this:Now, think a bit about what you are mapping with these associative arrays.  You can effectively building the adjacency matrix of a graph.  How would you go about finding all circles in a directed graph?"},
Scala

I have a quite heavy project with many modules aka sbt subprojects each of each has a big company name prefix. I've tried to find  command task key and override it, but didn't success. Is there any way to do this?The best thing to do is to create a dedicated object, with its own Scala file, that would define a def Project.That way you could have something like::in the same folder as your  file:That way you could create a  task that would call  with your company's prefix."},
Scala

I'm trying to generate a sql statement like this:using Scala's slick 1.0.1 and postgres.This is my code:but it's generating queries like the following:\"rows\" seems to be generated as expected:rowCount sure is odd.e is an unholy beast as well.I'm not quite certain, but it seems to me I don't quite grok aggregate/grouping functions(such as count(*)) and Scala slick.  Does anyone have a suggestion?"},
Scala

I'm working on getting a test case working with Play 2.1.1 and Specs2 and am running into an interesting problem. I create a FakeRequest to send to a Controller, but the function in the controller never gets called.Here's the test code (slightly simplified, but with all the moving parts):And here's the main function in the controller (well, at least just the start of it):This code never hits main. Strangely enough, though, if I make the FakeHeader with no parameters, and remove AnyContentAsXml, just sending the Xml Element to the controller, then it works:Does anyone have any idea why this would happen?Here is your test little modified showing two ways testing the controller. The reason AnyContentAsXml is not working for you because your testing is mixing two approaches together.}In the second approach Play is take care of unpacking the xml for the BodyParser to use. And here is the controller:"},
Scala

I have a special code to execute when a pool thread start to execute and another when it finished.I mean, A need to call an initialize() before a thread start to execute actors code, and a cleanup() after it, in order to initialize thread specific resources (Database connections as an example) and cleanup (Close any already open connection)It will be great to do it in a thread scope. I'm thinking of doing in a trait with all actors mixing, but in this scope, the initialization is by actor. I think I'll have a better performance if I make it by thread.Any suggestion will be appreciated!ThanksEspecially for your cleanup code you will have trouble because there is no hook which you could use. I would recommend using the Actor life-cycle to model your resource life-cycle, i.e. create one DB connection when you start the actor and close it in postStop. Then instead of using a ThreadLocal database handle you send your DB queries to the (pool of) actors. Do not worry about threads yourself, that is Akka\u2019s job. "},
Scala

If I'm using Play! to build a scala web app, how can I connect to a remote instance, run a map reduce job there? I have the scripts for the map reduce job, just not sure how I can connect to the instance within play and run the map reduce job on the instance using parameter data I get from the user through the web app? "},
Scala

I am writing scala and ssp files in Intellij, i want Intellij to auto-Indent my code. While it is working for scala files but it doesn't work for ssp files.Is there any way we can configure IntelliJ to auto-indent these files also.or is there any ssp editor available online ?Currently no support available for scalate in Intellij.For now you can use Textmate with . Working for me."},
Scala

I have a webservice running on jboss server. I can't change it to netty because i'm using other features of jboss. But i want to use finagles futures from the client. Is there a way ?The  class used in Finagle is part of , which is open source.  is usable on its own within any project that adds  as a dependency.You can always use a finagle client to make calls to an HTTP [or other RPC protocol] webservice. It doesn't matter how the service is implemented as along as it uses the protocol correctly. If you are using Java, this link should give you details on how to build a finagle client for an HTTP service: Here's some sample code to for a more elaborate finagle HTTP client: "},
Scala

Given the Scala code below: What info about the sender (actor1) can actor2 get ?How can it tell which actor the message came from if more than one actor\n can send the same message to actor2 ?  Is there metadata in sender that\n can be queried ?Am a newcomer to Scala. Thanks for your patience....Ken RYou can actually send the actor that sent the original message as part of the message. It should be noted, though, that you should only use this to send a message to the original sender. Calling a function directly on the actor could cause all sorts of terrible things to happen!I actually just read about this in Programming in Scala today, so if you want to look up more about it, I highly recommend the book."},
Scala

I have little previous experience with deprecated Scala actor, recently I started to learn Akka actor, they seem to be quite different.I completed this tutorial Next, I am trying to write an alternative Hello World, using a paradigm similar to deprecated Scala actor. But I have some difficulties (see in-line comments):There are a couple of things wrong with the code.1) You cannot create an actor by simply instantiating its class. You need to obtain an ActorRef using actorOf. To do this you need to start up an ActorSystem that will manage the creation of Actors.  2) Your receive method is wrong too. An pattern of type  will match everything including . Try something like this:Here a message is printed only if it is not  in which case it does not match the first case and falls of to the second one."},
Scala

I'm working on a Scala project that is managed with Maven, all on OS X. When I build the project, I will get errors that look like this:Sometimes they will be switched, e.g.Running \"mvn clean\" and then rebuilding the project is the only way I've been able to get around this. I would like to avoid doing that (and of course, inexplicable build errors are not good either :P)."},
Scala

I was wondering whether anyone could shed some light on this peculiar problem. I am using STS 3.2 (i.e. Eclipse 4.3 Kepler) with the Scala IDE and the Eclipse Maven plugin. The version of Maven I am using is Maven 3.0.5. I am using the maven surefire plugin version 2.4.3 and Scala version 2.10.2 . I have followed the instructions such as those provided here  and  however, however when I set break points in my JUnit scala tests, the break points are not being hit. I am not sure why this happening. Is there a problem with Eclipse Scala Maven and Maven Surefire??Thanks If you have flexibility in your choice of IDEs then I'd switch to IntelliJI've had issues like this in the past with maven-eclipse and while they are solvable, Intellij supports maven natively.  "},
Scala

i wanted to use the , which is written in , in Scala. But there are several problems that i cannot solve.In , if i wanted to search for a label with a Wrapper, i can do it in that way: If i want to do that in Scala, i get no working solution. I have tried it already in that way:But then scala tells me: - inferred type arguments  do not conform to method as's type parameter bounds The method \"as\":The method \"lookup\":The Class \"Parent\":So i don't get it, how i can use these interfaces in scala. Is there any solution, or are there limitations of the use between scala and java?I know nothing about JemmyFX, but here's my 2 cents.\nIt's not an interoperability issue between Scala and Java. It's an issue of correctly typing your call to the  method.The  method signature says  which means that the INTERFACE type must be parametrized exactly with the same type than TYPE. Because of this, you cannot use  in the first argument and  in the second argument: you must use either  or  twice.I've tried to reproduce the issue with the following Scala code:Note that if the  method had been defined like this:the last line in the example above would have compiled."},
Scala

I am having trouble using a left outer join in Slick. I'll start with some code : PS : The  &  are the objects extending  in opposition to  &  which are simple case classes.This is the error, I am getting when compiling the part above :I don't really understand this error. I know it has something to do with transformation, composition of queries but I have no idea how to change/fix it. Could some shed some light on this? The fix is explained here:  .  is not a query operation at the moment, use  instead."},
Scala

How can I ignore all strings in these grammar rules using correct placement of ~> or <~ operators?I found the solution, I should break  to 3 None terminal rules as below"},
Scala

I try to reproduce the Monoid examples from: I tried with Shapeless-2.0.0-SNAPSHOT and Shapeless-2.0.0-M1. Do i need some other things? Thanks \nFabianThe problem was that i missed the Monoid part of the example..."},
Scala

Given the JSON...Represented with case classes...I attempt the following which fails with .What is the correct way to parse this?For a strange reason I did not find an elegant solution to read a json model with only one value. For 2 and more values you may write:For a json with 1 field try using something like that:This should work but doesn't look nice :("},
Scala

I try to fill a form with the values of Systembut some of 'system' values are java.math.BigDecimal and it says :how can i handle this?Looks like problem in anorm or somewhere near. As you may see from error description  and  are s in query result, but declared as  in form.I am not familiar with anorm, but solution is to declare these ids as long in anorm, or declare them as  in form mapping or convert from  to  in your query."},
Scala

Given some object that has the ability to query its fields, is it possible to iterate over the fields to generate a list of mappings and to use the list of mappings to create a form?For example:Background:\nI need to build a basic crud interface for our data model which consists of a 100+ tables, some with up to a 100 columns. Refactoring the data model is not an option since this crud interface is just one of many other users of the data. We generate the model classes so it is possible to also generate the form classes but I am hoping that I can get around the 18 / 22 field limit by using a list of fields instead."},
Scala

I am using jetty 2.1.6 and sbt 0.7.7.Currently my app is running on http, but I want to run with httpsI tried following approach to run it with https :\nThen i set below code in build.scala file.But I did not get my work done. Please let me know , if i am doing anything wrong.Sorry, i mentioned it wrong earlier.Now I have successfully upgraded my jetty server to jetty-8.0.0.M3Now i am getting below error when I am writing above code in my build.scala file :[info] == jetty-run ==\n[error] Error running jetty-run: Error running Jetty: java.lang.NoSuchMethodError: org.eclipse.jetty.xml.XmlConfiguration.configure(Ljava/lang/Object;)V is a a pretty old version of SBT. I understand you may have reasons not to upgrade, but if you can there is the  SBT plugin that makes  in Jetty super easy."},
Scala

I installed , then I installed SVN. After restarting I was asked to choose my SVN Connector (I choose ). At this point, everything is working.Then I installed the , and everything is still working.Then I installed the , and suddenly after restarting Eclipse my SVN has stopped working. It was installed etc., but it isn't working.I figured, I needed to install the Scala plugin first. Then I installed SVN but after restarting I didn't get the message about choosing an SVN Connector, so I installed it manually. Still doesn't work.Is this a bug? How do I fix it?"},
Scala

I'm using Play 2.1.2 and I'm having some trouble with an  and I'm seeking ideas on how to debug this.I'm trying to stream some S3 data through my server.  I can get an  from the Amazon SDK for my S3 file ().  I then turn that  into an  using .All this type checks and on my local development machine it all works perfectly.  When I formulate my  in Play, I just return .The problem comes when I deploy this to a production server.  The very first time I request the file, it works just fine and I get the whole file.  But subsequent times it frequently gets part way through (different amounts each time) and then gets \"stuck\".  I wrapped the  as follows to be able to log whether the enumeration completed:As expected, on my development machine (and the first time through on the production machines), I get the message \"Contents fully enumerated\".  But after that, the production machine will start the download of the file, but it doesn't finish (in both the HTTP sense and in the  sense).I'm not sure how to debug this.  Obviously,  does some magic and I don't know how to figure out what is happening between chunks.  I thought this might be a thread pool issue so I wrapped the whole response in a  block, but it didn't appear to make any difference.I'm trying to avoid the hassle of creating a local temporary file from S3 and then building my  from that.  Using the  to create an  seemed like the elegant way to do this...if it worked.Suggestions?OK, so I think I figured this out.  It turns out that on the Play side, things appear to be working.  I tried all kinds of variations (different ways of constructing the enumerator, creating temporary files, etc).  It didn't really matter.What  matter was the proxy I was using.  I'm using  and if I make a request on the server behind the proxy, I get the correct response (directly from Play).  If I make the request on the server outside the proxy, I get an incorrect (empty) response.  So it looks like the proxy is \"dropping\" the response.It appears the issue is that the response is chunked by the  call and this is causing the problem with the proxy.  If I reformulate my response to be:Then play uses the  to construct a complete response (not streamed) and things work again.  Of course, it is stupid to have to form the complete response in this case, but it does work.  Hopefully I can find a better solution than this in the long term, but this seems to work for now."},
Scala

I have an application that takes Photo with photo overlay and then resize it, here is my code\n,is it possible to set size to the camera to avoid the resizing process after taking the picture, since after taking the picture I have some delay..View_Camera_OverlayCamera Overlay Camera activity would you please help me in this implementationThanks in advancedid you check  in Camera.Parameters\nAlso make sure that the camera supports the picture size. you can use  for that. "},
Scala

I would like to know if it is possible to merge JsResult objects, something similar to ~> operator in play 2.1+. In the following code I want to validate two inputs and then update user information accordingly. The  operator below between two validate method calls is not valid. Is there a way in play to combine two JsResult objects together in the following scenario ?You can use flatmap to combine the JsResults.This is how you can join two JsResult into one: and  is part of the  package."},
Scala

I'm building a java/Scala app which would be deployed in hundreds of nodes in cluster.  I thought of the following idea.  Instead of building rest api for my services where nodes would communicate and query and do operations one on each other.  I'll simply use akka actors in this way one actor can send messages to others and this would save me from the whole process of managing rest api's and even discovery of nodes load balancing etc (although in don't have to be asynchronous).Note I'm aware of the motivation to use actors as means for async programming instead of locks I just want to know if the use case I suggested is actually a good use case for Hakka actors or am I missing something thanks."},
Scala

I have the following architecture at the moment:Load(Play app with basic interface for load tests) -> Gateway(Spray application with REST interface for incoming messages) -> Processor(akka app that works with MongoDB) -> MongoDBEverything works fine as long as number of messages I am pushing through is low. However when I try to push 10000 events, that will eventully end up at MongoDB as documents, it stops at random places, for example on 742 message or 982 message and does nothing after.What would be the best way to debug such situations? On the load side I am just pushing hard into the REST service:and then in the workerRouterOn the spray side:On the processor side it's just basically an insert into a collection. Any suggestions on where to start from?Update:\nI tried to move the logic of creating messages to the Gatewat, did a cycle of 1 to 10000 and it works just fine. However if spray and play are involed in a pipeline it interrupts and random places. Any suggestions on how to debug in this case?In a distributed and parallel environment it is next to impossible to create a system that work reliably. Whatever debugging method you use it will only allow you to find a few bugs that will happen during the debug session.Once our team spent 3 months(!) while tuning an application for a robust 24/7 working. And still there were bugs. Then we applied a method of  (). Within a couple of weeks we implemented a model that allowed us to get a robust application. However,  requires a bit different way of thinking and it can be difficult to start.I moved the load test app to Spray framework and now it works like a charm. So I suppose the problem was somewhere in the way that I used WS API in Play framework:The problem is resovled but not solved, won't work on a solution based on Play. "},
Scala

I'm on the road to learn Scala and I'm having a hard time understanding contravariants, covariants, invariance, etc. From  I have learned how functions can be considered subtypes of another function. (Really useful to know!)The code below is what I believe are the important pieces to solving my puzzle. I have extracted parts that I think would add unneeded complexity to the problem. According to the example I have a Student object that will act as a factory to generate functions. Functions will take in types or subtyes of AnyVal (Int, Double, Long, etc.), and the return output will be of the same input type. To achieve this the student class takes in a generic (A) that is a subtype of AnyVal. The abstract class is there so that I can refer a list of these students by doing something like List[Master[AnyVal]]( Student.func1). The problem is that I cannot have the line \"val function: List[A] => A\" as I get error \"covariant type A occurs in contravariant position in type => List[A] => A of value function\". I don't know why the return type must be the contravariant of A. I can somewhat accept this fact for name based on the Function1 trait. So how would I define my function in the abstract Master class so that the return type is a contravariant of type A? I found an example of how to define this with function definitions (Ex. def function[B >: A](v: B): List[B]), but how would I implement this with an anonymous function? Remember \"A\" in the master abstract class must be covariant since there will be a list of function that take in all AnyVal types (Int, Double, etc.)Really appreciate the help! Let me know if any of my terminology is off. - Scala LearnerIt is very difficult to create generic classes or traits parameterised with a covariant type.  Once you add the variance annotation, you cannot use the type as a parameter for any of the class methods.  This is because functions are contra-variant in their parameters and covariant in their return types.  There is a very good explanation in  accepted answer.If you really want the type to be covariant, you have to write all the methods to take parameters of type [B >: A] - that is, to take supertypes of A as their parameter type.  This can be quite challenging; the online Scala documentation has an  of the acrobatics that might be required."},
Scala

I have a java project that I am adding some scala code to. Previously I used ant to build the project and am moving to using sbt. In the ant build file was an rmic task to build the RMI Stub classes in the project. This is a task that comes directly with ant. Has anyone used a similar task in sbt or do they know how I could define one?Thanks\nDes"},
Scala

I am converting some Matlab codes to Scala. In Matlab, there is the  function that is used to define the number of cores to use and \"open\" the core for parallel computations (and thereafter use for instance  instead of  to run loops in parallel). (\"opens\" 4 cores)(\"closes\" the cores for parallel processing)What is the equivalent of  in Scala?The Scala compiler generates regular JVM bytecode, so in runtime Scala code has the same capabilities that Java code does. The JVM provides parallelism through light-weight threads (see Thread class and Runnable interface), which will use as many cores as they can (no more than one per thread, off course). See: Twitter's Scala School has a concurrency page () which indeed shows how to use Java concurrency primitives from Scala.That said, there are facilities for parallel collections in Scala, which leverage the fork/join Java capabilities from JVM 6 onwards. See: